comment vnpy

This commit is contained in:
msincenselee 2015-11-15 15:53:54 +08:00
parent a69e8836d0
commit bdd35fb9d5
20 changed files with 747 additions and 577 deletions

2
.gitignore vendored
View File

@ -71,3 +71,5 @@ vn.strategy/strategydemo/strategy01.py
vn.strategy/strategydemo/strategy02.py
vn.trader/CTP_connect.json
*.vt
vn.trader/CTP_connect.json
vn.trader/CTP_connect.json

View File

@ -1,7 +1,8 @@
{
"brokerID": "8070",
"tdAddress": "tcp://180.168.214.246:41213",
"password": "154815",
"mdAddress": "tcp://180.168.214.246:41205",
"userID": "887733"
}
"brokerID":"9999",
"tdAddress":"tcp://180.168.146.187:10000",
"password":"jiajia",
"mdAddress":"tcp://180.168.146.187:10010",
"userID":"033513"
}

Binary file not shown.

View File

@ -17,7 +17,7 @@ from ctaStrategies import strategyClassDict
class StopOrder(object):
"""本地停止单"""
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def __init__(self):
"""Constructor"""
self.vtSymbol = EMPTY_STRING
@ -34,7 +34,7 @@ class StopOrder(object):
class CtaBarData(object):
"""K线数据"""
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def __init__(self):
"""Constructor"""
self.vtSymbol = EMPTY_STRING # vt系统代码
@ -58,7 +58,7 @@ class CtaBarData(object):
class CtaTickData(object):
"""Tick数据"""
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def __init__(self):
"""Constructor"""
self.vtSymbol = EMPTY_STRING # vt系统代码
@ -107,9 +107,11 @@ class CtaTickData(object):
########################################################################
class CtaEngine(object):
"""CTA策略引擎"""
# 策略配置文件
settingFileName = 'CTA_setting.json'
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def __init__(self, mainEngine, eventEngine, dataEngine):
"""Constructor"""
self.mainEngine = mainEngine
@ -137,29 +139,31 @@ class CtaEngine(object):
# key为stopOrderIDvalue为stopOrder对象
self.stopOrderDict = {} # 停止单撤销后不会从本字典中删除
self.workingStopOrderDict = {} # 停止单撤销后会从本字典中删除
# 注册事件监听
self.registerEvent()
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def sendOrder(self, vtSymbol, orderType, price, volume, strategy):
"""发单"""
# 1.查询合约对象
contract = self.dataEngine.getContract(vtSymbol)
# 2. 创建发单传入对象
req = VtOrderReq()
req.symbol = contract.symbol
req.exchange = contract.exchange
req.price = price
req.volume = volume
req.symbol = contract.symbol # 合约代码
req.exchange = contract.exchange # 交易所
req.price = price # 价格
req.volume = volume # 数量
# 设计为CTA引擎发出的委托只允许使用限价单
req.priceType = PRICETYPE_LIMITPRICE
req.priceType = PRICETYPE_LIMITPRICE # 价格类型
# CTA委托类型映射
if orderType == CTAORDER_BUY:
req.direction = DIRECTION_LONG
req.offset = OFFSET_OPEN
req.direction = DIRECTION_LONG # 合约方向
req.offset = OFFSET_OPEN # 开/平
elif orderType == CTAORDER_SELL:
req.direction = DIRECTION_SHORT
req.offset = OFFSET_CLOSE
@ -169,21 +173,24 @@ class CtaEngine(object):
elif orderType == CTAORDER_COVER:
req.direction = DIRECTION_LONG
req.offset = OFFSET_CLOSE
# 3.调用主引擎的发单接口进行发单保存OrderID与策略映射关系
vtOrderID = self.mainEngine.sendOrder(req) # 发单
self.orderDict[vtOrderID] = strategy # 保存vtOrderID和策略的映射关系
return vtOrderID
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def cancelOrder(self, vtOrderID):
"""撤单"""
# 查询报单对象
# 1.调用主引擎接口,查询委托单对象
order = self.dataEngine.getOrder(vtOrderID)
# 如果查询成功
if order:
# 检查是否报单还有效,只有有效时才发出撤单指令
orderFinished = (order.status==STATUS_ALLTRADED or order.status==STATUS_CANCELLED)
# 2.检查是否报单(委托单)还有效,只有有效时才发出撤单指令
orderFinished = (order.status == STATUS_ALLTRADED or order.status == STATUS_CANCELLED)
if not orderFinished:
req = VtCancelOrderReq()
req.symbol = order.symbol
@ -191,74 +198,104 @@ class CtaEngine(object):
req.frontID = order.frontID
req.sessionID = order.sessionID
req.orderID = order.orderID
self.mainEngine.cancelOrder(req, order.gatewayName)
#----------------------------------------------------------------------
self.mainEngine.cancelOrder(req, order.gatewayName)
else:
if order.status == STATUS_ALLTRADED:
self.writeCtaLog(u'委托单({0}已执行,无法撤销'.format(vtOrderID))
if order.status == STATUS_CANCELLED:
self.writeCtaLog(u'委托单({0}已撤销,无法再次撤销'.format(vtOrderID))
# 查询不成功
else:
self.writeCtaLog(u'委托单({0}不存在'.format(vtOrderID))
# ----------------------------------------------------------------------
def sendStopOrder(self, vtSymbol, orderType, price, volume, strategy):
"""发停止单(本地实现)"""
# 1.生成本地停止单ID
self.stopOrderCount += 1
stopOrderID = STOPORDERPREFIX + str(self.stopOrderCount)
# 2.创建停止单对象
so = StopOrder()
so.vtSymbol = vtSymbol
so.orderType = orderType
so.price = price
so.volume = volume
so.strategy = strategy
so.stopOrderID = stopOrderID
so.status = STOPORDER_WAITING
# 保存stopOrder对象到字典中
self.stopOrderDict[stopOrderID] = so
self.workingStopOrderDict[stopOrderID] = so
so.vtSymbol = vtSymbol # 代码
so.orderType = orderType # 停止单类型
so.price = price # 价格
so.volume = volume # 数量
so.strategy = strategy # 来源策略
so.stopOrderID = stopOrderID # Id
so.status = STOPORDER_WAITING # 状态
# 3.保存stopOrder对象到字典中
self.stopOrderDict[stopOrderID] = so # 字典中不会删除
self.workingStopOrderDict[stopOrderID] = so # 字典中会删除
self.writeCtaLog(u'发停止单成功,'
u'Id:{0},Symbol:{1},Type:{2},Price:{3},Volume:{4}'
u'.'.format(stopOrderID, vtSymbol, orderType, price, volume))
return stopOrderID
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def cancelStopOrder(self, stopOrderID):
"""撤销停止单"""
# 检查停止单是否存在
# 1.检查停止单是否存在
if stopOrderID in self.workingStopOrderDict:
so = self.workingStopOrderDict[stopOrderID]
so.status = STOPORDER_CANCELLED
del self.workingStopOrderDict[stopOrderID]
so.status = STOPORDER_CANCELLED # STOPORDER_WAITING =》STOPORDER_CANCELLED
del self.workingStopOrderDict[stopOrderID] # 删除
self.writeCtaLog(u'撤销停止单:{0}成功.'.format(stopOrderID))
else:
self.writeCtaLog(u'撤销停止单:{0}失败不存在Id.'.format(stopOrderID))
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def processStopOrder(self, tick):
"""收到行情后处理本地停止单(检查是否要立即发出)"""
vtSymbol = tick.vtSymbol
# 首先检查是否有策略交易该合约
# 1.首先检查是否有策略交易该合约
if vtSymbol in self.tickStrategyDict:
# 遍历等待中的停止单,检查是否会被触发
# 2.遍历等待中的停止单,检查是否会被触发
for so in self.workingStopOrderDict.values():
if so.vtSymbol == vtSymbol:
longTriggered = so.direction==DIRECTION_LONG and tick.lastPrice>=so.price # 多头停止单被触发
shortTriggered = so.direction==DIRECTION_SHORT and tick.lasatPrice<=so.price # 空头停止单被触发
# 3. 触发标识判断
longTriggered = so.direction == DIRECTION_LONG and tick.lastPrice >= so.price # 多头停止单被触发
shortTriggered = so.direction == DIRECTION_SHORT and tick.lasatPrice <= so.price # 空头停止单被触发
# 4.触发处理
if longTriggered or shortTriggered:
# 买入和卖出分别以涨停跌停价发单(模拟市价单)
if so.direction==DIRECTION_LONG:
# 5.设定价格,买入和卖出分别以涨停跌停价发单(模拟市价单)
if so.direction == DIRECTION_LONG:
price = tick.upperLimit
else:
price = tick.lowerLimit
# 6.更新停止单状态,触发
so.status = STOPORDER_TRIGGERED
# 7.发单
self.sendOrder(so.vtSymbol, so.orderType, price, so.volume, so.strategy)
# 8.删除停止单
del self.workingStopOrderDict[so.stopOrderID]
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def procecssTickEvent(self, event):
"""处理行情推送"""
"""处理行情推送事件"""
# 1. 获取事件的Tick数据
tick = event.dict_['data']
# 收到tick行情后先处理本地停止单检查是否要立即发出
# 2.收到tick行情后先处理本地停止单(检查是否要立即发出)
self.processStopOrder(tick)
# 推送tick到对应的策略对象进行处理
# 3.推送tick到对应的策略对象进行处理
if tick.vtSymbol in self.tickStrategyDict:
# 将vtTickData数据转化为ctaTickData
# 4.将vtTickData数据转化为ctaTickData
ctaTick = CtaTickData()
d = ctaTick.__dict__
for key in d.keys():
@ -266,52 +303,68 @@ class CtaEngine(object):
if key != 'datetime':
d[key] = tick.__getattribute__(key)
# 添加datetime字段
# 5.添加datetime字段
ctaTick.datetime = datetime.strptime(' '.join([tick.date, tick.time]), '%Y%m%d %H:%M:%S.%f')
# 逐个推送到策略对象中
l = self.tickStrategyDict[tick.vtSymbol]
for strategy in l:
strategy.onTick(tick)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def processOrderEvent(self, event):
"""处理委托推送"""
"""处理委托推送事件"""
# 1.获取事件的Order数据
order = event.dict_['data']
# 2.判断order是否在映射字典中
if order.vtOrderID in self.orderStrategyDict:
strategy = self.orderStrategyDict[order.vtOrderID]
# 3.提取对应的策略
strategy = self.orderStrategyDict[order.vtOrderID]
# 4.触发策略的委托推送事件方法
strategy.onOrder(order)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def processTradeEvent(self, event):
"""处理成交推送"""
trade = event.dict_['data']
"""处理成交推送事件"""
# 1.获取事件的Trade数据
trade = event.dict_['data']
# 2.判断Trade是否在映射字典中
if trade.vtOrderID in self.orderStrategyDict:
strategy = self.orderStrategyDict[order.vtOrderID]
# 3.提取对应的策略
strategy = self.orderStrategyDict[trade.vtOrderID]
# 4.触发策略的成交推送事件。
strategy.onTrade(trade)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def registerEvent(self):
"""注册事件监听"""
# 注册行情数据推送Tick数据到达的响应事件
self.eventEngine.register(EVENT_TICK, self.procecssTickEvent)
# 注册订单推送的响应事件
self.eventEngine.register(EVENT_ORDER, self.processOrderEvent)
# 注册成交推送(交易)的响应时间
self.eventEngine.register(EVENT_TRADE, self.processTradeEvent)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def insertData(self, dbName, collectionName, data):
"""插入数据到数据库这里的data可以是CtaTickData或者CtaBarData"""
self.mainEngine.dbInsert(dbName, collectionName, data.__dict__)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def loadBar(self, dbName, collectionName, startDate):
"""从数据库中读取Bar数据startDate是datetime对象"""
"""从数据库中读取Bar数据
startDate是datetime对象"""
d = {'datetime':{'$gte':startDate}}
cursor = self.mainEngine.dbQuery(dbName, collectionName, d)
@ -323,7 +376,7 @@ class CtaEngine(object):
return l
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def loadTick(self, dbName, collectionName, startDate):
"""从数据库中读取Tick数据startDate是datetime对象"""
d = {'datetime':{'$gte':startDate}}
@ -337,14 +390,14 @@ class CtaEngine(object):
return l
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def getToday(self):
"""获取代表今日的datetime对象"""
today = datetime.today()
today = today.replace(hour=0, minute=0, second=0, microsecond=0)
return today
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def writeCtaLog(self, content):
"""快速发出CTA模块日志事件"""
log = VtLogData()
@ -353,17 +406,17 @@ class CtaEngine(object):
event.dict_['data'] = log
self.eventEngine.put(event)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def initStrategy(self, name, strategyClass, paramDict=None):
"""初始化策略"""
# 防止策略重名
if name not in self.strategyDict:
# 创建策略对象
# 1.创建策略对象
strategy = strategyClass(self, name, paramDict)
self.strategyDict[name] = strategy
# 保存Tick映射关系
# 2.保存Tick映射关系symbol <==> Strategy[] )
if strategy.vtSymbol in self.tickStrategyDict:
l = self.tickStrategyDict[strategy.vtSymbol]
else:
@ -371,93 +424,136 @@ class CtaEngine(object):
self.tickStrategyDict[strategy.vtSymbol] = l
l.append(strategy)
# 订阅合约
# 3.订阅合约
contract = self.dataEngine.getContract(strategy.vtSymbol)
if contract:
# 4.构造订阅请求包
req = VtSubscribeReq()
req.symbol = contract.symbol
req.exchange = contract.exchange
# 5.调用主引擎的订阅接口
self.mainEngine.subscribe(req, contract.gatewayName)
else:
self.writeCtaLog(u'存在策略对象重名:' + name)
#---------------------------------------------------------------------
# ---------------------------------------------------------------------
def startStrategy(self, name):
"""启动策略"""
# 1.判断策略名称是否存在字典中
if name in self.strategyDict:
# 2.提取策略
strategy = self.strategyDict[name]
# 3.判断策略是否运行
if not strategy.trading:
# 4.设置运行状态
strategy.trading = True
# 5.启动策略
strategy.start()
else:
self.writeCtaLog(u'策略对象不存在:' + name)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def stopStrategy(self, name):
"""停止策略"""
"""停止策略运行"""
# 1.判断策略名称是否存在字典中
if name in self.strategyDict:
# 2.提取策略
strategy = self.strategyDict[name]
# 3.停止交易
if strategy.trading:
# 4.设置交易状态为False
strategy.trading = False
# 5.调用策略的停止方法
strategy.stop()
# 对该策略发出的所有限价单进行撤单
# 6.对该策略发出的所有限价单进行撤单
for vtOrderID, s in self.orderStrategyDict.items():
if s is strategy:
self.cancelOrder(vtOrderID)
# 对该策略发出的所有本地停止单撤单
# 7.对该策略发出的所有本地停止单撤单
for stopOrderID, so in self.workingStopOrderDict.items():
if so.strategy is strategy:
self.cancelStopOrder(stopOrderID)
else:
self.writeCtaLog(u'策略对象不存在:' + name)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def saveStrategySetting(self):
"""保存引擎中的策略配置"""
with open(self.settingFileName, 'w') as f:
d = {}
# 逐一循环name策略实例名称strategy策略
for name, strategy in self.strategyDict.items():
# 配置串
setting = {}
# 策略的类名称
setting['strategyClassName'] = strategy.strategyClassName
# 策略的参数
for param in strategy.paramList:
setting[param] = strategy.__getattribute__(param)
# 策略实例名,保存配置
d[name] = setting
# Json对象=》Json字符串
jsonD = json.dumps(d, indent=4)
# 保存文件
f.write(jsonD)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def loadStrategySetting(self):
"""读取引擎中的策略配置"""
with open(self.settingFileName) as f:
# 读取文件内容串=》Json对象
d = json.load(f)
# 策略实例名称,配置内容
for name, setting in d.items():
# 策略的类名称
strategyClassName = setting['strategyClassName']
if strategyClassName in strategyClassDict:
# 透过策略类字典,反射获取策略
strategyClass = strategyClassDict[strategyClassName]
# 初始化策略的设置
self.initStrategy(name, strategyClass, setting)
else:
self.writeCtaLog(u'无法找到策略类:' + strategyClassName)
break
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def getStrategyVar(self, name):
"""获取策略当前的变量字典"""
if name in self.strategyDict:
# 获取策略实例
strategy = self.strategyDict[name]
# 策略实例的所有属性
d = strategy.__dict__
# 变量字典
varDict = OrderedDict()
# 策略中的变量名称列表
for key in strategy.varList:
# 如果匹配就增加
if key in d:
varDict[key] = d[key]
@ -466,16 +562,23 @@ class CtaEngine(object):
self.writeCtaLog(u'策略对象不存在:' + name)
return None
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def getStrategyParam(self, name):
"""获取策略的参数字典"""
if name in self.strategyDict:
# 获取策略实例
strategy = self.strategyDict[name]
# 策略实例的所有属性
d = strategy.__dict__
# 参数字典
paramDict = OrderedDict()
# 策略内的参数名称列表
for key in strategy.paramList:
# 匹配的就添加
if key in d:
paramDict[key] = d[key]

