完成火币的Gateaway接入

This commit is contained in:
chenxy123 2017-02-18 00:14:52 +08:00
parent 796c529992
commit e2ae294a39
7 changed files with 452 additions and 120 deletions

View File

@ -119,7 +119,7 @@ class TradeApi(object):
# 发送请求 # 发送请求
payload = urllib.urlencode(params) 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: if r.status_code == 200:
data = r.json() data = r.json()
return data return data
@ -140,12 +140,12 @@ class TradeApi(object):
# 请求失败 # 请求失败
if 'code' in data and 'message' in data: if 'code' in data and 'message' in data:
error = u'错误信息:%s' %data['message'] error = u'错误信息:%s' %data['message']
self.onError(error, reqID) self.onError(error, req, reqID)
# 请求成功 # 请求成功
else: else:
if self.DEBUG: if self.DEBUG:
print callback.__name__ print callback.__name__
callback(data, reqID) callback(data, req, reqID)
except Empty: except Empty:
pass pass
@ -424,97 +424,97 @@ class TradeApi(object):
#################################################### ####################################################
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onError(self, error, reqID): def onError(self, error, req, reqID):
"""错误推送""" """错误推送"""
print error, reqID print error, reqID
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onGetAccountInfo(self, data, reqID): def onGetAccountInfo(self, data, req, reqID):
"""查询账户回调""" """查询账户回调"""
print data print data
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onGetOrders(self, data, reqID): def onGetOrders(self, data, req, reqID, fuck):
"""查询委托回调""" """查询委托回调"""
print data print data
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onOrderInfo(self, data, reqID): def onOrderInfo(self, data, req, reqID):
"""委托详情回调""" """委托详情回调"""
print data print data
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onBuy(self, data, reqID): def onBuy(self, data, req, reqID):
"""买入回调""" """买入回调"""
print data print data
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onSell(self, data, reqID): def onSell(self, data, req, reqID):
"""卖出回调""" """卖出回调"""
print data print data
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onBuyMarket(self, data, reqID): def onBuyMarket(self, data, req, reqID):
"""市价买入回调""" """市价买入回调"""
print data print data
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onSellMarket(self, data, reqID): def onSellMarket(self, data, req, reqID):
"""市价卖出回调""" """市价卖出回调"""
print data print data
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onCancelOrder(self, data, reqID): def onCancelOrder(self, data, req, reqID):
"""撤单回调""" """撤单回调"""
print data print data
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onGetNewDealOrders(self, data, reqID): def onGetNewDealOrders(self, data, req, reqID):
"""查询最新成交回调""" """查询最新成交回调"""
print data print data
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onGetOrderIdByTradeId(self, data, reqID): def onGetOrderIdByTradeId(self, data, req, reqID):
"""通过成交编号查询委托编号回调""" """通过成交编号查询委托编号回调"""
print data print data
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onWithdrawCoin(self, data, reqID): def onWithdrawCoin(self, data, req, reqID):
"""提币回调""" """提币回调"""
print data print data
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onCancelWithdrawCoin(self, data, reqID): def onCancelWithdrawCoin(self, data, req, reqID):
"""取消提币回调""" """取消提币回调"""
print data print data
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onGetWithdrawCoinResult(self, data, reqID): def onGetWithdrawCoinResult(self, data, req, reqID):
"""查询提币结果回调""" """查询提币结果回调"""
print data print data
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onTransfer(self, data, reqID): def onTransfer(self, data, req, reqID):
"""转账回调""" """转账回调"""
print data print data
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onLoan(self, data, reqID): def onLoan(self, data, req, reqID):
"""申请杠杆回调""" """申请杠杆回调"""
print data print data
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onRepayment(self, data, reqID): def onRepayment(self, data, req, reqID):
"""归还杠杆回调""" """归还杠杆回调"""
print data print data
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onLoanAvailable(self, data, reqID): def onLoanAvailable(self, data, req, reqID):
"""查询杠杆额度回调""" """查询杠杆额度回调"""
print data print data
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onGetLoans(self, data, reqID): def onGetLoans(self, data, req, reqID):
"""查询杠杆列表""" """查询杠杆列表"""
print data print data
@ -558,7 +558,7 @@ class DataApi(object):
self.taskThread = Thread(target=self.run) # 处理任务的线程 self.taskThread = Thread(target=self.run) # 处理任务的线程
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def init(self, interval): def init(self, interval, debug):
"""初始化""" """初始化"""
self.taskInterval = interval self.taskInterval = interval
self.DEBUG = debug self.DEBUG = debug

