The basis of any trading strategy is having a good backtesting solution, and you can’t backtest unless you have data.
Similar to the previous post on binance I’m going to step through how to download and save historical data from the Kucoin API over a given timeframe.
This example does not require an account on Kucoin as it utilises public API calls.
Working with dates
It’s convenient to be able to pass human readable dates, unfortunately the Kucoin server only understands unix timestamps in seconds
so we need to convert our date.
This can be done by using helper websites like current millis but we’ve got the power of python so let’s use it.
We’ll use the helper function we created in a previous blog for Binance timestamps and modify to return seconds.
With this function we can convert all sorts of handy date formats to seconds like the examples below.
Kucoin has 2 kline functions, their own and a Trading View version each having different output formats and parameters.
For now I’m just going to focus on the Trading View version call. As this endpoint returns every kline you ask for by default
we don’t have to create a loop or worry about convert our intervals to seconds which removes a lot of extra work.
The Trading View kline functions has the following parameters
symbol - e.g ETHBTC
interval - one of (1, 5, 15, 30, 60, 480, D, W)
from - timestamp in seconds
to - timestamp in seconds
The to parameter is required, so we need to make sure that we pass a value for the time now if we want everything.
The get_kline_data_tv endpoint returns each individual value we are after in a list of its own,
so we get all the opens in a list, all closes in a list and so on for high, low and timestamp.
I don’t find this very helpful to work with so let’s return it in a more standard list in the OHLCV format.
Fetch the Klines already
Ok let’s get down to it, we’re ready to build our function to fetch historical data and massage it into a more useful format.
With this function we have a really simple way of fetching a list of klines using simple to use dates and intervals.
Save to file
Once we have fetched the list of klines, it makes sense to save them to a file for later use.
Well as with the Binance example I may as well add these functions to the python-kucoin library for everyone to use.
date_to_seconds has been added to the new kucoin.helpers file.
get_historical_klines_tv has been added to the kucoin.client, so now all you need to do is run
With these cached klines we can open them at a later date and run backtesting on them.