1- import time
21import dateparser
32import pytz
43
@@ -53,83 +52,3 @@ def interval_to_milliseconds(interval):
5352 except ValueError :
5453 pass
5554 return ms
56-
57-
58- def get_historical_klines (symbol , interval , start_str , end_str = None ):
59- """Get Historical Klines from Binance
60-
61- See dateparse docs for valid start and end string formats http://dateparser.readthedocs.io/en/latest/
62-
63- If using offset strings for dates add "UTC" to date string e.g. "now UTC", "11 hours ago UTC"
64-
65- :param symbol: Name of symbol pair e.g BNBBTC
66- :type symbol: str
67- :param interval: Biannce Kline interval
68- :type interval: str
69- :param start_str: Start date string in UTC format
70- :type start_str: str
71- :param end_str: optional - end date string in UTC format
72- :type end_str: str
73-
74- :return: list of OHLCV values
75-
76- """
77- # create the Binance client, no need for api key
78- client = Client ("" , "" )
79-
80- # init our list
81- output_data = []
82-
83- # setup the max limit
84- limit = 500
85-
86- # convert interval to useful value in seconds
87- timeframe = interval_to_milliseconds (interval )
88-
89- # convert our date strings to milliseconds
90- start_ts = date_to_milliseconds (start_str )
91-
92- # if an end time was passed convert it
93- end_ts = None
94- if end_str :
95- end_ts = date_to_milliseconds (end_str )
96-
97- idx = 0
98- # it can be difficult to know when a symbol was listed on Binance so allow start time to be before list date
99- symbol_existed = False
100- while True :
101- # fetch the klines from start_ts up to max 500 entries or the end_ts if set
102- temp_data = client .get_klines (
103- symbol = symbol ,
104- interval = interval ,
105- limit = limit ,
106- startTime = start_ts ,
107- endTime = end_ts
108- )
109-
110- # handle the case where our start date is before the symbol pair listed on Binance
111- if not symbol_existed and len (temp_data ):
112- symbol_existed = True
113-
114- if symbol_existed :
115- # append this loops data to our output data
116- output_data += temp_data
117-
118- # update our start timestamp using the last value in the array and add the interval timeframe
119- start_ts = temp_data [len (temp_data ) - 1 ][0 ] + timeframe
120- else :
121- print ("doesn't exist yet" )
122- # it wasn't listed yet, increment our start date
123- start_ts += timeframe
124-
125- idx += 1
126- # check if we received less than the required limit and exit the loop
127- if len (temp_data ) < limit :
128- # exit the while loop
129- break
130-
131- # sleep after every 3rd call to be kind to the API
132- if idx % 3 == 0 :
133- time .sleep (1 )
134-
135- return output_data
0 commit comments