sammchardy / python-binance

Binance Exchange API python implementation for automated trading
https://python-binance.readthedocs.io/en/latest/
MIT License
6.09k stars 2.21k forks source link

Receive Wrong Data Using "get_historical_klines" #1095

Open hz7451 opened 2 years ago

hz7451 commented 2 years ago

Describe the bug Here's part of my code which create csv file after received data from Binance API, I checked OHLC in speicific period and found out the data received was wrong. Compare to TradingView or Binance

To Reproduce Code snippet to reproduce the behavior:

start_date = datetime.datetime.strptime('1 Nov 2021', '%d %b %Y')
today = datetime.datetime.today()

def binanceBarExtractor(symbol):
    print('working...')
    filename = '{}/BinanceData/{}_MinuteBars.csv'.format(os.getcwd(),symbol)

    klines = bclient.get_historical_klines(symbol, Client.KLINE_INTERVAL_1MINUTE, start_date.strftime('%d %b %Y %H:%M:%S'), today.strftime('%d %b %Y %H:%M:%S'), 1000)
    data = pd.DataFrame(klines, columns = ['timestamp', 'Open', 'High', 'Low', 'Close', 'Volume', 'close_time', 'quote_av', 'trades', 'tb_base_av', 'tb_quote_av', 'ignore' ])
    data['timestamp'] = pd.to_datetime(data['timestamp'], unit='ms')

    data.set_index('timestamp', inplace=True)
    data.to_csv(filename)
    print('finished!')

if __name__ == '__main__':
    binanceBarExtractor('SOLUSDT')

Expected behavior Price should be same as OHLC from TradingView or Binance

Environment (please complete the following information):

hz7451 commented 2 years ago

[Update]Oh, just a minor mistake. It was time zone problem I guess? Is there a way to get the data with custom time zone?

halfelf commented 2 years ago

:param start_str: Start date string in UTC format or timestamp in milliseconds

Binance API has nothing to do with timezone. This SDK only try to convert the start_str argument into a timestamp with UTC as the default timezone, if it is an instance of datetime.

I suggest using timestamp everywhere when needed. Just replace the datetime object with int(your_datetime.timestamp() * 1000), which is a milisec timestamp.