View File

@ -1,6 +1,7 @@
{ {
"accessKey": "3f669293-60e6dd7f-8e39c295-5aae5", "accessKey": "火币网站申请",
"secretKey": "7050aec8-43fc680d-06471837-57e38", "secretKey": "火币网站申请",
"interval": 0.5, "interval": 0.5,
"market": "cny" "market": "cny",
"debug": false
} }

View File

@ -17,6 +17,35 @@ import vnhuobi
from vtGateway import * 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): class HuobiGateway(VtGateway):
"""火币接口""" """火币接口"""
@ -55,6 +84,7 @@ class HuobiGateway(VtGateway):
secretKey = str(setting['secretKey']) secretKey = str(setting['secretKey'])
interval = setting['interval'] interval = setting['interval']
market = setting['market'] market = setting['market']
debug = setting['debug']
except KeyError: except KeyError:
log = VtLogData() log = VtLogData()
log.gatewayName = self.gatewayName log.gatewayName = self.gatewayName
@ -63,15 +93,15 @@ class HuobiGateway(VtGateway):
return return
# 初始化接口 # 初始化接口
self.tradeApi.connect(accessKey, secretKey) self.tradeApi.connect(accessKey, secretKey, market, debug)
self.writeLog(u'交易接口初始化成功') self.writeLog(u'交易接口初始化成功')
self.dataApi.connect(interval) self.dataApi.connect(interval, market, debug)
self.writeLog(u'行情接口初始化成功') self.writeLog(u'行情接口初始化成功')
# 启动查询 # 启动查询
#self.initQuery() self.initQuery()
#self.startQuery() self.startQuery()
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def writeLog(self, content): def writeLog(self, content):
@ -89,12 +119,12 @@ class HuobiGateway(VtGateway):
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def sendOrder(self, orderReq): def sendOrder(self, orderReq):
"""发单""" """发单"""
pass self.tradeApi.sendOrder(orderReq)
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def cancelOrder(self, cancelOrderReq): def cancelOrder(self, cancelOrderReq):
"""撤单""" """撤单"""
pass self.tradeApi.cancel(cancelOrderReq)
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def qryAccount(self): def qryAccount(self):
@ -116,33 +146,15 @@ class HuobiGateway(VtGateway):
def initQuery(self): def initQuery(self):
"""初始化连续查询""" """初始化连续查询"""
if self.qryEnabled: if self.qryEnabled:
# 需要循环的查询函数列表 self.qryFunctionList = [self.tradeApi.queryWorkingOrders, self.tradeApi.queryAccount]
self.qryFunctionList = [self.qryAccount]
self.qryCount = 0 # 查询触发倒计时
self.qryTrigger = 2 # 查询触发点
self.qryNextFunction = 0 # 上次运行的查询函数索引
self.startQuery() self.startQuery()
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def query(self, event): def query(self, event):
"""注册到事件处理引擎上的查询函数""" """注册到事件处理引擎上的查询函数"""
self.qryCount += 1 for function in self.qryFunctionList:
if self.qryCount > self.qryTrigger:
# 清空倒计时
self.qryCount = 0
# 执行查询函数
function = self.qryFunctionList[self.qryNextFunction]
function() function()
# 计算下次查询函数的索引如果超过了列表长度则重新设为0
self.qryNextFunction += 1
if self.qryNextFunction == len(self.qryFunctionList):
self.qryNextFunction = 0
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def startQuery(self): def startQuery(self):
"""启动连续查询""" """启动连续查询"""
@ -166,8 +178,17 @@ class HuobiTradeApi(vnhuobi.TradeApi):
self.gateway = gateway self.gateway = gateway
self.gatewayName = gateway.gatewayName 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 = VtErrorData()
err.gatewayName = self.gatewayName err.gatewayName = self.gatewayName
@ -176,11 +197,13 @@ class HuobiTradeApi(vnhuobi.TradeApi):
self.gateway.onError(err) self.gateway.onError(err)
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onGetAccountInfo(self, data, reqID): def onGetAccountInfo(self, data, req, reqID):
"""查询账户回调""" """查询账户回调"""
# 推送账户数据 # 推送账户数据
account = VtAccountData() account = VtAccountData()
account.gatewayName = self.gatewayName account.gatewayName = self.gatewayName
account.accountID = 'HUOBI'
account.vtAccountID = '.'.join([account.accountID, self.gatewayName])
account.balance = data['net_asset'] account.balance = data['net_asset']
self.gateway.onAccount(account) self.gateway.onAccount(account)
@ -188,124 +211,327 @@ class HuobiTradeApi(vnhuobi.TradeApi):
if self.market == 'cny': if self.market == 'cny':
posCny = VtPositionData() posCny = VtPositionData()
posCny.gatewayName = self.gatewayName 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.position = data['available_cny_display']
posCny.frozen = data['frozen_cny_display'] posCny.frozen = data['frozen_cny_display']
self.gateway.onPosition(posCny) self.gateway.onPosition(posCny)
posLtc = VtPositionData() posLtc = VtPositionData()
posLtc.gatewayName = self.gatewayName 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.position = data['available_ltc_display']
posLtc.frozen = data['frozen_ltc_display'] posLtc.frozen = data['frozen_ltc_display']
self.gateway.onPosition(posLtc) self.gateway.onPosition(posLtc)
else: else:
posUsd = VtPositionData() posUsd = VtPositionData()
posUsd.gatewayName = self.gatewayName 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.position = data['available_usd_display']
posUsd.frozen = data['frozen_usd_display'] posUsd.frozen = data['frozen_usd_display']
self.gateway.onPosition(posUsd) self.gateway.onPosition(posUsd)
posBtc = VtPositionData() posBtc = VtPositionData()
posBtc.gatewayName = self.gatewayName 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.position = data['available_btc_display']
posBtc.frozen = data['frozen_btc_display'] posBtc.frozen = data['frozen_btc_display']
self.gateway.onPosition(posBtc) self.gateway.onPosition(posBtc)
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onGetOrders(self, data, reqID): def onGetOrders(self, data, req, reqID):
"""查询委托回调""" """查询委托回调"""
for d in data: for d in data:
order = VtOrderData() order = VtOrderData()
order.gatewayName = self.gatewayName order.gatewayName = self.gatewayName
order # 合约代码
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 onOrderInfo(self, data, reqID): def onOrderInfo(self, data, req, reqID):
"""委托详情回调""" """委托详情回调"""
print data 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, reqID): 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 print data
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onSellMarket(self, data, reqID): def onSellMarket(self, data, req, reqID):
"""市价卖出回调""" """市价卖出回调"""
print data 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 print data
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onGetOrderIdByTradeId(self, data, reqID): def onGetOrderIdByTradeId(self, data, req, reqID):
"""通过成交编号查询委托编号回调""" """通过成交编号查询委托编号回调"""
print data print data
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onWithdrawCoin(self, data, reqID): def onWithdrawCoin(self, data, req, reqID):
"""提币回调""" """提币回调"""
print data print data
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onCancelWithdrawCoin(self, data, reqID): def onCancelWithdrawCoin(self, data, req, reqID):
"""取消提币回调""" """取消提币回调"""
print data print data
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onGetWithdrawCoinResult(self, data, reqID): def onGetWithdrawCoinResult(self, data, req, reqID):
"""查询提币结果回调""" """查询提币结果回调"""
print data print data
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onTransfer(self, data, reqID): def onTransfer(self, data, req, reqID):
"""转账回调""" """转账回调"""
print data print data
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onLoan(self, data, reqID): def onLoan(self, data, req, reqID):
"""申请杠杆回调""" """申请杠杆回调"""
print data print data
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onRepayment(self, data, reqID): def onRepayment(self, data, req, reqID):
"""归还杠杆回调""" """归还杠杆回调"""
print data print data
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onLoanAvailable(self, data, reqID): def onLoanAvailable(self, data, req, reqID):
"""查询杠杆额度回调""" """查询杠杆额度回调"""
print data print data
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onGetLoans(self, data, reqID): def onGetLoans(self, data, req, reqID):
"""查询杠杆列表""" """查询杠杆列表"""
print data print data
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def connect(self, accessKey, secretKey, market): def connect(self, accessKey, secretKey, market, debug=False):
"""连接服务器""" """连接服务器"""
self.market = market self.market = market
self.DEBUG = debug
self.init(accessKey, secretKey) 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): class HuobiDataApi(vnhuobi.DataApi):
@ -316,7 +542,13 @@ class HuobiDataApi(vnhuobi.DataApi):
"""Constructor""" """Constructor"""
super(HuobiDataApi, self).__init__() super(HuobiDataApi, self).__init__()
self.market = 'cny'
self.gateway = gateway self.gateway = gateway
self.gatewayName = gateway.gatewayName
self.tickDict = {} # key:symbol, value:tick
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onTick(self, data): def onTick(self, data):
@ -326,20 +558,109 @@ class HuobiDataApi(vnhuobi.DataApi):
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onQuote(self, data): 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): 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)

