0

我想使用 fetch_ohlcv() 从带有 CCXT 的 binance api 获取加密市场数据,但在运行下面的代码时收到错误。

我试过不带since关键字运行,效果很好。请问我的startTime参数有什么问题吗?还是CCXT有问题?谢谢!

以下是错误消息:

---------------------------------------------------------------------------
HTTPError                                 Traceback (most recent call last)
~/Desktop/crypto/trading/env/lib/python3.8/site-packages/ccxt/base/exchange.py in fetch(self, url, method, headers, body)
    592             self.logger.debug("%s %s, Response: %s %s %s", method, url, http_status_code, headers, http_response)
--> 593             response.raise_for_status()
    594 

~/Desktop/crypto/trading/env/lib/python3.8/site-packages/requests/models.py in raise_for_status(self)
    942         if http_error_msg:
--> 943             raise HTTPError(http_error_msg, response=self)
    944 

HTTPError: 400 Client Error: Bad Request for url: https://api.binance.com/api/v3/klines?symbol=ETHBTC&interval=1d&limit=50&startTime=1589817600.0&endTime=5909817599.0

During handling of the above exception, another exception occurred:

BadRequest                                Traceback (most recent call last)
<ipython-input-113-43d055cced8d> in <module>
----> 1 exchange.fetch_ohlcv(symbol, timeframe, since=startDate, limit=limit)

~/Desktop/crypto/trading/env/lib/python3.8/site-packages/ccxt/binance.py in fetch_ohlcv(self, symbol, timeframe, since, limit, params)
   1516         else:
   1517             method = 'publicGetTickerBookTicker'
-> 1518         response = getattr(self, method)(query)
   1519         return self.parse_tickers(response, symbols)
   1520 

~/Desktop/crypto/trading/env/lib/python3.8/site-packages/ccxt/base/exchange.py in inner(_self, params)
    459                             if params is not None:
    460                                 inner_kwargs['params'] = params
--> 461                             return entry(_self, **inner_kwargs)
    462                         return inner
    463                     to_bind = partialer()

~/Desktop/crypto/trading/env/lib/python3.8/site-packages/ccxt/binance.py in request(self, path, api, method, params, headers, body)
   3572         elif (type == 'delivery') or (type == 'inverse'):
   3573             method = 'dapiPrivateGetPositionRisk'
-> 3574         else:
   3575             raise NotSupported(self.id + ' fetchIsolatedPositions() supports linear and inverse contracts only')
   3576         response = getattr(self, method)(self.extend(request, params))

~/Desktop/crypto/trading/env/lib/python3.8/site-packages/ccxt/base/exchange.py in fetch2(self, path, api, method, params, headers, body)
    480         self.lastRestRequestTimestamp = self.milliseconds()
    481         request = self.sign(path, api, method, params, headers, body)
--> 482         return self.fetch(request['url'], request['method'], request['headers'], request['body'])
    483 
    484     def request(self, path, api='public', method='GET', params={}, headers=None, body=None):

~/Desktop/crypto/trading/env/lib/python3.8/site-packages/ccxt/base/exchange.py in fetch(self, url, method, headers, body)
    607         except HTTPError as e:
    608             details = ' '.join([self.id, method, url])
--> 609             self.handle_errors(http_status_code, http_status_text, url, method, headers, http_response, json_response, request_headers, request_body)
    610             self.handle_http_status_code(http_status_code, http_status_text, url, method, http_response)
    611             raise ExchangeError(details) from e

~/Desktop/crypto/trading/env/lib/python3.8/site-packages/ccxt/binance.py in handle_errors(self, code, reason, url, method, headers, body, response, requestHeaders, requestBody)
   3566                 raise NotSupported(self.id + ' fetchIsolatedPositions() supports linear and inverse contracts only')
   3567         defaultType = self.safe_string_2(self.options, 'fetchIsolatedPositions', 'defaultType', defaultType)
-> 3568         type = self.safe_string(params, 'type', defaultType)
   3569         params = self.omit(params, 'type')
   3570         if (type == 'future') or (type == 'linear'):

~/Desktop/crypto/trading/env/lib/python3.8/site-packages/ccxt/base/exchange.py in throw_exactly_matched_exception(self, exact, string, message)
    498     def throw_exactly_matched_exception(self, exact, string, message):
    499         if string in exact:
--> 500             raise exact[string](message)
    501 
    502     def throw_broadly_matched_exception(self, broad, string, message):

BadRequest: binance {"code":-1100,"msg":"Illegal characters found in parameter 'startTime'; legal range is '^[0-9]{1,20}$'."}

代码:

symbol = 'ETH/BTC'
timeframe = '1d'
limit = 50 #Default best for binance
startDate = "2020-05-19"
startDate = datetime.strptime(startDate, "%Y-%m-%d")
startDate = datetime.timestamp(startDate)

config = {
    'rateLimit': 10000,
    'apiKey': apiKey,
    'secret': secretKey
}
exchange = ccxt.binance(config)

exchange.fetch_ohlcv(symbol, timeframe, since=startDate, limit=limit)
4

1 回答 1

3

你的错误是 startDate 格式:

startDate = datetime.timestamp(startDate)
print(startDate) #output: 1589846400.0

首先,您必须将其转换为整数,然后乘以 1000 以转换为毫秒:

from datetime import datetime
startDate = "2020-05-19"
startDate = datetime.strptime(startDate, "%Y-%m-%d")
startDate = datetime.timestamp(startDate)
startDate = int(startDate) * 1000
print(startDate)  #output: 1589846400000
于 2021-06-19T12:44:49.730 回答