I'm trying to figure out how to create a 1 minute candlestick for trading pair BTC-USD using the binance package in Python.
So far I can get this down:
from binance.client import Client
candles = client.get_klines(symbol='BTCUSDT', interval=Client.KLINE_INTERVAL_1MINUTE)
for candlestick in candles:
print(candlestick)
But I'm not quite sure if this is correct.
Assuming that you have used Client
(capital-case) or at least the asynchronous equivalent AsyncClient
to create client
, then the following will print the most recent 1-minute candlestick. For example,
from binance import Client
client = Client(api_key = 'Enter Your Key', api_secret = 'Enter Your Secret Key')
candles = client.get_klines(symbol='BTCUSDT', interval=Client.KLINE_INTERVAL_1MINUTE)
print(candles[-1])
print(f"\nLength of candles: {len(candles)}")
Output
[1650011040000, # timestamp (opening time)
'40203.99000000', # opening price
'40237.03000000', # high price
'40198.01000000', # low price
'40198.01000000', # closing price
'20.07769000', # volume
1650011099999, # timestamp (closing time)
'807538.88381350', # quote asset volume
488, # number of trades
'6.25446000', # taker buy base asset volume
'251560.61470140', # taker buy quote asset volume
'0'] # ignore
Length of candles: 500
By default, candles
will be a list of the last 500 1-minute candles (each candle itself represented by a list) for the BTCUSDT
trading pair and you can specify a maximum of 1000 last 1-minute candles using the get_klines
method. The most recent candles are at the end of the list candles
and the oldest are at the beginning.
So your code (assuming you have used Client
or AsyncClient
to create client
) should be printing all 500 of the last 1-minute candles starting from the oldest to the most recent.
The details of each element in a list corresponding to a candle can be found here. In particular, in the output above (showing the most recent 1-minute candlestick), the first element is the timestamp, the second element is the opening price, the third the high price, the fourth the low price, the fifth the closing price, and the other elements are not strictly components of a trading candle but are useful information nonetheless (e.g. volume).
By the way, if you do not want to be restricted to only the most recent 500 1-minute candles, you can make use of the get_historical_klines
method which allows you to specify a start date/time and end date/time (still limited to 1000 candles per call).