View File

@ -2,6 +2,7 @@
'''
在本文件中引入所有希望在系统中使用的策略类
当作配置文件每次增加删除策略时需要维护此字典
'''
from ctaStrategyTemplate import TestStrategy

View File

@ -18,7 +18,7 @@ class CtaStrategyTemplate(object):
varList = ['trading']
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def __init__(self, ctaEngine, name, setting=None):
"""Constructor"""
self.ctaEngine = ctaEngine
@ -36,42 +36,42 @@ class CtaStrategyTemplate(object):
if setting:
self.setParam(setting)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def init(self):
"""初始化策略(必须由用户继承实现)"""
raise NotImplementedError
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def start(self):
"""启动策略(必须由用户继承实现)"""
raise NotImplementedError
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def stop(self):
"""停止策略(必须由用户继承实现)"""
raise NotImplementedError
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onTick(self, tick):
"""收到行情TICK推送必须由用户继承实现"""
raise NotImplementedError
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onOrder(self, order):
"""收到委托变化推送(必须由用户继承实现)"""
raise NotImplementedError
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onTrade(self, trade):
"""收到成交推送(必须由用户继承实现)"""
raise NotImplementedError
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onBar(self, bar):
"""收到Bar推送必须由用户继承实现"""
raise NotImplementedError
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def buy(self, price, volume, stop=False):
"""买开"""
# 如果stop为True则意味着发本地停止单
@ -84,7 +84,7 @@ class CtaStrategyTemplate(object):
else:
return None
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def sell(self, price, volume, stop=False):
"""卖平"""
# 如果stop为True则意味着发本地停止单
@ -97,7 +97,7 @@ class CtaStrategyTemplate(object):
else:
return None
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def short(self, price, volume, stop=False):
"""卖开"""
# 如果stop为True则意味着发本地停止单
@ -110,7 +110,7 @@ class CtaStrategyTemplate(object):
else:
return None
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def cover(self, price, volume, stop=False):
"""买平"""
if self.trading:
@ -123,7 +123,7 @@ class CtaStrategyTemplate(object):
else:
return None
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def cancelOrder(self, orderID):
"""撤单"""
if STOPORDERPREFIX in orderID:
@ -131,27 +131,27 @@ class CtaStrategyTemplate(object):
else:
self.ctaEngine.cancelOrder(orderID)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def insertTick(self, tick):
"""向数据库中插入tick数据"""
self.ctaEngine.insertData(self.tickDbName, self.vtSymbol, tick)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def insertBar(self, bar):
"""向数据库中插入bar数据"""
self.ctaEngine.insertData(self.barDbName, self.vtSymbol, bar)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def loadTick(self, startDate):
"""读取tick数据"""
return self.ctaEngine.loadTick(self.tickDbName, self.vtSymbol, startDate)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def loadBar(self, startDate):
"""读取bar数据"""
return self.ctaEngine.loadBar(self.barDbName, self.vtSymbol, startDate)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def setParam(self, setting):
"""设置参数"""
d = self.__dict__
@ -160,13 +160,13 @@ class CtaStrategyTemplate(object):
d[key] = setting[key]
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def getToday(self):
"""查询当前日期"""
return self.ctaEngine.getToday()
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def writeCtaLog(self, content):
"""记录CTA日志"""
self.ctaEngine.writeCtaLog(content)
@ -177,7 +177,7 @@ class CtaStrategyTemplate(object):
class TestStrategy(CtaStrategyTemplate):
"""测试策略"""
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def __init__(self, ctaEngine, name, setting=None):
"""Constructor"""
super(TestStrategy, self).__init__(ctaEngine, name, setting)
@ -195,38 +195,38 @@ class TestStrategy(CtaStrategyTemplate):
self.varList.append('pos')
self.varList.append('lastPrice')
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def init(self):
"""初始化策略(必须由用户继承实现)"""
self.writeCtaLog(u'测试策略%s初始化' %self.name)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def start(self):
"""启动策略(必须由用户继承实现)"""
self.writeCtaLog(u'测试策略%s启动' %self.name)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def stop(self):
"""停止策略(必须由用户继承实现)"""
self.writeCtaLog(u'测试策略%s停止' %self.name)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onTick(self, tick):
"""收到行情TICK推送必须由用户继承实现"""
self.writeCtaLog(u'测试策略%s收到Tick' %self.name)
self.lastPrice = tick.lastPrice
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onOrder(self, order):
"""收到委托变化推送(必须由用户继承实现)"""
self.writeCtaLog(u'onOrder不会被调用')
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onTrade(self, trade):
"""收到成交推送(必须由用户继承实现)"""
self.writeCtaLog(u'onTrade不会被调用')
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onBar(self, bar):
"""收到Bar推送必须由用户继承实现"""
self.writeCtaLog(u'测试策略%s收到Bar' %self.name)

View File

@ -2448,7 +2448,7 @@ typedefDict["TThostFtdcCloseStyleType"] = "string"
#//////////////////////////////////////////////////////////////////////
#TFtdcStatModeType是一个统计方式类型
#//////////////////////////////////////////////////////////////////////
#----
# ----
defineDict["THOST_FTDC_SM_Non"] = '0'
#按合约统计
defineDict["THOST_FTDC_SM_Instrument"] = '1'

View File

