Python

Get market data from Kraken exchange with Python

Get market data from Kraken exchange with Python

Kraken is a very popular crypto exchange that offers traders a wide variety of digital currencies to buy and sell. It is a secure, reliable platform that provides users with an intuitive interface and advanced trading tools. Kraken is an ideal choice for both experienced traders and beginners, offering a wide range of features at competitive fees.

Kraken also offers users the ability to download real-time data and create custom trading algorithms that can be run on the exchange. This allows traders to make better and more informed trading decisions and to automate their trading processes. With the data download feature, Kraken users can easily access the data they need to optimize their trading strategies. It this article I’ll show you how you can Kraken’s endpoints from Python to get market data.

First let’s start by importing libraries we’ll need in the code. All three are very basic Python libraries:

import datetime as dt     # working with dates
import pandas as pd       # working with data frames
import requests           # for "get" request to API

First we can explore the universe of supported instruments. Let’s get the list of supported assets first. This code will download all supported assets:

Supported assets

url_assets = "https://api.kraken.com/0/public/Assets"

result = requests.get(url_assets).json()

assets = pd.DataFrame(result["result"]).T

As you can see code is pretty simple. By default Kraken will output is results in a json format, but it’s quite simple to transform it into a nice Data Frame.

The code for supported asset pairs will be almost the same, but with a different endpoint:

url_asset_pairs = "https://api.kraken.com/0/public/AssetPairs"

res = requests.get(url_asset_pairs).json()["result"]

asset_pairs = pd.DataFrame(res).T

This will output us a huge data frame with all supported pairs and all the information for all of them:

OHLC Data

To get OHLC historical data you need to use a bit more complicated code. First you have to specify in parameters pair and timeframe you want to get data for:

url_ohlc = "https://api.kraken.com/0/public/OHLC"

req_params = {"pair": "XBTUSD", "interval": 60}

After that you can request the data and transform it into a dataframe:

result = requests.get(url_ohlc, params = req_params).json()["result"]

ohlc = pd.DataFrame(result[list(result.keys())[0]], columns=["datetime", "open", "high", "low", "close", "vwap", "volume", "count"])

This will output us okeish dataframe already, but it requires a bit more work:

To make it nice we have to fix data types to float and fix the index to be datetime:

ohlc = ohlc.astype({'open': float, 'high': float, 'low': float, 'close': float, 'vwap': float, 'volume': float})

ohlc.index = pd.to_datetime(ohlc["datetime"], unit='s')

Now the data frame looks good:

You might notice that Kraken outputs you only 720 records. And unfortunately, there is no way to expand that history and require more bars using the standard ohlc endpoint. There is a hack you can use to download entire history with trades, I’ll show it an another article later.

Live Quote

To get live quote for instruments in Kraken you have to write a bit more code, but it’s quite simple as well. The code looks like this for single ticker:

url_ticker_quote = "https://api.kraken.com/0/public/Ticker"

req_params = {"pair": "XBTUSD"}

res = requests.get(url_ticker_quote, params=req_params).json()["result"]

price_dict = res[list(res.keys())[0]]

This will output you a pretty big dictionary with a lot of live info the live signal:

To get from it only Ask, bid and last price for example you can use the following code:

ask_price, bid_price, close_price = list(map(lambda x: x[0], list(price_dict.values())[:3]))
[ask_price, bid_price, close_price]

You prices will look like this:

['21861.20000', '21861.10000', '21861.20000']

To get prices for all tickers you can use the same endpoint but omit the pair parameter:

url_ticker_quote = "https://api.kraken.com/0/public/Ticker"

res = requests.get(url_ticker_quote).json()["result"]

tickers = pd.DataFrame(res).T

resulting data frame will require a bit of work to look nice. this code will create a nice data frame with ask/bid and last:

tickers = tickers .iloc[:, :3]
tickers .rename(columns={"a": "ask", "b": "bid", "c": "last"}, inplace=True)
tickers = tickers .applymap(lambda x: x[0])

this will output you a nice data frame with prices for all supported pairs:


Follow me on TradingView and YouTube.

This image has an empty alt attribute; its file name is wide.png

2 thoughts on “Get market data from Kraken exchange with Python”

  1. I get this error:

    Traceback (most recent call last):
    File “C:/Users/Utente/Documents/Coding/kraken.py”, line 32, in
    df = df.iloc[:, :3]
    NameError: name ‘df’ is not defined. Did you mean: ‘dt’?

Leave a Comment

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Pine Script Programming Courses
Pine Script Programming Courses
Learn to build your own TradingView Indicators and Strategies
Sidebar Signup Form
If you want to be the first in this business, subscribe to the latest news