2 min read

How to Retrieve 1,000 Candles from Binance with Python

Learn how to retrieve 1000 candles from the Binance API, using Python3.
Clockwork Robot holding a red ‘trending up’ candle
Python Trading Bot

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:

  1. Connected to Binance
  2. 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.

  1. All data from the API is in string format (json)
  2. If you want to use Pandas Dataframes, you need to convert the datatypes to their corresponding type (float, int)
  3. I’ve normalized the data in my function to match my tutorials on MetaTrader and Coinbase
  4. Binance calls candlesticks klines (which is short for K Line data). This is the technical name for a candlestick
  5. 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.