@ -62,7 +62,7 @@ posiDirectionMapReverse = {v:k for k,v in posiDirectionMap.items()}
class CtpGateway(VtGateway):
"""CTP接口"""
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def __init__(self, eventEngine, gatewayName='CTP'):
"""Constructor"""
super(CtpGateway, self).__init__(eventEngine, gatewayName)
@ -75,7 +75,7 @@ class CtpGateway(VtGateway):
self.qryEnabled = False # 是否要启动循环查询
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def connect(self):
"""连接"""
# 载入json文件
@ -111,32 +111,32 @@ class CtpGateway(VtGateway):
# 初始化并启动查询
self.initQuery()
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def subscribe(self, subscribeReq):
"""订阅行情"""
self.mdApi.subscribe(subscribeReq)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def sendOrder(self, orderReq):
"""发单"""
return self.tdApi.sendOrder(orderReq)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def cancelOrder(self, cancelOrderReq):
"""撤单"""
self.tdApi.cancelOrder(cancelOrderReq)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def getAccount(self):
"""查询账户资金"""
self.tdApi.getAccount()
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def getPosition(self):
"""查询持仓"""
self.tdApi.getPosition()
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def close(self):
"""关闭"""
if self.mdConnected:
@ -144,7 +144,7 @@ class CtpGateway(VtGateway):
if self.tdConnected:
self.tdApi.close()
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def initQuery(self):
"""初始化连续查询"""
if self.qryEnabled:
@ -157,7 +157,7 @@ class CtpGateway(VtGateway):
self.startQuery()
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def query(self, event):
"""注册到事件处理引擎上的查询函数"""
self.qryCount += 1
@ -175,12 +175,12 @@ class CtpGateway(VtGateway):
if self.qryNextFunction == len(self.qryFunctionList):
self.qryNextFunction = 0
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def startQuery(self):
"""启动连续查询"""
self.eventEngine.register(EVENT_TIMER, self.query)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def setQryEnabled(self, qryEnabled):
"""设置是否要启动循环查询"""
self.qryEnabled = qryEnabled
@ -191,7 +191,7 @@ class CtpGateway(VtGateway):
class CtpMdApi(MdApi):
"""CTP行情API实现"""
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def __init__(self, gateway):
"""Constructor"""
super(CtpMdApi, self).__init__()
@ -211,7 +211,7 @@ class CtpMdApi(MdApi):
self.brokerID = EMPTY_STRING # 经纪商代码
self.address = EMPTY_STRING # 服务器地址
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onFrontConnected(self):
"""服务器连接"""
self.connectionStatus = True
@ -222,7 +222,7 @@ class CtpMdApi(MdApi):
self.gateway.onLog(log)
self.login()
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onFrontDisconnected(self, n):
"""服务器断开"""
self.connectionStatus = False
@ -234,13 +234,13 @@ class CtpMdApi(MdApi):
log.logContent = u'行情服务器连接断开'
self.gateway.onLog(log)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onHeartBeatWarning(self, n):
"""心跳报警"""
# 因为API的心跳报警比较常被触发且与API工作关系不大因此选择忽略
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspError(self, error, n, last):
"""错误回报"""
err = VtErrorData()
@ -249,7 +249,7 @@ class CtpMdApi(MdApi):
err.errorMsg = error['ErrorMsg'].decode('gbk')
self.gateway.onError(err)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspUserLogin(self, data, error, n, last):
"""登陆回报"""
# 如果登录成功,推送日志信息
@ -274,7 +274,7 @@ class CtpMdApi(MdApi):
err.errorMsg = error['ErrorMsg'].decode('gbk')
self.gateway.onError(err)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspUserLogout(self, data, error, n, last):
"""登出回报"""
# 如果登出成功,推送日志信息
@ -295,19 +295,19 @@ class CtpMdApi(MdApi):
err.errorMsg = error['ErrorMsg'].decode('gbk')
self.gateway.onError(err)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspSubMarketData(self, data, error, n, last):
"""订阅合约回报"""
# 通常不在乎订阅错误,选择忽略
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspUnSubMarketData(self, data, error, n, last):
"""退订合约回报"""
# 同上
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRtnDepthMarketData(self, data):
"""行情推送"""
tick = VtTickData()
@ -339,22 +339,22 @@ class CtpMdApi(MdApi):
self.gateway.onTick(tick)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspSubForQuoteRsp(self, data, error, n, last):
"""订阅期权询价"""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspUnSubForQuoteRsp(self, data, error, n, last):
"""退订期权询价"""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRtnForQuoteRsp(self, data):
"""期权询价推送"""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def connect(self, userID, password, brokerID, address):
"""初始化连接"""
self.userID = userID # 账号
@ -381,7 +381,7 @@ class CtpMdApi(MdApi):
if not self.loginStatus:
self.login()
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def subscribe(self, subscribeReq):
"""订阅合约"""
# 这里的设计是,如果尚未登录就调用了订阅方法
@ -391,7 +391,7 @@ class CtpMdApi(MdApi):
self.subscribedSymbols.add(subscribeReq)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def login(self):
"""登录"""
# 如果填入了用户名密码等,则登录
@ -403,7 +403,7 @@ class CtpMdApi(MdApi):
self.reqID += 1
self.reqUserLogin(req, self.reqID)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def close(self):
"""关闭"""
self.exit()
@ -413,7 +413,7 @@ class CtpMdApi(MdApi):
class CtpTdApi(TdApi):
"""CTP交易API实现"""
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def __init__(self, gateway):
"""API对象的初始化函数"""
super(CtpTdApi, self).__init__()
@ -435,7 +435,7 @@ class CtpTdApi(TdApi):
self.frontID = EMPTY_INT # 前置机编号
self.sessionID = EMPTY_INT # 会话编号
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onFrontConnected(self):
"""服务器连接"""
self.connectionStatus = True
@ -447,7 +447,7 @@ class CtpTdApi(TdApi):
self.login()
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onFrontDisconnected(self, n):
"""服务器断开"""
self.connectionStatus = False
@ -459,17 +459,17 @@ class CtpTdApi(TdApi):
log.logContent = u'交易服务器连接断开'
self.gateway.onLog(log)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onHeartBeatWarning(self, n):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspAuthenticate(self, data, error, n, last):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspUserLogin(self, data, error, n, last):
"""登陆回报"""
# 如果登录成功,推送日志信息
@ -498,8 +498,9 @@ class CtpTdApi(TdApi):
err.errorID = error['ErrorID']
err.errorMsg = error['ErrorMsg'].decode('gbk')
self.gateway.onError(err)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspUserLogout(self, data, error, n, last):
"""登出回报"""
# 如果登出成功,推送日志信息
@ -520,17 +521,17 @@ class CtpTdApi(TdApi):
err.errorMsg = error['ErrorMsg'].decode('gbk')
self.gateway.onError(err)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspUserPasswordUpdate(self, data, error, n, last):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspTradingAccountPasswordUpdate(self, data, error, n, last):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspOrderInsert(self, data, error, n, last):
"""发单错误(柜台)"""
err = VtErrorData()
@ -539,17 +540,17 @@ class CtpTdApi(TdApi):
err.errorMsg = error['ErrorMsg'].decode('gbk')
self.gateway.onError(err)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspParkedOrderInsert(self, data, error, n, last):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspParkedOrderAction(self, data, error, n, last):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspOrderAction(self, data, error, n, last):
"""撤单错误(柜台)"""
err = VtErrorData()
@ -558,12 +559,12 @@ class CtpTdApi(TdApi):
err.errorMsg = error['ErrorMsg'].decode('gbk')
self.gateway.onError(err)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspQueryMaxOrderVolume(self, data, error, n, last):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspSettlementInfoConfirm(self, data, error, n, last):
"""确认结算信息回报"""
log = VtLogData()
@ -575,52 +576,52 @@ class CtpTdApi(TdApi):
self.reqID += 1
self.reqQryInstrument({}, self.reqID)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspRemoveParkedOrder(self, data, error, n, last):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspRemoveParkedOrderAction(self, data, error, n, last):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspExecOrderInsert(self, data, error, n, last):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspExecOrderAction(self, data, error, n, last):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspForQuoteInsert(self, data, error, n, last):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspQuoteInsert(self, data, error, n, last):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspQuoteAction(self, data, error, n, last):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspQryOrder(self, data, error, n, last):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspQryTrade(self, data, error, n, last):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspQryInvestorPosition(self, data, error, n, last):
"""持仓查询回报"""
pos = VtPositionData()
@ -650,7 +651,7 @@ class CtpTdApi(TdApi):
# 推送
self.gateway.onPosition(pos)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspQryTradingAccount(self, data, error, n, last):
"""资金账户查询回报"""
account = VtAccountData()
@ -677,37 +678,37 @@ class CtpTdApi(TdApi):
# 推送
self.gateway.onAccount(account)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspQryInvestor(self, data, error, n, last):
"""投资者查询回报"""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspQryTradingCode(self, data, error, n, last):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspQryInstrumentMarginRate(self, data, error, n, last):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspQryInstrumentCommissionRate(self, data, error, n, last):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspQryExchange(self, data, error, n, last):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspQryProduct(self, data, error, n, last):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspQryInstrument(self, data, error, n, last):
"""合约查询回报"""
contract = VtContractData()
@ -749,112 +750,114 @@ class CtpTdApi(TdApi):
log.logContent = u'交易合约信息获取完成'
self.gateway.onLog(log)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspQryDepthMarketData(self, data, error, n, last):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspQrySettlementInfo(self, data, error, n, last):
"""查询结算信息回报"""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspQryTransferBank(self, data, error, n, last):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspQryInvestorPositionDetail(self, data, error, n, last):
""""""
"""投资者持仓详细查询应答。
当客户端发出投资者持仓查询指令后后交易托管系统返回响应时该方法会被调用
"""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspQryNotice(self, data, error, n, last):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspQrySettlementInfoConfirm(self, data, error, n, last):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspQryInvestorPositionCombineDetail(self, data, error, n, last):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspQryCFMMCTradingAccountKey(self, data, error, n, last):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspQryEWarrantOffset(self, data, error, n, last):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspQryInvestorProductGroupMargin(self, data, error, n, last):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspQryExchangeMarginRate(self, data, error, n, last):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspQryExchangeMarginRateAdjust(self, data, error, n, last):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspQryExchangeRate(self, data, error, n, last):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspQrySecAgentACIDMap(self, data, error, n, last):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspQryOptionInstrTradeCost(self, data, error, n, last):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspQryOptionInstrCommRate(self, data, error, n, last):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspQryExecOrder(self, data, error, n, last):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspQryForQuote(self, data, error, n, last):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspQryQuote(self, data, error, n, last):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspQryTransferSerial(self, data, error, n, last):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspQryAccountregister(self, data, error, n, last):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspError(self, error, n, last):
"""错误回报"""
err = VtErrorData()
@ -863,7 +866,7 @@ class CtpTdApi(TdApi):
err.errorMsg = error['ErrorMsg'].decode('gbk')
self.gateway.onError(err)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRtnOrder(self, data):
"""报单回报"""
# 更新最大报单编号
@ -927,7 +930,7 @@ class CtpTdApi(TdApi):
# 推送
self.gateway.onOrder(order)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRtnTrade(self, data):
"""成交回报"""
# 创建报单数据对象
@ -959,7 +962,7 @@ class CtpTdApi(TdApi):
# 推送
self.gateway.onTrade(trade)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onErrRtnOrderInsert(self, data, error):
"""发单错误回报(交易所)"""
err = VtErrorData()
@ -968,7 +971,7 @@ class CtpTdApi(TdApi):
err.errorMsg = error['ErrorMsg'].decode('gbk')
self.gateway.onError(err)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onErrRtnOrderAction(self, data, error):
"""撤单错误回报(交易所)"""
err = VtErrorData()
@ -977,202 +980,202 @@ class CtpTdApi(TdApi):
err.errorMsg = error['ErrorMsg'].decode('gbk')
self.gateway.onError(err)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRtnInstrumentStatus(self, data):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRtnTradingNotice(self, data):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRtnErrorConditionalOrder(self, data):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRtnExecOrder(self, data):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onErrRtnExecOrderInsert(self, data, error):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onErrRtnExecOrderAction(self, data, error):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onErrRtnForQuoteInsert(self, data, error):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRtnQuote(self, data):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onErrRtnQuoteInsert(self, data, error):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onErrRtnQuoteAction(self, data, error):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRtnForQuoteRsp(self, data):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspQryContractBank(self, data, error, n, last):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspQryParkedOrder(self, data, error, n, last):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspQryParkedOrderAction(self, data, error, n, last):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspQryTradingNotice(self, data, error, n, last):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspQryBrokerTradingParams(self, data, error, n, last):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspQryBrokerTradingAlgos(self, data, error, n, last):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRtnFromBankToFutureByBank(self, data):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRtnFromFutureToBankByBank(self, data):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRtnRepealFromBankToFutureByBank(self, data):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRtnRepealFromFutureToBankByBank(self, data):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRtnFromBankToFutureByFuture(self, data):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRtnFromFutureToBankByFuture(self, data):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRtnRepealFromBankToFutureByFutureManual(self, data):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRtnRepealFromFutureToBankByFutureManual(self, data):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRtnQueryBankBalanceByFuture(self, data):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onErrRtnBankToFutureByFuture(self, data, error):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onErrRtnFutureToBankByFuture(self, data, error):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onErrRtnRepealBankToFutureByFutureManual(self, data, error):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onErrRtnRepealFutureToBankByFutureManual(self, data, error):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onErrRtnQueryBankBalanceByFuture(self, data, error):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRtnRepealFromBankToFutureByFuture(self, data):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRtnRepealFromFutureToBankByFuture(self, data):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspFromBankToFutureByFuture(self, data, error, n, last):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspFromFutureToBankByFuture(self, data, error, n, last):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspQueryBankAccountMoneyByFuture(self, data, error, n, last):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRtnOpenAccountByBank(self, data):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRtnCancelAccountByBank(self, data):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRtnChangeAccountByBank(self, data):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def connect(self, userID, password, brokerID, address):
"""初始化连接"""
self.userID = userID # 账号
@ -1199,7 +1202,7 @@ class CtpTdApi(TdApi):
if not self.loginStatus:
self.login()
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def login(self):
"""连接服务器"""
# 如果填入了用户名密码等,则登录
@ -1211,13 +1214,13 @@ class CtpTdApi(TdApi):
self.reqID += 1
self.reqUserLogin(req, self.reqID)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def getAccount(self):
"""查询账户"""
self.reqID += 1
self.reqQryTradingAccount({}, self.reqID)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def getPosition(self):
"""查询持仓"""
self.reqID += 1
@ -1226,7 +1229,7 @@ class CtpTdApi(TdApi):
req['InvestorID'] = self.userID
self.reqQryInvestorPosition(req, self.reqID)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def sendOrder(self, orderReq):
"""发单"""
self.reqID += 1
@ -1265,7 +1268,7 @@ class CtpTdApi(TdApi):
vtOrderID = '.'.join([self.gatewayName, str(self.orderRef)])
return vtOrderID
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def cancelOrder(self, cancelOrderReq):
"""撤单"""
self.reqID += 1
@ -1284,13 +1287,13 @@ class CtpTdApi(TdApi):
self.reqOrderAction(req, self.reqID)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def close(self):
"""关闭"""
self.exit()
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def test():
"""测试"""
from PyQt4 import QtCore

View File

@ -49,7 +49,7 @@ class EventEngine:
"""
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def __init__(self):
"""初始化事件引擎"""
# 事件队列
@ -69,7 +69,7 @@ class EventEngine:
# 其中每个键对应的值是一个列表,列表中保存了对该事件进行监听的函数功能
self.__handlers = {}
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def __run(self):
"""引擎运行"""
while self.__active == True:
@ -79,7 +79,7 @@ class EventEngine:
except Empty:
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def __process(self, event):
"""处理事件"""
# 检查是否存在对该事件进行监听的处理函数
@ -91,7 +91,7 @@ class EventEngine:
#for handler in self.__handlers[event.type_]:
#handler(event)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def __onTimer(self):
"""向事件队列中存入计时器事件"""
# 创建计时器事件
@ -100,7 +100,7 @@ class EventEngine:
# 向队列中存入计时器事件
self.put(event)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def start(self):
"""引擎启动"""
# 将引擎设为启动
@ -112,7 +112,7 @@ class EventEngine:
# 启动计时器计时器事件间隔默认设定为1秒
self.__timer.start(1000)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def stop(self):
"""停止引擎"""
# 将引擎设为停止
@ -124,7 +124,7 @@ class EventEngine:
# 等待事件处理线程退出
self.__thread.join()
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def register(self, type_, handler):
"""注册事件处理函数监听"""
# 尝试获取该事件类型对应的处理函数列表,若无则创建
@ -138,7 +138,7 @@ class EventEngine:
if handler not in handlerList:
handlerList.append(handler)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def unregister(self, type_, handler):
"""注销事件处理函数监听"""
# 尝试获取该事件类型对应的处理函数列表,若无则忽略该次注销请求
@ -155,7 +155,7 @@ class EventEngine:
except KeyError:
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def put(self, event):
"""向事件队列中存入事件"""
self.__queue.put(event)
@ -165,14 +165,14 @@ class EventEngine:
class Event:
"""事件对象"""
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def __init__(self, type_=None):
"""Constructor"""
self.type_ = type_ # 事件类型
self.dict_ = {} # 字典用于保存具体的事件数据
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def test():
"""测试函数"""
import sys

View File

@ -31,7 +31,7 @@ EVENT_CTA_LOG = 'eCtaLog' # CTA相关的日志事件
EVENT_WIND_CONNECTREQ = 'eWindConnectReq' # Wind接口请求连接事件
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def test():
"""检查是否存在内容重复的常量定义"""
check_dict = {}

View File

@ -105,7 +105,7 @@ accountKeyMap['MaintMarginReq'] = 'margin'
class IbGateway(VtGateway):
"""IB接口"""
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def __init__(self, eventEngine, gatewayName='IB'):
"""Constructor"""
super(IbGateway, self).__init__(eventEngine, gatewayName)
@ -127,7 +127,7 @@ class IbGateway(VtGateway):
self.wrapper = IbWrapper(self) # 回调接口
self.connection = EClientSocket(self.wrapper) # 主动接口
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def connect(self):
"""连接"""
# 载入json文件
@ -163,7 +163,7 @@ class IbGateway(VtGateway):
# 请求账户数据主推更新
self.connection.reqAccountUpdates(True, '')
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def subscribe(self, subscribeReq):
"""订阅行情"""
# 订阅行情
@ -188,7 +188,7 @@ class IbGateway(VtGateway):
tick.gatewayName = self.gatewayName
self.tickDict[self.tickerId] = tick
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def sendOrder(self, orderReq):
"""发单"""
# 增加报单号1最后再次进行查询
@ -222,12 +222,12 @@ class IbGateway(VtGateway):
# 查询下一个有效编号
self.connection.reqIds(1)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def cancelOrder(self, cancelOrderReq):
"""撤单"""
self.connection.cancelOrder(cancelOrderReq.orderID)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def getAccount(self):
"""查询账户资金"""
log = VtLogData()
@ -235,7 +235,7 @@ class IbGateway(VtGateway):
log.logContent = u'IB接口账户信息提供主推更新无需查询'
self.onLog(log)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def getPosition(self):
"""查询持仓"""
log = VtLogData()
@ -243,7 +243,7 @@ class IbGateway(VtGateway):
log.logContent = u'IB接口持仓信息提供主推更新无需查询'
self.onLog(log)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def close(self):
"""关闭"""
self.connection.eDisconnect()
@ -253,7 +253,7 @@ class IbGateway(VtGateway):
class IbWrapper(EWrapper):
"""IB回调接口的实现"""
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def __init__(self, gateway):
"""Constructor"""
super(IbWrapper, self).__init__()
@ -267,7 +267,7 @@ class IbWrapper(EWrapper):
self.orderDict = gateway.orderDict # order字典
self.accountDict = gateway.accountDict # account字典
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def tickPrice(self, tickerId, field, price, canAutoExecute):
"""行情推送(价格相关)"""
if field in tickFieldMap:
@ -277,7 +277,7 @@ class IbWrapper(EWrapper):
else:
print field
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def tickSize(self, tickerId, field, size):
"""行情推送(量相关)"""
if field in tickFieldMap:
@ -287,17 +287,17 @@ class IbWrapper(EWrapper):
else:
print field
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def tickOptionComputation(self, tickerId, field, impliedVol, delta, optPrice, pvDividend, gamma, vega, theta, undPrice):
"""行情推送(期权数值)"""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def tickGeneric(self, tickerId, tickType, value):
"""行情推送(某些通用字段)"""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def tickString(self, tickerId, tickType, value):
"""行情推送,特殊字段相关"""
if tickType == 45:
@ -312,12 +312,12 @@ class IbWrapper(EWrapper):
newtick = copy(tick)
self.gateway.onTick(newtick)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def tickEFP(self, tickerId, tickType, basisPoints, formattedBasisPoints, impliedFuture, holdDays, futureExpiry, dividendImpact, dividendsToExpiry):
"""行情推送(合约属性相关)"""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def orderStatus(self, orderId, status, filled, remaining, avgFillPrice, permId, parentId, lastFillPrice, clientId, whyHeld):
"""报单成交回报"""
pass
@ -338,7 +338,7 @@ class IbWrapper(EWrapper):
newod = copy(od)
self.gateway.onOrder(newod)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def openOrder(self, orderId, contract, order, orderState):
"""报单信息推送"""
orderId = str(orderId) # orderId是整数
@ -362,12 +362,12 @@ class IbWrapper(EWrapper):
newod = copy(od)
self.gateway.onOrder(newod)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def openOrderEnd(self):
""" generated source for method openOrderEnd """
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def updateAccountValue(self, key, value, currency, accountName):
"""更新账户数据"""
# 仅逐个字段更新数据这里对于没有currency的推送忽略
@ -387,7 +387,7 @@ class IbWrapper(EWrapper):
k = accountKeyMap[key]
account.__setattr__(k, float(value))
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def updatePortfolio(self, contract, position, marketPrice, marketValue, averageCost, unrealizedPNL, realizedPNL, accountName):
"""持仓更新推送"""
pos = VtPositionData()
@ -403,7 +403,7 @@ class IbWrapper(EWrapper):
self.gateway.onPosition(pos)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def updateAccountTime(self, timeStamp):
"""更新账户数据的时间"""
# 推送数据
@ -411,31 +411,31 @@ class IbWrapper(EWrapper):
newaccount = copy(account)
self.gateway.onAccount(newaccount)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def accountDownloadEnd(self, accountName):
""" generated source for method accountDownloadEnd """
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def nextValidId(self, orderId):
"""下一个有效报单编号更新"""
self.gateway.orderId = orderId
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def contractDetails(self, reqId, contractDetails):
""" generated source for method contractDetails """
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def bondContractDetails(self, reqId, contractDetails):
""" generated source for method bondContractDetails """
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def contractDetailsEnd(self, reqId):
""" generated source for method contractDetailsEnd """
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def execDetails(self, reqId, contract, execution):
"""成交推送"""
trade = VtTradeData()
@ -455,62 +455,62 @@ class IbWrapper(EWrapper):
self.gateway.onTrade(trade)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def execDetailsEnd(self, reqId):
""" generated source for method execDetailsEnd """
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def updateMktDepth(self, tickerId, position, operation, side, price, size):
""" generated source for method updateMktDepth """
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def updateMktDepthL2(self, tickerId, position, marketMaker, operation, side, price, size):
""" generated source for method updateMktDepthL2 """
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def updateNewsBulletin(self, msgId, msgType, message, origExchange):
""" generated source for method updateNewsBulletin """
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def managedAccounts(self, accountsList):
""" generated source for method managedAccounts """
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def receiveFA(self, faDataType, xml):
""" generated source for method receiveFA """
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def historicalData(self, reqId, date, open, high, low, close, volume, count, WAP, hasGaps):
""" generated source for method historicalData """
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def scannerParameters(self, xml):
""" generated source for method scannerParameters """
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def scannerData(self, reqId, rank, contractDetails, distance, benchmark, projection, legsStr):
''' generated source for method scannerData '''
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def scannerDataEnd(self, reqId):
""" generated source for method scannerDataEnd """
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def realtimeBar(self, reqId, time, open, high, low, close, volume, wap, count):
""" generated source for method realtimeBar """
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def currentTime(self, time):
""" generated source for method currentTime """
t = strftime('%H:%M:%S', localtime(time))
@ -523,52 +523,52 @@ class IbWrapper(EWrapper):
log.logContent = (u'IB接口连接成功当前服务器时间%s' %t)
self.gateway.onLog(log)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def fundamentalData(self, reqId, data):
""" generated source for method fundamentalData """
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def deltaNeutralValidation(self, reqId, underComp):
""" generated source for method deltaNeutralValidation """
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def tickSnapshotEnd(self, reqId):
""" generated source for method tickSnapshotEnd """
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def marketDataType(self, reqId, marketDataType):
""" generated source for method marketDataType """
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def commissionReport(self, commissionReport):
""" generated source for method commissionReport """
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def position(self, account, contract, pos, avgCost):
""" generated source for method position """
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def positionEnd(self):
""" generated source for method positionEnd """
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def accountSummary(self, reqId, account, tag, value, currency):
""" generated source for method accountSummary """
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def accountSummaryEnd(self, reqId):
""" generated source for method accountSummaryEnd """
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def error(self, id=None, errorCode=None, errorMsg=None):
"""错误回报"""
err = VtErrorData()
@ -577,7 +577,7 @@ class IbWrapper(EWrapper):
err.errorMsg = errorMsg
self.gateway.onError(err)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def error_0(self, strval=None):
"""错误回报(单一字符串)"""
err = VtErrorData()
@ -585,7 +585,7 @@ class IbWrapper(EWrapper):
err.errorMsg = strval
self.gateway.onError(err)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def error_1(self, id=None, errorCode=None, errorMsg=None):
"""错误回报(字符串和代码)"""
err = VtErrorData()
@ -594,7 +594,7 @@ class IbWrapper(EWrapper):
err.errorMsg = errorMsg
self.gateway.onError(err)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def connectionClosed(self):
"""连接断开"""
self.connectionStatus = False

View File

@ -55,7 +55,7 @@ posiDirectionMapReverse = {v:k for k,v in posiDirectionMap.items()}
class LtsGateway(VtGateway):
"""Lts接口"""
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def __init__(self, eventEngine, gatewayName='LTS'):
"""Constructor"""
super(LtsGateway, self).__init__(eventEngine, gatewayName)
@ -70,7 +70,7 @@ class LtsGateway(VtGateway):
self.qryEnabled = False # 是否要启动循环查询
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def connect(self):
"""连接"""
# 载入json 文件
@ -112,32 +112,32 @@ class LtsGateway(VtGateway):
self.initQuery()
self.startQuery()
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def subscribe(self, subscribeReq):
"""订阅行情"""
self.mdApi.subscribe(subscribeReq)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def sendOrder(self, orderReq):
"""发单"""
return self.tdApi.sendOrder(orderReq)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def cancelOrder(self, cancelOrderReq):
"""撤单"""
self.tdApi.cancelOrder(cancelOrderReq)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def getAccount(self):
"""查询账户资金"""
self.qryApi.getAccount()
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def getPosition(self):
"""查询持仓"""
self.qryApi.getPosition()
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def close(self):
"""关闭"""
if self.mdConnected:
@ -147,7 +147,7 @@ class LtsGateway(VtGateway):
if self.qryConnected:
self.qryApi.close()
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def initQuery(self):
"""初始化连续查询"""
if self.qryEnabled:
@ -160,7 +160,7 @@ class LtsGateway(VtGateway):
self.startQuery()
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def query(self, event):
"""注册到事件处理引擎上的查询函数"""
self.qryCount += 1
@ -178,12 +178,12 @@ class LtsGateway(VtGateway):
if self.qryNextFunction == len(self.qryFunctionList):
self.qryNextFunction = 0
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def startQuery(self):
"""启动连续查询"""
self.eventEngine.register(EVENT_TIMER, self.query)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def setQryEnabled(self, qryEnabled):
"""设置是否要启动循环查询"""
self.qryEnabled = qryEnabled
@ -193,7 +193,7 @@ class LtsGateway(VtGateway):
class LtsMdApi(MdApi):
"""Lts行情API实现"""
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def __init__(self, gateway):
"""Constructor"""
super(LtsMdApi, self).__init__()
@ -213,7 +213,7 @@ class LtsMdApi(MdApi):
self.brokerID = EMPTY_STRING # 经纪商代码
self.address = EMPTY_STRING # 服务器地址
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onFrontConnected(self):
"""服务器连接"""
self.connectionStatus = True
@ -224,7 +224,7 @@ class LtsMdApi(MdApi):
self.gateway.onLog(log)
self.login()
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onFrontDisconnected(self,n):
"""服务器断开"""
self.connectionStatus= False
@ -236,12 +236,12 @@ class LtsMdApi(MdApi):
log.logContent = u'行情服务器连接断开'
self.gateway.onLog(log)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onHeartBeatWarning(self, n):
"""心跳报警"""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspError(self,error,n,last):
"""错误回报"""
err = VtErrorData()
@ -250,7 +250,7 @@ class LtsMdApi(MdApi):
err.errorMsg = error['ErrorMsg'].decode('gbk')
self.gateway.onError(err)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspUserLogin(self, data, error, n, last):
"""登陆回报"""
# 如果登录成功,推送日志信息
@ -275,7 +275,7 @@ class LtsMdApi(MdApi):
err.errorMsg = error['ErrorMsg'].decode('gbk')
self.gateway.onError(err)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspUserLogout(self, data, error, n, last):
"""登出回报"""
# 如果登出成功,推送日志信息
@ -296,19 +296,19 @@ class LtsMdApi(MdApi):
err.errorMsg = error['ErrorMsg'].decode('gbk')
self.gateway.onError(err)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspSubMarketData(self, data, error, n, last):
"""订阅合约回报"""
# 通常不在乎订阅错误,选择忽略
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspUnSubMarketData(self, data, error, n, last):
"""退订合约回报"""
# 同上
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRtnDepthMarketData(self, data):
"""行情推送"""
tick = VtTickData()
@ -360,7 +360,7 @@ class LtsMdApi(MdApi):
self.gateway.onTick(tick)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def connect(self, userID, password, brokerID, address):
"""初始化连接"""
self.userID = userID # 账号
@ -387,7 +387,7 @@ class LtsMdApi(MdApi):
if not self.loginStatus:
self.login()
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def subscribe(self, subscribeReq):
"""订阅合约"""
req = {}
@ -403,7 +403,7 @@ class LtsMdApi(MdApi):
self.subscribedSymbols.add(subscribeReq)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def login(self):
"""登录"""
# 如果填入了用户名密码等,则登录
@ -415,7 +415,7 @@ class LtsMdApi(MdApi):
self.reqID += 1
self.reqUserLogin(req, self.reqID)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def close(self):
"""关闭"""
self.exit()
@ -425,7 +425,7 @@ class LtsMdApi(MdApi):
class LtsTdApi(TdApi):
"""LTS交易API实现"""
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def __init__(self, gateway):
"""API对象的初始化函数"""
super(LtsTdApi, self).__init__()
@ -450,7 +450,7 @@ class LtsTdApi(TdApi):
self.frontID = EMPTY_INT # 前置机编号
self.sessionID = EMPTY_INT # 会话编号
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onFrontConnected(self):
"""服务器连接"""
self.connectionStatus = True
@ -464,7 +464,7 @@ class LtsTdApi(TdApi):
self.reqID += 1
self.reqFetchAuthRandCode({}, self.reqID)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onFrontDisconnected(self, n):
"""服务器断开"""
self.connectionStatus = False
@ -476,12 +476,12 @@ class LtsTdApi(TdApi):
log.logContent = u'交易服务器连接断开'
self.gateway.onLog(log)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onHeartBeatWarning(self, n):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspUserLogin(self, data, error, n, last):
"""登陆回报"""
# 如果登录成功,推送日志信息
@ -504,7 +504,7 @@ class LtsTdApi(TdApi):
err.errorMsg = error['ErrorMsg'].decode('gbk')
self.gateway.onError(err)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspUserLogout(self, data, error, n, last):
"""登出回报"""
# 如果登出成功,推送日志信息
@ -525,23 +525,23 @@ class LtsTdApi(TdApi):
err.errorMsg = error['ErrorMsg'].decode('gbk')
self.gateway.onError(err)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspFetchAuthRandCode(self, data, error, n, last):
"""请求随机认证码"""
self.randCode = data['RandCode']
self.login()
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspUserPasswordUpdate(self, data, error, n, last):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspTradingAccountPasswordUpdate(self, data, error, n, last):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspOrderInsert(self, data, error, n, last):
"""发单错误(柜台)"""
err = VtErrorData()
@ -550,7 +550,7 @@ class LtsTdApi(TdApi):
err.errorMsg = error['ErrorMsg'].decode('gbk')
self.gateway.onError(err)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspOrderAction(self, data, error, n, last):
"""撤单错误(柜台)"""
err = VtErrorData()
@ -559,7 +559,7 @@ class LtsTdApi(TdApi):
err.errorMsg = error['ErrorMsg'].decode('gbk')
self.gateway.onError(err)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspError(self, error, n, last):
"""错误回报"""
err = VtErrorData()
@ -568,7 +568,7 @@ class LtsTdApi(TdApi):
err.errorMsg = error['ErrorMsg'].decode('gbk')
self.gateway.onError(err)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRtnOrder(self, data):
"""报单回报"""
@ -630,7 +630,7 @@ class LtsTdApi(TdApi):
# 推送
self.gateway.onOrder(order)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRtnTrade(self, data):
"""成交回报"""
# 创建报单数据对象
@ -662,7 +662,7 @@ class LtsTdApi(TdApi):
# 推送
self.gateway.onTrade(trade)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onErrRtnOrderInsert(self, data, error):
"""发单错误回报(交易所)"""
@ -676,7 +676,7 @@ class LtsTdApi(TdApi):
err.errorMsg = error['ErrorMsg'].decode('gbk')
self.gateway.onError(err)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onErrRtnOrderAction(self, data, error):
"""撤单错误回报(交易所)"""
err = VtErrorData()
@ -685,42 +685,42 @@ class LtsTdApi(TdApi):
err.errorMsg = error['ErrorMsg'].decode('gbk')
self.gateway.onError(err)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspFundOutByLiber(self, data, error, n, last):
"""LTS发起出金应答"""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRtnFundOutByLiber(self, data):
"""LTS发起出金通知"""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onErrRtnFundOutByLiber(self, data, error):
"""LTS发起出金错误回报"""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRtnFundInByBank(self, data):
"""银行发起入金通知"""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspFundInterTransfer(self, data, error, n, last):
"""资金内转应答"""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRtnFundInterTransferSerial(self, data):
"""资金内转流水通知"""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onErrRtnFundInterTransfer(self, data, error):
"""资金内转错误回报"""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def connect(self, userID, password, brokerID, address, productInfo, authCode):
"""初始化连接"""
self.userID = userID # 账号
@ -749,7 +749,7 @@ class LtsTdApi(TdApi):
if not self.loginStatus:
self.login()
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def login(self):
"""连接服务器"""
# 如果填入了用户名密码等,则登录
@ -764,7 +764,7 @@ class LtsTdApi(TdApi):
self.reqID += 1
self.reqUserLogin(req, self.reqID)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def sendOrder(self, orderReq):
"""发单"""
self.reqID += 1
@ -806,7 +806,7 @@ class LtsTdApi(TdApi):
vtOrderID = '.'.join([self.gatewayName, str(self.orderRef)])
return vtOrderID
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def cancelOrder(self, cancelOrderReq):
"""撤单"""
self.reqID += 1
@ -825,7 +825,7 @@ class LtsTdApi(TdApi):
self.reqOrderAction(req, self.reqID)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def close(self):
"""关闭"""
self.exit()
@ -835,7 +835,7 @@ class LtsTdApi(TdApi):
class LtsQryApi(QryApi):
"""Lts账户查询实现"""
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def __init__(self, gateway):
"""API对象的初始化函数"""
super(LtsQryApi, self).__init__()
@ -860,7 +860,7 @@ class LtsQryApi(QryApi):
self.frontID = EMPTY_INT # 前置机编号
self.sessionID = EMPTY_INT # 会话编号
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onFrontConnected(self):
"""服务器连接"""
self.connectionStatus = True
@ -874,7 +874,7 @@ class LtsQryApi(QryApi):
self.reqID += 1
self.reqFetchAuthRandCode({}, self.reqID)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onFrontDisconnected(self, n):
"""服务器断开"""
self.connectionStatus = False
@ -886,12 +886,12 @@ class LtsQryApi(QryApi):
log.logContent = u'查询服务器连接断开'
self.gateway.onLog(log)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onHeartBeatWarning(self, n):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspError(self, error, n, last):
"""错误回报"""
err = VtErrorData()
@ -900,7 +900,7 @@ class LtsQryApi(QryApi):
err.errorMsg = error['ErrorMsg'].decode('gbk')
self.gateway.onError(err)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspUserLogin(self, data, error, n, last):
"""登陆回报"""
# 如果登录成功,推送日志信息
@ -927,7 +927,7 @@ class LtsQryApi(QryApi):
err.errorMsg = error['ErrorMsg'].decode('gbk')
self.gateway.onError(err)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspUserLogout(self, data, error, n, last):
"""登出回报"""
# 如果登出成功,推送日志信息
@ -948,17 +948,17 @@ class LtsQryApi(QryApi):
err.errorMsg = error['ErrorMsg'].decode('gbk')
self.gateway.onError(err)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspFetchAuthRandCode(self, data, error, n, last):
"""请求随机认证码"""
self.randCode = data['RandCode']
self.login()
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspQryExchange(self, data, error, n, last):
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspQryInstrument(self, data, error, n, last):
"""合约查询回报"""
contract = VtContractData()
@ -1004,17 +1004,17 @@ class LtsQryApi(QryApi):
log.logContent = u'交易合约信息获取完成'
self.gateway.onLog(log)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspQryInvestor(self, data, error, n, last):
"""投资者查询回报"""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspQryTradingCode(self, data, error, n, last):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspQryTradingAccount(self, data, error, n, last):
"""资金账户查询回报"""
account = VtAccountData()
@ -1038,102 +1038,102 @@ class LtsQryApi(QryApi):
# 推送
self.gateway.onAccount(account)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspQryBondInterest(self, data, error, n, last):
"""债券利息查询回报"""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspQryMarketRationInfo(self, data, error, n, last):
"""市值配售查询回报"""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspQryInstrumentCommissionRate(self, data, error, n, last):
"""合约手续费查询回报"""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspQryETFInstrument(self, data, error, n, last):
"""ETF基金查询回报"""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspQryETFBasket(self, data, error, n, last):
"""ETF股票篮查询回报"""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspQryOFInstrument(self, data, error, n, last):
"""OF合约查询回报"""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspQrySFInstrument(self, data, error, n, last):
"""SF合约查询回报"""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspQryInstrumentUnitMargin(self, data, error, n, last):
"""查询单手保证金"""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspQryPreDelivInfo(self, data, error, n , last):
"""查询预交割信息"""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRsyQryCreditStockAssignInfo(self, data, error, n, last):
"""查询可融券分配"""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspQryCreditCashAssignInfo(self, data, error, n , last):
"""查询可融资分配"""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRsyQryConversionRate(self, data, error, n, last):
"""查询证券这算率"""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspQryHisCreditDebtInfo(self,data, error, n, last):
"""查询历史信用负债"""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspQryMarketDataStaticInfo(self, data, error, n, last):
"""查询行情静态信息"""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspQryExpireRepurchInfo(self, data, error, n, last):
"""查询到期回购信息响应"""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspQryBondPledgeRate(self, data, error, n, last):
"""查询债券质押为标准券比例"""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspQryPledgeBond(self, data, error, n, last):
"""查询债券质押代码对照关系"""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspQryOrder(self, data, error, n, last):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspQryTrade(self, data, error, n, last):
""""""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspQryInvestorPosition(self, data, error, n, last):
"""持仓查询回报"""
pos = VtPositionData()
@ -1164,17 +1164,17 @@ class LtsQryApi(QryApi):
# 推送
self.gateway.onPosition(pos)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def OnRspQryFundTransferSerial(self, data, error, n, last):
"""资金转账查询"""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onRspQryFundInterTransferSerial(self, data, error,n, last):
"""资金内转流水查询"""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def connect(self, userID, password, brokerID, address, productInfo, authCode):
"""初始化连接"""
self.userID = userID # 账号
@ -1203,7 +1203,7 @@ class LtsQryApi(QryApi):
if not self.loginStatus:
self.login()
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def login(self):
"""连接服务器"""
# 如果填入了用户名密码等,则登录
@ -1220,7 +1220,7 @@ class LtsQryApi(QryApi):
self.reqUserLogin(req, self.reqID)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def getAccount(self):
"""查询账户"""
self.reqID += 1
@ -1230,7 +1230,7 @@ class LtsQryApi(QryApi):
req['InvestorID'] = self.userID
self.reqQryTradingAccount(req, self.reqID)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def getPosition(self):
"""查询持仓"""
self.reqID += 1
@ -1239,7 +1239,7 @@ class LtsQryApi(QryApi):
req['InvestorID'] = self.userID
self.reqQryInvestorPosition(req, self.reqID)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def close(self):
"""关闭"""
self.exit()

View File

@ -16,7 +16,7 @@ BASIC_FONT = QtGui.QFont(u'微软雅黑', 12)
class BasicCell(QtGui.QTableWidgetItem):
"""基础的单元格"""
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def __init__(self, text=None):
"""Constructor"""
super(BasicCell, self).__init__()
@ -24,7 +24,7 @@ class BasicCell(QtGui.QTableWidgetItem):
if text:
self.setContent(text)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def setContent(self, text):
"""设置内容"""
@ -38,7 +38,7 @@ class BasicCell(QtGui.QTableWidgetItem):
class DirectionCell(QtGui.QTableWidgetItem):
"""用来显示买卖方向的单元格"""
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def __init__(self, text=None):
"""Constructor"""
super(DirectionCell, self).__init__()
@ -46,7 +46,7 @@ class DirectionCell(QtGui.QTableWidgetItem):
if text:
self.setContent(text)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def setContent(self, text):
"""设置内容"""
if text == DIRECTION_LONG or text == DIRECTION_NET:
@ -61,7 +61,7 @@ class NameCell(QtGui.QTableWidgetItem):
"""用来显示合约中文的单元格"""
dataEngine = None
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def __init__(self, text=None, dataEngine=None):
"""Constructor"""
super(NameCell, self).__init__()
@ -69,13 +69,13 @@ class NameCell(QtGui.QTableWidgetItem):
if text:
self.setContent(text)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
@staticmethod
def setDataEngine(self, dataEngine):
"""设置读取合约用的数据引擎对象"""
self.dataEngine = dataEngine
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def setContent(self, text):
"""设置内容"""
if self.dataEngine:
@ -97,7 +97,7 @@ class NameCell(QtGui.QTableWidgetItem):
class BidCell(QtGui.QTableWidgetItem):
"""买价单元格"""
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def __init__(self, text=None):
"""Constructor"""
super(BidCell, self).__init__()
@ -108,7 +108,7 @@ class BidCell(QtGui.QTableWidgetItem):
if text:
self.setContent(text)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def setContent(self, text):
"""设置内容"""
self.setText(text)
@ -118,7 +118,7 @@ class BidCell(QtGui.QTableWidgetItem):
class AskCell(QtGui.QTableWidgetItem):
"""买价单元格"""
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def __init__(self, text=None):
"""Constructor"""
super(AskCell, self).__init__()
@ -129,7 +129,7 @@ class AskCell(QtGui.QTableWidgetItem):
if text:
self.setContent(text)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def setContent(self, text):
"""设置内容"""
self.setText(text)
@ -146,7 +146,7 @@ class BasicMonitor(QtGui.QTableWidget):
"""
signal = QtCore.pyqtSignal(type(Event()))
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def __init__(self, eventEngine=None, parent=None):
"""Constructor"""
super(BasicMonitor, self).__init__(parent)
@ -170,33 +170,33 @@ class BasicMonitor(QtGui.QTableWidget):
# 保存数据对象到单元格
self.saveData = False
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def setHeaderDict(self, headerDict):
"""设置表头有序字典"""
self.headerDict = headerDict
self.headerList = headerDict.keys()
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def setDataKey(self, dataKey):
"""设置数据字典的键"""
self.dataKey = dataKey
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def setEventType(self, eventType):
"""设置监控的事件类型"""
self.eventType = eventType
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def setFont(self, font):
"""设置字体"""
self.font = font
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def setSaveData(self, saveData):
"""设置是否要保存数据到单元格"""
self.saveData = saveData
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def initTable(self):
"""初始化表格"""
# 设置表格的列数
@ -216,19 +216,19 @@ class BasicMonitor(QtGui.QTableWidget):
# 设为行交替颜色
self.setAlternatingRowColors(True)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def registerEvent(self):
"""注册GUI更新相关的事件监听"""
self.signal.connect(self.updateEvent)
self.eventEngine.register(self.eventType, self.signal.emit)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def updateEvent(self, event):
"""收到事件更新"""
data = event.dict_['data']
self.updateData(data)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def updateData(self, data):
"""将数据更新到表格中"""
# 如果设置了dataKey则采用存量更新模式
@ -281,7 +281,7 @@ class BasicMonitor(QtGui.QTableWidget):
# 调整列宽
self.resizeColumns()
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def resizeColumns(self):
"""调整各列的大小"""
self.horizontalHeader().resizeSections(QtGui.QHeaderView.ResizeToContents)
@ -291,7 +291,7 @@ class BasicMonitor(QtGui.QTableWidget):
class MarketMonitor(BasicMonitor):
"""市场监控组件"""
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def __init__(self, eventEngine, parent=None):
"""Constructor"""
super(MarketMonitor, self).__init__(eventEngine, parent)
@ -334,7 +334,7 @@ class MarketMonitor(BasicMonitor):
class LogMonitor(BasicMonitor):
"""日志监控"""
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def __init__(self, eventEngine, parent=None):
"""Constructor"""
super(LogMonitor, self).__init__(eventEngine, parent)
@ -355,7 +355,7 @@ class LogMonitor(BasicMonitor):
class ErrorMonitor(BasicMonitor):
"""错误监控"""
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def __init__(self, eventEngine, parent=None):
"""Constructor"""
super(ErrorMonitor, self).__init__(eventEngine, parent)
@ -377,7 +377,7 @@ class ErrorMonitor(BasicMonitor):
class TradeMonitor(BasicMonitor):
"""成交监控"""
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def __init__(self, eventEngine, parent=None):
"""Constructor"""
super(TradeMonitor, self).__init__(eventEngine, parent)
@ -405,7 +405,7 @@ class TradeMonitor(BasicMonitor):
class OrderMonitor(BasicMonitor):
"""委托监控"""
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def __init__(self, eventEngine, mainEngine, parent=None):
"""Constructor"""
super(OrderMonitor, self).__init__(eventEngine, parent)
@ -439,13 +439,13 @@ class OrderMonitor(BasicMonitor):
self.connectSignal()
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def connectSignal(self):
"""连接信号"""
# 双击单元格撤单
self.itemDoubleClicked.connect(self.cancelOrder)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def cancelOrder(self, cell):
"""根据单元格的数据撤单"""
order = cell.data
@ -463,7 +463,7 @@ class OrderMonitor(BasicMonitor):
class PositionMonitor(BasicMonitor):
"""持仓监控"""
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def __init__(self, eventEngine, parent=None):
"""Constructor"""
super(PositionMonitor, self).__init__(eventEngine, parent)
@ -489,7 +489,7 @@ class PositionMonitor(BasicMonitor):
class AccountMonitor(BasicMonitor):
"""账户监控"""
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def __init__(self, eventEngine, parent=None):
"""Constructor"""
super(AccountMonitor, self).__init__(eventEngine, parent)
@ -552,7 +552,7 @@ class TradingWidget(QtGui.QFrame):
gatewayList = ['']
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def __init__(self, mainEngine, eventEngine, dataEngine, parent=None):
"""Constructor"""
super(TradingWidget, self).__init__(parent)
@ -568,7 +568,7 @@ class TradingWidget(QtGui.QFrame):
self.initUi()
self.connectSignal()
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def initUi(self):
"""初始化界面"""
self.setWindowTitle(u'交易')
@ -756,7 +756,7 @@ class TradingWidget(QtGui.QFrame):
buttonCancelAll.clicked.connect(self.cancelAll)
self.lineSymbol.returnPressed.connect(self.updateSymbol)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def updateSymbol(self):
"""合约变化"""
@ -874,7 +874,7 @@ class TradingWidget(QtGui.QFrame):
# 更新组件当前交易的合约
self.symbol = vtSymbol
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def updateTick(self, event):
"""更新行情"""
tick = event.dict_['data']
@ -914,12 +914,12 @@ class TradingWidget(QtGui.QFrame):
else:
self.labelReturn.setText('')
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def connectSignal(self):
"""连接Signal"""
self.signal.connect(self.updateTick)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def sendOrder(self):
"""发单"""
@ -954,7 +954,7 @@ class TradingWidget(QtGui.QFrame):
self.mainEngine.sendOrder(req, gatewayName)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def cancelAll(self):
"""一键撤销所有委托"""
l = self.dataEngine.getAllWorkingOrders()
@ -972,7 +972,7 @@ class TradingWidget(QtGui.QFrame):
class ContractMonitor(BasicMonitor):
"""合约查询"""
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def __init__(self, dataEngine, parent=None):
"""Constructor"""
super(ContractMonitor, self).__init__(parent=parent)
@ -994,7 +994,7 @@ class ContractMonitor(BasicMonitor):
self.initUi()
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def initUi(self):
"""初始化界面"""
self.setWindowTitle(u'合约查询')
@ -1003,7 +1003,7 @@ class ContractMonitor(BasicMonitor):
self.initTable()
self.initMenu()
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def showAllContracts(self):
"""显示所有合约数据"""
l = self.dataEngine.getAllContracts()
@ -1029,7 +1029,7 @@ class ContractMonitor(BasicMonitor):
row = row + 1
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def refresh(self):
"""刷新"""
self.clearContents()
@ -1037,7 +1037,7 @@ class ContractMonitor(BasicMonitor):
self.showAllContracts()
self.menu.close() # 关闭菜单
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def initMenu(self):
"""初始化右键菜单"""
refreshAction = QtGui.QAction(u'刷新', self)
@ -1046,12 +1046,12 @@ class ContractMonitor(BasicMonitor):
self.menu = QtGui.QMenu(self)
self.menu.addAction(refreshAction)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def contextMenuEvent(self, event):
"""右键点击事件"""
self.menu.popup(QtGui.QCursor.pos())
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def show(self):
"""显示"""
super(ContractMonitor, self).show()

View File

@ -12,7 +12,7 @@ class ValueMonitor(QtGui.QTableWidget):
"""数值监控"""
signal = QtCore.pyqtSignal()
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def __init__(self, parent=None):
"""Constructor"""
super(ValueMonitor , self).__init__(parent)
@ -24,7 +24,7 @@ class ValueMonitor(QtGui.QTableWidget):
self.initUi()
self.signal.connect(self.updateTable)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def initUi(self):
"""初始化界面"""
self.setColumnCount(2)
@ -35,13 +35,13 @@ class ValueMonitor(QtGui.QTableWidget):
self.setEditTriggers(self.NoEditTriggers)
self.setAlternatingRowColors(True)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def updateData(self, data):
"""更新数据"""
self.data = data
self.signal.emit()
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def updateTable(self):
"""更新表格"""
for key, value in self.data.items():
@ -63,9 +63,11 @@ class ValueMonitor(QtGui.QTableWidget):
########################################################################
class CtaStrategyManager(QtGui.QGroupBox):
"""策略管理组件"""
"""策略管理组件
即策略的UI提供了启动停止查看参数参看变量等显示信息
"""
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def __init__(self, ctaEngine, eventEngine, name, parent=None):
"""Constructor"""
super(CtaStrategyManager, self).__init__(parent)
@ -78,7 +80,7 @@ class CtaStrategyManager(QtGui.QGroupBox):
self.updateMonitor()
self.registerEvent()
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def initUi(self):
"""初始化界面"""
self.setTitle(self.name)
@ -107,28 +109,32 @@ class CtaStrategyManager(QtGui.QGroupBox):
vbox.addWidget(self.varMonitor)
self.setLayout(vbox)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def updateMonitor(self, event=None):
"""显示策略最新状态"""
# 调用CTA策略引擎,获取策略的所有参数的值依赖策略的ParamList配置
paramDict = self.ctaEngine.getStrategyParam(self.name)
if paramDict:
self.paramMonitor.updateData(paramDict)
# 调用CTA策略引擎,获取策略的所有变量的值依赖策略的varList配置
varDict = self.ctaEngine.getStrategyVar(self.name)
if varDict:
self.varMonitor.updateData(varDict)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def registerEvent(self):
"""注册事件监听"""
# 注册定时器,定时更新策略最新状态
self.eventEngine.register(EVENT_TIMER, self.updateMonitor)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def start(self):
"""启动策略"""
self.ctaEngine.startStrategy(self.name)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def stop(self):
"""停止策略"""
self.ctaEngine.stopStrategy(self.name)
@ -138,9 +144,11 @@ class CtaStrategyManager(QtGui.QGroupBox):
########################################################################
class CtaEngineManager(QtGui.QWidget):
"""CTA引擎管理组件"""
# 定义信号对象为Event的类型
signal = QtCore.pyqtSignal(type(Event()))
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def __init__(self, ctaEngine, eventEngine, parent=None):
"""Constructor"""
super(CtaEngineManager, self).__init__(parent)
@ -156,7 +164,7 @@ class CtaEngineManager(QtGui.QWidget):
# 记录日志
self.ctaEngine.writeCtaLog(u'CTA引擎启动成功')
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def initUi(self):
"""初始化界面"""
self.setWindowTitle(u'CTA策略')
@ -190,50 +198,66 @@ class CtaEngineManager(QtGui.QWidget):
vbox.addWidget(self.ctaLogMonitor)
self.setLayout(vbox)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def initStrategyManager(self):
"""初始化策略管理组件界面"""
"""初始化策略管理组件界面"""
# 构建组件w
w = QtGui.QWidget()
# 构建Layout层
hbox = QtGui.QHBoxLayout()
# 将策略UI组件逐一添加Layout层
for name in self.ctaEngine.strategyDict.keys():
strategyManager = CtaStrategyManager(self.ctaEngine, self.eventEngine, name)
hbox.addWidget(strategyManager)
# w绑定Layout层
w.setLayout(hbox)
# 滚动区域设置为组件w
self.scrollArea.setWidget(w)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def startAll(self):
"""全部启动"""
for name in self.ctaEngine.strategyDict.keys():
self.ctaEngine.startStrategy(name)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def stopAll(self):
"""全部停止"""
for name in self.ctaEngine.strategyDict.keys():
self.ctaEngine.stopStrategy(name)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def load(self):
"""加载策略"""
if not self.strategyLoaded:
# 调用策略引擎,加载所有策略设置
self.ctaEngine.loadStrategySetting()
# 初始化所有策略的UI组件
self.initStrategyManager()
self.strategyLoaded = True
self.ctaEngine.writeCtaLog(u'策略加载成功')
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def updateCtaLog(self, event):
"""更新CTA相关日志"""
log = event.dict_['data']
content = '\t'.join([log.logTime, log.logContent])
self.ctaLogMonitor.append(content)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def registerEvent(self):
"""注册事件监听"""
# 定义信号绑定方法
self.signal.connect(self.updateCtaLog)
# 注册EVENT_CAT_LOG类型的事件触发方法为信号的焕发emit
self.eventEngine.register(EVENT_CTA_LOG, self.signal.emit)

