def __init__(self, strategy=None): """ 构造函数 :param strategy: 上层策略,主要用与使用writeLog() """ self.strategy = strategy self.client = Client('', '')
def __init__(self, strategy): """ 构造函数 :param strategy: 上层策略,主要用与使用strategy.writeCtaLog() """ self.strategy = strategy self.client = Client('-', '-')
def connect_Subpot(self, apiKey , secretKey ): self.apiKey = apiKey self.secretKey = secretKey self.client = Client( apiKey , secretKey) self.bm = BinanceSocketManager(self.client) self.bm.start_user_socket( self.onMessage) self.bm.start() self.active = True self.reqThread.start()
def init_client(self): fileName = globalSetting.get('gateway_name', '') + '_connect.json' filePath = getJsonPath(fileName, __file__) try: with open(filePath, 'r') as f: # 解析json文件 setting = json.load(f) apiKey = setting.get('accessKey', None) secretKey = setting.get('secretKey', None) if apiKey is not None and secretKey is not None: self.client = Client(apiKey, secretKey) except IOError: self.strategy.writeCtaError( u'BINANCE读取连接配置{}出错,请检查'.format(filePath)) return
def init_client(self): fileName = globalSetting.get('gateway_name', '') + '_connect.json' filePath = getJsonPath(fileName, __file__) try: with open(filePath, 'r') as f: # 解析json文件 setting = json.load(f) apiKey = setting.get('accessKey',None) secretKey = setting.get('secretKey',None) if apiKey is not None and secretKey is not None: self.client = Client(apiKey, secretKey) except IOError: self.strategy.writeCtaError(u'BINANCE读取连接配置{}出错,请检查'.format(filePath)) return
class BinanceData(object): # ---------------------------------------------------------------------- def __init__(self, strategy): """ 构造函数 :param strategy: 上层策略,主要用与使用strategy.writeCtaLog() """ self.strategy = strategy self.client = Client('-', '-') def get_bars(self, symbol, period, callback, bar_is_completed=False, bar_freq=1, start_dt=None): """ 返回k线数据 symbol:合约 period: 周期: 1min,3min,5min,15min,30min,1day,3day,1hour,2hour,4hour,6hour,12hour """ ret_bars = [] if symbol not in SYMBOL_LIST: self.strategy.writeCtaError(u'{} 合约{}不在下载清单中'.format( datetime.now(), symbol)) return False, ret_bars if period not in PERIOD_MAPPING: self.strategy.writeCtaError(u'{} 周期{}不在下载清单中'.format( datetime.now(), period)) return False, ret_bars if self.client is None: return False, ret_bars binance_symbol = symbol.upper().replace('_', '') binance_period = PERIOD_MAPPING.get(period) self.strategy.writeCtaLog('{}开始下载binance:{} {}数据.'.format( datetime.now(), binance_symbol, binance_period)) try: bars = self.client.get_klines(symbol=binance_symbol, interval=binance_period) for i, bar in enumerate(bars): add_bar = CtaBarData() try: add_bar.vtSymbol = symbol add_bar.symbol = symbol add_bar.datetime = datetime.fromtimestamp(bar[0] / 1000) add_bar.date = add_bar.datetime.strftime('%Y-%m-%d') add_bar.time = add_bar.datetime.strftime('%H:%M:%S') add_bar.tradingDay = add_bar.date add_bar.open = float(bar[1]) add_bar.high = float(bar[2]) add_bar.low = float(bar[3]) add_bar.close = float(bar[4]) add_bar.volume = float(bar[5]) except Exception as ex: self.strategy.writeCtaError( 'error when convert bar:{},ex:{},t:{}'.format( bar, str(ex), traceback.format_exc())) return False if start_dt is not None and bar.datetime < start_dt: continue ret_bars.append(add_bar) if callback is not None: callback(add_bar, bar_is_completed, bar_freq) return True, ret_bars except Exception as ex: self.strategy.writeCtaError('exception in get:{},{},{}'.format( binance_symbol, str(ex), traceback.format_exc())) return False, ret_bars
class BinanceSpotApi(object): """基于Websocket的API对象""" #---------------------------------------------------------------------- def __init__(self): """Constructor""" self.apiKey = '' # 用户名 self.secretKey = '' # 密码 self.client = None # 客户端管理器 self.bm = None # sockets 管理器 self.reqID = 0 # 请求编号 # self.reqQueue = Queue() # 请求队列 self.reqQueue = [] # 请求的队列 self.reqThread = Thread(target=self.processQueue) # 请求处理线程 self.active = False # API工作状态 self.DEBUG = False self.writeLog = None self.writeError = None #---------------------------------------------------------------------- def connect_Subpot(self, apiKey, secretKey): self.apiKey = apiKey self.secretKey = secretKey self.client = Client(apiKey, secretKey, self) self.client.DEBUG = self.DEBUG self.bm = BinanceSocketManager(self.client) self.bm.start_user_socket(self.onMessage) self.bm.start() self.active = True self.reqThread.start() #---------------------------------------------------------------------- def processQueue(self): """处理请求队列中的请求""" while self.active: if len(self.reqQueue) == 0: continue (Type, req) = self.reqQueue[0] if req is None: self.reqQueue.pop(0) continue callback = req.get('callback', None) reqID = req.get('reqID', None) try: data = self.processRequest(req) # 请求成功 if data != None: if self.DEBUG: self.writeLog(callback.__name__) callback(data, req, reqID) except Exception as ex: self.writeError(u'processQueue exception:{},{}'.format( str(ex), traceback.format_exc())) self.reqQueue.pop(0) sleep(0.1) #---------------------------------------------------------------------- def processRequest(self, req): """ 处理各类请求 :param req: :return: """ try: method = req['method'] reqID = req["reqID"] callback = req['callback'] data = None # 请求账号信息 if method == FUNCTIONCODE_GET_ACCOUNT_BINANCE: data = self.client.get_account() # 替换 一些 symbol for b_symbol_dic in data["balances"]: b_symbol_dic["asset"] = symbolFromBinanceToOtherExchanges( b_symbol_dic["asset"]) self.onGetAccount(data, req, reqID) # 请求委托单 elif method == FUNCTIONCODE_GET_OPEN_ORDERS: kwargs = req["kwargs"] symbol = kwargs["symbol"] if symbol != None: data = self.client.get_open_orders(symbol=symbol) # update symbol for dic in data: dic["symbol"] = symbolFromBinanceToOtherExchanges( dic["symbol"]) callback(data, req, reqID) else: data = self.client.get_open_orders() # update symbol for dic in data: dic["symbol"] = symbolFromBinanceToOtherExchanges( dic["symbol"]) callback(data, req, reqID) # 请求所有委托单 elif method == FUNCTIONCODE_GET_ALL_ORDERS: kwargs = req["kwargs"] symbol = kwargs["symbol"] #if '_' not in symbol and len(symbol) in [3,4]: # return None data = self.client.get_all_orders(symbol=symbol) # update symbol for dic in data: dic["symbol"] = symbolFromBinanceToOtherExchanges( dic["symbol"]) callback(data, req, reqID) # 买入现货 elif method == FUNCTIONCODE_BUY_ORDER_BINANCE: kwargs = req["kwargs"] symbol = self.legalSymbolUpper(kwargs["symbol"]) quantity = float(kwargs["quantity"]) price = float(kwargs["price"]) price = str('%.8f' % float(price)) data = self.client.order_limit_buy(symbol=symbol, price=price, quantity=quantity) # update symbol data["symbol"] = symbolFromBinanceToOtherExchanges( data["symbol"]) callback(data, req, reqID) # 卖出现货 elif method == FUNCTIONCODE_SELL_ORDER_BINANCE: kwargs = req["kwargs"] symbol = self.legalSymbolUpper(kwargs["symbol"]) quantity = float(kwargs["quantity"]) price = float(kwargs["price"]) price = str('%.8f' % float(price)) data = self.client.order_limit_sell(symbol=symbol, price=price, quantity=quantity) # update symbol data["symbol"] = symbolFromBinanceToOtherExchanges( data["symbol"]) callback(data, req, reqID) # 取消订单 elif method == FUNCTIONCODE_CANCEL_ORDER_BINANCE: kwargs = req["kwargs"] symbol = self.legalSymbolUpper(kwargs["symbol"]) orderId = int(kwargs["orderId"]) data = self.client.cancel_order(symbol=symbol, orderId=orderId) # update symbol data["symbol"] = symbolFromBinanceToOtherExchanges( data["symbol"]) callback(data, req, reqID) # 获取交易所信息 elif method == FUNCTIONCODE_GET_EXCHANGE_INFO: data = self.client.get_exchange_info() # update symbol for symbol_dic in data["symbols"]: symbol_dic["symbol"] = symbolFromBinanceToOtherExchanges( symbol_dic["symbol"]) symbol_dic[ "baseAsset"] = symbolFromBinanceToOtherExchanges( symbol_dic["baseAsset"]) callback(data, req, reqID) except Exception as ex: if req is not None or reqID is not None: self.onAllError(ex, req, reqID) self.writeError(u'processRequest exception:{},{}'.format( str(ex), traceback.format_exc())) # pass #---------------------------------------------------------------------- def legalSymbolLower(self, symbol): symbol = symbol.lower() symbol = ''.join(symbol.split('_')) return symbol #---------------------------------------------------------------------- def legalSymbolUpper(self, symbol): symbol = symbol.upper() symbol = ''.join(symbol.split('_')) return symbol #---------------------------------------------------------------------- def exit(self): """退出""" self.active = False if self.bm != None: self.bm.close() if self.reqThread.isAlive(): self.reqThread.join() #----------------------------------------------------------------------- def sendTradingRequest(self, method, callback, kwargs=None, optional=None): # 请求编号加1 self.reqID += 1 # 生成请求字典并放入队列中 req = {} req['method'] = method req['callback'] = callback req['optional'] = optional req['kwargs'] = kwargs req['reqID'] = self.reqID if method in [ FUNCTIONCODE_GET_OPEN_ORDERS, FUNCTIONCODE_GET_ACCOUNT_BINANCE ]: flag = False for use_method, r in self.reqQueue: if use_method == method: flag = True break if False == flag: self.reqQueue.append((method, req)) else: self.reqQueue.append((method, req)) # 返回请求编号 return self.reqID #---------------------------------------------------------------------- def spotTrade(self, symbol_pair, type_, price, amount): """现货委托""" symbol_pair = self.legalSymbolUpper(symbol_pair) symbol_pair = symbolFromOtherExchangesToBinance(symbol_pair) if type_ == "buy": return self.sendTradingRequest( method=FUNCTIONCODE_BUY_ORDER_BINANCE, callback=self.onTradeOrder, kwargs={ "symbol": symbol_pair, "price": price, "quantity": amount }, optional=None) elif type_ == "sell": return self.sendTradingRequest( method=FUNCTIONCODE_SELL_ORDER_BINANCE, callback=self.onTradeOrder, kwargs={ "symbol": symbol_pair, "price": price, "quantity": amount }, optional=None) return None #---------------------------------------------------------------------- def spotCancelOrder(self, symbol_pair, orderid): """现货委托撤单""" symbol_pair = self.legalSymbolUpper(symbol_pair) symbol_pair = symbolFromOtherExchangesToBinance(symbol_pair) return self.sendTradingRequest( method=FUNCTIONCODE_CANCEL_ORDER_BINANCE, callback=self.onGetCancelOrder, kwargs={ "symbol": symbol_pair, "orderId": int(orderid) }, optional=None) #---------------------------------------------------------------------- def spotAccountInfo(self): """列出账户""" return self.sendTradingRequest(method=FUNCTIONCODE_GET_ACCOUNT_BINANCE, callback=self.onGetAccount, kwargs={}, optional=None) #---------------------------------------------------------------------- def spotListOpenOrders(self, symbol=None): """列出所有的 orders""" if symbol != None: symbol = self.legalSymbolUpper(symbol) symbol = symbolFromOtherExchangesToBinance(symbol) return self.sendTradingRequest(method=FUNCTIONCODE_GET_OPEN_ORDERS, callback=self.onGetOpenOrders, kwargs={"symbol": symbol}, optional=None) #---------------------------------------------------------------------- def spotListAllOrders(self, symbol): symbol = self.legalSymbolUpper(symbol) symbol = symbolFromOtherExchangesToBinance(symbol) return self.sendTradingRequest(method=FUNCTIONCODE_GET_ALL_ORDERS, callback=self.onGetAllOrders, kwargs={"symbol": symbol}, optional=None) #---------------------------------------------------------------------- def spotExchangeInfo(self): return self.sendTradingRequest(method=FUNCTIONCODE_GET_EXCHANGE_INFO, callback=self.onExchangeInfo, kwargs={}, optional=None) #---------------------------------------------------------------------- # def subcribeSymbol(self , symbol): # symbol = self.legalSymbolLower(symbol) # symbol = symbolFromOtherExchangesToBinance(symbol) # #self.bm.start_symbol_ticker_socket( symbol , self.onTick) # self.bm.start_multiplex_socket([symbol + "@ticker" , symbol + "@depth5" , symbol + "@trade"] , callback=self.onMessage) #---------------------------------------------------------------------- def subscribeAllTicker(self): self.bm.start_ticker_socket(callback=self.onPreDealAllTicker) #---------------------------------------------------------------------- def subscribeSpotTicker(self, symbol): if self.bm != None: # print "self.bm != None:" symbol = self.legalSymbolLower(symbol) symbol = symbolFromOtherExchangesToBinance(symbol) self.bm.start_symbol_ticker_socket(symbol, self.onPreDealTicker) #---------------------------------------------------------------------- def subscribeSpotDepth(self, symbol): if self.bm != None: symbol = self.legalSymbolLower(symbol) symbol = symbolFromOtherExchangesToBinance(symbol) self.bm.start_depth_socket(symbol, self.onPreDealDepth) #---------------------------------------------------------------------- def subscribeSpotTrades(self, symbol): if self.bm != None: symbol = self.legalSymbolLower(symbol) symbol = symbolFromOtherExchangesToBinance(symbol) self.bm.start_trade_socket(symbol, self.onPreDealTrades) #---------------------------------------------------------------------- def http_get_request(self, url, params, add_to_headers=None): headers = { "Content-type": "application/x-www-form-urlencoded", 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:53.0) Gecko/20100101 Firefox/53.0' } if add_to_headers: headers.update(add_to_headers) postdata = urllib.parse.urlencode(params) try: #response = requests.get(url, postdata, headers=headers, timeout=5) response = requests.get(url) if response.status_code == 200: return response.json() else: return {"status": "fail"} except Exception as e: self.writeError('httpGet failed, detail is:{}'.format(str(e))) return {"status": "fail", "msg": e} # limit in [5, 10, 20, 50, 100, 500, 1000] #---------------------------------------------------------------------- def getDepthSymbol(self, symbol, limit=10): symbol = self.legalSymbolUpper(symbol) symbol = symbolFromOtherExchangesToBinance(symbol) url = "https://www.binance.com/api/v1/depth?symbol=%s&limit=%s" % ( symbol, str(limit)) data = self.http_get_request(url, "") return data #---------------------------------------------------------------------- def onMessage(self, msg): if 's' in msg.keys(): msg['s'] = symbolFromBinanceToOtherExchanges(msg["s"]) if "lastUpdateId" in msg.keys(): self.onDepth(msg) else: if msg["e"] == "trade": self.onTrades(msg) elif "ticker" in msg["e"]: self.onTick(msg) #---------------------------------------------------------------------- def onAllError(self, ex, req, reqID): self.writeError("onAllError" + str(ex)) #---------------------------------------------------------------------- def onPreDealAllTicker(self, msg): for dic in msg: dic["s"] = symbolFromBinanceToOtherExchanges(dic["s"]) self.onAllTicker(msg) #---------------------------------------------------------------------- def onAllTicker(self, msg): """币安支持所有 ticker 同时socket过来""" self.writeLog(u'onAllTicker:'.format(msg)) # ---------------------------------------------------------------------- def onPreDealTicker(self, msg): if 's' in msg.keys(): msg['s'] = symbolFromBinanceToOtherExchanges(msg["s"]) self.onTick(msg) #---------------------------------------------------------------------- def onTick(self, msg): self.writeLog(u'onTick:'.format(msg)) # ---------------------------------------------------------------------- def onPreDealDepth(self, msg): if 's' in msg.keys(): msg['s'] = symbolFromBinanceToOtherExchanges(msg["s"]) self.onDepth(msg) #---------------------------------------------------------------------- def onDepth(self, msg): self.writeLog(u'onDepth:'.format(msg)) # ---------------------------------------------------------------------- def onPreDealTrades(self, msg): if 's' in msg.keys(): msg['s'] = symbolFromBinanceToOtherExchanges(msg["s"]) self.onTrades(msg) #---------------------------------------------------------------------- def onTrades(self, msg): self.writeLog(u'onTrades:{}'.format(msg)) #---------------------------------------------------------------------- def onGetAccount(self, data, req, reqID): self.writeLog(u'onGetAccount:'.format(data, req, reqID)) #---------------------------------------------------------------------- def onGetOpenOrders(self, data, req, reqID): self.writeLog(u'onGetOpenOrders:ata:{}, req:{}, reqID:{}'.format( data, req, reqID)) #---------------------------------------------------------------------- def onGetAllOrders(self, data, req, reqID): self.writeLog(u'onGetAllOrders:data:{}, req:{}, reqID:{}'.format( data, req, reqID)) #---------------------------------------------------------------------- def onGetBuyOrder(self, data, req, reqID): self.writeLog(u'onGetBuyOrder:data:{}, req:{}, reqID:{}'.format( data, req, reqID)) #---------------------------------------------------------------------- def onGetSellOrder(self, data, req, reqID): self.writeLog(u'onGetSellOrder:data:{}, req:{}, reqID:{}'.format( data, req, reqID)) #---------------------------------------------------------------------- def onGetCancelOrder(self, data, req, reqID): self.writeLog(u'onGetCancelOrder:data:{},req:{},reqId:{}'.format( data, req, reqID)) #---------------------------------------------------------------------- def onExchangeInfo(self, data, req, reqID): self.writeLog(u'onExchangeInfo:data:{},req:{},reqId:{}'.format( data, req, reqID)) # ---------------------------------------------------------------------- def onTradeOrder(self, data, req, reqID): self.writeLog(u'onTradeOrder:{}'.format(data))
class BinanceData(object): # ---------------------------------------------------------------------- def __init__(self, strategy=None): """ 构造函数 :param strategy: 上层策略,主要用与使用writeLog() """ self.strategy = strategy self.client = Client('', '') def writeLog(self, content): if self.strategy and hasattr(self.strategy, 'writeCtaLog'): self.strategy.writeCtaLog(content) else: print(content) def writeError(self, content): if self.strategy and hasattr(self.strategy, 'writeCtaError'): self.strategy.writeCtaError(content) else: print(content, file=sys.stderr) def get_bars(self, symbol, period, callback, bar_is_completed=False, bar_freq=1, start_dt=None): """ 返回k线数据 symbol:合约 period: 周期: 1min,3min,5min,15min,30min,1day,3day,1hour,2hour,4hour,6hour,12hour """ ret_bars = [] if symbol not in SYMBOL_LIST: self.writeError(u'{} 合约{}不在下载清单中'.format(datetime.now(), symbol)) return False, ret_bars if period not in PERIOD_MAPPING: self.writeError(u'{} 周期{}不在下载清单中'.format(datetime.now(), period)) return False, ret_bars if self.client is None: return False, ret_bars binance_symbol = symbol.upper().replace('_', '') # 转换一下 binance_symbol = symbolFromOtherExchangesToBinance(binance_symbol) binance_period = PERIOD_MAPPING.get(period) self.writeLog('{}开始下载binance:{} {}数据.'.format(datetime.now(), binance_symbol, binance_period)) bars = [] try: bars = self.client.get_klines(symbol=binance_symbol, interval=binance_period) bar_len = len(bars) for i, bar in enumerate(bars): add_bar = CtaBarData() try: add_bar.vtSymbol = symbol add_bar.symbol = symbol add_bar.datetime = datetime.fromtimestamp(bar[0] / 1000) utcdatetime = datetime.utcfromtimestamp(bar[0] / 1e3) add_bar.date = add_bar.datetime.strftime('%Y-%m-%d') add_bar.time = add_bar.datetime.strftime('%H:%M:%S') # 币安的交易日,是按照utc来计算的 add_bar.tradingDay = utcdatetime.strftime('%Y-%m-%d') add_bar.open = float(bar[1]) add_bar.high = float(bar[2]) add_bar.low = float(bar[3]) add_bar.close = float(bar[4]) add_bar.volume = float(bar[5]) ret_bars.append(add_bar) except Exception as ex: self.writeError( 'error when convert bar:{},ex:{},t:{}'.format( bar, str(ex), traceback.format_exc())) return False, ret_bars if start_dt is not None and bar.datetime < start_dt: continue if callback is not None: # 最后一个bar,可能是不完整的,强制修改 if i == bar_len - 1 and bar_is_completed: # 根据秒数算的话,要+1,例如13:31,freq=31,第31根bar freq = int((datetime.now() - add_bar.datetime).total_seconds() / 60) + 1 callback(add_bar, False, freq) else: callback(add_bar, bar_is_completed, bar_freq) return True, ret_bars except Exception as ex: self.writeError('exception in get:{},{},{}'.format( binance_symbol, str(ex), traceback.format_exc())) return False, ret_bars def download_bars(self, symbol, period, start_dt=None): """ 返回k线数据 symbol:合约 period: 周期: 1min,3min,5min,15min,30min,1day,3day,1hour,2hour,4hour,6hour,12hour """ ret_bars = [] if symbol not in SYMBOL_LIST: self.writeError(u'{} 合约{}不在下载清单中'.format(datetime.now(), symbol)) return ret_bars if period not in PERIOD_MAPPING: self.writeError(u'{} 周期{}不在下载清单中'.format(datetime.now(), period)) return ret_bars if self.client is None: return ret_bars binance_symbol = symbol.upper().replace('_', '') # 转换一下 binance_symbol = symbolFromOtherExchangesToBinance(binance_symbol) binance_period = PERIOD_MAPPING.get(period) self.writeLog('{}开始下载binance:{} {}数据.'.format(datetime.now(), binance_symbol, binance_period)) if isinstance(start_dt, datetime): start_timestamp = int(start_dt.timestamp() * 1e3) else: start_timestamp = None try: bars = [] if start_timestamp is not None: end_timestamp = int(datetime.now().timestamp() * 1e3) while start_timestamp <= end_timestamp: try: self.writeLog(u'从{} ~{} 下载 {}数据'.format( datetime.fromtimestamp(start_timestamp / 1e3), datetime.fromtimestamp(end_timestamp / 1e3), binance_symbol)) bars_per_loop = self.client.get_klines( symbol=binance_symbol, interval=binance_period, startTime=start_timestamp, endTime=end_timestamp, limit=1000) if len(bars_per_loop) == 0: self.writeLog(u'数据长度为0,结束') break # 更新开始时间,为这次取得最后一个值 start_timestamp = bars_per_loop[-1][0] if len(bars) > 0: while bars[-1][0] >= bars_per_loop[0][0]: if len(bars_per_loop) == 1: bars_per_loop = [] start_timestamp = end_timestamp + 1 break bars_per_loop = bars_per_loop[1:] # 追加bars bars.extend(bars_per_loop) except Exception as ex: self.writeError(u'下载数据{} {} 异常:{},{}'.format( binance_symbol, binance_period, str(ex), traceback.format_exc())) break else: bars = self.client.get_klines(symbol=binance_symbol, interval=binance_period) for i, bar in enumerate(bars): add_bar = {} try: bar_datetime = datetime.fromtimestamp(bar[0] / 1e3) utc_datetime = datetime.utcfromtimestamp(bar[0] / 1e3) add_bar['datetime'] = bar_datetime.strftime( '%Y-%m-%d %H:%M:%S') add_bar['date'] = bar_datetime.strftime('%Y-%m-%d') add_bar['time'] = bar_datetime.strftime('%H:%M:%S') add_bar['open'] = float(bar[1]) add_bar['high'] = float(bar[2]) add_bar['low'] = float(bar[3]) add_bar['close'] = float(bar[4]) add_bar['volume'] = float(bar[5]) add_bar['tradingDay'] = utc_datetime.strftime('%Y-%m-%d') ret_bars.append(add_bar) except Exception as ex: self.writeError( 'error when convert bar:{},ex:{},t:{}'.format( bar, str(ex), traceback.format_exc())) return ret_bars if start_dt is not None and bar_datetime < start_dt: continue return ret_bars except Exception as ex: self.writeError('exception in get:{},{},{}'.format( binance_symbol, str(ex), traceback.format_exc())) return ret_bars
from vnpy.api.binance.client import Client apiKey = "xxx" secretKey = "xxxx" client = Client(apiKey, secretKey) # # get market depth # depth = client.get_order_book(symbol='BNBBTC') # # place a test market buy order, to place an actual order use the create_order function # order = client.create_test_order( # symbol='BNBBTC', # side=Client.SIDE_BUY, # type=Client.ORDER_TYPE_MARKET, # quantity=100) # # get all symbol prices # prices = client.get_all_tickers() # # withdraw 100 ETH # # check docs for assumptions around withdrawals # from binance.exceptions import BinanceAPIException, BinanceWithdrawException # try: # result = client.withdraw( # asset='ETH', # address='<eth_address>', # amount=100) # except BinanceAPIException as e: # print(e) # except BinanceWithdrawException as e:
class BinanceData(object): # ---------------------------------------------------------------------- def __init__(self, strategy): """ 构造函数 :param strategy: 上层策略,主要用与使用strategy.writeCtaLog() """ self.strategy = strategy self.client = None self.init_client() def init_client(self): fileName = globalSetting.get('gateway_name', '') + '_connect.json' filePath = getJsonPath(fileName, __file__) try: with open(filePath, 'r') as f: # 解析json文件 setting = json.load(f) apiKey = setting.get('accessKey',None) secretKey = setting.get('secretKey',None) if apiKey is not None and secretKey is not None: self.client = Client(apiKey, secretKey) except IOError: self.strategy.writeCtaError(u'BINANCE读取连接配置{}出错,请检查'.format(filePath)) return def get_bars(self, symbol, period, callback, bar_is_completed=False,bar_freq=1, start_dt=None): """ 返回k线数据 symbol:合约 period: 周期: 1min,3min,5min,15min,30min,1day,3day,1hour,2hour,4hour,6hour,12hour """ if symbol not in SYMBOL_LIST: self.strategy.writeCtaError(u'{} 合约{}不在下载清单中'.format(datetime.now(), symbol)) return False if period not in PERIOD_MAPPING: self.strategy.writeCtaError(u'{} 周期{}不在下载清单中'.format(datetime.now(), period)) return False if self.client is None: return False binance_symbol = symbol.upper().replace('_' , '') binance_period = PERIOD_MAPPING.get(period) self.strategy.writeCtaLog('{}开始下载binance:{} {}数据.'.format(datetime.now(), binance_symbol, binance_period)) bars = [] try: bars = self.client.get_klines(symbol=binance_symbol, interval=binance_period) for i, bar in enumerate(bars): add_bar = CtaBarData() try: add_bar.vtSymbol = symbol add_bar.symbol = symbol add_bar.datetime = datetime.fromtimestamp(bar[0] / 1000) add_bar.date = add_bar.datetime.strftime('%Y-%m-%d') add_bar.time = add_bar.datetime.strftime('%H:%M:%S') add_bar.tradingDay = add_bar.date add_bar.open = float(bar[1]) add_bar.high = float(bar[2]) add_bar.low = float(bar[3]) add_bar.close = float(bar[4]) add_bar.volume = float(bar[5]) except Exception as ex: self.strategy.writeCtaError( 'error when convert bar:{},ex:{},t:{}'.format(bar, str(ex), traceback.format_exc())) return False if start_dt is not None and bar.datetime < start_dt: continue if callback is not None: callback(add_bar, bar_is_completed, bar_freq) return True except Exception as ex: self.strategy.writeCtaError('exception in get:{},{},{}'.format(binance_symbol,str(ex), traceback.format_exc())) return False
class BinanceData(object): # ---------------------------------------------------------------------- def __init__(self, strategy): """ 构造函数 :param strategy: 上层策略,主要用与使用strategy.writeCtaLog() """ self.strategy = strategy self.client = None self.init_client() def init_client(self): fileName = globalSetting.get('gateway_name', '') + '_connect.json' filePath = getJsonPath(fileName, __file__) try: with open(filePath, 'r') as f: # 解析json文件 setting = json.load(f) apiKey = setting.get('accessKey', None) secretKey = setting.get('secretKey', None) if apiKey is not None and secretKey is not None: self.client = Client(apiKey, secretKey) except IOError: self.strategy.writeCtaError( u'BINANCE读取连接配置{}出错,请检查'.format(filePath)) return def get_bars(self, symbol, period, callback, bar_is_completed=False, bar_freq=1, start_dt=None): """ 返回k线数据 symbol:合约 period: 周期: 1min,3min,5min,15min,30min,1day,3day,1hour,2hour,4hour,6hour,12hour """ if symbol not in SYMBOL_LIST: self.strategy.writeCtaError(u'{} 合约{}不在下载清单中'.format( datetime.now(), symbol)) return False if period not in PERIOD_MAPPING: self.strategy.writeCtaError(u'{} 周期{}不在下载清单中'.format( datetime.now(), period)) return False if self.client is None: return False binance_symbol = symbol.upper().replace('_', '') binance_period = PERIOD_MAPPING.get(period) self.strategy.writeCtaLog('{}开始下载binance:{} {}数据.'.format( datetime.now(), binance_symbol, binance_period)) bars = [] try: bars = self.client.get_klines(symbol=binance_symbol, interval=binance_period) for i, bar in enumerate(bars): add_bar = CtaBarData() try: add_bar.vtSymbol = symbol add_bar.symbol = symbol add_bar.datetime = datetime.fromtimestamp(bar[0] / 1000) add_bar.date = add_bar.datetime.strftime('%Y-%m-%d') add_bar.time = add_bar.datetime.strftime('%H:%M:%S') add_bar.tradingDay = add_bar.date add_bar.open = float(bar[1]) add_bar.high = float(bar[2]) add_bar.low = float(bar[3]) add_bar.close = float(bar[4]) add_bar.volume = float(bar[5]) except Exception as ex: self.strategy.writeCtaError( 'error when convert bar:{},ex:{},t:{}'.format( bar, str(ex), traceback.format_exc())) return False if start_dt is not None and bar.datetime < start_dt: continue if callback is not None: callback(add_bar, bar_is_completed, bar_freq) return True except Exception as ex: self.strategy.writeCtaError('exception in get:{},{},{}'.format( binance_symbol, str(ex), traceback.format_exc())) return False