简体   繁体   中英

python-binance : How I can use time parameter to the function?

在此处输入图像描述

I tried to use this function but I got error. I think need to change date format of time parameters.

now = datetime.now()
past = now - timedelta(days=2)
past = str(past)

bars = client.get_historical_klines("BTCUSDT", "1m", start_str = past, end_str = None, limit = 1000)

But I got error.. When I delete the start_str and end_str, it works.

How I can handle the date str for this function. Could you help me?!(example is the best!)

---------ERROR------------

TypeError                                 Traceback (most recent call last)
Input In [46], in <cell line: 1>()
----> 1 bars = client.get_historical_klines(symbol="BTCUSDT", interval="1m",
      2                                             start_str=past, end_str=None, limit=1000)

File ~/opt/anaconda3/lib/python3.9/site-packages/binance/client.py:934, in Client.get_historical_klines(self, symbol, interval, start_str, end_str, limit, klines_type)
    914 def get_historical_klines(self, symbol, interval, start_str=None, end_str=None, limit=1000,
    915                           klines_type: HistoricalKlinesType = HistoricalKlinesType.SPOT):
    916     """Get Historical Klines from Binance
    917 
    918     :param symbol: Name of symbol pair e.g BNBBTC
   (...)
    932 
    933     """
--> 934     return self._historical_klines(
    935         symbol, interval, start_str=start_str, end_str=end_str, limit=limit, klines_type=klines_type
    936     )

File ~/opt/anaconda3/lib/python3.9/site-packages/binance/client.py:969, in Client._historical_klines(self, symbol, interval, start_str, end_str, limit, klines_type)
    966 timeframe = interval_to_milliseconds(interval)
    968 # if a start time was passed convert it
--> 969 start_ts = convert_ts_str(start_str)
    971 # establish first available start timestamp
    972 if start_ts is not None:

File ~/opt/anaconda3/lib/python3.9/site-packages/binance/helpers.py:76, in convert_ts_str(ts_str)
     74 if type(ts_str) == int:
     75     return ts_str
---> 76 return date_to_milliseconds(ts_str)

File ~/opt/anaconda3/lib/python3.9/site-packages/binance/helpers.py:24, in date_to_milliseconds(date_str)
     22 epoch: datetime = datetime.utcfromtimestamp(0).replace(tzinfo=pytz.utc)
     23 # parse our date string
---> 24 d: Optional[datetime] = dateparser.parse(date_str, settings={'TIMEZONE': "UTC"})
     25 if not d:
     26     raise UnknownDateFormat(date_str)

File ~/opt/anaconda3/lib/python3.9/site-packages/dateparser/conf.py:92, in apply_settings.<locals>.wrapper(*args, **kwargs)
     89 if not isinstance(kwargs['settings'], Settings):
     90     raise TypeError("settings can only be either dict or instance of Settings class")
---> 92 return f(*args, **kwargs)

File ~/opt/anaconda3/lib/python3.9/site-packages/dateparser/__init__.py:61, in parse(date_string, date_formats, languages, locales, region, settings, detect_languages_function)
     57 if languages or locales or region or detect_languages_function or not settings._default:
     58     parser = DateDataParser(languages=languages, locales=locales,
     59                             region=region, settings=settings, detect_languages_function=detect_languages_function)
---> 61 data = parser.get_date_data(date_string, date_formats)
     63 if data:
     64     return data['date_obj']

File ~/opt/anaconda3/lib/python3.9/site-packages/dateparser/date.py:419, in DateDataParser.get_date_data(self, date_string, date_formats)
    376 """
    377 Parse string representing date and/or time in recognizable localized formats.
    378 Supports parsing multiple languages and timezones.
   (...)
    416 
    417 """
    418 if not isinstance(date_string, str):
--> 419     raise TypeError('Input type must be str')
    421 res = parse_with_formats(date_string, date_formats or [], self._settings)
    422 if res['date_obj']:

TypeError: Input type must be str

binance.client.Client.get_historical_klines() takes int or str as input value for start_str , see the documentation of this method:

def get_historical_klines(self, symbol, interval, start_str, end_str=None, limit=500,
              klines_type: HistoricalKlinesType = HistoricalKlinesType.SPOT):
    """Get Historical Klines from Binance

    :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
    :param limit: Default 500; max 1000.
    :type limit: int
    :param klines_type: Historical klines type: SPOT or FUTURES
    :type klines_type: HistoricalKlinesType

    :return: list of OHLCV values

    """
    return self._historical_klines(symbol, interval, start_str, end_str=end_str, limit=limit, klines_type=klines_type)

You're trying to pass an datetime.datetime object.

You can convert this object to a timestamp (ms) with:

import datetime as dt

now = dt.datetime.now(dt.timezone.utc)
past = now - dt.timedelta(days=2)

# Gives you a timestamp in ms
past_timestamp_ms = int(round(past.timestamp() * 1000, 0))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM