From e2ae294a39fbfaa2b2263c4fa66426013e0d5962 Mon Sep 17 00:00:00 2001 From: chenxy123 Date: Sat, 18 Feb 2017 00:14:52 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=8C=E6=88=90=E7=81=AB=E5=B8=81=E7=9A=84Ga?= =?UTF-8?q?teaway=E6=8E=A5=E5=85=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- vn.huobi/vnhuobi.py | 50 +-- vn.trader/huobiGateway/HUOBI_connect.json | 7 +- vn.trader/huobiGateway/huobiGateway.py | 449 +++++++++++++++++++--- vn.trader/huobiGateway/vnhuobi.py | 50 +-- vn.trader/uiMainWindow.py | 4 +- vn.trader/vtConstant.py | 1 + vn.trader/vtEngine.py | 11 +- 7 files changed, 452 insertions(+), 120 deletions(-) diff --git a/vn.huobi/vnhuobi.py b/vn.huobi/vnhuobi.py index 4f5f865c..fd00a771 100644 --- a/vn.huobi/vnhuobi.py +++ b/vn.huobi/vnhuobi.py @@ -118,8 +118,8 @@ class TradeApi(object): # 发送请求 payload = urllib.urlencode(params) - - r = requests.post(HUOBI_TRADE_API_API, params=payload) + + r = requests.post(HUOBI_TRADE_API, params=payload) if r.status_code == 200: data = r.json() return data @@ -140,12 +140,12 @@ class TradeApi(object): # 请求失败 if 'code' in data and 'message' in data: error = u'错误信息:%s' %data['message'] - self.onError(error, reqID) + self.onError(error, req, reqID) # 请求成功 else: if self.DEBUG: - print callback.__name__ - callback(data, reqID) + print callback.__name__ + callback(data, req, reqID) except Empty: pass @@ -424,97 +424,97 @@ class TradeApi(object): #################################################### #---------------------------------------------------------------------- - def onError(self, error, reqID): + def onError(self, error, req, reqID): """错误推送""" print error, reqID #---------------------------------------------------------------------- - def onGetAccountInfo(self, data, reqID): + def onGetAccountInfo(self, data, req, reqID): """查询账户回调""" print data #---------------------------------------------------------------------- - def onGetOrders(self, data, reqID): + def onGetOrders(self, data, req, reqID, fuck): """查询委托回调""" print data #---------------------------------------------------------------------- - def onOrderInfo(self, data, reqID): + def onOrderInfo(self, data, req, reqID): """委托详情回调""" print data #---------------------------------------------------------------------- - def onBuy(self, data, reqID): + def onBuy(self, data, req, reqID): """买入回调""" print data #---------------------------------------------------------------------- - def onSell(self, data, reqID): + def onSell(self, data, req, reqID): """卖出回调""" print data #---------------------------------------------------------------------- - def onBuyMarket(self, data, reqID): + def onBuyMarket(self, data, req, reqID): """市价买入回调""" print data #---------------------------------------------------------------------- - def onSellMarket(self, data, reqID): + def onSellMarket(self, data, req, reqID): """市价卖出回调""" print data #---------------------------------------------------------------------- - def onCancelOrder(self, data, reqID): + def onCancelOrder(self, data, req, reqID): """撤单回调""" print data #---------------------------------------------------------------------- - def onGetNewDealOrders(self, data, reqID): + def onGetNewDealOrders(self, data, req, reqID): """查询最新成交回调""" print data #---------------------------------------------------------------------- - def onGetOrderIdByTradeId(self, data, reqID): + def onGetOrderIdByTradeId(self, data, req, reqID): """通过成交编号查询委托编号回调""" print data #---------------------------------------------------------------------- - def onWithdrawCoin(self, data, reqID): + def onWithdrawCoin(self, data, req, reqID): """提币回调""" print data #---------------------------------------------------------------------- - def onCancelWithdrawCoin(self, data, reqID): + def onCancelWithdrawCoin(self, data, req, reqID): """取消提币回调""" print data #---------------------------------------------------------------------- - def onGetWithdrawCoinResult(self, data, reqID): + def onGetWithdrawCoinResult(self, data, req, reqID): """查询提币结果回调""" print data #---------------------------------------------------------------------- - def onTransfer(self, data, reqID): + def onTransfer(self, data, req, reqID): """转账回调""" print data #---------------------------------------------------------------------- - def onLoan(self, data, reqID): + def onLoan(self, data, req, reqID): """申请杠杆回调""" print data #---------------------------------------------------------------------- - def onRepayment(self, data, reqID): + def onRepayment(self, data, req, reqID): """归还杠杆回调""" print data #---------------------------------------------------------------------- - def onLoanAvailable(self, data, reqID): + def onLoanAvailable(self, data, req, reqID): """查询杠杆额度回调""" print data #---------------------------------------------------------------------- - def onGetLoans(self, data, reqID): + def onGetLoans(self, data, req, reqID): """查询杠杆列表""" print data @@ -558,7 +558,7 @@ class DataApi(object): self.taskThread = Thread(target=self.run) # 处理任务的线程 #---------------------------------------------------------------------- - def init(self, interval): + def init(self, interval, debug): """初始化""" self.taskInterval = interval self.DEBUG = debug diff --git a/vn.trader/huobiGateway/HUOBI_connect.json b/vn.trader/huobiGateway/HUOBI_connect.json index 939ae0d8..3c427281 100644 --- a/vn.trader/huobiGateway/HUOBI_connect.json +++ b/vn.trader/huobiGateway/HUOBI_connect.json @@ -1,6 +1,7 @@ { - "accessKey": "3f669293-60e6dd7f-8e39c295-5aae5", - "secretKey": "7050aec8-43fc680d-06471837-57e38", + "accessKey": "火币网站申请", + "secretKey": "火币网站申请", "interval": 0.5, - "market": "cny" + "market": "cny", + "debug": false } \ No newline at end of file diff --git a/vn.trader/huobiGateway/huobiGateway.py b/vn.trader/huobiGateway/huobiGateway.py index ad67c4fd..36b9ca3e 100644 --- a/vn.trader/huobiGateway/huobiGateway.py +++ b/vn.trader/huobiGateway/huobiGateway.py @@ -17,6 +17,35 @@ import vnhuobi from vtGateway import * +SYMBOL_BTCCNY = 'BTCCNY' +SYMBOL_LTCCNY = 'LTCCNY' +SYMBOL_BTCUSD = 'BTCUSD' + +SYMBOL_MAP = {} +SYMBOL_MAP[(vnhuobi.COINTYPE_BTC, 'cny')] = SYMBOL_BTCCNY +SYMBOL_MAP[(vnhuobi.COINTYPE_LTC, 'cny')] = SYMBOL_LTCCNY +SYMBOL_MAP[(vnhuobi.COINTYPE_BTC, 'usd')] = SYMBOL_BTCUSD +SYMBOL_MAP_REVERSE = {v: k for k, v in SYMBOL_MAP.items()} + +MDSYMBOL_MAP = {} +MDSYMBOL_MAP['btccny'] = SYMBOL_BTCCNY +MDSYMBOL_MAP['ltccny'] = SYMBOL_LTCCNY +MDSYMBOL_MAP['btcusd'] = SYMBOL_BTCUSD + +DIRECTION_MAP = {} +DIRECTION_MAP[1] = DIRECTION_LONG +DIRECTION_MAP[2] = DIRECTION_SHORT + +STATUS_MAP = {} +STATUS_MAP[0] = STATUS_NOTTRADED +STATUS_MAP[1] = STATUS_PARTTRADED +STATUS_MAP[2] = STATUS_ALLTRADED +STATUS_MAP[3] = STATUS_CANCELLED +STATUS_MAP[5] = STATUS_UNKNOWN +STATUS_MAP[7] = STATUS_UNKNOWN + + + ######################################################################## class HuobiGateway(VtGateway): """火币接口""" @@ -55,6 +84,7 @@ class HuobiGateway(VtGateway): secretKey = str(setting['secretKey']) interval = setting['interval'] market = setting['market'] + debug = setting['debug'] except KeyError: log = VtLogData() log.gatewayName = self.gatewayName @@ -63,15 +93,15 @@ class HuobiGateway(VtGateway): return # 初始化接口 - self.tradeApi.connect(accessKey, secretKey) + self.tradeApi.connect(accessKey, secretKey, market, debug) self.writeLog(u'交易接口初始化成功') - self.dataApi.connect(interval) + self.dataApi.connect(interval, market, debug) self.writeLog(u'行情接口初始化成功') # 启动查询 - #self.initQuery() - #self.startQuery() + self.initQuery() + self.startQuery() #---------------------------------------------------------------------- def writeLog(self, content): @@ -89,12 +119,12 @@ class HuobiGateway(VtGateway): #---------------------------------------------------------------------- def sendOrder(self, orderReq): """发单""" - pass + self.tradeApi.sendOrder(orderReq) #---------------------------------------------------------------------- def cancelOrder(self, cancelOrderReq): """撤单""" - pass + self.tradeApi.cancel(cancelOrderReq) #---------------------------------------------------------------------- def qryAccount(self): @@ -116,32 +146,14 @@ class HuobiGateway(VtGateway): def initQuery(self): """初始化连续查询""" if self.qryEnabled: - # 需要循环的查询函数列表 - self.qryFunctionList = [self.qryAccount] - - self.qryCount = 0 # 查询触发倒计时 - self.qryTrigger = 2 # 查询触发点 - self.qryNextFunction = 0 # 上次运行的查询函数索引 - + self.qryFunctionList = [self.tradeApi.queryWorkingOrders, self.tradeApi.queryAccount] self.startQuery() #---------------------------------------------------------------------- def query(self, event): """注册到事件处理引擎上的查询函数""" - self.qryCount += 1 - - if self.qryCount > self.qryTrigger: - # 清空倒计时 - self.qryCount = 0 - - # 执行查询函数 - function = self.qryFunctionList[self.qryNextFunction] + for function in self.qryFunctionList: function() - - # 计算下次查询函数的索引,如果超过了列表长度,则重新设为0 - self.qryNextFunction += 1 - if self.qryNextFunction == len(self.qryFunctionList): - self.qryNextFunction = 0 #---------------------------------------------------------------------- def startQuery(self): @@ -165,9 +177,18 @@ class HuobiTradeApi(vnhuobi.TradeApi): self.gateway = gateway self.gatewayName = gateway.gatewayName + + self.localID = 0 # 本地委托号 + self.localSystemDict = {} # key:localID, value:systemID + self.systemLocalDict = {} # key:systemID, value:localID + self.workingOrderDict = {} # key:localID, value:order + self.reqLocalDict = {} # key:reqID, value:localID + self.cancelDict = {} # key:localID, value:cancelOrderReq + + self.tradeID = 0 # 本地成交号 #---------------------------------------------------------------------- - def onError(self, error, reqID): + def onError(self, error, req, reqID): """错误推送""" err = VtErrorData() err.gatewayName = self.gatewayName @@ -176,11 +197,13 @@ class HuobiTradeApi(vnhuobi.TradeApi): self.gateway.onError(err) #---------------------------------------------------------------------- - def onGetAccountInfo(self, data, reqID): + def onGetAccountInfo(self, data, req, reqID): """查询账户回调""" # 推送账户数据 account = VtAccountData() account.gatewayName = self.gatewayName + account.accountID = 'HUOBI' + account.vtAccountID = '.'.join([account.accountID, self.gatewayName]) account.balance = data['net_asset'] self.gateway.onAccount(account) @@ -188,125 +211,328 @@ class HuobiTradeApi(vnhuobi.TradeApi): if self.market == 'cny': posCny = VtPositionData() posCny.gatewayName = self.gatewayName + posCny.symbol = 'CNY' + posCny.exchange = EXCHANGE_HUOBI + posCny.vtSymbol = '.'.join([posCny.symbol, posCny.exchange]) + posCny.vtPositionName = posCny.vtSymbol posCny.position = data['available_cny_display'] posCny.frozen = data['frozen_cny_display'] self.gateway.onPosition(posCny) posLtc = VtPositionData() posLtc.gatewayName = self.gatewayName + posLtc.symbol = 'LTC' + posLtc.exchange = EXCHANGE_HUOBI + posLtc.vtSymbol = '.'.join([posLtc.symbol, posLtc.exchange]) + posLtc.vtPositionName = posLtc.vtSymbol posLtc.position = data['available_ltc_display'] posLtc.frozen = data['frozen_ltc_display'] self.gateway.onPosition(posLtc) else: posUsd = VtPositionData() posUsd.gatewayName = self.gatewayName + posUsd.symbol = 'USD' + posUsd.exchange = EXCHANGE_HUOBI + posUsd.vtSymbol = '.'.join([posUsd.symbol, posUsd.exchange]) + posUsd.vtPositionName = posUsd.vtSymbol posUsd.position = data['available_usd_display'] posUsd.frozen = data['frozen_usd_display'] self.gateway.onPosition(posUsd) posBtc = VtPositionData() posBtc.gatewayName = self.gatewayName + posBtc.symbol = 'BTC' + posBtc.exchange = EXCHANGE_HUOBI + posBtc.vtSymbol = '.'.join([posBtc.symbol, posBtc.exchange]) + posBtc.vtPositionName = posBtc.vtSymbol posBtc.position = data['available_btc_display'] posBtc.frozen = data['frozen_btc_display'] self.gateway.onPosition(posBtc) #---------------------------------------------------------------------- - def onGetOrders(self, data, reqID): + def onGetOrders(self, data, req, reqID): """查询委托回调""" for d in data: order = VtOrderData() order.gatewayName = self.gatewayName - - order - - #---------------------------------------------------------------------- - def onOrderInfo(self, data, reqID): - """委托详情回调""" - print data + + # 合约代码 + params = req['params'] + coin = params['coin_type'] + order.symbol = SYMBOL_MAP[(coin, self.market)] + order.exchange = EXCHANGE_HUOBI + order.vtSymbol = '.'.join([order.symbol, order.exchange]) + + # 委托号 + systemID = d['id'] + self.localID += 1 + localID = str(self.localID) + self.systemLocalDict[systemID] = localID + self.localSystemDict[localID] = systemID + order.orderID = localID + order.vtOrderID = '.'.join([order.orderID, order.gatewayName]) + + # 其他信息 + order.direction = DIRECTION_MAP[d['type']] + order.offset = OFFSET_NONE + order.price = float(d['order_price']) + order.totalVolume = float(d['order_amount']) + order.tradedVolume = float(d['processed_amount']) + order.orderTime = d['order_time'] + + # 委托状态 + if order.tradedVolume == 0: + order.status = STATUS_NOTTRADED + else: + order.status = STATUS_PARTTRADED + + # 缓存病推送 + self.workingOrderDict[localID] = order + self.gateway.onOrder(order) #---------------------------------------------------------------------- - def onBuy(self, data, reqID): + def onOrderInfo(self, data, req, reqID): + """委托详情回调""" + systemID = data['id'] + localID = self.systemLocalDict[systemID] + order = self.workingOrderDict.get(localID, None) + if not order: + return + + # 记录最新成交的金额 + newTradeVolume = float(data['processed_amount']) - order.tradedVolume + if newTradeVolume: + trade = VtTradeData() + trade.gatewayName = self.gatewayName + trade.symbol = order.symbol + trade.vtSymbol = order.vtSymbol + + self.tradeID += 1 + trade.tradeID = str(self.tradeID) + trade.vtTradeID = '.'.join([trade.tradeID, trade.gatewayName]) + + trade.volume = newTradeVolume + trade.price = data['processed_price'] + trade.direction = order.direction + trade.offset = order.offset + trade.exchange = order.exchange + trade.tradeTime = datetime.now().strftime('%H:%M:%S') + + self.gateway.onTrade(trade) + + # 更新委托状态 + order.tradedVolume = float(data['processed_amount']) + order.status = STATUS_MAP.get(data['status'], STATUS_UNKNOWN) + + if newTradeVolume: + self.gateway.onOrder(order) + + if order.status == STATUS_ALLTRADED or order.status == STATUS_CANCELLED: + del self.workingOrderDict[order.orderID] + + #---------------------------------------------------------------------- + def onBuy(self, data, req, reqID): """买入回调""" - print data + localID = self.reqLocalDict[reqID] + systemID = data['id'] + self.localSystemDict[localID] = systemID + self.systemLocalDict[systemID] = localID + + # 撤单 + if localID in self.cancelDict: + req = self.cancelDict[localID] + self.cancel(req) + del self.cancelDict[localID] + + # 推送委托信息 + order = self.workingOrderDict[localID] + if data['result'] == 'success': + order.status = STATUS_NOTTRADED + self.gateway.onOrder(order) #---------------------------------------------------------------------- - def onSell(self, data, reqID): + def onSell(self, data, req, reqID): """卖出回调""" - print data + localID = self.reqLocalDict[reqID] + systemID = data['id'] + self.localSystemDict[localID] = systemID + self.systemLocalDict[systemID] = localID + + # 撤单 + if localID in self.cancelDict: + req = self.cancelDict[localID] + self.cancel(req) + del self.cancelDict[localID] + + # 推送委托信息 + order = self.workingOrderDict[localID] + if data['result'] == 'success': + order.status = STATUS_NOTTRADED + self.gateway.onOrder(order) #---------------------------------------------------------------------- - def onBuyMarket(self, data, reqID): + def onBuyMarket(self, data, req, reqID): """市价买入回调""" print data #---------------------------------------------------------------------- - def onSellMarket(self, data, reqID): + def onSellMarket(self, data, req, reqID): """市价卖出回调""" print data #---------------------------------------------------------------------- - def onCancelOrder(self, data, reqID): + def onCancelOrder(self, data, req, reqID): """撤单回调""" - print data + if data['result'] == 'success': + systemID = req['params']['id'] + localID = self.systemLocalDict[systemID] + + order = self.workingOrderDict[localID] + order.status = STATUS_CANCELLED + + del self.workingOrderDict[localID] + self.gateway.onOrder(order) #---------------------------------------------------------------------- - def onGetNewDealOrders(self, data, reqID): + def onGetNewDealOrders(self, data, req, reqID): """查询最新成交回调""" print data #---------------------------------------------------------------------- - def onGetOrderIdByTradeId(self, data, reqID): + def onGetOrderIdByTradeId(self, data, req, reqID): """通过成交编号查询委托编号回调""" print data #---------------------------------------------------------------------- - def onWithdrawCoin(self, data, reqID): + def onWithdrawCoin(self, data, req, reqID): """提币回调""" print data #---------------------------------------------------------------------- - def onCancelWithdrawCoin(self, data, reqID): + def onCancelWithdrawCoin(self, data, req, reqID): """取消提币回调""" print data #---------------------------------------------------------------------- - def onGetWithdrawCoinResult(self, data, reqID): + def onGetWithdrawCoinResult(self, data, req, reqID): """查询提币结果回调""" print data #---------------------------------------------------------------------- - def onTransfer(self, data, reqID): + def onTransfer(self, data, req, reqID): """转账回调""" print data #---------------------------------------------------------------------- - def onLoan(self, data, reqID): + def onLoan(self, data, req, reqID): """申请杠杆回调""" print data #---------------------------------------------------------------------- - def onRepayment(self, data, reqID): + def onRepayment(self, data, req, reqID): """归还杠杆回调""" print data #---------------------------------------------------------------------- - def onLoanAvailable(self, data, reqID): + def onLoanAvailable(self, data, req, reqID): """查询杠杆额度回调""" print data #---------------------------------------------------------------------- - def onGetLoans(self, data, reqID): + def onGetLoans(self, data, req, reqID): """查询杠杆列表""" print data #---------------------------------------------------------------------- - def connect(self, accessKey, secretKey, market): + def connect(self, accessKey, secretKey, market, debug=False): """连接服务器""" self.market = market + self.DEBUG = debug self.init(accessKey, secretKey) - - + + # 查询未成交委托 + self.getOrders(vnhuobi.COINTYPE_BTC, self.market) + + if self.market == vnhuobi.MARKETTYPE_CNY: + # 只有人民币市场才有莱特币 + self.getOrders(vnhuobi.COINTYPE_LTC, self.market) + + # ---------------------------------------------------------------------- + def queryWorkingOrders(self): + """查询活动委托状态""" + for order in self.workingOrderDict.values(): + # 如果尚未返回委托号,则无法查询 + if order.orderID in self.localSystemDict: + systemID = self.localSystemDict[order.orderID] + coin, market = SYMBOL_MAP_REVERSE[order.symbol] + self.orderInfo(systemID, coin, market) + + # ---------------------------------------------------------------------- + def queryAccount(self): + """查询活动委托状态""" + self.getAccountInfo(self.market) + + # ---------------------------------------------------------------------- + def sendOrder(self, req): + """发送委托""" + # 检查是否填入了价格,禁止市价委托 + if req.priceType != PRICETYPE_LIMITPRICE: + err = VtErrorData() + err.gatewayName = self.gatewayName + err.errorMsg = u'火币接口仅支持限价单' + err.errorTime = datetime.now().strftime('%H:%M:%S') + self.gateway.onError(err) + return None + + # 发送限价委托 + coin, market = SYMBOL_MAP_REVERSE[req.symbol] + + if req.direction == DIRECTION_LONG: + reqID = self.buy(req.price, req.volume, coinType=coin, market=self.market) + else: + reqID = self.sell(req.price, req.volume, coinType=coin, market=self.market) + + self.localID += 1 + localID = str(self.localID) + self.reqLocalDict[reqID] = localID + + # 推送委托信息 + order = VtOrderData() + order.gatewayName = self.gatewayName + + order.symbol = req.symbol + order.exchange = EXCHANGE_HUOBI + order.vtSymbol = '.'.join([order.symbol, order.exchange]) + + order.orderID = localID + order.vtOrderID = '.'.join([order.orderID, order.gatewayName]) + + order.direction = req.direction + order.offset = OFFSET_UNKNOWN + order.price = req.price + order.volume = req.volume + order.orderTime = datetime.now().strftime('%H:%M:%S') + order.status = STATUS_UNKNOWN + + self.workingOrderDict[localID] = order + self.gateway.onOrder(order) + + # 返回委托号 + return order.vtOrderID + + # ---------------------------------------------------------------------- + def cancel(self, req): + """撤单""" + localID = req.orderID + if localID in self.localSystemDict: + systemID = self.localSystemDict[localID] + coin, market = SYMBOL_MAP_REVERSE[req.symbol] + self.cancelOrder(systemID, coin, self.market) + else: + self.cancelDict[localID] = req + + ######################################################################## class HuobiDataApi(vnhuobi.DataApi): """行情接口""" @@ -315,8 +541,14 @@ class HuobiDataApi(vnhuobi.DataApi): def __init__(self, gateway): """Constructor""" super(HuobiDataApi, self).__init__() + + self.market = 'cny' self.gateway = gateway + self.gatewayName = gateway.gatewayName + + self.tickDict = {} # key:symbol, value:tick + #---------------------------------------------------------------------- def onTick(self, data): @@ -326,20 +558,109 @@ class HuobiDataApi(vnhuobi.DataApi): #---------------------------------------------------------------------- def onQuote(self, data): """实时报价推送""" - print data + ticker = data['ticker'] + symbol = MDSYMBOL_MAP[ticker['symbol']] + + if symbol not in self.tickDict: + tick = VtTickData() + tick.gatewayName = self.gatewayName + + tick.symbol = symbol + tick.exchange = EXCHANGE_HUOBI + tick.vtSymbol = '.'.join([tick.symbol, tick.exchange]) + self.tickDict[symbol] = tick + else: + tick = self.tickDict[symbol] + + tick.highPrice = ticker['high'] + tick.lowPrice = ticker['low'] + tick.lastPrice = ticker['last'] + tick.volume = ticker['vol'] #---------------------------------------------------------------------- def onDepth(self, data): """实时深度推送""" - print data + symbol = MDSYMBOL_MAP[data['symbol']] + if symbol not in self.tickDict: + tick = VtTickData() + tick.gatewayName = self.gatewayName + + tick.symbol = symbol + tick.exchange = EXCHANGE_HUOBI + tick.vtSymbol = '.'.join([tick.symbol, tick.exchange]) + self.tickDict[symbol] = tick + else: + tick = self.tickDict[symbol] + + tick.bidPrice1, tick.bidVolume1 = data['bids'][0] + tick.bidPrice2, tick.bidVolume2 = data['bids'][1] + tick.bidPrice3, tick.bidVolume3 = data['bids'][2] + tick.bidPrice4, tick.bidVolume4 = data['bids'][3] + tick.bidPrice5, tick.bidVolume5 = data['bids'][4] + + tick.askPrice1, tick.askVolume1 = data['asks'][0] + tick.askPrice2, tick.askVolume2 = data['asks'][1] + tick.askPrice3, tick.askVolume3 = data['asks'][2] + tick.askPrice4, tick.askVolume4 = data['asks'][3] + tick.askPrice5, tick.askVolume5 = data['asks'][4] + + now = datetime.now() + tick.time = now.strftime('%H:%M:%S') + tick.date = now.strftime('%Y%m%d') + + self.gateway.onTick(tick) #---------------------------------------------------------------------- - def connect(self, interval): + def connect(self, interval, market, debug=False): """连接服务器""" - self.init(interval) - - - + self.market = market + + self.init(interval, debug) + + # 订阅行情并推送合约信息 + if self.market == vnhuobi.MARKETTYPE_CNY: + self.subscribeQuote(vnhuobi.SYMBOL_BTCCNY) + self.subscribeQuote(vnhuobi.SYMBOL_LTCCNY) + + self.subscribeDepth(vnhuobi.SYMBOL_BTCCNY, 5) + self.subscribeDepth(vnhuobi.SYMBOL_LTCCNY, 5) + + contract = VtContractData() + contract.gatewayName = self.gatewayName + contract.symbol = SYMBOL_BTCCNY + contract.exchange = EXCHANGE_HUOBI + contract.vtSymbol = '.'.join([contract.symbol, contract.exchange]) + contract.name = u'人民币现货BTC' + contract.size = 1 + contract.priceTick = 0.01 + contract.productClass = PRODUCT_SPOT + self.gateway.onContract(contract) + + contract = VtContractData() + contract.gatewayName = self.gatewayName + contract.symbol = SYMBOL_LTCCNY + contract.exchange = EXCHANGE_HUOBI + contract.vtSymbol = '.'.join([contract.symbol, contract.exchange]) + contract.name = u'人民币现货LTC' + contract.size = 1 + contract.priceTick = 0.01 + contract.productClass = PRODUCT_SPOT + self.gateway.onContract(contract) + else: + self.subscribeQuote(vnhuobi.SYMBOL_BTCUSD) + + self.subscribeDepth(vnhuobi.SYMBOL_BTCUSD) + + contract = VtContractData() + contract.gatewayName = self.gatewayName + contract.symbol = SYMBOL_BTCUSD + contract.exchange = EXCHANGE_HUOBI + contract.vtSymbol = '.'.join([contract.symbol, contract.exchange]) + contract.name = u'美元现货BTC' + contract.size = 1 + contract.priceTick = 0.01 + contract.productClass = PRODUCT_SPOT + self.gateway.onContract(contract) diff --git a/vn.trader/huobiGateway/vnhuobi.py b/vn.trader/huobiGateway/vnhuobi.py index 4f5f865c..fd00a771 100644 --- a/vn.trader/huobiGateway/vnhuobi.py +++ b/vn.trader/huobiGateway/vnhuobi.py @@ -118,8 +118,8 @@ class TradeApi(object): # 发送请求 payload = urllib.urlencode(params) - - r = requests.post(HUOBI_TRADE_API_API, params=payload) + + r = requests.post(HUOBI_TRADE_API, params=payload) if r.status_code == 200: data = r.json() return data @@ -140,12 +140,12 @@ class TradeApi(object): # 请求失败 if 'code' in data and 'message' in data: error = u'错误信息:%s' %data['message'] - self.onError(error, reqID) + self.onError(error, req, reqID) # 请求成功 else: if self.DEBUG: - print callback.__name__ - callback(data, reqID) + print callback.__name__ + callback(data, req, reqID) except Empty: pass @@ -424,97 +424,97 @@ class TradeApi(object): #################################################### #---------------------------------------------------------------------- - def onError(self, error, reqID): + def onError(self, error, req, reqID): """错误推送""" print error, reqID #---------------------------------------------------------------------- - def onGetAccountInfo(self, data, reqID): + def onGetAccountInfo(self, data, req, reqID): """查询账户回调""" print data #---------------------------------------------------------------------- - def onGetOrders(self, data, reqID): + def onGetOrders(self, data, req, reqID, fuck): """查询委托回调""" print data #---------------------------------------------------------------------- - def onOrderInfo(self, data, reqID): + def onOrderInfo(self, data, req, reqID): """委托详情回调""" print data #---------------------------------------------------------------------- - def onBuy(self, data, reqID): + def onBuy(self, data, req, reqID): """买入回调""" print data #---------------------------------------------------------------------- - def onSell(self, data, reqID): + def onSell(self, data, req, reqID): """卖出回调""" print data #---------------------------------------------------------------------- - def onBuyMarket(self, data, reqID): + def onBuyMarket(self, data, req, reqID): """市价买入回调""" print data #---------------------------------------------------------------------- - def onSellMarket(self, data, reqID): + def onSellMarket(self, data, req, reqID): """市价卖出回调""" print data #---------------------------------------------------------------------- - def onCancelOrder(self, data, reqID): + def onCancelOrder(self, data, req, reqID): """撤单回调""" print data #---------------------------------------------------------------------- - def onGetNewDealOrders(self, data, reqID): + def onGetNewDealOrders(self, data, req, reqID): """查询最新成交回调""" print data #---------------------------------------------------------------------- - def onGetOrderIdByTradeId(self, data, reqID): + def onGetOrderIdByTradeId(self, data, req, reqID): """通过成交编号查询委托编号回调""" print data #---------------------------------------------------------------------- - def onWithdrawCoin(self, data, reqID): + def onWithdrawCoin(self, data, req, reqID): """提币回调""" print data #---------------------------------------------------------------------- - def onCancelWithdrawCoin(self, data, reqID): + def onCancelWithdrawCoin(self, data, req, reqID): """取消提币回调""" print data #---------------------------------------------------------------------- - def onGetWithdrawCoinResult(self, data, reqID): + def onGetWithdrawCoinResult(self, data, req, reqID): """查询提币结果回调""" print data #---------------------------------------------------------------------- - def onTransfer(self, data, reqID): + def onTransfer(self, data, req, reqID): """转账回调""" print data #---------------------------------------------------------------------- - def onLoan(self, data, reqID): + def onLoan(self, data, req, reqID): """申请杠杆回调""" print data #---------------------------------------------------------------------- - def onRepayment(self, data, reqID): + def onRepayment(self, data, req, reqID): """归还杠杆回调""" print data #---------------------------------------------------------------------- - def onLoanAvailable(self, data, reqID): + def onLoanAvailable(self, data, req, reqID): """查询杠杆额度回调""" print data #---------------------------------------------------------------------- - def onGetLoans(self, data, reqID): + def onGetLoans(self, data, req, reqID): """查询杠杆列表""" print data @@ -558,7 +558,7 @@ class DataApi(object): self.taskThread = Thread(target=self.run) # 处理任务的线程 #---------------------------------------------------------------------- - def init(self, interval): + def init(self, interval, debug): """初始化""" self.taskInterval = interval self.DEBUG = debug diff --git a/vn.trader/uiMainWindow.py b/vn.trader/uiMainWindow.py index 348ed439..12545039 100644 --- a/vn.trader/uiMainWindow.py +++ b/vn.trader/uiMainWindow.py @@ -79,7 +79,9 @@ class MainWindow(QtGui.QMainWindow): self.addConnectAction(sysMenu, 'IB') self.addConnectAction(sysMenu, 'SHZD', u'直达') self.addConnectAction(sysMenu, 'OANDA') - self.addConnectAction(sysMenu, 'OKCOIN') + sysMenu.addSeparator() + self.addConnectAction(sysMenu, 'OKCOIN') + self.addConnectAction(sysMenu, 'HUOBI', u'火币') sysMenu.addSeparator() self.addConnectAction(sysMenu, 'Wind') diff --git a/vn.trader/vtConstant.py b/vn.trader/vtConstant.py index 2fd78b62..b1c0cf47 100644 --- a/vn.trader/vtConstant.py +++ b/vn.trader/vtConstant.py @@ -74,6 +74,7 @@ EXCHANGE_ICE = 'ICE' # ICE交易所 EXCHANGE_OANDA = 'OANDA' # OANDA外汇做市商 EXCHANGE_OKCOIN = 'OKCOIN' # OKCOIN比特币交易所 +EXCHANGE_HUOBI = 'HUOBI' # 火币比特币交易所 # 货币类型 CURRENCY_USD = 'USD' # 美元 diff --git a/vn.trader/vtEngine.py b/vn.trader/vtEngine.py index 08ece81a..5a0ea369 100644 --- a/vn.trader/vtEngine.py +++ b/vn.trader/vtEngine.py @@ -145,9 +145,16 @@ class MainEngine(object): self.addGateway(OkcoinGateway, 'OKCOIN') self.gatewayDict['OKCOIN'].setQryEnabled(True) except Exception, e: - print e + print e - #---------------------------------------------------------------------- + try: + from huobiGateway.huobiGateway import HuobiGateway + self.addGateway(HuobiGateway, 'HUOBI') + self.gatewayDict['HUOBI'].setQryEnabled(True) + except Exception, e: + print e + + #---------------------------------------------------------------------- def addGateway(self, gateway, gatewayName=None): """创建接口""" self.gatewayDict[gatewayName] = gateway(self.eventEngine, gatewayName)