Using python to fetch crypto market data from the binance API


I have never actively traded crypto, but with the new all-time-highs of Bitcoin and Ehtereum, I am wondering if I should.

To get historical market data I am using this simple script. You need a Binance-account to create the necessary API key and secret. In this example I am reading those from the environment variables BINANCE_API_KEY and BINANCE_API_SECRET. You could also just paste them into the script, if you don’t care.

Once fetched, the market data is written to a CSV-file in the current directory using the Pandas library. The binance API client I am using here is unicorn_binance_rest_api:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import logging
from os import environ

import pandas
from unicorn_binance_rest_api import BinanceRestApiManager

from config.binance import get_readonly_credentials


def main():
    crypto_pair = "BTCUSDT"
    interval = BinanceRestApiManager.KLINE_INTERVAL_5MINUTE
    start = "2021-01-01 00:00 UTC"
    binance_api_key = enivron["BINANCE_API_KEY"]
    binance_api_secret = enivron["BINANCE_API_SECRET"]
    client = BinanceRestApiManager(
        api_key=binance_api_key, api_secret=binance_api_secret
    )

    market_data = client.get_historical_klines(
        symbol=crypto_pair, interval=interval, start_str=start, limit=500
    )

    dataframe = pandas.DataFrame(market_data)
    dataframe.columns = [
        "open_time",
        "open",
        "high",
        "low",
        "close",
        "volume",
        "close_time",
        "quote_asset_volume",
        "trades",
        "taker_buy_base_asset_volume",
        "taker_buy_quote_asset_volume",
        "ignore",
    ]

    dataframe.to_csv(f"{crypto_pair}_{interval}_{start}.csv", index=False)


if __name__ == "__main__":
    main()

See also