Predictive Hacks

How to get the ROI of your Cryptocurrencies with Kraken API

cryptocurrencies

Many cryptocurrency investors and traders use Kraken. So far, Kraken does not show you directly the P/L and/or ROI of your cryptocurrencies. In this tutorial, we will show you how to get the ROI of your cryptocurrencies using the Kraken API and Python. The ROI of each cryptocurrency is defined as:

\(\frac{CurrentValue}{OrderValue}-1\)

It is common for an investor to buy assets in different time periods. For example:

  • At time 1 they buy 3 Polkadot at $20
  • At time 2 they buy 2 Polkadot at $18
  • At time 3 they buy 5 Polkadot at $21

Thus, the average order value of the Polkadot is (3 x 20+2 x 18+ 5 x 21)/(3+2+5) = 20.1 USD. This means that if the current value of the Polkadot is $25 it means that the ROI is around 24.38%.

Notice that the average order value does not change even if we have sold some assets. Enough with the theory, let’s dive into coding, but before we start you may find useful the other Kraken tutorials that we have written.

Get the ROI (P/L) of each Cryptocurrency

First, we will need to pass the access and secret keys and create some functions in order to call the Kraken API.

import requests
import pandas as pd
import time
import os
import urllib.parse
import hashlib
import hmac
import base64

# Read Kraken API key and secret stored in environment variables
api_url = "https://api.kraken.com"
api_key = 'XXX'
api_sec = 'YYY'


def get_kraken_signature(urlpath, data, secret):

    postdata = urllib.parse.urlencode(data)
    encoded = (str(data['nonce']) + postdata).encode()
    message = urlpath.encode() + hashlib.sha256(encoded).digest()

    mac = hmac.new(base64.b64decode(secret), message, hashlib.sha512)
    sigdigest = base64.b64encode(mac.digest())
    return sigdigest.decode()


# Attaches auth headers and returns results of a POST request
def kraken_request(uri_path, data, api_key, api_sec):
    headers = {}
    headers['API-Key'] = api_key
    # get_kraken_signature() as defined in the 'Authentication' section
    headers['API-Sign'] = get_kraken_signature(uri_path, data, api_sec)             
    req = requests.post((api_url + uri_path), headers=headers, data=data)
    return req
 

Get the History of your Orders

We will extract the history of the orders that we have made as follows:

# Construct the request and print the result
resp = kraken_request('/0/private/TradesHistory', {
    "nonce": str(int(1000*time.time())),
    "trades": True
}, api_key, api_sec)
 

This is a JSON with nested dictionaries. In our case, we care only about the “buy” order types, the pairs, the volume and the cost and the fees.

my_assets = []
my_volume = []
my_cost = []

for trade, values in resp.json()['result']['trades'].items():
    #print(trade, values)
    if values['type']=='buy':
        my_assets.append(values['pair'])
        my_volume.append(float(values['vol']))
        my_cost.append(float(values['cost'])+float(values['fee']))

df = pd.DataFrame({'pairs':my_assets, 'volume':my_volume, 'cost':my_cost })
df = df.groupby('pairs').sum()
df['avg_price'] = df['cost']/df['volume']

df.head()
 

Now, we want to get the current price of the pair. We will work as follows:

current_value = []
for crypto in df.index:
    resp = requests.get(f'https://api.kraken.com/0/public/Ticker?pair={crypto}'.format(crypto))
    current_value.append(float(resp.json()['result'][crypto]['a'][0]))

df['current_value'] = current_value

df['ROI'] = df['current_value']/df['avg_price']-1
df.head()
 

As we can see the ADA has a 27.38% ROI and the BAT has -11.05% ROI

Want some Free Cryptos?

You can get $25 in Bitcoin by investing $100 in Nexo

Share This Post

Share on facebook
Share on linkedin
Share on twitter
Share on email

Leave a Comment

Subscribe To Our Newsletter

Get updates and learn from the best

More To Explore

Python

Image Captioning with HuggingFace

Image captioning with AI is a fascinating application of artificial intelligence (AI) that involves generating textual descriptions for images automatically.

Python

Intro to Chatbots with HuggingFace

In this tutorial, we will show you how to use the Transformers library from HuggingFace to build chatbot pipelines. Let’s