Last Updated on April 3, 2023
Table of contents:
- What is the Kraken API?
- What is Kraken?
- Is Kraken API free?
- Why should I use Kraken API?
- Why shouldn’t I use the Kraken API?
- Is Kraken API available in my country?
- What are the alternatives to using Kraken API?
- What clients are available for the Kraken API?
- How to get started with Kraken API?
- How to get asset info with Kraken API?
- How to get Price Data on Kraken API?
- How to get historical data with Kraken API?
- How to access technical indicators such as the 20 SMA with the Kraken API?
- How to get Order Book data with Kraken API?
- How to execute a trade on ETH when BTC hits a certain price with the Kraken API?
- How to execute an ETH trade when BTC moves 5% in the last 5 minutes with the Kraken API?
- How to cancel orders with Kraken API?
- Can Kraken API be used in Google Sheets?
- Full code
What is the Kraken API?
Kraken API is a method that allows us to automatically trade cryptocurrencies on Kraken via code.
Link: https://www.kraken.com
What is Kraken?
Kraken is an online cryptocurrency exchange platform that allows users to trade over 50 coins and tokens. Kraken also features OTC, Fiat and spot, futures, and margin trading.
As one of the most popular US-based exchanges, Kraken brings a competitive edge to trading. Its API is favored by many algorithmic traders and in this article, we will explore it thoroughly.
Is Kraken API free?
Creating a Kraken account and using the Kraken API is completely free, but when it comes to trading there are fees. The fees depend on various things like the assets you’re trading, the platform you’re using, monthly trading volume, and more.
On Kraken, there are 5 types of fee schedules and they are the following:
- Instant Buy
- Kraken Pro
- Stablecoin & FX Pairs
- Margin
- Futures
The Instant Buy fee schedule allows you to buy, sell or convert Bitcoin or other cryptos on Kraken via the Kraken App that can be found on both iOS and Android.
If you are buying stablecoins with USD or other stablecoins, there is a 0.9% fee issued. On the other hand, buying a stablecoin with another cryptocurrency results in a 1.5% fee.
Stablecoins can also be purchased via Payment cards (3.75% + €0.25 fee) or Online Banking (1.7% + €0.10 fee), but these features are still being worked on and they aren’t available to all users.
The Kraken Pro fee schedule utilizes the maker-taker fee system with volume incentives that are calculated on your activity in the past 30 days. Have in mind that the volume obtained from the Instant Buy feature isn’t being counted for.
By default, fees are calculated as a percentage of the trade’s quote currency volume. Certain pairs allow the fee to be calculated based on the trade’s base currency, which can be specified when ordering using the Fee Currency option.
Basically, the more you trade the lower do the fees get. Please check out the picture below for a better understanding of the fees:
Stablecoin & FX fee schedule applies to FX pairs (e.g. EUR/USD) and where a stablecoin is the base currency (e.g. USDT/USD). In a case when the stable coin is the quote currency only (e.g. BTC/DAI), the fee schedule in the “Trading” tab is used.
All Margin fees are added in addition to trading fees at the opening and closing of margin positions. For a complete understanding visit the following link: https://www.kraken.com/en-us/features/fee-schedule
And lastly, the Futures fee schedule also follows the maker-taker fee system where the previous non-futures orders don’t apply.
Why should I use Kraken API?
- Kraken is free
- Kraken is easy to use and beginner-friendly
- Has competitive fees
- Offers a decent API
- Has a good track record
- Is highly customizable
- Offers a wide selection of assets
Why shouldn’t I use Kraken API?
- The customer support can be too slow
- Isn’t private (required ID verification)
- Doesn’t offer a test environment
Is Kraken API available in my country?
Citizens of the following countries cannot use Kraken:
- Afghanistan
- Cuba
- Iran
- Iraq
- Japan
- North Korea
- Tajikistan
What are the alternatives to using Kraken API?
Kraken can be replaced with other websites that can be more suitable for your needs. Here are some of them:
What clients are available for the Kraken API?
Available clients for the Kraken API are the following:
How to get started with Kraken API?
In order to get started with the Kraken API we will first need to obtain the API Key that allows access to private endpoints. This means that we need an account so let us make one.
Proceed to the following link and click the “Create Account” button that is found in the upper right corner:
A new screen will appear where you will enter your email, username, and password while specifying the country of residence.
After that, you will be requested to confirm your account activation via an email from Kraken. Be sure to do that.
When done, you will be taken to the main website and welcomed. When there, click on your name in the upper right corner and go to security -> API.
Now click on Add key and specify what your API Key is allowed to do. You can regulate the API key on three categories which are Funds, Order & Trades, and Other. You can also add an expiration and query start/end date.
For this article, I’ll give the Key all permissions and generate it.
Be sure to safely store your keys as the Private Key won’t be visible again after you close the window. Now that we have what we need, we can start exploring the Kraken API.
For this, we will use the pykrakenapi library that Implements the Kraken API methods using the low-level krakenex python package. To install it use the following command:
pip install pykrakenapi
How to get asset info with Kraken API?
Available assets on the Kraken exchange can be obtained via their API by utilizing the get_asset_info
function which returns a pandas data frame. We call it as follows:
data = k.get_asset_info()
data
If you want to obtain info from Kraken by urself (without the library) you can write requests in the following way:
import requests
data1 = requests.get('https://api.kraken.com/0/public/Assets').json()
data1['result']
{'AAVE': {Caclass': 'currency',
'altname': 'AAVE',
'decimals': 10,
'display_decimals': 5},
'ADA': {'aclass': 'currency',
'altname': 'ADA',
'decimals': 8,
'display_decimals': 6},
Let us obtain all the tradable asset pairs now:
pairs = k.get_tradable_asset_pairs()
pairs
How to get Price Data on Kraken API?
Kraken ticker price data can be obtained through the get_ticker_information
function. It also comes in a form of a pandas data frame.
ticker = k.get_ticker_information('BTCUSD')
ticker.T
As you can see some response categories come as arrays. Thus, we will need to get acquainted with the response:
index = pair name
a = ask array(<price>, <whole lot volume>, <lot volume>)
b = bid array(<price>, <whole lot volume>, <lot volume>)
c = last trade closed array(<price>, <lot volume>)
v = volume array(<today>, <last 24 hours>)
p = volume weighted average price array(<today>, <last 24 hours>)
t = number of trades array(<today>, <last 24 hours>)
l = low array(<today>, <last 24 hours>)
h = high array(<today>, <last 24 hours>)
o = today’s opening price
How to get historical data with Kraken API?
Historical data can be obtained from Kraken by using the get_ohlc_data
function. We will ask for the BTC historical hourly data expressed in US dollars.
ohlc = k.get_ohlc_data('BTCUSD', interval=1440, ascending = True)
ohlc[0].head()
But what if we want to create some indicators like the 20 SMA?
How to access technical indicators such as the 20 SMA with the Kraken API?
Kraken API doesn’t offer indicators but they can be created in many ways. The one that we will use will be the simple pandas rolling feature to create a 20 SMA (Simple Moving Average).
For more advanced indicators such as the RSI be sure to give the btalib library a look. Now. let us import pandas and calculate the 20 SMA:
import pandas as pd
ohlc[0]['20 SMA'] = ohlc[0]['close'].rolling(20).mean()
ohlc[0].tail()
As we already have all the required data for a nice interactive chart, let us go ahead and create one. For this, we will use the plotly library:
import plotly.graph_objects as go
import plotly.express as px
fig = go.Figure(data=[go.Candlestick(x = ohlc[0].index,
open = ohlc[0]['open'],
high = ohlc[0]['high'],
low = ohlc[0]['low'],
close = ohlc[0]['close'],
),
go.Scatter(x=ohlc[0].index, y=ohlc[0]['20 SMA'], line=dict(color='purple', width=1))])
fig.show()
How to get Order Book data with Kraken API?
Order book data can be obtained from Kraken by using the get_order_book
function. The depth of the order book can go up to 100 and is specified by the count
parameter.
book = k.get_order_book('AAVEUSD', count = 20)
print(book[0].head())
print(book[1].head())
If you wish to merge the two sub-datasets (bids and asks) by their index value you can use the pandas merge feature like this:
df = pd.merge(book[0], book[1], left_index=True, right_index=True)
df = df.rename({"price_x":"Bid Price","volume_x":"Bid Amount", "time_x":"Bid Time",
"price_y":"Ask Price","volume_y":"Ask Amount", "time_y":"Ask Time"}, axis='columns')
df
How to execute a trade on ETH when BTC hits a certain price with the Kraken API?
In this first example, I will show you how to properly and securely launch an order with specified requirements. The thing that we want to do is to launch a trade on ETH when BTC hits a certain price (e.g. $60k).
In order to make this work, we will need to set our order foundation and then create a loop that will check if the price level is hit. If the price is hit, we will execute a market order. On the contrary, we will continue looping around.
When the price is executed we will wait for a few seconds and check if the order was really filled. This additional step is very important to add to your trading strategies as the exchange server may encounter some troubles.
Now that the logic is set, let’s import the relevant libraries and set up the API:
from time import sleep
import krakenex
from pykrakenapi import KrakenAPI
api = krakenex.API()
kraken = KrakenAPI(api)
api.load_key('KrakenPass.txt')
Notice the kraken.load_key
part – it loads the text file where you need to store your API Key and API Secret on separate lines. Now is the time to create the full loop:
while True:
try:
BTC = kraken.get_ticker_information('BTCUSD')
except exception as e:
print(f'Unable to obtain BTC data: {e}')
if float(BTC['b'][0][0]) >= 57300.00:
try:
ETH = float((kraken.get_ticker_information('ETHUSD'))['a'][0][0]) + 2
response = kraken.add_standard_order(pair='ETHUSD', type='buy', ordertype='limit',
volume='0.007', price=ETH, validate=False)
print(response)
except exception as e:
print(f'Error placing order: {e}')
sleep(3)
check_order = kraken.query_orders_info(response['txid'][0])
if check_order['status'][0] == 'open' or 'closed':
print('Order completed sucessfully')
break
else:
print('Order rejected')
break
else:
print('Requirement not reached')
sleep(30)
If you get stuck or need any help just type this command:
help(KrakenAPI)
How to execute an ETH trade when BTC moves 5% in the last 5 minutes with the Kraken API?
The main task will be to execute an ETH trade when BTC moves 5% in the last 5 minutes. This means that we will want to create a loop that will obtain the prices of the two cryptos and calculate the percentage change between the two.
If the percentage change is less than 5%, the program will be sleeping for 5 minutes and calculating the percentage change again. If the percentage change is equal to or more than 5% the trade will execute.
After the trade execution, we will sleep for a few seconds and then check on the trade if it was filled or not. Have in mind that libraries and API setup remain the same as in the previous example.
Now that the logic is set, it is time to code it out:
while True:
try:
BTC_old = float((kraken.get_ticker_information('BTCUSD'))['b'][0][0])
except Exception as e:
print(f'Unable to obtain BTC data: {e}')
sleep(60)
try:
BTC_new = float((kraken.get_ticker_information('BTCUSD'))['b'][0][0])
except Exception as e:
print(f'Unable to obtain BTC data: {e}')
percent = ((BTC_new - BTC_old)*100) / BTC_old
if percent >= 5:
try:
ETH = float((kraken.get_ticker_information('ETHUSD'))['a'][0][0]) + 2
response = kraken.add_standard_order(pair='ETHUSD', type='buy', ordertype='limit',
volume='0.007', price=ETH, validate=False)
print(response)
except Exception as e:
print(f'Error placing order: {e}')
sleep(3)
check_order = kraken.query_orders_info(response['txid'][0])
if check_order['status'][0] == 'open' or 'closed':
print('Order completed sucessfully')
break
else:
print('Order rejected')
break
else:
print('Requirement not reached')
How to cancel orders with Kraken API?
If you want to cancel a particular order with the Kraken API you will need to use the cancel_open_order
function and pass in the order id as the txid
parameter.
k.cancel_open_order(self, txid, otp=None)
Can Kraken API be used in Google Sheets?
Yes! Kraken API can be called through Google Sheets by utilizing the API Connector add-on. In order to do this, you will need to download the add-on from the Google Workspace Marketplace that is found here.
After you install the add-on it will offer you a quick guide on how to use it. If you are skeptical about the feature or just want to see it before you install, I got you.
Open up a Google spreadsheet and go to Add-ons -> API Connector -> Open.
After the API Connector interface opens up on the right side of your screen click the “Create” button and write your http request in the API URL path.
I will plug in the Kraken API assets URL, set the destination sheet to current and, under Output options, set the Report Style to compact. Let’s give the request a name and click “Run” to see how the output looks like:
As you can see, we will need to transpose this output, as we did with the pandas data frame. To do this in Excel click on the first asset and then run the Shift + Ctrl + Right arrow key shortcut to select all the assets on the right side of the selected asset.
After that, click on a new cell where you want to transpose the outputs (in this case the error cell) and then right-click -> Paste special -> Paste transposed.
Feel free to try out some other endpoints like the following:
Order Book:
https://api.kraken.com/0/public/Depth?pair=xbteur&count=20
Ticker:
https://api.kraken.com/0/public/Ticker?pair=xbtusd
9 Replies to “Kraken API – A Complete Guide”
Comments are closed.