View File

@ -119,7 +119,7 @@ class TradeApi(object):
# 发送请求 # 发送请求
payload = urllib.urlencode(params) 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: if r.status_code == 200:
data = r.json() data = r.json()
return data return data
@ -140,12 +140,12 @@ class TradeApi(object):
# 请求失败 # 请求失败
if 'code' in data and 'message' in data: if 'code' in data and 'message' in data:
error = u'错误信息:%s' %data['message'] error = u'错误信息:%s' %data['message']
self.onError(error, reqID) self.onError(error, req, reqID)
# 请求成功 # 请求成功
else: else:
if self.DEBUG: if self.DEBUG:
print callback.__name__ print callback.__name__
callback(data, reqID) callback(data, req, reqID)
except Empty: except Empty:
pass pass
@ -424,97 +424,97 @@ class TradeApi(object):
#################################################### ####################################################
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onError(self, error, reqID): def onError(self, error, req, reqID):
"""错误推送""" """错误推送"""
print error, reqID print error, reqID
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onGetAccountInfo(self, data, reqID): def onGetAccountInfo(self, data, req, reqID):
"""查询账户回调""" """查询账户回调"""
print data print data
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onGetOrders(self, data, reqID): def onGetOrders(self, data, req, reqID, fuck):
"""查询委托回调""" """查询委托回调"""
print data print data
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onOrderInfo(self, data, reqID): def onOrderInfo(self, data, req, reqID):
"""委托详情回调""" """委托详情回调"""
print data print data
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onBuy(self, data, reqID): def onBuy(self, data, req, reqID):
"""买入回调""" """买入回调"""
print data print data
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onSell(self, data, reqID): def onSell(self, data, req, reqID):
"""卖出回调""" """卖出回调"""
print data print data
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onBuyMarket(self, data, reqID): def onBuyMarket(self, data, req, reqID):
"""市价买入回调""" """市价买入回调"""
print data print data
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onSellMarket(self, data, reqID): def onSellMarket(self, data, req, reqID):
"""市价卖出回调""" """市价卖出回调"""
print data print data
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onCancelOrder(self, data, reqID): def onCancelOrder(self, data, req, reqID):
"""撤单回调""" """撤单回调"""
print data print data
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onGetNewDealOrders(self, data, reqID): def onGetNewDealOrders(self, data, req, reqID):
"""查询最新成交回调""" """查询最新成交回调"""
print data print data
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onGetOrderIdByTradeId(self, data, reqID): def onGetOrderIdByTradeId(self, data, req, reqID):
"""通过成交编号查询委托编号回调""" """通过成交编号查询委托编号回调"""
print data print data
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onWithdrawCoin(self, data, reqID): def onWithdrawCoin(self, data, req, reqID):
"""提币回调""" """提币回调"""
print data print data
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onCancelWithdrawCoin(self, data, reqID): def onCancelWithdrawCoin(self, data, req, reqID):
"""取消提币回调""" """取消提币回调"""
print data print data
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onGetWithdrawCoinResult(self, data, reqID): def onGetWithdrawCoinResult(self, data, req, reqID):
"""查询提币结果回调""" """查询提币结果回调"""
print data print data
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onTransfer(self, data, reqID): def onTransfer(self, data, req, reqID):
"""转账回调""" """转账回调"""
print data print data
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onLoan(self, data, reqID): def onLoan(self, data, req, reqID):
"""申请杠杆回调""" """申请杠杆回调"""
print data print data
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onRepayment(self, data, reqID): def onRepayment(self, data, req, reqID):
"""归还杠杆回调""" """归还杠杆回调"""
print data print data
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onLoanAvailable(self, data, reqID): def onLoanAvailable(self, data, req, reqID):
"""查询杠杆额度回调""" """查询杠杆额度回调"""
print data print data
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onGetLoans(self, data, reqID): def onGetLoans(self, data, req, reqID):
"""查询杠杆列表""" """查询杠杆列表"""
print data print data
@ -558,7 +558,7 @@ class DataApi(object):
self.taskThread = Thread(target=self.run) # 处理任务的线程 self.taskThread = Thread(target=self.run) # 处理任务的线程
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def init(self, interval): def init(self, interval, debug):
"""初始化""" """初始化"""
self.taskInterval = interval self.taskInterval = interval
self.DEBUG = debug self.DEBUG = debug

