How to Retrieve 1,000 Candles from Binance with Python
Python Trading Bot
Binance is the world’s largest and most active cryptocurrency exchange. It’s a great place to build a crypto trading bot, with a robust API and client libraries for several different programming languages.
I’ve used it extensively and even written a series about how to build a trading bot on it. It’s in the process of being integrated into my open-source Python Trading Bot.
If you’re looking to do some candlestick analysis (Binance calls them klines), this tutorial will really help you out!
Assumptions
I’ll assume that you’ve already:
- Connected to Binance
- Installed Python and the Binance spot library —
from binance.spot import Spot
Code
How To
There are a couple of things to note about candles from Binance. I’ll list them here to help the code make sense.
- All data from the API is in string format (json)
- If you want to use Pandas Dataframes, you need to convert the datatypes to their corresponding type (float, int)
- I’ve normalized the data in my function to match my tutorials on MetaTrader and Coinbase
- Binance calls candlesticks klines (which is short for K Line data). This is the technical name for a candlestick
- The maximum number of candlesticks you can retrieve from Binance in one API call is 1,000
Function
Here’s the function:
# Function to query Binance for candlestick data
def get_candlestick_data(symbol, timeframe, qty):
# Retrieve the raw data
raw_data = Spot().klines(symbol=symbol, interval=timeframe, limit=qty)
# Set up the return array
converted_data = []
# Convert each element into a Python dictionary object, then add to converted_data
for candle in raw_data:
# Dictionary object
converted_candle = {
'time': candle[0],
'open': float(candle[1]),
'high': float(candle[2]),
'low': float(candle[3]),
'close': float(candle[4]),
'volume': float(candle[5]),
'close_time': candle[6],
'quote_asset_volume': float(candle[7]),
'number_of_trades': int(candle[8]),
'taker_buy_base_asset_volume': float(candle[9]),
'taker_buy_quote_asset_volume': float(candle[10])
}
# Add to converted_data
converted_data.append(converted_candle)
# Return converted data
return converted_data
Say Hi!
I love hearing from my readers, so feel free to reach out. It means a ton to me when you clap for my articles or drop a friendly comment — it helps me know that my content is helping.
❤