CCXT币安fetch_ohlcv函数

问题描述

我想使用 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",http_status_code,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,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,params,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,body)
    480         self.lastRestRequestTimestamp = self.milliseconds()
    481         request = self.sign(path,body)
--> 482         return self.fetch(request['url'],request['method'],request['headers'],request['body'])
    483 
    484     def request(self,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,body)
    607         except HTTPError as e:
    608             details = ' '.join([self.id,url])
--> 609             self.handle_errors(http_status_code,http_status_text,http_response,json_response,request_headers,request_body)
    610             self.handle_http_status_code(http_status_code,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,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,message):
    499         if string in exact:
--> 500             raise exact[string](message)
    501 
    502     def throw_broadly_matched_exception(self,broad,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,limit=limit)

解决方法

你的错误是 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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...