View File

@ -10,7 +10,7 @@ from uiCtaWidget import CtaEngineManager
class MainWindow(QtGui.QMainWindow):
"""主窗口"""
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def __init__(self, mainEngine, eventEngine, dataEngine):
"""Constructor"""
super(MainWindow, self).__init__()
@ -21,7 +21,7 @@ class MainWindow(QtGui.QMainWindow):
self.initUi()
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def initUi(self):
"""初始化界面"""
self.setWindowTitle('VnTrader')
@ -29,7 +29,7 @@ class MainWindow(QtGui.QMainWindow):
self.initMenu()
self.initStatusBar()
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def initCentral(self):
"""初始化中心区域"""
marketM = MarketMonitor(self.eventEngine)
@ -65,13 +65,23 @@ class MainWindow(QtGui.QMainWindow):
central.setLayout(grid)
self.setCentralWidget(central)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def initMenu(self):
"""初始化菜单"""
# 创建操作
connectCtpAction = QtGui.QAction(u'连接CTP', self)
connectCtpAction.triggered.connect(self.connectCtp)
connectCtpProdAction = QtGui.QAction(u'连接生产CTP', self)
connectCtpProdAction.triggered.connect(self.connectCtpProd)
connectCtpPostAction = QtGui.QAction(u'连接盘后CTP', self)
connectCtpPostAction.triggered.connect(self.connectCtpPost)
connectCtpTestAction = QtGui.QAction(u'连接测试CTP', self)
connectCtpTestAction.triggered.connect(self.connectCtpTest)
#connectCtpAction = QtGui.QAction(u'连接CTP', self)
#connectCtpAction.triggered.connect(self.connectCtp)
connectLtsAction = QtGui.QAction(u'连接LTS', self)
connectLtsAction.triggered.connect(self.connectLts)
@ -104,7 +114,11 @@ class MainWindow(QtGui.QMainWindow):
menubar = self.menuBar()
sysMenu = menubar.addMenu(u'系统')
sysMenu.addAction(connectCtpAction)
sysMenu.addAction(connectCtpProdAction)
sysMenu.addAction(connectCtpPostAction)
sysMenu.addAction(connectCtpTestAction)
#sysMenu.addAction(connectCtpAction)
sysMenu.addAction(connectLtsAction)
sysMenu.addAction(connectWindAction)
@ -121,7 +135,7 @@ class MainWindow(QtGui.QMainWindow):
helpMenu = menubar.addMenu(u'帮助')
helpMenu.addAction(aboutAction)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def initStatusBar(self):
"""初始化状态栏"""
self.statusLabel = QtGui.QLabel()
@ -134,7 +148,7 @@ class MainWindow(QtGui.QMainWindow):
self.sbTrigger = 10 # 10秒刷新一次
self.eventEngine.register(EVENT_TIMER, self.updateStatusBar)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def updateStatusBar(self, event):
"""在状态栏更新CPU和内存信息"""
self.sbCount += 1
@ -143,35 +157,48 @@ class MainWindow(QtGui.QMainWindow):
self.sbCount = 0
self.statusLabel.setText(self.getCpuMemory())
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def getCpuMemory(self):
"""获取CPU和内存状态信息"""
cpuPercent = psutil.cpu_percent()
memoryPercent = psutil.virtual_memory().percent
return u'CPU使用率%d%% 内存使用率:%d%%' % (cpuPercent, memoryPercent)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def connectCtpProd(self):
"""连接生产环境CTP接口"""
self.mainEngine.connect('CTP_Prod')
# ----------------------------------------------------------------------
def connectCtpPost(self):
"""连接盘后CTP接口"""
self.mainEngine.connect('CTP_Post')
def connectCtpTest(self):
"""连接测试环境CTP接口"""
self.mainEngine.connect('CTP_Test')
def connectCtp(self):
"""连接CTP接口"""
self.mainEngine.connect('CTP')
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def connectLts(self):
"""连接LTS接口"""
self.mainEngine.connect('LTS')
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def connectWind(self):
"""连接Wind接口"""
self.mainEngine.connect('Wind')
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def connectIb(self):
"""连接Ib"""
self.mainEngine.connect('IB')
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def testSubscribe(self):
"""测试订阅"""
req = VtSubscribeReq()
@ -193,7 +220,7 @@ class MainWindow(QtGui.QMainWindow):
req.symbol = 'GE'
self.mainEngine.subscribe(req, 'IB')
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def openAbout(self):
"""打开关于"""
try:
@ -202,7 +229,7 @@ class MainWindow(QtGui.QMainWindow):
self.aboutW = AboutWidget(self)
self.aboutW.show()
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def openContract(self):
"""打开合约查询"""
try:
@ -212,7 +239,7 @@ class MainWindow(QtGui.QMainWindow):
self.contractM.show()
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def openCta(self):
"""打开CTA组件"""
try:
@ -222,7 +249,7 @@ class MainWindow(QtGui.QMainWindow):
self.ctaM.show()
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def closeEvent(self, event):
"""关闭事件"""
reply = QtGui.QMessageBox.question(self, u'退出',
@ -240,14 +267,14 @@ class MainWindow(QtGui.QMainWindow):
class AboutWidget(QtGui.QDialog):
"""显示关于信息"""
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def __init__(self, parent=None):
"""Constructor"""
super(AboutWidget, self).__init__(parent)
self.initUi()
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def initUi(self):
""""""
self.setWindowTitle(u'关于')

View File

@ -20,7 +20,7 @@ from ctaEngine import CtaEngine
class MainEngine(object):
"""主引擎"""
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def __init__(self):
"""Constructor"""
# 创建事件引擎
@ -37,6 +37,15 @@ class MainEngine(object):
# 创建我们想要接入的接口对象
self.addGateway(CtpGateway, 'CTP')
self.gatewayDict['CTP'].setQryEnabled(True)
self.addGateway(CtpGateway, 'CTP_Prod')
self.gatewayDict['CTP_Prod'].setQryEnabled(True)
self.addGateway(CtpGateway, 'CTP_Post')
self.gatewayDict['CTP_Post'].setQryEnabled(True)
self.addGateway(CtpGateway, 'CTP_Test')
self.gatewayDict['CTP_Test'].setQryEnabled(True)
self.addGateway(LtsGateway, 'LTS')
self.gatewayDict['LTS'].setQryEnabled(True)
@ -51,12 +60,12 @@ class MainEngine(object):
# CTA引擎
self.ctaEngine = CtaEngine(self, self.eventEngine, self.dataEngine)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def addGateway(self, gateway, gatewayName=None):
"""创建接口"""
self.gatewayDict[gatewayName] = gateway(self.eventEngine, gatewayName)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def connect(self, gatewayName):
"""连接特定名称的接口"""
if gatewayName in self.gatewayDict:
@ -65,7 +74,7 @@ class MainEngine(object):
else:
self.writeLog(u'接口不存在:%s' %gatewayName)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def subscribe(self, subscribeReq, gatewayName):
"""订阅特定接口的行情"""
if gatewayName in self.gatewayDict:
@ -74,7 +83,7 @@ class MainEngine(object):
else:
self.writeLog(u'接口不存在:%s' %gatewayName)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def sendOrder(self, orderReq, gatewayName):
"""对特定接口发单"""
if gatewayName in self.gatewayDict:
@ -83,7 +92,7 @@ class MainEngine(object):
else:
self.writeLog(u'接口不存在:%s' %gatewayName)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def cancelOrder(self, cancelOrderReq, gatewayName):
"""对特定接口撤单"""
if gatewayName in self.gatewayDict:
@ -92,7 +101,7 @@ class MainEngine(object):
else:
self.writeLog(u'接口不存在:%s' %gatewayName)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def getAccont(self, gatewayName):
"""查询特定接口的账户"""
if gatewayName in self.gatewayDict:
@ -101,7 +110,7 @@ class MainEngine(object):
else:
self.writeLog(u'接口不存在:%s' %gatewayName)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def getPosition(self, gatewayName):
"""查询特定接口的持仓"""
if gatewayName in self.gatewayDict:
@ -110,7 +119,7 @@ class MainEngine(object):
else:
self.writeLog(u'接口不存在:%s' %gatewayName)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def exit(self):
"""退出程序前调用,保证正常退出"""
# 安全关闭所有接口
@ -123,7 +132,7 @@ class MainEngine(object):
# 保存数据引擎里的合约数据到硬盘
self.dataEngine.saveContracts()
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def writeLog(self, content):
"""快速发出日志事件"""
log = VtLogData()
@ -132,7 +141,7 @@ class MainEngine(object):
event.dict_['data'] = log
self.eventEngine.put(event)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def dbConnect(self):
"""连接MongoDB数据库"""
if not self.dbClient:
@ -142,7 +151,7 @@ class MainEngine(object):
except ConnectionFailure:
self.writeLog(u'MongoDB连接失败')
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def dbInsert(self, dbName, collectionName, d):
"""向MongoDB中插入数据d是具体数据"""
if self.dbClient:
@ -150,7 +159,7 @@ class MainEngine(object):
collection = db[collectionName]
collection.insert(d)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def dbQuery(self, dbName, collectionName, d):
"""从MongoDB中读取数据d是查询要求返回的是数据库查询的指针"""
if self.dbClient:
@ -167,7 +176,7 @@ class DataEngine(object):
"""数据引擎"""
contractFileName = 'ContractData.vt'
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def __init__(self, eventEngine):
"""Constructor"""
self.eventEngine = eventEngine
@ -187,14 +196,14 @@ class DataEngine(object):
# 注册事件监听
self.registerEvent()
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def updateContract(self, event):
"""更新合约数据"""
contract = event.dict_['data']
self.contractDict[contract.vtSymbol] = contract
self.contractDict[contract.symbol] = contract # 使用常规代码(不包括交易所)可能导致重复
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def getContract(self, vtSymbol):
"""查询合约对象"""
try:
@ -202,19 +211,19 @@ class DataEngine(object):
except KeyError:
return None
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def getAllContracts(self):
"""查询所有合约对象(返回列表)"""
return self.contractDict.values()
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def saveContracts(self):
"""保存所有合约对象到硬盘"""
f = shelve.open(self.contractFileName)
f['data'] = self.contractDict
f.close()
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def loadContracts(self):
"""从硬盘读取合约对象"""
f = shelve.open(self.contractFileName)
@ -224,7 +233,7 @@ class DataEngine(object):
self.contractDict[key] = value
f.close()
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def updateOrder(self, event):
"""更新委托数据"""
order = event.dict_['data']
@ -238,20 +247,20 @@ class DataEngine(object):
else:
self.workingOrderDict[order.vtOrderID] = order
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def getOrder(self, vtOrderID):
"""查询委托"""
"""查询委托单(报单)"""
try:
return self.orderDict[vtOrderID]
except KeyError:
return None
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def getAllWorkingOrders(self):
"""查询所有活动委托(返回列表)"""
return self.workingOrderDict.values()
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def registerEvent(self):
"""注册事件监听"""
self.eventEngine.register(EVENT_CONTRACT, self.updateContract)

View File

@ -9,7 +9,7 @@ import decimal
MAX_NUMBER = 1000000000
MAX_DECIMAL = 4
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def safeUnicode(value):
"""检查接口数据潜在的错误,保证转化为的字符串正确"""
# 检查是数字接近0时会出现的浮点数上限

View File

@ -11,13 +11,13 @@ from vtConstant import *
class VtGateway(object):
"""交易接口"""
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def __init__(self, eventEngine, gatewayName):
"""Constructor"""
self.eventEngine = eventEngine
self.gatewayName = gatewayName
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onTick(self, tick):
"""市场行情推送"""
# 通用事件
@ -30,7 +30,7 @@ class VtGateway(object):
event2.dict_['data'] = tick
self.eventEngine.put(event2)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onTrade(self, trade):
"""成交信息推送"""
# 因为成交通常都是事后才会知道成交编号,因此只需要推送通用事件
@ -38,7 +38,7 @@ class VtGateway(object):
event1.dict_['data'] = trade
self.eventEngine.put(event1)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onOrder(self, order):
"""订单变化推送"""
# 通用事件
@ -51,7 +51,7 @@ class VtGateway(object):
event2.dict_['data'] = order
self.eventEngine.put(event2)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onPosition(self, position):
"""持仓信息推送"""
# 通用事件
@ -64,7 +64,7 @@ class VtGateway(object):
event2.dict_['data'] = position
self.eventEngine.put(event2)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onAccount(self, account):
"""账户信息推送"""
# 通用事件
@ -77,7 +77,7 @@ class VtGateway(object):
event2.dict_['data'] = account
self.eventEngine.put(event2)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onError(self, error):
"""错误信息推送"""
# 通用事件
@ -85,7 +85,7 @@ class VtGateway(object):
event1.dict_['data'] = error
self.eventEngine.put(event1)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onLog(self, log):
"""日志推送"""
# 通用事件
@ -93,7 +93,7 @@ class VtGateway(object):
event1.dict_['data'] = log
self.eventEngine.put(event1)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def onContract(self, contract):
"""合约基础信息推送"""
# 通用事件
@ -101,37 +101,37 @@ class VtGateway(object):
event1.dict_['data'] = contract
self.eventEngine.put(event1)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def connect(self):
"""连接"""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def subscribe(self, subscribeReq):
"""订阅行情"""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def sendOrder(self, orderReq):
"""发单"""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def cancelOrder(self, cancelOrderReq):
"""撤单"""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def getAccount(self):
"""查询账户资金"""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def getPosition(self):
"""查询持仓"""
pass
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def close(self):
"""关闭"""
pass
@ -141,7 +141,7 @@ class VtGateway(object):
class VtBaseData(object):
"""回调函数推送数据的基础类,其他数据类继承于此"""
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def __init__(self):
"""Constructor"""
self.gatewayName = EMPTY_STRING # Gateway名称
@ -152,7 +152,7 @@ class VtBaseData(object):
class VtTickData(VtBaseData):
"""Tick行情数据类"""
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def __init__(self):
"""Constructor"""
super(VtTickData, self).__init__()
@ -209,7 +209,7 @@ class VtTickData(VtBaseData):
class VtTradeData(VtBaseData):
"""成交数据类"""
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def __init__(self):
"""Constructor"""
super(VtTradeData, self).__init__()
@ -237,7 +237,7 @@ class VtTradeData(VtBaseData):
class VtOrderData(VtBaseData):
"""订单数据类"""
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def __init__(self):
"""Constructor"""
super(VtOrderData, self).__init__()
@ -270,7 +270,7 @@ class VtOrderData(VtBaseData):
class VtPositionData(VtBaseData):
"""持仓数据类"""
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def __init__(self):
"""Constructor"""
super(VtPositionData, self).__init__()
@ -292,7 +292,7 @@ class VtPositionData(VtBaseData):
class VtAccountData(VtBaseData):
"""账户数据类"""
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def __init__(self):
"""Constructor"""
super(VtAccountData, self).__init__()
@ -315,7 +315,7 @@ class VtAccountData(VtBaseData):
class VtErrorData(VtBaseData):
"""错误数据类"""
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def __init__(self):
"""Constructor"""
super(VtErrorData, self).__init__()
@ -329,7 +329,7 @@ class VtErrorData(VtBaseData):
class VtLogData(VtBaseData):
"""日志数据类"""
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def __init__(self):
"""Constructor"""
super(VtLogData, self).__init__()
@ -342,7 +342,7 @@ class VtLogData(VtBaseData):
class VtContractData(VtBaseData):
"""合约详细信息类"""
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def __init__(self):
"""Constructor"""
super(VtBaseData, self).__init__()
@ -366,7 +366,7 @@ class VtContractData(VtBaseData):
class VtSubscribeReq:
"""订阅行情时传入的对象类"""
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def __init__(self):
"""Constructor"""
self.symbol = EMPTY_STRING # 代码
@ -384,7 +384,7 @@ class VtSubscribeReq:
class VtOrderReq:
"""发单时传入的对象类"""
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def __init__(self):
"""Constructor"""
self.symbol = EMPTY_STRING # 代码
@ -408,7 +408,7 @@ class VtOrderReq:
class VtCancelOrderReq:
"""撤单时传入的对象类"""
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def __init__(self):
"""Constructor"""
self.symbol = EMPTY_STRING # 代码

View File

@ -6,7 +6,7 @@ import ctypes
from vtEngine import MainEngine
from uiMainWindow import *
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def main():
"""主程序入口"""
# 设置底部任务栏图标win7以下请注释掉

View File

@ -67,7 +67,7 @@ class WindGateway(VtGateway):
wsqParam = ','.join(wsqParamMap.keys())
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def __init__(self, eventEngine, gatewayName='Wind'):
"""Constructor"""
super(WindGateway, self).__init__(eventEngine, gatewayName)
@ -81,7 +81,7 @@ class WindGateway(VtGateway):
self.registerEvent()
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def connect(self):
"""连接"""
# 由于w.start方法会阻塞较长时间
@ -90,13 +90,13 @@ class WindGateway(VtGateway):
event = Event(type_=EVENT_WIND_CONNECTREQ)
self.eventEngine.put(event)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def subscribe(self, subscribeReq):
"""订阅行情"""
windSymbol = '.'.join([subscribeReq.symbol, exchangeMap[subscribeReq.exchange]])
data = self.w.wsq(windSymbol, self.wsqParam, func=self.wsqCallBack)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def sendOrder(self, orderReq):
"""发单"""
log = VtLogData()
@ -104,7 +104,7 @@ class WindGateway(VtGateway):
log.logContent = u'Wind接口未实现发单功能'
self.onLog(log)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def cancelOrder(self, cancelOrderReq):
"""撤单"""
log = VtLogData()
@ -112,7 +112,7 @@ class WindGateway(VtGateway):
log.logContent = u'Wind接口未实现撤单功能'
self.onLog(log)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def getAccount(self):
"""查询账户资金"""
log = VtLogData()
@ -120,7 +120,7 @@ class WindGateway(VtGateway):
log.logContent = u'Wind接口未实现查询账户功能'
self.onLog(log)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def getPosition(self):
"""查询持仓"""
log = VtLogData()
@ -128,16 +128,16 @@ class WindGateway(VtGateway):
log.logContent = u'Wind接口未实现查询持仓功能'
self.onLog(log)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def close(self):
self.w.stop()
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def registerEvent(self):
"""注册事件监听"""
self.eventEngine.register(EVENT_WIND_CONNECTREQ, self.wConnect)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def wsqCallBack(self, data):
"""收到wsq推送"""
windSymbol = data.Codes[0]
@ -168,7 +168,7 @@ class WindGateway(VtGateway):
self.onTick(tick)
#----------------------------------------------------------------------
# ----------------------------------------------------------------------
def wConnect(self, event):
"""利用事件处理线程去异步连接Wind接口"""
result = self.w.start()