Python get klines
12 Python code examples are found related to "
get klines".
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
Example 1
Source File: client.py From vnpy_crypto with MIT License | 9 votes |
def get_klines(self, **params): """Kline/candlestick bars for a symbol. Klines are uniquely identified by their open time. https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#klinecandlestick-data :param symbol: required :type symbol: str :param interval: - :type interval: enum :param limit: - Default 500; max 500. :type limit: int :param startTime: :type startTime: int :param endTime: :type endTime: int :returns: API response .. code-block:: python [ [ 1499040000000, # Open time "0.01634790", # Open "0.80000000", # High "0.01575800", # Low "0.01577100", # Close "148976.11427815", # Volume 1499644799999, # Close time "2434.19055334", # Quote asset volume 308, # Number of trades "1756.87402397", # Taker buy base asset volume "28.46694368", # Taker buy quote asset volume "17928899.62484339" # Can be ignored ] ] :raises: BinanceResponseException, BinanceAPIException """ return self._get('klines', data=params)
Example 2
Source File: binance.py From archon with MIT License | 5 votes |
def get_historical_klines(self, symbol, interval, start_str, end_str=None): """Get Historical Klines from Binance""" # init our list output_data = [] # setup the max limit limit = 500 # convert interval to useful value in seconds timeframe = interval_to_milliseconds(interval) # convert our date strings to milliseconds if type(start_str) == int: start_ts = start_str else: start_ts = date_to_milliseconds(start_str) # establish first available start timestamp first_valid_ts = self._get_earliest_valid_timestamp(symbol, interval) start_ts = max(start_ts, first_valid_ts) # if an end time was passed convert it end_ts = None if end_str: if type(end_str) == int: end_ts = end_str else: end_ts = date_to_milliseconds(end_str) idx = 0 while True: # fetch the klines from start_ts up to max 500 entries or the end_ts if set temp_data = self.get_klines( symbol=symbol, interval=interval, limit=limit, startTime=start_ts, endTime=end_ts ) # handle the case where exactly the limit amount of data was returned last loop if not len(temp_data): break # append this loops data to our output data output_data += temp_data # set our start timestamp using the last value in the array start_ts = temp_data[-1][0] idx += 1 # check if we received less than the required limit and exit the loop if len(temp_data) < limit: # exit the while loop break # increment next call by our timeframe start_ts += timeframe # sleep after every 3rd call to be kind to the API if idx % 3 == 0: time.sleep(1) return output_data
Example 3
Source File: turtle_trade.py From Binance-bot with GNU General Public License v3.0 | 5 votes |
def get_klines(self, pair, interval, limit): klines = [] got_klines = False while not got_klines: try: klines = client.klines(pair, interval=interval, limit=limit) except (MalformedRequest, InternalError, StatusUnknown, ConnectionError, RemoteDisconnected, ProtocolError, HTTPException) as e: print(str(e) + ' ' + str(e.__traceback__)) client.set_offset() else: got_klines = True return klines
Example 4
Source File: client.py From python-binance with MIT License | 4 votes |
def get_klines(self, **params): """Kline/candlestick bars for a symbol. Klines are uniquely identified by their open time. https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md#klinecandlestick-data :param symbol: required :type symbol: str :param interval: - :type interval: str :param limit: - Default 500; max 500. :type limit: int :param startTime: :type startTime: int :param endTime: :type endTime: int :returns: API response .. code-block:: python [ [ 1499040000000, # Open time "0.01634790", # Open "0.80000000", # High "0.01575800", # Low "0.01577100", # Close "148976.11427815", # Volume 1499644799999, # Close time "2434.19055334", # Quote asset volume 308, # Number of trades "1756.87402397", # Taker buy base asset volume "28.46694368", # Taker buy quote asset volume "17928899.62484339" # Can be ignored ] ] :raises: BinanceRequestException, BinanceAPIException """ return self._get('klines', data=params)
Example 5
Source File: save_historical_data.py From python-binance with MIT License | 4 votes |
def get_historical_klines(symbol, interval, start_str, end_str=None): """Get Historical Klines from Binance See dateparse docs for valid start and end string formats http://dateparser.readthedocs.io/en/latest/ If using offset strings for dates add "UTC" to date string e.g. "now UTC", "11 hours ago UTC" :param symbol: Name of symbol pair e.g BNBBTC :type symbol: str :param interval: Biannce Kline interval :type interval: str :param start_str: Start date string in UTC format :type start_str: str :param end_str: optional - end date string in UTC format :type end_str: str :return: list of OHLCV values """ # create the Binance client, no need for api key client = Client("", "") # init our list output_data = [] # setup the max limit limit = 500 # convert interval to useful value in seconds timeframe = interval_to_milliseconds(interval) # convert our date strings to milliseconds start_ts = date_to_milliseconds(start_str) # if an end time was passed convert it end_ts = None if end_str: end_ts = date_to_milliseconds(end_str) idx = 0 # it can be difficult to know when a symbol was listed on Binance so allow start time to be before list date symbol_existed = False while True: # fetch the klines from start_ts up to max 500 entries or the end_ts if set temp_data = client.get_klines( symbol=symbol, interval=interval, limit=limit, startTime=start_ts, endTime=end_ts ) # handle the case where our start date is before the symbol pair listed on Binance if not symbol_existed and len(temp_data): symbol_existed = True if symbol_existed: # append this loops data to our output data output_data += temp_data # update our start timestamp using the last value in the array and add the interval timeframe start_ts = temp_data[len(temp_data) - 1][0] + timeframe else: # it wasn't listed yet, increment our start date start_ts += timeframe idx += 1 # check if we received less than the required limit and exit the loop if len(temp_data) < limit: # exit the while loop break # sleep after every 3rd call to be kind to the API if idx % 3 == 0: time.sleep(1) return output_data
Example 6
Source File: client.py From python-binance with MIT License | 4 votes |
def get_historical_klines_generator(self, symbol, interval, start_str, end_str=None): """Get Historical Klines from Binance See dateparser docs for valid start and end string formats http://dateparser.readthedocs.io/en/latest/ If using offset strings for dates add "UTC" to date string e.g. "now UTC", "11 hours ago UTC" :param symbol: Name of symbol pair e.g BNBBTC :type symbol: str :param interval: Binance Kline interval :type interval: str :param start_str: Start date string in UTC format or timestamp in milliseconds :type start_str: str|int :param end_str: optional - end date string in UTC format or timestamp in milliseconds (default will fetch everything up to now) :type end_str: str|int :return: generator of OHLCV values """ # setup the max limit limit = 500 # convert interval to useful value in seconds timeframe = interval_to_milliseconds(interval) # convert our date strings to milliseconds if type(start_str) == int: start_ts = start_str else: start_ts = date_to_milliseconds(start_str) # establish first available start timestamp first_valid_ts = self._get_earliest_valid_timestamp(symbol, interval) start_ts = max(start_ts, first_valid_ts) # if an end time was passed convert it end_ts = None if end_str: if type(end_str) == int: end_ts = end_str else: end_ts = date_to_milliseconds(end_str) idx = 0 while True: # fetch the klines from start_ts up to max 500 entries or the end_ts if set output_data = self.get_klines( symbol=symbol, interval=interval, limit=limit, startTime=start_ts, endTime=end_ts ) # handle the case where exactly the limit amount of data was returned last loop if not len(output_data): break # yield data for o in output_data: yield o # set our start timestamp using the last value in the array start_ts = output_data[-1][0] idx += 1 # check if we received less than the required limit and exit the loop if len(output_data) < limit: # exit the while loop break # increment next call by our timeframe start_ts += timeframe # sleep after every 3rd call to be kind to the API if idx % 3 == 0: time.sleep(1)
Example 7
Source File: binance_utils.py From binance-downloader with MIT License | 4 votes |
def get_klines( symbol, interval: str, start_time=None, end_time=None, limit=None ) -> List: """Helper function to get klines from Binance for a single request :param symbol: (str) Symbol pair of interest (e.g. 'XRPBTC') :param interval: (str) Valid kline interval (e.g. '1m'). :param start_time: (int, str, pandas.Timestamp) First kline open time desired. If int, should be in milliseconds since Epoch. If string or pandas.Timestamp, will assume UTC unless otherwise specified. :param end_time: (int, str, pandas.Timestamp) Last kline open time desired. If int, should be in milliseconds since Epoch. If string or pandas.Timestamp, will assume UTC unless otherwise specified. :param limit: (int) Maximum number of klines to fetch. Will be clamped to 1000 if higher due to current maximum Binance limit. A value <= 0 will be assumed as no limit, and 1000 will be used. :return: List[List]] Returns a list of klines in list format if successful (may be empty list) """ if not isinstance(symbol, str): raise ValueError(f"Cannot get kline for symbol {symbol}") if not isinstance(start_time, int) and start_time is not None: start_time = date_to_milliseconds(start_time) if not isinstance(end_time, int) and end_time is not None: end_time = date_to_milliseconds(end_time) if limit is None: limit = 1000 elif limit > 1000: log.warn("Clamping kline request limit to 1000") limit = 1000 elif limit <= 0: log.warn("Cannot have negative limit. Using 1000") limit = 1000 # Set parameters and make the request params = {"symbol": symbol, "interval": interval, "limit": limit} if end_time is not None: params["endTime"] = end_time if start_time is not None: params["startTime"] = start_time response = requests.get(KLINE_URL, params=params) # Check for valid response _validate_api_response(response) return response.json()
Example 8
Source File: kucoin.py From archon with MIT License | 4 votes |
def get_historical_klines_tv(self, symbol, interval, start_str, end_str=None): """Get Historical Klines in OHLCV format (Trading View)""" # init our array for klines klines = [] # convert our date strings to seconds if type(start_str) == int: start_ts = start_str else: start_ts = date_to_seconds(start_str) # if an end time was not passed we need to use now if end_str is None: end_str = 'now UTC' if type(end_str) == 'int': end_ts = end_str else: end_ts = date_to_seconds(end_str) kline_res = self.get_kline_data_tv(symbol, interval, start_ts, end_ts) # check if we got a result if 't' in kline_res and len(kline_res['t']): # now convert this array to OHLCV format and add to the array for i in range(1, len(kline_res['t'])): klines.append(( kline_res['t'][i], kline_res['o'][i], kline_res['h'][i], kline_res['l'][i], kline_res['c'][i], kline_res['v'][i] )) # finally return our converted klines return klines
Example 9
Source File: binance.py From archon with MIT License | 4 votes |
def get_historical_klines_generator(self, symbol, interval, start_str, end_str=None): """Get Historical Klines""" # setup the max limit limit = 500 # convert interval to useful value in seconds timeframe = interval_to_milliseconds(interval) # convert our date strings to milliseconds if type(start_str) == int: start_ts = start_str else: start_ts = date_to_milliseconds(start_str) # establish first available start timestamp first_valid_ts = self._get_earliest_valid_timestamp(symbol, interval) start_ts = max(start_ts, first_valid_ts) # if an end time was passed convert it end_ts = None if end_str: if type(end_str) == int: end_ts = end_str else: end_ts = date_to_milliseconds(end_str) idx = 0 while True: # fetch the klines from start_ts up to max 500 entries or the end_ts if set output_data = self.get_klines( symbol=symbol, interval=interval, limit=limit, startTime=start_ts, endTime=end_ts ) # handle the case where exactly the limit amount of data was returned last loop if not len(output_data): break # yield data for o in output_data: yield o # set our start timestamp using the last value in the array start_ts = output_data[-1][0] idx += 1 # check if we received less than the required limit and exit the loop if len(output_data) < limit: # exit the while loop break # increment next call by our timeframe start_ts += timeframe # sleep after every 3rd call to be kind to the API if idx % 3 == 0: time.sleep(1)
Example 10
Source File: trade_simulator.py From czsc with MIT License | 4 votes |
def get_klines(ts_code, end_date, freqs='1min,5min,30min,D', asset='E'): """获取不同级别K线""" klines = dict() freqs = freqs.split(",") for freq in freqs: df = get_kline(ts_code, end_date, freq=freq, asset=asset) klines[freq_map[freq]] = df return klines
Example 11
Source File: http.py From python-binance-chain with MIT License | 4 votes |
def get_klines(self, symbol: str, interval: KlineInterval, limit: Optional[int] = 300, start_time: Optional[int] = None, end_time: Optional[int] = None): """Gets candlestick/kline bars for a symbol. Bars are uniquely identified by their open time https://binance-chain.github.io/api-reference/dex-api/paths.html#apiv1klines :param symbol: required e.g NNB-0AD_BNB :param interval: required e.g 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 6h, 8h, 12h, 1d, 3d, 1w, 1M :param limit: :param start_time: :param end_time: .. code:: python klines = client.get_klines('NNB-0AD_BNB', KlineInterval.ONE_DAY) :return: API Response """ data = { 'symbol': symbol, 'interval': interval.value } if limit is not None: data['limit'] = limit if start_time is not None: data['startTime'] = start_time if end_time is not None: data['endTime'] = end_time return self._get("klines", data=data)
Example 12
Source File: save_historical_data_Roibal.py From Cryptocurrency-Trading-Bots-Python-Beginner-Advance with MIT License | 4 votes |
def get_historical_klines(symbol, interval, start_str, end_str=None): """Get Historical Klines from Binance See dateparse docs for valid start and end string formats http://dateparser.readthedocs.io/en/latest/ If using offset strings for dates add "UTC" to date string e.g. "now UTC", "11 hours ago UTC" :param symbol: Name of symbol pair e.g BNBBTC :type symbol: str :param interval: Biannce Kline interval :type interval: str :param start_str: Start date string in UTC format :type start_str: str :param end_str: optional - end date string in UTC format :type end_str: str :return: list of OHLCV values """ # create the Binance client, no need for api key client = Client("", "") # init our list output_data = [] # setup the max limit limit = 500 # convert interval to useful value in seconds timeframe = interval_to_milliseconds(interval) # convert our date strings to milliseconds start_ts = date_to_milliseconds(start_str) # if an end time was passed convert it end_ts = None if end_str: end_ts = date_to_milliseconds(end_str) idx = 0 # it can be difficult to know when a symbol was listed on Binance so allow start time to be before list date symbol_existed = False while True: # fetch the klines from start_ts up to max 500 entries or the end_ts if set temp_data = client.get_klines( symbol=symbol, interval=interval, limit=limit, startTime=start_ts, endTime=end_ts ) # handle the case where our start date is before the symbol pair listed on Binance if not symbol_existed and len(temp_data): symbol_existed = True if symbol_existed: # append this loops data to our output data output_data += temp_data # update our start timestamp using the last value in the array and add the interval timeframe start_ts = temp_data[len(temp_data) - 1][0] + timeframe else: # it wasn't listed yet, increment our start date start_ts += timeframe idx += 1 # check if we received less than the required limit and exit the loop if len(temp_data) < limit: # exit the while loop break # sleep after every 3rd call to be kind to the API if idx % 3 == 0: time.sleep(1) return output_data