-change : 适配Python3语法
This commit is contained in:
parent
b956769f9c
commit
7f256596cf
@ -30,10 +30,10 @@ RUN echo "开始配置系vnpy环境" \
|
||||
&& echo "deb-src http://mirrors.163.com/ubuntu/ xenial-updates main multiverse restricted universe" >> /etc/apt/sources.list \
|
||||
&& apt-get clean \
|
||||
&& apt-get update \
|
||||
&& echo "安装编译环境" \
|
||||
&& apt-get install -y build-essential libboost-all-dev python-dev cmake \
|
||||
&& echo "从 apt 获取软件" \
|
||||
&& apt-get install -y bzip2 wget \
|
||||
&& echo "安装编译环境" \
|
||||
&& apt-get install -y build-essential libboost-all-dev python-dev cmake \
|
||||
&& apt-get clean \
|
||||
&& echo "安装 ta-lib 内核" \
|
||||
&& cd /opt \
|
||||
@ -57,7 +57,11 @@ RUN echo "开始配置系vnpy环境" \
|
||||
&& echo "设置 conda 国内源, 从 conda 安装 python 库" \
|
||||
&& conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/ \
|
||||
&& conda config --set show_channel_urls yes \
|
||||
&& conda install -y pymongo bsddb pyzmq numpy msgpack-python \
|
||||
&& conda install -y bsddb pymongo pyzmq numpy msgpack-python \
|
||||
&& echo "更改 pip 源" \
|
||||
&& mkdir ~/.pip \
|
||||
&& echo "[global]" >> ~/.pip/pip.conf \
|
||||
&& echo "index-url = http://pypi.douban.com/simple" >> ~/.pip/pip.conf \
|
||||
&& echo "使用 pip 安装 python 库" \
|
||||
&& pip install TA-Lib \
|
||||
&& conda clean -ay \
|
||||
|
@ -465,7 +465,7 @@ class BacktestingEngine(object):
|
||||
#----------------------------------------------------------------------
|
||||
def output(self, content):
|
||||
"""输出内容"""
|
||||
print str(datetime.now()) + "\t" + content
|
||||
print(str(datetime.now()) + "\t" + content)
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def calculateBacktestingResult(self):
|
||||
@ -877,11 +877,11 @@ class OptimizationSetting(object):
|
||||
return
|
||||
|
||||
if end < start:
|
||||
print u'参数起始点必须不大于终止点'
|
||||
print(u'参数起始点必须不大于终止点')
|
||||
return
|
||||
|
||||
if step <= 0:
|
||||
print u'参数布进必须大于0'
|
||||
print(u'参数布进必须大于0')
|
||||
return
|
||||
|
||||
l = []
|
||||
|
@ -18,6 +18,7 @@
|
||||
|
||||
from __future__ import division
|
||||
|
||||
import traceback
|
||||
import json
|
||||
import os
|
||||
import traceback
|
||||
@ -37,77 +38,77 @@ class CtaEngine(object):
|
||||
"""CTA策略引擎"""
|
||||
settingFileName = 'CTA_setting.json'
|
||||
path = os.path.abspath(os.path.dirname(__file__))
|
||||
settingFileName = os.path.join(path, settingFileName)
|
||||
settingFileName = os.path.join(path, settingFileName)
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def __init__(self, mainEngine, eventEngine):
|
||||
"""Constructor"""
|
||||
self.mainEngine = mainEngine
|
||||
self.eventEngine = eventEngine
|
||||
|
||||
|
||||
# 当前日期
|
||||
self.today = todayDate()
|
||||
|
||||
|
||||
# 保存策略实例的字典
|
||||
# key为策略名称,value为策略实例,注意策略名称不允许重复
|
||||
self.strategyDict = {}
|
||||
|
||||
|
||||
# 保存vtSymbol和策略实例映射的字典(用于推送tick数据)
|
||||
# 由于可能多个strategy交易同一个vtSymbol,因此key为vtSymbol
|
||||
# value为包含所有相关strategy对象的list
|
||||
self.tickStrategyDict = {}
|
||||
|
||||
|
||||
# 保存vtOrderID和strategy对象映射的字典(用于推送order和trade数据)
|
||||
# key为vtOrderID,value为strategy对象
|
||||
self.orderStrategyDict = {}
|
||||
|
||||
self.orderStrategyDict = {}
|
||||
|
||||
# 本地停止单编号计数
|
||||
self.stopOrderCount = 0
|
||||
# stopOrderID = STOPORDERPREFIX + str(stopOrderCount)
|
||||
|
||||
|
||||
# 本地停止单字典
|
||||
# key为stopOrderID,value为stopOrder对象
|
||||
self.stopOrderDict = {} # 停止单撤销后不会从本字典中删除
|
||||
self.workingStopOrderDict = {} # 停止单撤销后会从本字典中删除
|
||||
|
||||
|
||||
# 持仓缓存字典
|
||||
# key为vtSymbol,value为PositionBuffer对象
|
||||
self.posBufferDict = {}
|
||||
|
||||
|
||||
# 成交号集合,用来过滤已经收到过的成交推送
|
||||
self.tradeSet = set()
|
||||
|
||||
|
||||
# 引擎类型为实盘
|
||||
self.engineType = ENGINETYPE_TRADING
|
||||
|
||||
|
||||
# 注册事件监听
|
||||
self.registerEvent()
|
||||
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def sendOrder(self, vtSymbol, orderType, price, volume, strategy):
|
||||
"""发单"""
|
||||
contract = self.mainEngine.getContract(vtSymbol)
|
||||
|
||||
|
||||
req = VtOrderReq()
|
||||
req.symbol = contract.symbol
|
||||
req.exchange = contract.exchange
|
||||
req.price = self.roundToPriceTick(contract.priceTick, price)
|
||||
req.volume = volume
|
||||
|
||||
|
||||
req.productClass = strategy.productClass
|
||||
req.currency = strategy.currency
|
||||
|
||||
req.currency = strategy.currency
|
||||
|
||||
# 设计为CTA引擎发出的委托只允许使用限价单
|
||||
req.priceType = PRICETYPE_LIMITPRICE
|
||||
|
||||
req.priceType = PRICETYPE_LIMITPRICE
|
||||
|
||||
# CTA委托类型映射
|
||||
if orderType == CTAORDER_BUY:
|
||||
req.direction = DIRECTION_LONG
|
||||
req.offset = OFFSET_OPEN
|
||||
|
||||
|
||||
elif orderType == CTAORDER_SELL:
|
||||
req.direction = DIRECTION_SHORT
|
||||
|
||||
|
||||
# 只有上期所才要考虑平今平昨
|
||||
if contract.exchange != EXCHANGE_SHFE:
|
||||
req.offset = OFFSET_CLOSE
|
||||
@ -123,14 +124,14 @@ class CtaEngine(object):
|
||||
# 其他情况使用平昨
|
||||
else:
|
||||
req.offset = OFFSET_CLOSE
|
||||
|
||||
|
||||
elif orderType == CTAORDER_SHORT:
|
||||
req.direction = DIRECTION_SHORT
|
||||
req.offset = OFFSET_OPEN
|
||||
|
||||
|
||||
elif orderType == CTAORDER_COVER:
|
||||
req.direction = DIRECTION_LONG
|
||||
|
||||
|
||||
# 只有上期所才要考虑平今平昨
|
||||
if contract.exchange != EXCHANGE_SHFE:
|
||||
req.offset = OFFSET_CLOSE
|
||||
@ -146,21 +147,21 @@ class CtaEngine(object):
|
||||
# 其他情况使用平昨
|
||||
else:
|
||||
req.offset = OFFSET_CLOSE
|
||||
|
||||
|
||||
vtOrderID = self.mainEngine.sendOrder(req, contract.gatewayName) # 发单
|
||||
self.orderStrategyDict[vtOrderID] = strategy # 保存vtOrderID和策略的映射关系
|
||||
|
||||
self.writeCtaLog(u'策略%s发送委托,%s,%s,%s@%s'
|
||||
self.writeCtaLog(u'策略%s发送委托,%s,%s,%s@%s'
|
||||
%(strategy.name, vtSymbol, req.direction, volume, price))
|
||||
|
||||
|
||||
return vtOrderID
|
||||
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def cancelOrder(self, vtOrderID):
|
||||
"""撤单"""
|
||||
# 查询报单对象
|
||||
order = self.mainEngine.getOrder(vtOrderID)
|
||||
|
||||
|
||||
# 如果查询成功
|
||||
if order:
|
||||
# 检查是否报单还有效,只有有效时才发出撤单指令
|
||||
@ -172,14 +173,14 @@ 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)
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def sendStopOrder(self, vtSymbol, orderType, price, volume, strategy):
|
||||
"""发停止单(本地实现)"""
|
||||
self.stopOrderCount += 1
|
||||
stopOrderID = STOPORDERPREFIX + str(self.stopOrderCount)
|
||||
|
||||
|
||||
so = StopOrder()
|
||||
so.vtSymbol = vtSymbol
|
||||
so.orderType = orderType
|
||||
@ -188,7 +189,7 @@ class CtaEngine(object):
|
||||
so.strategy = strategy
|
||||
so.stopOrderID = stopOrderID
|
||||
so.status = STOPORDER_WAITING
|
||||
|
||||
|
||||
if orderType == CTAORDER_BUY:
|
||||
so.direction = DIRECTION_LONG
|
||||
so.offset = OFFSET_OPEN
|
||||
@ -200,14 +201,14 @@ class CtaEngine(object):
|
||||
so.offset = OFFSET_OPEN
|
||||
elif orderType == CTAORDER_COVER:
|
||||
so.direction = DIRECTION_LONG
|
||||
so.offset = OFFSET_CLOSE
|
||||
|
||||
so.offset = OFFSET_CLOSE
|
||||
|
||||
# 保存stopOrder对象到字典中
|
||||
self.stopOrderDict[stopOrderID] = so
|
||||
self.workingStopOrderDict[stopOrderID] = so
|
||||
|
||||
|
||||
return stopOrderID
|
||||
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def cancelStopOrder(self, stopOrderID):
|
||||
"""撤销停止单"""
|
||||
@ -221,7 +222,7 @@ class CtaEngine(object):
|
||||
def processStopOrder(self, tick):
|
||||
"""收到行情后处理本地停止单(检查是否要立即发出)"""
|
||||
vtSymbol = tick.vtSymbol
|
||||
|
||||
|
||||
# 首先检查是否有策略交易该合约
|
||||
if vtSymbol in self.tickStrategyDict:
|
||||
# 遍历等待中的停止单,检查是否会被触发
|
||||
@ -229,14 +230,14 @@ class CtaEngine(object):
|
||||
if so.vtSymbol == vtSymbol:
|
||||
longTriggered = so.direction==DIRECTION_LONG and tick.lastPrice>=so.price # 多头停止单被触发
|
||||
shortTriggered = so.direction==DIRECTION_SHORT and tick.lastPrice<=so.price # 空头停止单被触发
|
||||
|
||||
|
||||
if longTriggered or shortTriggered:
|
||||
# 买入和卖出分别以涨停跌停价发单(模拟市价单)
|
||||
if so.direction==DIRECTION_LONG:
|
||||
price = tick.upperLimit
|
||||
else:
|
||||
price = tick.lowerLimit
|
||||
|
||||
|
||||
so.status = STOPORDER_TRIGGERED
|
||||
self.sendOrder(so.vtSymbol, so.orderType, price, so.volume, so.strategy)
|
||||
del self.workingStopOrderDict[so.stopOrderID]
|
||||
@ -247,7 +248,7 @@ class CtaEngine(object):
|
||||
tick = event.dict_['data']
|
||||
# 收到tick行情后,先处理本地停止单(检查是否要立即发出)
|
||||
self.processStopOrder(tick)
|
||||
|
||||
|
||||
# 推送tick到对应的策略实例进行处理
|
||||
if tick.vtSymbol in self.tickStrategyDict:
|
||||
# 将vtTickData数据转化为ctaTickData
|
||||
@ -258,43 +259,43 @@ class CtaEngine(object):
|
||||
d[key] = tick.__getattribute__(key)
|
||||
# 添加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:
|
||||
self.callStrategyFunc(strategy, strategy.onTick, ctaTick)
|
||||
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def processOrderEvent(self, event):
|
||||
"""处理委托推送"""
|
||||
order = event.dict_['data']
|
||||
|
||||
|
||||
if order.vtOrderID in self.orderStrategyDict:
|
||||
strategy = self.orderStrategyDict[order.vtOrderID]
|
||||
strategy = self.orderStrategyDict[order.vtOrderID]
|
||||
self.callStrategyFunc(strategy, strategy.onOrder, order)
|
||||
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def processTradeEvent(self, event):
|
||||
"""处理成交推送"""
|
||||
trade = event.dict_['data']
|
||||
|
||||
|
||||
# 过滤已经收到过的成交回报
|
||||
if trade.vtTradeID in self.tradeSet:
|
||||
return
|
||||
self.tradeSet.add(trade.vtTradeID)
|
||||
|
||||
|
||||
# 将成交推送到策略对象中
|
||||
if trade.vtOrderID in self.orderStrategyDict:
|
||||
strategy = self.orderStrategyDict[trade.vtOrderID]
|
||||
|
||||
|
||||
# 计算策略持仓
|
||||
if trade.direction == DIRECTION_LONG:
|
||||
strategy.pos += trade.volume
|
||||
else:
|
||||
strategy.pos -= trade.volume
|
||||
|
||||
|
||||
self.callStrategyFunc(strategy, strategy.onTrade, trade)
|
||||
|
||||
|
||||
# 更新持仓缓存数据
|
||||
if trade.vtSymbol in self.tickStrategyDict:
|
||||
posBuffer = self.posBufferDict.get(trade.vtSymbol, None)
|
||||
@ -302,13 +303,13 @@ class CtaEngine(object):
|
||||
posBuffer = PositionBuffer()
|
||||
posBuffer.vtSymbol = trade.vtSymbol
|
||||
self.posBufferDict[trade.vtSymbol] = posBuffer
|
||||
posBuffer.updateTradeData(trade)
|
||||
|
||||
posBuffer.updateTradeData(trade)
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def processPositionEvent(self, event):
|
||||
"""处理持仓推送"""
|
||||
pos = event.dict_['data']
|
||||
|
||||
|
||||
# 更新持仓缓存数据
|
||||
if pos.vtSymbol in self.tickStrategyDict:
|
||||
posBuffer = self.posBufferDict.get(pos.vtSymbol, None)
|
||||
@ -317,7 +318,7 @@ class CtaEngine(object):
|
||||
posBuffer.vtSymbol = pos.vtSymbol
|
||||
self.posBufferDict[pos.vtSymbol] = posBuffer
|
||||
posBuffer.updatePositionData(pos)
|
||||
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def registerEvent(self):
|
||||
"""注册事件监听"""
|
||||
@ -325,42 +326,42 @@ class CtaEngine(object):
|
||||
self.eventEngine.register(EVENT_ORDER, self.processOrderEvent)
|
||||
self.eventEngine.register(EVENT_TRADE, self.processTradeEvent)
|
||||
self.eventEngine.register(EVENT_POSITION, self.processPositionEvent)
|
||||
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def insertData(self, dbName, collectionName, data):
|
||||
"""插入数据到数据库(这里的data可以是CtaTickData或者CtaBarData)"""
|
||||
self.mainEngine.dbInsert(dbName, collectionName, data.__dict__)
|
||||
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def loadBar(self, dbName, collectionName, days):
|
||||
"""从数据库中读取Bar数据,startDate是datetime对象"""
|
||||
startDate = self.today - timedelta(days)
|
||||
|
||||
|
||||
d = {'datetime':{'$gte':startDate}}
|
||||
barData = self.mainEngine.dbQuery(dbName, collectionName, d)
|
||||
|
||||
|
||||
l = []
|
||||
for d in barData:
|
||||
bar = CtaBarData()
|
||||
bar.__dict__ = d
|
||||
l.append(bar)
|
||||
return l
|
||||
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def loadTick(self, dbName, collectionName, days):
|
||||
"""从数据库中读取Tick数据,startDate是datetime对象"""
|
||||
startDate = self.today - timedelta(days)
|
||||
|
||||
|
||||
d = {'datetime':{'$gte':startDate}}
|
||||
tickData = self.mainEngine.dbQuery(dbName, collectionName, d)
|
||||
|
||||
|
||||
l = []
|
||||
for d in tickData:
|
||||
tick = CtaTickData()
|
||||
tick.__dict__ = d
|
||||
l.append(tick)
|
||||
return l
|
||||
|
||||
return l
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def writeCtaLog(self, content):
|
||||
"""快速发出CTA模块日志事件"""
|
||||
@ -368,32 +369,32 @@ class CtaEngine(object):
|
||||
log.logContent = content
|
||||
event = Event(type_=EVENT_CTA_LOG)
|
||||
event.dict_['data'] = log
|
||||
self.eventEngine.put(event)
|
||||
|
||||
self.eventEngine.put(event)
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def loadStrategy(self, setting):
|
||||
"""载入策略"""
|
||||
try:
|
||||
name = setting['name']
|
||||
className = setting['className']
|
||||
except Exception, e:
|
||||
self.writeCtaLog(u'载入策略出错:%s' %e)
|
||||
except:
|
||||
self.writeCtaLog(u'载入策略出错:%s' %traceback.format_exc())
|
||||
return
|
||||
|
||||
|
||||
# 获取策略类
|
||||
strategyClass = STRATEGY_CLASS.get(className, None)
|
||||
if not strategyClass:
|
||||
self.writeCtaLog(u'找不到策略类:%s' %className)
|
||||
return
|
||||
|
||||
|
||||
# 防止策略重名
|
||||
if name in self.strategyDict:
|
||||
self.writeCtaLog(u'策略实例重名:%s' %name)
|
||||
else:
|
||||
# 创建策略实例
|
||||
strategy = strategyClass(self, setting)
|
||||
strategy = strategyClass(self, setting)
|
||||
self.strategyDict[name] = strategy
|
||||
|
||||
|
||||
# 保存Tick映射关系
|
||||
if strategy.vtSymbol in self.tickStrategyDict:
|
||||
l = self.tickStrategyDict[strategy.vtSymbol]
|
||||
@ -401,18 +402,18 @@ class CtaEngine(object):
|
||||
l = []
|
||||
self.tickStrategyDict[strategy.vtSymbol] = l
|
||||
l.append(strategy)
|
||||
|
||||
|
||||
# 订阅合约
|
||||
contract = self.mainEngine.getContract(strategy.vtSymbol)
|
||||
if contract:
|
||||
req = VtSubscribeReq()
|
||||
req.symbol = contract.symbol
|
||||
req.exchange = contract.exchange
|
||||
|
||||
|
||||
# 对于IB接口订阅行情时所需的货币和产品类型,从策略属性中获取
|
||||
req.currency = strategy.currency
|
||||
req.productClass = strategy.productClass
|
||||
|
||||
|
||||
self.mainEngine.subscribe(req, contract.gatewayName)
|
||||
else:
|
||||
self.writeCtaLog(u'%s的交易合约%s无法找到' %(name, strategy.vtSymbol))
|
||||
@ -422,111 +423,111 @@ class CtaEngine(object):
|
||||
"""初始化策略"""
|
||||
if name in self.strategyDict:
|
||||
strategy = self.strategyDict[name]
|
||||
|
||||
|
||||
if not strategy.inited:
|
||||
strategy.inited = True
|
||||
self.callStrategyFunc(strategy, strategy.onInit)
|
||||
else:
|
||||
self.writeCtaLog(u'请勿重复初始化策略实例:%s' %name)
|
||||
else:
|
||||
self.writeCtaLog(u'策略实例不存在:%s' %name)
|
||||
self.writeCtaLog(u'策略实例不存在:%s' %name)
|
||||
|
||||
#---------------------------------------------------------------------
|
||||
def startStrategy(self, name):
|
||||
"""启动策略"""
|
||||
if name in self.strategyDict:
|
||||
strategy = self.strategyDict[name]
|
||||
|
||||
|
||||
if strategy.inited and not strategy.trading:
|
||||
strategy.trading = True
|
||||
self.callStrategyFunc(strategy, strategy.onStart)
|
||||
else:
|
||||
self.writeCtaLog(u'策略实例不存在:%s' %name)
|
||||
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def stopStrategy(self, name):
|
||||
"""停止策略"""
|
||||
if name in self.strategyDict:
|
||||
strategy = self.strategyDict[name]
|
||||
|
||||
|
||||
if strategy.trading:
|
||||
strategy.trading = False
|
||||
self.callStrategyFunc(strategy, strategy.onStop)
|
||||
|
||||
|
||||
# 对该策略发出的所有限价单进行撤单
|
||||
for vtOrderID, s in self.orderStrategyDict.items():
|
||||
if s is strategy:
|
||||
self.cancelOrder(vtOrderID)
|
||||
|
||||
|
||||
# 对该策略发出的所有本地停止单撤单
|
||||
for stopOrderID, so in self.workingStopOrderDict.items():
|
||||
if so.strategy is strategy:
|
||||
self.cancelStopOrder(stopOrderID)
|
||||
self.cancelStopOrder(stopOrderID)
|
||||
else:
|
||||
self.writeCtaLog(u'策略实例不存在:%s' %name)
|
||||
|
||||
self.writeCtaLog(u'策略实例不存在:%s' %name)
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def saveSetting(self):
|
||||
"""保存策略配置"""
|
||||
with open(self.settingFileName, 'w') as f:
|
||||
l = []
|
||||
|
||||
|
||||
for strategy in self.strategyDict.values():
|
||||
setting = {}
|
||||
for param in strategy.paramList:
|
||||
setting[param] = strategy.__getattribute__(param)
|
||||
l.append(setting)
|
||||
|
||||
|
||||
jsonL = json.dumps(l, indent=4)
|
||||
f.write(jsonL)
|
||||
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def loadSetting(self):
|
||||
"""读取策略配置"""
|
||||
with open(self.settingFileName) as f:
|
||||
l = json.load(f)
|
||||
|
||||
|
||||
for setting in l:
|
||||
self.loadStrategy(setting)
|
||||
|
||||
|
||||
self.loadPosition()
|
||||
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def getStrategyVar(self, name):
|
||||
"""获取策略当前的变量字典"""
|
||||
if name in self.strategyDict:
|
||||
strategy = self.strategyDict[name]
|
||||
varDict = OrderedDict()
|
||||
|
||||
|
||||
for key in strategy.varList:
|
||||
varDict[key] = strategy.__getattribute__(key)
|
||||
|
||||
|
||||
return varDict
|
||||
else:
|
||||
self.writeCtaLog(u'策略实例不存在:' + name)
|
||||
self.writeCtaLog(u'策略实例不存在:' + name)
|
||||
return None
|
||||
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def getStrategyParam(self, name):
|
||||
"""获取策略的参数字典"""
|
||||
if name in self.strategyDict:
|
||||
strategy = self.strategyDict[name]
|
||||
paramDict = OrderedDict()
|
||||
|
||||
for key in strategy.paramList:
|
||||
|
||||
for key in strategy.paramList:
|
||||
paramDict[key] = strategy.__getattribute__(key)
|
||||
|
||||
|
||||
return paramDict
|
||||
else:
|
||||
self.writeCtaLog(u'策略实例不存在:' + name)
|
||||
return None
|
||||
|
||||
self.writeCtaLog(u'策略实例不存在:' + name)
|
||||
return None
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def putStrategyEvent(self, name):
|
||||
"""触发策略状态变化事件(通常用于通知GUI更新)"""
|
||||
event = Event(EVENT_CTA_STRATEGY+name)
|
||||
self.eventEngine.put(event)
|
||||
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def callStrategyFunc(self, strategy, func, params=None):
|
||||
"""调用策略的函数,若触发异常则捕捉"""
|
||||
@ -539,29 +540,29 @@ class CtaEngine(object):
|
||||
# 停止策略,修改状态为未初始化
|
||||
strategy.trading = False
|
||||
strategy.inited = False
|
||||
|
||||
|
||||
# 发出日志
|
||||
content = '\n'.join([u'策略%s触发异常已停止' %strategy.name,
|
||||
traceback.format_exc()])
|
||||
self.writeCtaLog(content)
|
||||
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def savePosition(self):
|
||||
"""保存所有策略的持仓情况到数据库"""
|
||||
for strategy in self.strategyDict.values():
|
||||
flt = {'name': strategy.name,
|
||||
'vtSymbol': strategy.vtSymbol}
|
||||
|
||||
|
||||
d = {'name': strategy.name,
|
||||
'vtSymbol': strategy.vtSymbol,
|
||||
'pos': strategy.pos}
|
||||
|
||||
|
||||
self.mainEngine.dbUpdate(POSITION_DB_NAME, strategy.className,
|
||||
d, flt, True)
|
||||
|
||||
|
||||
content = '策略%s持仓保存成功' %strategy.name
|
||||
self.writeCtaLog(content)
|
||||
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def loadPosition(self):
|
||||
"""从数据库载入策略的持仓情况"""
|
||||
@ -569,18 +570,18 @@ class CtaEngine(object):
|
||||
flt = {'name': strategy.name,
|
||||
'vtSymbol': strategy.vtSymbol}
|
||||
posData = self.mainEngine.dbQuery(POSITION_DB_NAME, strategy.className, flt)
|
||||
|
||||
|
||||
for d in posData:
|
||||
strategy.pos = d['pos']
|
||||
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def roundToPriceTick(self, priceTick, price):
|
||||
"""取整价格到合约最小价格变动"""
|
||||
if not priceTick:
|
||||
return price
|
||||
|
||||
|
||||
newPrice = round(price/priceTick, 0) * priceTick
|
||||
return newPrice
|
||||
return newPrice
|
||||
|
||||
|
||||
########################################################################
|
||||
@ -591,17 +592,17 @@ class PositionBuffer(object):
|
||||
def __init__(self):
|
||||
"""Constructor"""
|
||||
self.vtSymbol = EMPTY_STRING
|
||||
|
||||
|
||||
# 多头
|
||||
self.longPosition = EMPTY_INT
|
||||
self.longToday = EMPTY_INT
|
||||
self.longYd = EMPTY_INT
|
||||
|
||||
|
||||
# 空头
|
||||
self.shortPosition = EMPTY_INT
|
||||
self.shortToday = EMPTY_INT
|
||||
self.shortYd = EMPTY_INT
|
||||
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def updatePositionData(self, pos):
|
||||
"""更新持仓数据"""
|
||||
@ -613,7 +614,7 @@ class PositionBuffer(object):
|
||||
self.shortPosition = pos.position
|
||||
self.shortYd = pos.ydPosition
|
||||
self.shortToday = self.shortPosition - self.shortYd
|
||||
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def updateTradeData(self, trade):
|
||||
"""更新成交数据"""
|
||||
@ -641,9 +642,9 @@ class PositionBuffer(object):
|
||||
else:
|
||||
self.longPosition -= trade.volume
|
||||
self.longYd -= trade.volume
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
@ -90,9 +90,9 @@ class HistoryDataEngine(object):
|
||||
|
||||
self.dbClient[SETTING_DB_NAME]['FuturesSymbol'].update_one(flt, {'$set':symbolDict},
|
||||
upsert=True)
|
||||
print u'期货合约代码下载完成'
|
||||
print(u'期货合约代码下载完成')
|
||||
else:
|
||||
print u'期货合约代码下载失败'
|
||||
print(u'期货合约代码下载失败')
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def downloadFuturesDailyBar(self, symbol):
|
||||
@ -100,7 +100,7 @@ class HistoryDataEngine(object):
|
||||
下载期货合约的日行情,symbol是合约代码,
|
||||
若最后四位为0000(如IF0000),代表下载连续合约。
|
||||
"""
|
||||
print u'开始下载%s日行情' %symbol
|
||||
print(u'开始下载%s日行情' %symbol)
|
||||
|
||||
# 查询数据库中已有数据的最后日期
|
||||
cl = self.dbClient[DAILY_DB_NAME][symbol]
|
||||
@ -152,24 +152,24 @@ class HistoryDataEngine(object):
|
||||
bar.volume = d.get('turnoverVol', 0)
|
||||
bar.openInterest = d.get('openInt', 0)
|
||||
except KeyError:
|
||||
print d
|
||||
print(d)
|
||||
|
||||
flt = {'datetime': bar.datetime}
|
||||
self.dbClient[DAILY_DB_NAME][symbol].update_one(flt, {'$set':bar.__dict__}, upsert=True)
|
||||
|
||||
print u'%s下载完成' %symbol
|
||||
print(u'%s下载完成' %symbol)
|
||||
else:
|
||||
print u'找不到合约%s' %symbol
|
||||
print(u'找不到合约%s' %symbol)
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def downloadAllFuturesDailyBar(self):
|
||||
"""下载所有期货的主力合约日行情"""
|
||||
start = time()
|
||||
print u'开始下载所有期货的主力合约日行情'
|
||||
print(u'开始下载所有期货的主力合约日行情')
|
||||
|
||||
productSymbolSet = self.readFuturesProductSymbol()
|
||||
|
||||
print u'代码列表读取成功,产品代码:%s' %productSymbolSet
|
||||
print(u'代码列表读取成功,产品代码:%s' %productSymbolSet)
|
||||
|
||||
# 这里也测试了线程池,但可能由于下载函数中涉及较多的数据格
|
||||
# 式转换,CPU开销较大,多线程效率并无显著改变。
|
||||
@ -181,12 +181,12 @@ class HistoryDataEngine(object):
|
||||
for productSymbol in productSymbolSet:
|
||||
self.downloadFuturesDailyBar(productSymbol+'0000')
|
||||
|
||||
print u'所有期货的主力合约日行情已经全部下载完成, 耗时%s秒' %(time()-start)
|
||||
print(u'所有期货的主力合约日行情已经全部下载完成, 耗时%s秒' %(time()-start))
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def downloadFuturesIntradayBar(self, symbol):
|
||||
"""下载期货的日内分钟行情"""
|
||||
print u'开始下载%s日内分钟行情' %symbol
|
||||
print(u'开始下载%s日内分钟行情' %symbol)
|
||||
|
||||
# 日内分钟行情只有具体合约
|
||||
path = 'api/market/getFutureBarRTIntraDay.json'
|
||||
@ -220,14 +220,14 @@ class HistoryDataEngine(object):
|
||||
bar.volume = d.get('totalVolume', 0)
|
||||
bar.openInterest = 0
|
||||
except KeyError:
|
||||
print d
|
||||
print(d)
|
||||
|
||||
flt = {'datetime': bar.datetime}
|
||||
self.dbClient[MINUTE_DB_NAME][symbol].update_one(flt, {'$set':bar.__dict__}, upsert=True)
|
||||
|
||||
print u'%s下载完成' %symbol
|
||||
print(u'%s下载完成' %symbol)
|
||||
else:
|
||||
print u'找不到合约%s' %symbol
|
||||
print(u'找不到合约%s' %symbol)
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def downloadEquitySymbol(self, tradeDate=''):
|
||||
@ -254,16 +254,16 @@ class HistoryDataEngine(object):
|
||||
|
||||
self.dbClient[SETTING_DB_NAME]['EquitySymbol'].update_one(flt, {'$set':symbolDict},
|
||||
upsert=True)
|
||||
print u'股票代码下载完成'
|
||||
print(u'股票代码下载完成')
|
||||
else:
|
||||
print u'股票代码下载失败'
|
||||
print(u'股票代码下载失败')
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def downloadEquityDailyBar(self, symbol):
|
||||
"""
|
||||
下载股票的日行情,symbol是股票代码
|
||||
"""
|
||||
print u'开始下载%s日行情' %symbol
|
||||
print(u'开始下载%s日行情' %symbol)
|
||||
|
||||
# 查询数据库中已有数据的最后日期
|
||||
cl = self.dbClient[DAILY_DB_NAME][symbol]
|
||||
@ -303,14 +303,14 @@ class HistoryDataEngine(object):
|
||||
bar.datetime = datetime.strptime(bar.date, '%Y%m%d')
|
||||
bar.volume = d.get('turnoverVol', 0)
|
||||
except KeyError:
|
||||
print d
|
||||
print(d)
|
||||
|
||||
flt = {'datetime': bar.datetime}
|
||||
self.dbClient[DAILY_DB_NAME][symbol].update_one(flt, {'$set':bar.__dict__}, upsert=True)
|
||||
|
||||
print u'%s下载完成' %symbol
|
||||
print(u'%s下载完成' %symbol)
|
||||
else:
|
||||
print u'找不到合约%s' %symbol
|
||||
print(u'找不到合约%s' %symbol)
|
||||
|
||||
|
||||
|
||||
@ -319,7 +319,7 @@ def downloadEquityDailyBarts(self, symbol):
|
||||
"""
|
||||
下载股票的日行情,symbol是股票代码
|
||||
"""
|
||||
print u'开始下载%s日行情' %symbol
|
||||
print(u'开始下载%s日行情' %symbol)
|
||||
|
||||
# 查询数据库中已有数据的最后日期
|
||||
cl = self.dbClient[DAILY_DB_NAME][symbol]
|
||||
@ -355,21 +355,21 @@ def downloadEquityDailyBarts(self, symbol):
|
||||
bar.datetime = datetime.strptime(bar.date, '%Y%m%d')
|
||||
bar.volume = d.get('volume')
|
||||
except KeyError:
|
||||
print d
|
||||
print(d)
|
||||
|
||||
flt = {'datetime': bar.datetime}
|
||||
self.dbClient[DAILY_DB_NAME][symbol].update_one(flt, {'$set':bar.__dict__}, upsert=True)
|
||||
|
||||
print u'%s下载完成' %symbol
|
||||
print(u'%s下载完成' %symbol)
|
||||
else:
|
||||
print u'找不到合约%s' %symbol
|
||||
print(u'找不到合约%s' %symbol)
|
||||
#----------------------------------------------------------------------
|
||||
def loadMcCsv(fileName, dbName, symbol):
|
||||
"""将Multicharts导出的csv格式的历史数据插入到Mongo数据库中"""
|
||||
import csv
|
||||
|
||||
start = time()
|
||||
print u'开始读取CSV文件%s中的数据插入到%s的%s中' %(fileName, dbName, symbol)
|
||||
print(u'开始读取CSV文件%s中的数据插入到%s的%s中' %(fileName, dbName, symbol))
|
||||
|
||||
# 锁定集合,并创建索引
|
||||
host, port, logging = loadMongoSetting()
|
||||
@ -395,9 +395,9 @@ def loadMcCsv(fileName, dbName, symbol):
|
||||
|
||||
flt = {'datetime': bar.datetime}
|
||||
collection.update_one(flt, {'$set':bar.__dict__}, upsert=True)
|
||||
print bar.date, bar.time
|
||||
print(bar.date, bar.time)
|
||||
|
||||
print u'插入完毕,耗时:%s' % (time()-start)
|
||||
print(u'插入完毕,耗时:%s' % (time()-start))
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def loadTdxCsv(fileName, dbName, symbol):
|
||||
@ -405,7 +405,7 @@ def loadTdxCsv(fileName, dbName, symbol):
|
||||
import csv
|
||||
|
||||
start = time()
|
||||
print u'开始读取CSV文件%s中的数据插入到%s的%s中' %(fileName, dbName, symbol)
|
||||
print(u'开始读取CSV文件%s中的数据插入到%s的%s中' %(fileName, dbName, symbol))
|
||||
|
||||
# 锁定集合,并创建索引
|
||||
host, port, logging = loadMongoSetting()
|
||||
@ -432,9 +432,9 @@ def loadTdxCsv(fileName, dbName, symbol):
|
||||
|
||||
flt = {'datetime': bar.datetime}
|
||||
collection.update_one(flt, {'$set':bar.__dict__}, upsert=True)
|
||||
print bar.date, bar.time
|
||||
print(bar.date, bar.time)
|
||||
|
||||
print u'插入完毕,耗时:%s' % (time()-start)
|
||||
print(u'插入完毕,耗时:%s' % (time()-start))
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def loadTBCsv(fileName, dbName, symbol):
|
||||
@ -446,7 +446,7 @@ def loadTBCsv(fileName, dbName, symbol):
|
||||
import csv
|
||||
|
||||
start = time()
|
||||
print u'开始读取CSV文件%s中的数据插入到%s的%s中' %(fileName, dbName, symbol)
|
||||
print(u'开始读取CSV文件%s中的数据插入到%s的%s中' %(fileName, dbName, symbol))
|
||||
|
||||
# 锁定集合,并创建索引
|
||||
host, port, logging = loadMongoSetting()
|
||||
@ -477,9 +477,9 @@ def loadTBCsv(fileName, dbName, symbol):
|
||||
|
||||
flt = {'datetime': bar.datetime}
|
||||
collection.update_one(flt, {'$set':bar.__dict__}, upsert=True)
|
||||
print '%s \t %s' % (bar.date, bar.time)
|
||||
print('%s \t %s' % (bar.date, bar.time))
|
||||
|
||||
print u'插入完毕,耗时:%s' % (time()-start)
|
||||
print(u'插入完毕,耗时:%s' % (time()-start))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
@ -35,7 +35,7 @@ class DatayesClient(object):
|
||||
FILENAME = os.path.join(path, FILENAME)
|
||||
f = file(FILENAME)
|
||||
except IOError:
|
||||
print u'%s无法打开配置文件' % self.name
|
||||
print(u'%s无法打开配置文件' % self.name)
|
||||
return
|
||||
|
||||
setting = json.load(f)
|
||||
@ -44,28 +44,28 @@ class DatayesClient(object):
|
||||
self.version = str(setting['version'])
|
||||
self.token = str(setting['token'])
|
||||
except KeyError:
|
||||
print u'%s配置文件字段缺失' % self.name
|
||||
print(u'%s配置文件字段缺失' % self.name)
|
||||
return
|
||||
|
||||
self.header['Connection'] = 'keep_alive'
|
||||
self.header['Authorization'] = 'Bearer ' + self.token
|
||||
self.settingLoaded = True
|
||||
|
||||
print u'%s配置载入完成' % self.name
|
||||
print(u'%s配置载入完成' % self.name)
|
||||
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def downloadData(self, path, params):
|
||||
"""下载数据"""
|
||||
if not self.settingLoaded:
|
||||
print u'%s配置未载入' % self.name
|
||||
print(u'%s配置未载入' % self.name)
|
||||
return None
|
||||
else:
|
||||
url = '/'.join([self.domain, self.version, path])
|
||||
r = requests.get(url=url, headers=self.header, params=params)
|
||||
|
||||
if r.status_code != HTTP_OK:
|
||||
print u'%shttp请求失败,状态代码%s' %(self.name, r.status_code)
|
||||
print(u'%shttp请求失败,状态代码%s' %(self.name, r.status_code))
|
||||
return None
|
||||
else:
|
||||
result = r.json()
|
||||
@ -73,9 +73,9 @@ class DatayesClient(object):
|
||||
return result['data']
|
||||
else:
|
||||
if 'retMsg' in result:
|
||||
print u'%s查询失败,返回信息%s' %(self.name, result['retMsg'])
|
||||
print(u'%s查询失败,返回信息%s' %(self.name, result['retMsg']))
|
||||
elif 'message' in result:
|
||||
print u'%s查询失败,返回信息%s' %(self.name, result['message'])
|
||||
print(u'%s查询失败,返回信息%s' %(self.name, result['message']))
|
||||
return None
|
||||
|
||||
|
||||
|
@ -32,6 +32,6 @@ for root, subdirs, files in os.walk(path):
|
||||
v = module.__getattribute__(k)
|
||||
STRATEGY_CLASS[k] = v
|
||||
except:
|
||||
print '-' * 20
|
||||
print ('Failed to import strategy file %s:' %moduleName)
|
||||
print('-' * 20)
|
||||
print('Failed to import strategy file %s:' %moduleName)
|
||||
traceback.print_exc()
|
||||
|
@ -157,7 +157,7 @@ class BacktestEngineMultiTF(BacktestingEngine):
|
||||
try:
|
||||
self.infobar[info_symbol] = next(self.InfoCursor[info_symbol])
|
||||
except StopIteration:
|
||||
print "Data of information symbols is empty! Input must be a list, not str."
|
||||
print("Data of information symbols is empty! Input must be a list, not str.")
|
||||
raise
|
||||
|
||||
temp = {}
|
||||
|
@ -216,7 +216,7 @@ class Prototype(AtrRsiStrategy):
|
||||
try:
|
||||
self.initInfobar[info_symbol] = next(initInfoCursorDict[info_symbol])
|
||||
except StopIteration:
|
||||
print "Data of information symbols is empty! Input is a list, not str."
|
||||
print("Data of information symbols is empty! Input is a list, not str.")
|
||||
raise
|
||||
|
||||
# 若有某一品种的 TimeStamp 和执行报价的 TimeStamp 匹配, 则将"initInfobar"中的数据推送,
|
||||
@ -407,4 +407,4 @@ if __name__ == '__main__':
|
||||
# 显示回测结果
|
||||
engine.showBacktestingResult()
|
||||
|
||||
print 'Time consumed:%s' % (time.time() - start)
|
||||
print('Time consumed:%s' % (time.time() - start))
|
@ -113,7 +113,7 @@ class BreakOut(CtaTemplate):
|
||||
try:
|
||||
self.initInfobar[info_symbol] = next(initInfoCursorDict[info_symbol])
|
||||
except StopIteration:
|
||||
print "Data of information symbols is empty! Input is a list, not str."
|
||||
print("Data of information symbols is empty! Input is a list, not str.")
|
||||
raise
|
||||
|
||||
# 若有某一品种的 TimeStamp 和执行报价的 TimeStamp 匹配, 则将"initInfobar"中的数据推送,
|
||||
@ -314,4 +314,4 @@ if __name__ == '__main__':
|
||||
# 显示回测结果
|
||||
engine.showBacktestingResult()
|
||||
|
||||
print 'Time consumed:%s' % (time.time() - start)
|
||||
print('Time consumed:%s' % (time.time() - start))
|
@ -51,12 +51,12 @@ def test():
|
||||
|
||||
for key, value in check_dict.items():
|
||||
if len(value)>1:
|
||||
print u'存在重复的常量定义:' + str(key)
|
||||
print(u'存在重复的常量定义:' + str(key))
|
||||
for name in value:
|
||||
print name
|
||||
print ''
|
||||
print(name)
|
||||
print('')
|
||||
|
||||
print u'测试完毕'
|
||||
print(u'测试完毕')
|
||||
|
||||
|
||||
# 直接运行脚本可以进行测试
|
||||
|
@ -1472,7 +1472,7 @@ def test():
|
||||
|
||||
def print_log(event):
|
||||
log = event.dict_['data']
|
||||
print ':'.join([log.logTime, log.logContent])
|
||||
print(':'.join([log.logTime, log.logContent]))
|
||||
|
||||
app = QtCore.QCoreApplication(sys.argv)
|
||||
|
||||
|
@ -605,10 +605,10 @@ class FemasTdApi(TdApi):
|
||||
# 如果登录成功,推送日志信息
|
||||
if error['ErrorID'] == 0:
|
||||
for k, v in data.items():
|
||||
print k, ':', v
|
||||
print(k, ':', v)
|
||||
if data['MaxOrderLocalID']:
|
||||
self.localID = int(data['MaxOrderLocalID']) # 目前最大本地报单号
|
||||
print 'id now', self.localID
|
||||
print('id now', self.localID)
|
||||
|
||||
self.loginStatus = True
|
||||
self.gateway.mdConnected = True
|
||||
@ -960,7 +960,7 @@ def test():
|
||||
|
||||
def print_log(event):
|
||||
log = event.dict_['data']
|
||||
print ':'.join([log.logTime, log.logContent])
|
||||
print(':'.join([log.logTime, log.logContent]))
|
||||
|
||||
app = QtCore.QCoreApplication(sys.argv)
|
||||
|
||||
|
@ -373,12 +373,12 @@ class HuobiTradeApi(vnhuobi.TradeApi):
|
||||
#----------------------------------------------------------------------
|
||||
def onBuyMarket(self, data, req, reqID):
|
||||
"""市价买入回调"""
|
||||
print data
|
||||
print(data)
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def onSellMarket(self, data, req, reqID):
|
||||
"""市价卖出回调"""
|
||||
print data
|
||||
print(data)
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def onCancelOrder(self, data, req, reqID):
|
||||
@ -396,52 +396,52 @@ class HuobiTradeApi(vnhuobi.TradeApi):
|
||||
#----------------------------------------------------------------------
|
||||
def onGetNewDealOrders(self, data, req, reqID):
|
||||
"""查询最新成交回调"""
|
||||
print data
|
||||
print(data)
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def onGetOrderIdByTradeId(self, data, req, reqID):
|
||||
"""通过成交编号查询委托编号回调"""
|
||||
print data
|
||||
print(data)
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def onWithdrawCoin(self, data, req, reqID):
|
||||
"""提币回调"""
|
||||
print data
|
||||
print(data)
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def onCancelWithdrawCoin(self, data, req, reqID):
|
||||
"""取消提币回调"""
|
||||
print data
|
||||
print(data)
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def onGetWithdrawCoinResult(self, data, req, reqID):
|
||||
"""查询提币结果回调"""
|
||||
print data
|
||||
print(data)
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def onTransfer(self, data, req, reqID):
|
||||
"""转账回调"""
|
||||
print data
|
||||
print(data)
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def onLoan(self, data, req, reqID):
|
||||
"""申请杠杆回调"""
|
||||
print data
|
||||
print(data)
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def onRepayment(self, data, req, reqID):
|
||||
"""归还杠杆回调"""
|
||||
print data
|
||||
print(data)
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def onLoanAvailable(self, data, req, reqID):
|
||||
"""查询杠杆额度回调"""
|
||||
print data
|
||||
print(data)
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def onGetLoans(self, data, req, reqID):
|
||||
"""查询杠杆列表"""
|
||||
print data
|
||||
print(data)
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def connect(self, accessKey, secretKey, market, debug=False):
|
||||
@ -553,7 +553,7 @@ class HuobiDataApi(vnhuobi.DataApi):
|
||||
#----------------------------------------------------------------------
|
||||
def onTick(self, data):
|
||||
"""实时成交推送"""
|
||||
print data
|
||||
print(data)
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def onQuote(self, data):
|
||||
|
@ -2,6 +2,7 @@
|
||||
|
||||
import urllib
|
||||
import hashlib
|
||||
import traceback
|
||||
|
||||
import json
|
||||
import requests
|
||||
@ -144,7 +145,7 @@ class TradeApi(object):
|
||||
# 请求成功
|
||||
else:
|
||||
if self.DEBUG:
|
||||
print callback.__name__
|
||||
print(callback.__name__)
|
||||
callback(data, req, reqID)
|
||||
|
||||
except Empty:
|
||||
@ -428,97 +429,97 @@ class TradeApi(object):
|
||||
#----------------------------------------------------------------------
|
||||
def onError(self, error, req, reqID):
|
||||
"""错误推送"""
|
||||
print error, reqID
|
||||
print(error, reqID)
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def onGetAccountInfo(self, data, req, reqID):
|
||||
"""查询账户回调"""
|
||||
print data
|
||||
print(data)
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def onGetOrders(self, data, req, reqID, fuck):
|
||||
"""查询委托回调"""
|
||||
print data
|
||||
print(data)
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def onOrderInfo(self, data, req, reqID):
|
||||
"""委托详情回调"""
|
||||
print data
|
||||
print(data)
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def onBuy(self, data, req, reqID):
|
||||
"""买入回调"""
|
||||
print data
|
||||
print(data)
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def onSell(self, data, req, reqID):
|
||||
"""卖出回调"""
|
||||
print data
|
||||
print(data)
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def onBuyMarket(self, data, req, reqID):
|
||||
"""市价买入回调"""
|
||||
print data
|
||||
print(data)
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def onSellMarket(self, data, req, reqID):
|
||||
"""市价卖出回调"""
|
||||
print data
|
||||
print(data)
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def onCancelOrder(self, data, req, reqID):
|
||||
"""撤单回调"""
|
||||
print data
|
||||
print(data)
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def onGetNewDealOrders(self, data, req, reqID):
|
||||
"""查询最新成交回调"""
|
||||
print data
|
||||
print(data)
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def onGetOrderIdByTradeId(self, data, req, reqID):
|
||||
"""通过成交编号查询委托编号回调"""
|
||||
print data
|
||||
print(data)
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def onWithdrawCoin(self, data, req, reqID):
|
||||
"""提币回调"""
|
||||
print data
|
||||
print(data)
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def onCancelWithdrawCoin(self, data, req, reqID):
|
||||
"""取消提币回调"""
|
||||
print data
|
||||
print(data)
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def onGetWithdrawCoinResult(self, data, req, reqID):
|
||||
"""查询提币结果回调"""
|
||||
print data
|
||||
print(data)
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def onTransfer(self, data, req, reqID):
|
||||
"""转账回调"""
|
||||
print data
|
||||
print(data)
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def onLoan(self, data, req, reqID):
|
||||
"""申请杠杆回调"""
|
||||
print data
|
||||
print(data)
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def onRepayment(self, data, req, reqID):
|
||||
"""归还杠杆回调"""
|
||||
print data
|
||||
print(data)
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def onLoanAvailable(self, data, req, reqID):
|
||||
"""查询杠杆额度回调"""
|
||||
print data
|
||||
print(data)
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def onGetLoans(self, data, req, reqID):
|
||||
"""查询杠杆列表"""
|
||||
print data
|
||||
print(data)
|
||||
|
||||
|
||||
########################################################################
|
||||
@ -586,10 +587,11 @@ class DataApi(object):
|
||||
if r.status_code == 200:
|
||||
data = r.json()
|
||||
if self.DEBUG:
|
||||
print callback.__name__
|
||||
print(callback.__name__)
|
||||
callback(data)
|
||||
except Exception, e:
|
||||
print e
|
||||
except:
|
||||
traceback.print_exc()
|
||||
|
||||
|
||||
sleep(self.taskInterval)
|
||||
|
||||
@ -621,17 +623,17 @@ class DataApi(object):
|
||||
#----------------------------------------------------------------------
|
||||
def onTick(self, data):
|
||||
"""实时成交推送"""
|
||||
print data
|
||||
print(data)
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def onQuote(self, data):
|
||||
"""实时报价推送"""
|
||||
print data
|
||||
print(data)
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def onDepth(self, data):
|
||||
"""实时深度推送"""
|
||||
print data
|
||||
print(data)
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def getKline(self, symbol, period, length=0):
|
||||
@ -647,6 +649,6 @@ class DataApi(object):
|
||||
if r.status_code == 200:
|
||||
data = r.json()
|
||||
return data
|
||||
except Exception, e:
|
||||
print e
|
||||
except:
|
||||
traceback.print_exc()
|
||||
return None
|
@ -372,7 +372,7 @@ class IbWrapper(IbApi):
|
||||
newtick = copy(tick)
|
||||
self.gateway.onTick(newtick)
|
||||
else:
|
||||
print field
|
||||
print(field)
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def tickSize(self, tickerId, field, size):
|
||||
@ -382,7 +382,7 @@ class IbWrapper(IbApi):
|
||||
key = tickFieldMap[field]
|
||||
tick.__setattr__(key, size)
|
||||
else:
|
||||
print field
|
||||
print(field)
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def tickOptionComputation(self, tickerId, tickType, impliedVol, delta, optPrice, pvDividend, gamma, vega, theta, undPrice):
|
||||
|
@ -1825,7 +1825,7 @@ def test():
|
||||
|
||||
def print_log(event):
|
||||
log = event.dict_['data']
|
||||
print ':'.join([log.logTime, log.logContent])
|
||||
print(':'.join([log.logTime, log.logContent]))
|
||||
|
||||
app = QtCore.QCoreApplication(sys.argv)
|
||||
|
||||
|
@ -244,11 +244,11 @@ class LhangApi(vnlhang.LhangApi):
|
||||
# ----------------------------------------------------------------------
|
||||
def onGetTrades(self, data, req, reqID):
|
||||
"""查询历史成交"""
|
||||
print data, reqID
|
||||
print(data, reqID)
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
def onGetKline(self, data, req, reqID):
|
||||
print data, reqID
|
||||
print(data, reqID)
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
def onGetUserInfo(self, data, req, reqID):
|
||||
|
@ -120,7 +120,7 @@ class LhangApi(object):
|
||||
# 请求成功
|
||||
else:
|
||||
if self.DEBUG:
|
||||
print callback.__name__
|
||||
print(callback.__name__)
|
||||
callback(data, req, reqID)
|
||||
|
||||
# 流控等待
|
||||
@ -149,7 +149,7 @@ class LhangApi(object):
|
||||
#----------------------------------------------------------------------
|
||||
def onError(self, error, req, reqID):
|
||||
"""错误推送"""
|
||||
print error, req, reqID
|
||||
print(error, req, reqID)
|
||||
|
||||
###############################################
|
||||
# 行情接口
|
||||
@ -203,22 +203,22 @@ class LhangApi(object):
|
||||
#----------------------------------------------------------------------
|
||||
def onGetTicker(self, data, req, reqID):
|
||||
"""查询行情回调"""
|
||||
print data, reqID
|
||||
print(data, reqID)
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
def onGetDepth(self, data, req, reqID):
|
||||
"""查询深度回调"""
|
||||
print data, reqID
|
||||
print(data, reqID)
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
def onGetTrades(self, data, req, reqID):
|
||||
"""查询历史成交"""
|
||||
print data, reqID
|
||||
print(data, reqID)
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
def onGetKline(self, data, req, reqID):
|
||||
"""查询K线回报"""
|
||||
print data, reqID
|
||||
print(data, reqID)
|
||||
|
||||
###############################################
|
||||
# 交易接口
|
||||
@ -283,25 +283,25 @@ class LhangApi(object):
|
||||
# ----------------------------------------------------------------------
|
||||
def onGetUserInfo(self, data, req, reqID):
|
||||
"""查询K线回报"""
|
||||
print data, reqID
|
||||
print(data, reqID)
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
def onCreateOrder(self, data, req, reqID):
|
||||
"""委托回报"""
|
||||
print data, reqID
|
||||
print(data, reqID)
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
def onCancelOrder(self, data, req, reqID):
|
||||
"""撤单回报"""
|
||||
print data, reqID
|
||||
print(data, reqID)
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
def onGetOrdersInfo(self, data, req, reqID):
|
||||
"""查询委托回报"""
|
||||
print data, reqID
|
||||
print(data, reqID)
|
||||
|
||||
# ----------------------------------------------------------------------
|
||||
def onGetOrdersInfoHistory(self, data, req, reqID):
|
||||
"""撤单回报"""
|
||||
print data, reqID
|
||||
print(data, reqID)
|
||||
|
||||
|
@ -987,7 +987,7 @@ class LtsQryApi(QryApi):
|
||||
elif data['ProductClass'] == '8':
|
||||
contract.productClass = PRODUCT_EQUITY
|
||||
else:
|
||||
print data['ProductClass']
|
||||
print(data['ProductClass'])
|
||||
|
||||
# 期权类型
|
||||
if data['InstrumentType'] == '1':
|
||||
|
@ -1,5 +1,6 @@
|
||||
# encoding: utf-8
|
||||
|
||||
import traceback
|
||||
import json
|
||||
import requests
|
||||
from Queue import Queue, Empty
|
||||
@ -208,8 +209,8 @@ class OandaApi(object):
|
||||
|
||||
try:
|
||||
r = self.session.send(pre, stream=stream)
|
||||
except Exception, e:
|
||||
error = e
|
||||
except :
|
||||
error = traceback.format_exc()
|
||||
|
||||
return r, error
|
||||
|
||||
@ -228,10 +229,10 @@ class OandaApi(object):
|
||||
try:
|
||||
data = r.json()
|
||||
if self.DEBUG:
|
||||
print callback.__name__
|
||||
print(callback.__name__)
|
||||
callback(data, reqID)
|
||||
except Exception, e:
|
||||
self.onError(str(e), reqID)
|
||||
except :
|
||||
self.onError(traceback.format_exc(), reqID)
|
||||
else:
|
||||
self.onError(error, reqID)
|
||||
except Empty:
|
||||
@ -260,7 +261,7 @@ class OandaApi(object):
|
||||
#----------------------------------------------------------------------
|
||||
def onError(self, error, reqID):
|
||||
"""错误信息回调"""
|
||||
print error, reqID
|
||||
print(error, reqID)
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def getInstruments(self, params):
|
||||
@ -526,12 +527,12 @@ class OandaApi(object):
|
||||
#----------------------------------------------------------------------
|
||||
def onPrice(self, data):
|
||||
"""行情推送"""
|
||||
print data
|
||||
print(data)
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def onEvent(self, data):
|
||||
"""事件推送(成交等)"""
|
||||
print data
|
||||
print(data)
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def processStreamPrices(self):
|
||||
@ -546,8 +547,8 @@ class OandaApi(object):
|
||||
try:
|
||||
data = r.json()
|
||||
symbols = [d['instrument'] for d in data['instruments']]
|
||||
except Exception, e:
|
||||
self.onError(e, -1)
|
||||
except :
|
||||
self.onError(traceback.format_exc(), -1)
|
||||
return
|
||||
else:
|
||||
self.onError(error, -1)
|
||||
@ -570,11 +571,11 @@ class OandaApi(object):
|
||||
msg = json.loads(line)
|
||||
|
||||
if self.DEBUG:
|
||||
print self.onPrice.__name__
|
||||
print(self.onPrice.__name__)
|
||||
|
||||
self.onPrice(msg)
|
||||
except Exception, e:
|
||||
self.onError(e, -1)
|
||||
except :
|
||||
self.onError(traceback.format_exc(), -1)
|
||||
|
||||
if not self.active:
|
||||
break
|
||||
@ -597,11 +598,11 @@ class OandaApi(object):
|
||||
msg = json.loads(line)
|
||||
|
||||
if self.DEBUG:
|
||||
print self.onEvent.__name__
|
||||
print(self.onEvent.__name__)
|
||||
|
||||
self.onEvent(msg)
|
||||
except Exception, e:
|
||||
self.onError(e, -1)
|
||||
except :
|
||||
self.onError(traceback.format_exc(), -1)
|
||||
|
||||
if not self.active:
|
||||
break
|
||||
|
@ -123,25 +123,25 @@ class OkCoinApi(object):
|
||||
#----------------------------------------------------------------------
|
||||
def onMessage(self, ws, evt):
|
||||
"""信息推送"""
|
||||
print 'onMessage'
|
||||
print('onMessage')
|
||||
data = self.readData(evt)
|
||||
print data
|
||||
print(data)
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def onError(self, ws, evt):
|
||||
"""错误推送"""
|
||||
print 'onError'
|
||||
print evt
|
||||
print('onError')
|
||||
print(evt)
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def onClose(self, ws):
|
||||
"""接口断开"""
|
||||
print 'onClose'
|
||||
print('onClose')
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def onOpen(self, ws):
|
||||
"""接口打开"""
|
||||
print 'onOpen'
|
||||
print('onOpen')
|
||||
|
||||
#----------------------------------------------------------------------
|
||||
def connect(self, host, apiKey, secretKey, trace=False):
|
||||
|
@ -1423,7 +1423,7 @@ def test():
|
||||
|
||||
def print_log(event):
|
||||
log = event.dict_['data']
|
||||
print ':'.join([log.logTime, log.logContent])
|
||||
print(':'.join([log.logTime, log.logContent]))
|
||||
|
||||
app = QtCore.QCoreApplication(sys.argv)
|
||||
|
||||
|
@ -722,9 +722,9 @@ class ShzdGatewayApi(ShzdApi):
|
||||
#----------------------------------------------------------------------
|
||||
def printDict(d):
|
||||
"""打印字典"""
|
||||
print '-' * 50
|
||||
print('-' * 50)
|
||||
l = d.keys()
|
||||
l.sort()
|
||||
for k in l:
|
||||
print k, ':', d[k]
|
||||
print(k, ':', d[k])
|
||||
|
7
vn.trader/tmp/CTP_connect.json
Normal file
7
vn.trader/tmp/CTP_connect.json
Normal file
@ -0,0 +1,7 @@
|
||||
{
|
||||
"password": "325800",
|
||||
"userID": "901201302",
|
||||
"brokerID": "1080",
|
||||
"tdAddress": "tcp://180.169.112.52:41205",
|
||||
"mdAddress": "tcp://180.169.112.52:41213"
|
||||
}
|
18
vn.trader/tmp/VT_setting.json
Normal file
18
vn.trader/tmp/VT_setting.json
Normal file
@ -0,0 +1,18 @@
|
||||
{
|
||||
"fontFamily": "微软雅黑",
|
||||
"fontSize": 12,
|
||||
|
||||
"mongoHost": "192.168.31.204",
|
||||
"mongoPort": 27017,
|
||||
"mongoLogging": true,
|
||||
"automongodb": false,
|
||||
|
||||
"darkStyle": true,
|
||||
"language": "chinese",
|
||||
|
||||
"CTP_connect": "/srv/vnpy/vn.trader/tmp/CTP_connect.json",
|
||||
"autoctp": false,
|
||||
|
||||
"autoshutdown": true
|
||||
|
||||
}
|
3
vn.trader/tmp/server.sh
Executable file
3
vn.trader/tmp/server.sh
Executable file
@ -0,0 +1,3 @@
|
||||
#/bin/bash
|
||||
|
||||
python /srv/vnpy/vn.trader/vtServer.py --VT_setting /srv/vnpy/vn.trader/tmp/VT_setting.json
|
Loading…
Reference in New Issue
Block a user