View File

@ -79,7 +79,9 @@ class MainWindow(QtGui.QMainWindow):
self.addConnectAction(sysMenu, 'IB') self.addConnectAction(sysMenu, 'IB')
self.addConnectAction(sysMenu, 'SHZD', u'直达') self.addConnectAction(sysMenu, 'SHZD', u'直达')
self.addConnectAction(sysMenu, 'OANDA') self.addConnectAction(sysMenu, 'OANDA')
sysMenu.addSeparator()
self.addConnectAction(sysMenu, 'OKCOIN') self.addConnectAction(sysMenu, 'OKCOIN')
self.addConnectAction(sysMenu, 'HUOBI', u'火币')
sysMenu.addSeparator() sysMenu.addSeparator()
self.addConnectAction(sysMenu, 'Wind') self.addConnectAction(sysMenu, 'Wind')

View File

@ -74,6 +74,7 @@ EXCHANGE_ICE = 'ICE' # ICE交易所
EXCHANGE_OANDA = 'OANDA' # OANDA外汇做市商 EXCHANGE_OANDA = 'OANDA' # OANDA外汇做市商
EXCHANGE_OKCOIN = 'OKCOIN' # OKCOIN比特币交易所 EXCHANGE_OKCOIN = 'OKCOIN' # OKCOIN比特币交易所
EXCHANGE_HUOBI = 'HUOBI' # 火币比特币交易所
# 货币类型 # 货币类型
CURRENCY_USD = 'USD' # 美元 CURRENCY_USD = 'USD' # 美元

View File

@ -147,6 +147,13 @@ class MainEngine(object):
except Exception, e: 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): def addGateway(self, gateway, gatewayName=None):
"""创建接口""" """创建接口"""