-change : 适配Python3语法

This commit is contained in:
lamter 2017-04-27 16:02:43 +08:00
parent b956769f9c
commit 7f256596cf
26 changed files with 298 additions and 262 deletions

View File

@ -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 \ && echo "deb-src http://mirrors.163.com/ubuntu/ xenial-updates main multiverse restricted universe" >> /etc/apt/sources.list \
&& apt-get clean \ && apt-get clean \
&& apt-get update \ && apt-get update \
&& echo "安装编译环境" \
&& apt-get install -y build-essential libboost-all-dev python-dev cmake \
&& echo "从 apt 获取软件" \ && echo "从 apt 获取软件" \
&& apt-get install -y bzip2 wget \ && apt-get install -y bzip2 wget \
&& echo "安装编译环境" \
&& apt-get install -y build-essential libboost-all-dev python-dev cmake \
&& apt-get clean \ && apt-get clean \
&& echo "安装 ta-lib 内核" \ && echo "安装 ta-lib 内核" \
&& cd /opt \ && cd /opt \
@ -57,7 +57,11 @@ RUN echo "开始配置系vnpy环境" \
&& echo "设置 conda 国内源, 从 conda 安装 python 库" \ && echo "设置 conda 国内源, 从 conda 安装 python 库" \
&& conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/ \ && conda config --add channels https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/ \
&& conda config --set show_channel_urls yes \ && 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 库" \ && echo "使用 pip 安装 python 库" \
&& pip install TA-Lib \ && pip install TA-Lib \
&& conda clean -ay \ && conda clean -ay \

View File

@ -465,7 +465,7 @@ class BacktestingEngine(object):
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def output(self, content): def output(self, content):
"""输出内容""" """输出内容"""
print str(datetime.now()) + "\t" + content print(str(datetime.now()) + "\t" + content)
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def calculateBacktestingResult(self): def calculateBacktestingResult(self):
@ -877,11 +877,11 @@ class OptimizationSetting(object):
return return
if end < start: if end < start:
print u'参数起始点必须不大于终止点' print(u'参数起始点必须不大于终止点')
return return
if step <= 0: if step <= 0:
print u'参数布进必须大于0' print(u'参数布进必须大于0')
return return
l = [] l = []

View File

@ -18,6 +18,7 @@
from __future__ import division from __future__ import division
import traceback
import json import json
import os import os
import traceback import traceback
@ -37,77 +38,77 @@ class CtaEngine(object):
"""CTA策略引擎""" """CTA策略引擎"""
settingFileName = 'CTA_setting.json' settingFileName = 'CTA_setting.json'
path = os.path.abspath(os.path.dirname(__file__)) 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): def __init__(self, mainEngine, eventEngine):
"""Constructor""" """Constructor"""
self.mainEngine = mainEngine self.mainEngine = mainEngine
self.eventEngine = eventEngine self.eventEngine = eventEngine
# 当前日期 # 当前日期
self.today = todayDate() self.today = todayDate()
# 保存策略实例的字典 # 保存策略实例的字典
# key为策略名称value为策略实例注意策略名称不允许重复 # key为策略名称value为策略实例注意策略名称不允许重复
self.strategyDict = {} self.strategyDict = {}
# 保存vtSymbol和策略实例映射的字典用于推送tick数据 # 保存vtSymbol和策略实例映射的字典用于推送tick数据
# 由于可能多个strategy交易同一个vtSymbol因此key为vtSymbol # 由于可能多个strategy交易同一个vtSymbol因此key为vtSymbol
# value为包含所有相关strategy对象的list # value为包含所有相关strategy对象的list
self.tickStrategyDict = {} self.tickStrategyDict = {}
# 保存vtOrderID和strategy对象映射的字典用于推送order和trade数据 # 保存vtOrderID和strategy对象映射的字典用于推送order和trade数据
# key为vtOrderIDvalue为strategy对象 # key为vtOrderIDvalue为strategy对象
self.orderStrategyDict = {} self.orderStrategyDict = {}
# 本地停止单编号计数 # 本地停止单编号计数
self.stopOrderCount = 0 self.stopOrderCount = 0
# stopOrderID = STOPORDERPREFIX + str(stopOrderCount) # stopOrderID = STOPORDERPREFIX + str(stopOrderCount)
# 本地停止单字典 # 本地停止单字典
# key为stopOrderIDvalue为stopOrder对象 # key为stopOrderIDvalue为stopOrder对象
self.stopOrderDict = {} # 停止单撤销后不会从本字典中删除 self.stopOrderDict = {} # 停止单撤销后不会从本字典中删除
self.workingStopOrderDict = {} # 停止单撤销后会从本字典中删除 self.workingStopOrderDict = {} # 停止单撤销后会从本字典中删除
# 持仓缓存字典 # 持仓缓存字典
# key为vtSymbolvalue为PositionBuffer对象 # key为vtSymbolvalue为PositionBuffer对象
self.posBufferDict = {} self.posBufferDict = {}
# 成交号集合,用来过滤已经收到过的成交推送 # 成交号集合,用来过滤已经收到过的成交推送
self.tradeSet = set() self.tradeSet = set()
# 引擎类型为实盘 # 引擎类型为实盘
self.engineType = ENGINETYPE_TRADING self.engineType = ENGINETYPE_TRADING
# 注册事件监听 # 注册事件监听
self.registerEvent() self.registerEvent()
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def sendOrder(self, vtSymbol, orderType, price, volume, strategy): def sendOrder(self, vtSymbol, orderType, price, volume, strategy):
"""发单""" """发单"""
contract = self.mainEngine.getContract(vtSymbol) contract = self.mainEngine.getContract(vtSymbol)
req = VtOrderReq() req = VtOrderReq()
req.symbol = contract.symbol req.symbol = contract.symbol
req.exchange = contract.exchange req.exchange = contract.exchange
req.price = self.roundToPriceTick(contract.priceTick, price) req.price = self.roundToPriceTick(contract.priceTick, price)
req.volume = volume req.volume = volume
req.productClass = strategy.productClass req.productClass = strategy.productClass
req.currency = strategy.currency req.currency = strategy.currency
# 设计为CTA引擎发出的委托只允许使用限价单 # 设计为CTA引擎发出的委托只允许使用限价单
req.priceType = PRICETYPE_LIMITPRICE req.priceType = PRICETYPE_LIMITPRICE
# CTA委托类型映射 # CTA委托类型映射
if orderType == CTAORDER_BUY: if orderType == CTAORDER_BUY:
req.direction = DIRECTION_LONG req.direction = DIRECTION_LONG
req.offset = OFFSET_OPEN req.offset = OFFSET_OPEN
elif orderType == CTAORDER_SELL: elif orderType == CTAORDER_SELL:
req.direction = DIRECTION_SHORT req.direction = DIRECTION_SHORT
# 只有上期所才要考虑平今平昨 # 只有上期所才要考虑平今平昨
if contract.exchange != EXCHANGE_SHFE: if contract.exchange != EXCHANGE_SHFE:
req.offset = OFFSET_CLOSE req.offset = OFFSET_CLOSE
@ -123,14 +124,14 @@ class CtaEngine(object):
# 其他情况使用平昨 # 其他情况使用平昨
else: else:
req.offset = OFFSET_CLOSE req.offset = OFFSET_CLOSE
elif orderType == CTAORDER_SHORT: elif orderType == CTAORDER_SHORT:
req.direction = DIRECTION_SHORT req.direction = DIRECTION_SHORT
req.offset = OFFSET_OPEN req.offset = OFFSET_OPEN
elif orderType == CTAORDER_COVER: elif orderType == CTAORDER_COVER:
req.direction = DIRECTION_LONG req.direction = DIRECTION_LONG
# 只有上期所才要考虑平今平昨 # 只有上期所才要考虑平今平昨
if contract.exchange != EXCHANGE_SHFE: if contract.exchange != EXCHANGE_SHFE:
req.offset = OFFSET_CLOSE req.offset = OFFSET_CLOSE
@ -146,21 +147,21 @@ class CtaEngine(object):
# 其他情况使用平昨 # 其他情况使用平昨
else: else:
req.offset = OFFSET_CLOSE req.offset = OFFSET_CLOSE
vtOrderID = self.mainEngine.sendOrder(req, contract.gatewayName) # 发单 vtOrderID = self.mainEngine.sendOrder(req, contract.gatewayName) # 发单
self.orderStrategyDict[vtOrderID] = strategy # 保存vtOrderID和策略的映射关系 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)) %(strategy.name, vtSymbol, req.direction, volume, price))
return vtOrderID return vtOrderID
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def cancelOrder(self, vtOrderID): def cancelOrder(self, vtOrderID):
"""撤单""" """撤单"""
# 查询报单对象 # 查询报单对象
order = self.mainEngine.getOrder(vtOrderID) order = self.mainEngine.getOrder(vtOrderID)
# 如果查询成功 # 如果查询成功
if order: if order:
# 检查是否报单还有效,只有有效时才发出撤单指令 # 检查是否报单还有效,只有有效时才发出撤单指令
@ -172,14 +173,14 @@ class CtaEngine(object):
req.frontID = order.frontID req.frontID = order.frontID
req.sessionID = order.sessionID req.sessionID = order.sessionID
req.orderID = order.orderID req.orderID = order.orderID
self.mainEngine.cancelOrder(req, order.gatewayName) self.mainEngine.cancelOrder(req, order.gatewayName)
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def sendStopOrder(self, vtSymbol, orderType, price, volume, strategy): def sendStopOrder(self, vtSymbol, orderType, price, volume, strategy):
"""发停止单(本地实现)""" """发停止单(本地实现)"""
self.stopOrderCount += 1 self.stopOrderCount += 1
stopOrderID = STOPORDERPREFIX + str(self.stopOrderCount) stopOrderID = STOPORDERPREFIX + str(self.stopOrderCount)
so = StopOrder() so = StopOrder()
so.vtSymbol = vtSymbol so.vtSymbol = vtSymbol
so.orderType = orderType so.orderType = orderType
@ -188,7 +189,7 @@ class CtaEngine(object):
so.strategy = strategy so.strategy = strategy
so.stopOrderID = stopOrderID so.stopOrderID = stopOrderID
so.status = STOPORDER_WAITING so.status = STOPORDER_WAITING
if orderType == CTAORDER_BUY: if orderType == CTAORDER_BUY:
so.direction = DIRECTION_LONG so.direction = DIRECTION_LONG
so.offset = OFFSET_OPEN so.offset = OFFSET_OPEN
@ -200,14 +201,14 @@ class CtaEngine(object):
so.offset = OFFSET_OPEN so.offset = OFFSET_OPEN
elif orderType == CTAORDER_COVER: elif orderType == CTAORDER_COVER:
so.direction = DIRECTION_LONG so.direction = DIRECTION_LONG
so.offset = OFFSET_CLOSE so.offset = OFFSET_CLOSE
# 保存stopOrder对象到字典中 # 保存stopOrder对象到字典中
self.stopOrderDict[stopOrderID] = so self.stopOrderDict[stopOrderID] = so
self.workingStopOrderDict[stopOrderID] = so self.workingStopOrderDict[stopOrderID] = so
return stopOrderID return stopOrderID
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def cancelStopOrder(self, stopOrderID): def cancelStopOrder(self, stopOrderID):
"""撤销停止单""" """撤销停止单"""
@ -221,7 +222,7 @@ class CtaEngine(object):
def processStopOrder(self, tick): def processStopOrder(self, tick):
"""收到行情后处理本地停止单(检查是否要立即发出)""" """收到行情后处理本地停止单(检查是否要立即发出)"""
vtSymbol = tick.vtSymbol vtSymbol = tick.vtSymbol
# 首先检查是否有策略交易该合约 # 首先检查是否有策略交易该合约
if vtSymbol in self.tickStrategyDict: if vtSymbol in self.tickStrategyDict:
# 遍历等待中的停止单,检查是否会被触发 # 遍历等待中的停止单,检查是否会被触发
@ -229,14 +230,14 @@ class CtaEngine(object):
if so.vtSymbol == vtSymbol: if so.vtSymbol == vtSymbol:
longTriggered = so.direction==DIRECTION_LONG and tick.lastPrice>=so.price # 多头停止单被触发 longTriggered = so.direction==DIRECTION_LONG and tick.lastPrice>=so.price # 多头停止单被触发
shortTriggered = so.direction==DIRECTION_SHORT and tick.lastPrice<=so.price # 空头停止单被触发 shortTriggered = so.direction==DIRECTION_SHORT and tick.lastPrice<=so.price # 空头停止单被触发
if longTriggered or shortTriggered: if longTriggered or shortTriggered:
# 买入和卖出分别以涨停跌停价发单(模拟市价单) # 买入和卖出分别以涨停跌停价发单(模拟市价单)
if so.direction==DIRECTION_LONG: if so.direction==DIRECTION_LONG:
price = tick.upperLimit price = tick.upperLimit
else: else:
price = tick.lowerLimit price = tick.lowerLimit
so.status = STOPORDER_TRIGGERED so.status = STOPORDER_TRIGGERED
self.sendOrder(so.vtSymbol, so.orderType, price, so.volume, so.strategy) self.sendOrder(so.vtSymbol, so.orderType, price, so.volume, so.strategy)
del self.workingStopOrderDict[so.stopOrderID] del self.workingStopOrderDict[so.stopOrderID]
@ -247,7 +248,7 @@ class CtaEngine(object):
tick = event.dict_['data'] tick = event.dict_['data']
# 收到tick行情后先处理本地停止单检查是否要立即发出 # 收到tick行情后先处理本地停止单检查是否要立即发出
self.processStopOrder(tick) self.processStopOrder(tick)
# 推送tick到对应的策略实例进行处理 # 推送tick到对应的策略实例进行处理
if tick.vtSymbol in self.tickStrategyDict: if tick.vtSymbol in self.tickStrategyDict:
# 将vtTickData数据转化为ctaTickData # 将vtTickData数据转化为ctaTickData
@ -258,43 +259,43 @@ class CtaEngine(object):
d[key] = tick.__getattribute__(key) d[key] = tick.__getattribute__(key)
# 添加datetime字段 # 添加datetime字段
ctaTick.datetime = datetime.strptime(' '.join([tick.date, tick.time]), '%Y%m%d %H:%M:%S.%f') ctaTick.datetime = datetime.strptime(' '.join([tick.date, tick.time]), '%Y%m%d %H:%M:%S.%f')
# 逐个推送到策略实例中 # 逐个推送到策略实例中
l = self.tickStrategyDict[tick.vtSymbol] l = self.tickStrategyDict[tick.vtSymbol]
for strategy in l: for strategy in l:
self.callStrategyFunc(strategy, strategy.onTick, ctaTick) self.callStrategyFunc(strategy, strategy.onTick, ctaTick)
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def processOrderEvent(self, event): def processOrderEvent(self, event):
"""处理委托推送""" """处理委托推送"""
order = event.dict_['data'] order = event.dict_['data']
if order.vtOrderID in self.orderStrategyDict: if order.vtOrderID in self.orderStrategyDict:
strategy = self.orderStrategyDict[order.vtOrderID] strategy = self.orderStrategyDict[order.vtOrderID]
self.callStrategyFunc(strategy, strategy.onOrder, order) self.callStrategyFunc(strategy, strategy.onOrder, order)
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def processTradeEvent(self, event): def processTradeEvent(self, event):
"""处理成交推送""" """处理成交推送"""
trade = event.dict_['data'] trade = event.dict_['data']
# 过滤已经收到过的成交回报 # 过滤已经收到过的成交回报
if trade.vtTradeID in self.tradeSet: if trade.vtTradeID in self.tradeSet:
return return
self.tradeSet.add(trade.vtTradeID) self.tradeSet.add(trade.vtTradeID)
# 将成交推送到策略对象中 # 将成交推送到策略对象中
if trade.vtOrderID in self.orderStrategyDict: if trade.vtOrderID in self.orderStrategyDict:
strategy = self.orderStrategyDict[trade.vtOrderID] strategy = self.orderStrategyDict[trade.vtOrderID]
# 计算策略持仓 # 计算策略持仓
if trade.direction == DIRECTION_LONG: if trade.direction == DIRECTION_LONG:
strategy.pos += trade.volume strategy.pos += trade.volume
else: else:
strategy.pos -= trade.volume strategy.pos -= trade.volume
self.callStrategyFunc(strategy, strategy.onTrade, trade) self.callStrategyFunc(strategy, strategy.onTrade, trade)
# 更新持仓缓存数据 # 更新持仓缓存数据
if trade.vtSymbol in self.tickStrategyDict: if trade.vtSymbol in self.tickStrategyDict:
posBuffer = self.posBufferDict.get(trade.vtSymbol, None) posBuffer = self.posBufferDict.get(trade.vtSymbol, None)
@ -302,13 +303,13 @@ class CtaEngine(object):
posBuffer = PositionBuffer() posBuffer = PositionBuffer()
posBuffer.vtSymbol = trade.vtSymbol posBuffer.vtSymbol = trade.vtSymbol
self.posBufferDict[trade.vtSymbol] = posBuffer self.posBufferDict[trade.vtSymbol] = posBuffer
posBuffer.updateTradeData(trade) posBuffer.updateTradeData(trade)
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def processPositionEvent(self, event): def processPositionEvent(self, event):
"""处理持仓推送""" """处理持仓推送"""
pos = event.dict_['data'] pos = event.dict_['data']
# 更新持仓缓存数据 # 更新持仓缓存数据
if pos.vtSymbol in self.tickStrategyDict: if pos.vtSymbol in self.tickStrategyDict:
posBuffer = self.posBufferDict.get(pos.vtSymbol, None) posBuffer = self.posBufferDict.get(pos.vtSymbol, None)
@ -317,7 +318,7 @@ class CtaEngine(object):
posBuffer.vtSymbol = pos.vtSymbol posBuffer.vtSymbol = pos.vtSymbol
self.posBufferDict[pos.vtSymbol] = posBuffer self.posBufferDict[pos.vtSymbol] = posBuffer
posBuffer.updatePositionData(pos) posBuffer.updatePositionData(pos)
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def registerEvent(self): def registerEvent(self):
"""注册事件监听""" """注册事件监听"""
@ -325,42 +326,42 @@ class CtaEngine(object):
self.eventEngine.register(EVENT_ORDER, self.processOrderEvent) self.eventEngine.register(EVENT_ORDER, self.processOrderEvent)
self.eventEngine.register(EVENT_TRADE, self.processTradeEvent) self.eventEngine.register(EVENT_TRADE, self.processTradeEvent)
self.eventEngine.register(EVENT_POSITION, self.processPositionEvent) self.eventEngine.register(EVENT_POSITION, self.processPositionEvent)
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def insertData(self, dbName, collectionName, data): def insertData(self, dbName, collectionName, data):
"""插入数据到数据库这里的data可以是CtaTickData或者CtaBarData""" """插入数据到数据库这里的data可以是CtaTickData或者CtaBarData"""
self.mainEngine.dbInsert(dbName, collectionName, data.__dict__) self.mainEngine.dbInsert(dbName, collectionName, data.__dict__)
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def loadBar(self, dbName, collectionName, days): def loadBar(self, dbName, collectionName, days):
"""从数据库中读取Bar数据startDate是datetime对象""" """从数据库中读取Bar数据startDate是datetime对象"""
startDate = self.today - timedelta(days) startDate = self.today - timedelta(days)
d = {'datetime':{'$gte':startDate}} d = {'datetime':{'$gte':startDate}}
barData = self.mainEngine.dbQuery(dbName, collectionName, d) barData = self.mainEngine.dbQuery(dbName, collectionName, d)
l = [] l = []
for d in barData: for d in barData:
bar = CtaBarData() bar = CtaBarData()
bar.__dict__ = d bar.__dict__ = d
l.append(bar) l.append(bar)
return l return l
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def loadTick(self, dbName, collectionName, days): def loadTick(self, dbName, collectionName, days):
"""从数据库中读取Tick数据startDate是datetime对象""" """从数据库中读取Tick数据startDate是datetime对象"""
startDate = self.today - timedelta(days) startDate = self.today - timedelta(days)
d = {'datetime':{'$gte':startDate}} d = {'datetime':{'$gte':startDate}}
tickData = self.mainEngine.dbQuery(dbName, collectionName, d) tickData = self.mainEngine.dbQuery(dbName, collectionName, d)
l = [] l = []
for d in tickData: for d in tickData:
tick = CtaTickData() tick = CtaTickData()
tick.__dict__ = d tick.__dict__ = d
l.append(tick) l.append(tick)
return l return l
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def writeCtaLog(self, content): def writeCtaLog(self, content):
"""快速发出CTA模块日志事件""" """快速发出CTA模块日志事件"""
@ -368,32 +369,32 @@ class CtaEngine(object):
log.logContent = content log.logContent = content
event = Event(type_=EVENT_CTA_LOG) event = Event(type_=EVENT_CTA_LOG)
event.dict_['data'] = log event.dict_['data'] = log
self.eventEngine.put(event) self.eventEngine.put(event)
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def loadStrategy(self, setting): def loadStrategy(self, setting):
"""载入策略""" """载入策略"""
try: try:
name = setting['name'] name = setting['name']
className = setting['className'] className = setting['className']
except Exception, e: except:
self.writeCtaLog(u'载入策略出错:%s' %e) self.writeCtaLog(u'载入策略出错:%s' %traceback.format_exc())
return return
# 获取策略类 # 获取策略类
strategyClass = STRATEGY_CLASS.get(className, None) strategyClass = STRATEGY_CLASS.get(className, None)
if not strategyClass: if not strategyClass:
self.writeCtaLog(u'找不到策略类:%s' %className) self.writeCtaLog(u'找不到策略类:%s' %className)
return return
# 防止策略重名 # 防止策略重名
if name in self.strategyDict: if name in self.strategyDict:
self.writeCtaLog(u'策略实例重名:%s' %name) self.writeCtaLog(u'策略实例重名:%s' %name)
else: else:
# 创建策略实例 # 创建策略实例
strategy = strategyClass(self, setting) strategy = strategyClass(self, setting)
self.strategyDict[name] = strategy self.strategyDict[name] = strategy
# 保存Tick映射关系 # 保存Tick映射关系
if strategy.vtSymbol in self.tickStrategyDict: if strategy.vtSymbol in self.tickStrategyDict:
l = self.tickStrategyDict[strategy.vtSymbol] l = self.tickStrategyDict[strategy.vtSymbol]
@ -401,18 +402,18 @@ class CtaEngine(object):
l = [] l = []
self.tickStrategyDict[strategy.vtSymbol] = l self.tickStrategyDict[strategy.vtSymbol] = l
l.append(strategy) l.append(strategy)
# 订阅合约 # 订阅合约
contract = self.mainEngine.getContract(strategy.vtSymbol) contract = self.mainEngine.getContract(strategy.vtSymbol)
if contract: if contract:
req = VtSubscribeReq() req = VtSubscribeReq()
req.symbol = contract.symbol req.symbol = contract.symbol
req.exchange = contract.exchange req.exchange = contract.exchange
# 对于IB接口订阅行情时所需的货币和产品类型从策略属性中获取 # 对于IB接口订阅行情时所需的货币和产品类型从策略属性中获取
req.currency = strategy.currency req.currency = strategy.currency
req.productClass = strategy.productClass req.productClass = strategy.productClass
self.mainEngine.subscribe(req, contract.gatewayName) self.mainEngine.subscribe(req, contract.gatewayName)
else: else:
self.writeCtaLog(u'%s的交易合约%s无法找到' %(name, strategy.vtSymbol)) self.writeCtaLog(u'%s的交易合约%s无法找到' %(name, strategy.vtSymbol))
@ -422,111 +423,111 @@ class CtaEngine(object):
"""初始化策略""" """初始化策略"""
if name in self.strategyDict: if name in self.strategyDict:
strategy = self.strategyDict[name] strategy = self.strategyDict[name]
if not strategy.inited: if not strategy.inited:
strategy.inited = True strategy.inited = True
self.callStrategyFunc(strategy, strategy.onInit) self.callStrategyFunc(strategy, strategy.onInit)
else: else:
self.writeCtaLog(u'请勿重复初始化策略实例:%s' %name) self.writeCtaLog(u'请勿重复初始化策略实例:%s' %name)
else: else:
self.writeCtaLog(u'策略实例不存在:%s' %name) self.writeCtaLog(u'策略实例不存在:%s' %name)
#--------------------------------------------------------------------- #---------------------------------------------------------------------
def startStrategy(self, name): def startStrategy(self, name):
"""启动策略""" """启动策略"""
if name in self.strategyDict: if name in self.strategyDict:
strategy = self.strategyDict[name] strategy = self.strategyDict[name]
if strategy.inited and not strategy.trading: if strategy.inited and not strategy.trading:
strategy.trading = True strategy.trading = True
self.callStrategyFunc(strategy, strategy.onStart) self.callStrategyFunc(strategy, strategy.onStart)
else: else:
self.writeCtaLog(u'策略实例不存在:%s' %name) self.writeCtaLog(u'策略实例不存在:%s' %name)
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def stopStrategy(self, name): def stopStrategy(self, name):
"""停止策略""" """停止策略"""
if name in self.strategyDict: if name in self.strategyDict:
strategy = self.strategyDict[name] strategy = self.strategyDict[name]
if strategy.trading: if strategy.trading:
strategy.trading = False strategy.trading = False
self.callStrategyFunc(strategy, strategy.onStop) self.callStrategyFunc(strategy, strategy.onStop)
# 对该策略发出的所有限价单进行撤单 # 对该策略发出的所有限价单进行撤单
for vtOrderID, s in self.orderStrategyDict.items(): for vtOrderID, s in self.orderStrategyDict.items():
if s is strategy: if s is strategy:
self.cancelOrder(vtOrderID) self.cancelOrder(vtOrderID)
# 对该策略发出的所有本地停止单撤单 # 对该策略发出的所有本地停止单撤单
for stopOrderID, so in self.workingStopOrderDict.items(): for stopOrderID, so in self.workingStopOrderDict.items():
if so.strategy is strategy: if so.strategy is strategy:
self.cancelStopOrder(stopOrderID) self.cancelStopOrder(stopOrderID)
else: else:
self.writeCtaLog(u'策略实例不存在:%s' %name) self.writeCtaLog(u'策略实例不存在:%s' %name)
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def saveSetting(self): def saveSetting(self):
"""保存策略配置""" """保存策略配置"""
with open(self.settingFileName, 'w') as f: with open(self.settingFileName, 'w') as f:
l = [] l = []
for strategy in self.strategyDict.values(): for strategy in self.strategyDict.values():
setting = {} setting = {}
for param in strategy.paramList: for param in strategy.paramList:
setting[param] = strategy.__getattribute__(param) setting[param] = strategy.__getattribute__(param)
l.append(setting) l.append(setting)
jsonL = json.dumps(l, indent=4) jsonL = json.dumps(l, indent=4)
f.write(jsonL) f.write(jsonL)
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def loadSetting(self): def loadSetting(self):
"""读取策略配置""" """读取策略配置"""
with open(self.settingFileName) as f: with open(self.settingFileName) as f:
l = json.load(f) l = json.load(f)
for setting in l: for setting in l:
self.loadStrategy(setting) self.loadStrategy(setting)
self.loadPosition() self.loadPosition()
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def getStrategyVar(self, name): def getStrategyVar(self, name):
"""获取策略当前的变量字典""" """获取策略当前的变量字典"""
if name in self.strategyDict: if name in self.strategyDict:
strategy = self.strategyDict[name] strategy = self.strategyDict[name]
varDict = OrderedDict() varDict = OrderedDict()
for key in strategy.varList: for key in strategy.varList:
varDict[key] = strategy.__getattribute__(key) varDict[key] = strategy.__getattribute__(key)
return varDict return varDict
else: else:
self.writeCtaLog(u'策略实例不存在:' + name) self.writeCtaLog(u'策略实例不存在:' + name)
return None return None
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def getStrategyParam(self, name): def getStrategyParam(self, name):
"""获取策略的参数字典""" """获取策略的参数字典"""
if name in self.strategyDict: if name in self.strategyDict:
strategy = self.strategyDict[name] strategy = self.strategyDict[name]
paramDict = OrderedDict() paramDict = OrderedDict()
for key in strategy.paramList: for key in strategy.paramList:
paramDict[key] = strategy.__getattribute__(key) paramDict[key] = strategy.__getattribute__(key)
return paramDict return paramDict
else: else:
self.writeCtaLog(u'策略实例不存在:' + name) self.writeCtaLog(u'策略实例不存在:' + name)
return None return None
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def putStrategyEvent(self, name): def putStrategyEvent(self, name):
"""触发策略状态变化事件通常用于通知GUI更新""" """触发策略状态变化事件通常用于通知GUI更新"""
event = Event(EVENT_CTA_STRATEGY+name) event = Event(EVENT_CTA_STRATEGY+name)
self.eventEngine.put(event) self.eventEngine.put(event)
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def callStrategyFunc(self, strategy, func, params=None): def callStrategyFunc(self, strategy, func, params=None):
"""调用策略的函数,若触发异常则捕捉""" """调用策略的函数,若触发异常则捕捉"""
@ -539,29 +540,29 @@ class CtaEngine(object):
# 停止策略,修改状态为未初始化 # 停止策略,修改状态为未初始化
strategy.trading = False strategy.trading = False
strategy.inited = False strategy.inited = False
# 发出日志 # 发出日志
content = '\n'.join([u'策略%s触发异常已停止' %strategy.name, content = '\n'.join([u'策略%s触发异常已停止' %strategy.name,
traceback.format_exc()]) traceback.format_exc()])
self.writeCtaLog(content) self.writeCtaLog(content)
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def savePosition(self): def savePosition(self):
"""保存所有策略的持仓情况到数据库""" """保存所有策略的持仓情况到数据库"""
for strategy in self.strategyDict.values(): for strategy in self.strategyDict.values():
flt = {'name': strategy.name, flt = {'name': strategy.name,
'vtSymbol': strategy.vtSymbol} 'vtSymbol': strategy.vtSymbol}
d = {'name': strategy.name, d = {'name': strategy.name,
'vtSymbol': strategy.vtSymbol, 'vtSymbol': strategy.vtSymbol,
'pos': strategy.pos} 'pos': strategy.pos}
self.mainEngine.dbUpdate(POSITION_DB_NAME, strategy.className, self.mainEngine.dbUpdate(POSITION_DB_NAME, strategy.className,
d, flt, True) d, flt, True)
content = '策略%s持仓保存成功' %strategy.name content = '策略%s持仓保存成功' %strategy.name
self.writeCtaLog(content) self.writeCtaLog(content)
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def loadPosition(self): def loadPosition(self):
"""从数据库载入策略的持仓情况""" """从数据库载入策略的持仓情况"""
@ -569,18 +570,18 @@ class CtaEngine(object):
flt = {'name': strategy.name, flt = {'name': strategy.name,
'vtSymbol': strategy.vtSymbol} 'vtSymbol': strategy.vtSymbol}
posData = self.mainEngine.dbQuery(POSITION_DB_NAME, strategy.className, flt) posData = self.mainEngine.dbQuery(POSITION_DB_NAME, strategy.className, flt)
for d in posData: for d in posData:
strategy.pos = d['pos'] strategy.pos = d['pos']
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def roundToPriceTick(self, priceTick, price): def roundToPriceTick(self, priceTick, price):
"""取整价格到合约最小价格变动""" """取整价格到合约最小价格变动"""
if not priceTick: if not priceTick:
return price return price
newPrice = round(price/priceTick, 0) * priceTick newPrice = round(price/priceTick, 0) * priceTick
return newPrice return newPrice
######################################################################## ########################################################################
@ -591,17 +592,17 @@ class PositionBuffer(object):
def __init__(self): def __init__(self):
"""Constructor""" """Constructor"""
self.vtSymbol = EMPTY_STRING self.vtSymbol = EMPTY_STRING
# 多头 # 多头
self.longPosition = EMPTY_INT self.longPosition = EMPTY_INT
self.longToday = EMPTY_INT self.longToday = EMPTY_INT
self.longYd = EMPTY_INT self.longYd = EMPTY_INT
# 空头 # 空头
self.shortPosition = EMPTY_INT self.shortPosition = EMPTY_INT
self.shortToday = EMPTY_INT self.shortToday = EMPTY_INT
self.shortYd = EMPTY_INT self.shortYd = EMPTY_INT
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def updatePositionData(self, pos): def updatePositionData(self, pos):
"""更新持仓数据""" """更新持仓数据"""
@ -613,7 +614,7 @@ class PositionBuffer(object):
self.shortPosition = pos.position self.shortPosition = pos.position
self.shortYd = pos.ydPosition self.shortYd = pos.ydPosition
self.shortToday = self.shortPosition - self.shortYd self.shortToday = self.shortPosition - self.shortYd
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def updateTradeData(self, trade): def updateTradeData(self, trade):
"""更新成交数据""" """更新成交数据"""
@ -641,9 +642,9 @@ class PositionBuffer(object):
else: else:
self.longPosition -= trade.volume self.longPosition -= trade.volume
self.longYd -= trade.volume self.longYd -= trade.volume

View File

@ -90,9 +90,9 @@ class HistoryDataEngine(object):
self.dbClient[SETTING_DB_NAME]['FuturesSymbol'].update_one(flt, {'$set':symbolDict}, self.dbClient[SETTING_DB_NAME]['FuturesSymbol'].update_one(flt, {'$set':symbolDict},
upsert=True) upsert=True)
print u'期货合约代码下载完成' print(u'期货合约代码下载完成')
else: else:
print u'期货合约代码下载失败' print(u'期货合约代码下载失败')
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def downloadFuturesDailyBar(self, symbol): def downloadFuturesDailyBar(self, symbol):
@ -100,7 +100,7 @@ class HistoryDataEngine(object):
下载期货合约的日行情symbol是合约代码 下载期货合约的日行情symbol是合约代码
若最后四位为0000如IF0000代表下载连续合约 若最后四位为0000如IF0000代表下载连续合约
""" """
print u'开始下载%s日行情' %symbol print(u'开始下载%s日行情' %symbol)
# 查询数据库中已有数据的最后日期 # 查询数据库中已有数据的最后日期
cl = self.dbClient[DAILY_DB_NAME][symbol] cl = self.dbClient[DAILY_DB_NAME][symbol]
@ -152,24 +152,24 @@ class HistoryDataEngine(object):
bar.volume = d.get('turnoverVol', 0) bar.volume = d.get('turnoverVol', 0)
bar.openInterest = d.get('openInt', 0) bar.openInterest = d.get('openInt', 0)
except KeyError: except KeyError:
print d print(d)
flt = {'datetime': bar.datetime} flt = {'datetime': bar.datetime}
self.dbClient[DAILY_DB_NAME][symbol].update_one(flt, {'$set':bar.__dict__}, upsert=True) self.dbClient[DAILY_DB_NAME][symbol].update_one(flt, {'$set':bar.__dict__}, upsert=True)
print u'%s下载完成' %symbol print(u'%s下载完成' %symbol)
else: else:
print u'找不到合约%s' %symbol print(u'找不到合约%s' %symbol)
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def downloadAllFuturesDailyBar(self): def downloadAllFuturesDailyBar(self):
"""下载所有期货的主力合约日行情""" """下载所有期货的主力合约日行情"""
start = time() start = time()
print u'开始下载所有期货的主力合约日行情' print(u'开始下载所有期货的主力合约日行情')
productSymbolSet = self.readFuturesProductSymbol() productSymbolSet = self.readFuturesProductSymbol()
print u'代码列表读取成功,产品代码:%s' %productSymbolSet print(u'代码列表读取成功,产品代码:%s' %productSymbolSet)
# 这里也测试了线程池,但可能由于下载函数中涉及较多的数据格 # 这里也测试了线程池,但可能由于下载函数中涉及较多的数据格
# 式转换CPU开销较大多线程效率并无显著改变。 # 式转换CPU开销较大多线程效率并无显著改变。
@ -181,12 +181,12 @@ class HistoryDataEngine(object):
for productSymbol in productSymbolSet: for productSymbol in productSymbolSet:
self.downloadFuturesDailyBar(productSymbol+'0000') self.downloadFuturesDailyBar(productSymbol+'0000')
print u'所有期货的主力合约日行情已经全部下载完成, 耗时%s' %(time()-start) print(u'所有期货的主力合约日行情已经全部下载完成, 耗时%s' %(time()-start))
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def downloadFuturesIntradayBar(self, symbol): def downloadFuturesIntradayBar(self, symbol):
"""下载期货的日内分钟行情""" """下载期货的日内分钟行情"""
print u'开始下载%s日内分钟行情' %symbol print(u'开始下载%s日内分钟行情' %symbol)
# 日内分钟行情只有具体合约 # 日内分钟行情只有具体合约
path = 'api/market/getFutureBarRTIntraDay.json' path = 'api/market/getFutureBarRTIntraDay.json'
@ -220,14 +220,14 @@ class HistoryDataEngine(object):
bar.volume = d.get('totalVolume', 0) bar.volume = d.get('totalVolume', 0)
bar.openInterest = 0 bar.openInterest = 0
except KeyError: except KeyError:
print d print(d)
flt = {'datetime': bar.datetime} flt = {'datetime': bar.datetime}
self.dbClient[MINUTE_DB_NAME][symbol].update_one(flt, {'$set':bar.__dict__}, upsert=True) self.dbClient[MINUTE_DB_NAME][symbol].update_one(flt, {'$set':bar.__dict__}, upsert=True)
print u'%s下载完成' %symbol print(u'%s下载完成' %symbol)
else: else:
print u'找不到合约%s' %symbol print(u'找不到合约%s' %symbol)
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def downloadEquitySymbol(self, tradeDate=''): def downloadEquitySymbol(self, tradeDate=''):
@ -254,16 +254,16 @@ class HistoryDataEngine(object):
self.dbClient[SETTING_DB_NAME]['EquitySymbol'].update_one(flt, {'$set':symbolDict}, self.dbClient[SETTING_DB_NAME]['EquitySymbol'].update_one(flt, {'$set':symbolDict},
upsert=True) upsert=True)
print u'股票代码下载完成' print(u'股票代码下载完成')
else: else:
print u'股票代码下载失败' print(u'股票代码下载失败')
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def downloadEquityDailyBar(self, symbol): def downloadEquityDailyBar(self, symbol):
""" """
下载股票的日行情symbol是股票代码 下载股票的日行情symbol是股票代码
""" """
print u'开始下载%s日行情' %symbol print(u'开始下载%s日行情' %symbol)
# 查询数据库中已有数据的最后日期 # 查询数据库中已有数据的最后日期
cl = self.dbClient[DAILY_DB_NAME][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.datetime = datetime.strptime(bar.date, '%Y%m%d')
bar.volume = d.get('turnoverVol', 0) bar.volume = d.get('turnoverVol', 0)
except KeyError: except KeyError:
print d print(d)
flt = {'datetime': bar.datetime} flt = {'datetime': bar.datetime}
self.dbClient[DAILY_DB_NAME][symbol].update_one(flt, {'$set':bar.__dict__}, upsert=True) self.dbClient[DAILY_DB_NAME][symbol].update_one(flt, {'$set':bar.__dict__}, upsert=True)
print u'%s下载完成' %symbol print(u'%s下载完成' %symbol)
else: else:
print u'找不到合约%s' %symbol print(u'找不到合约%s' %symbol)
@ -319,7 +319,7 @@ def downloadEquityDailyBarts(self, symbol):
""" """
下载股票的日行情symbol是股票代码 下载股票的日行情symbol是股票代码
""" """
print u'开始下载%s日行情' %symbol print(u'开始下载%s日行情' %symbol)
# 查询数据库中已有数据的最后日期 # 查询数据库中已有数据的最后日期
cl = self.dbClient[DAILY_DB_NAME][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.datetime = datetime.strptime(bar.date, '%Y%m%d')
bar.volume = d.get('volume') bar.volume = d.get('volume')
except KeyError: except KeyError:
print d print(d)
flt = {'datetime': bar.datetime} flt = {'datetime': bar.datetime}
self.dbClient[DAILY_DB_NAME][symbol].update_one(flt, {'$set':bar.__dict__}, upsert=True) self.dbClient[DAILY_DB_NAME][symbol].update_one(flt, {'$set':bar.__dict__}, upsert=True)
print u'%s下载完成' %symbol print(u'%s下载完成' %symbol)
else: else:
print u'找不到合约%s' %symbol print(u'找不到合约%s' %symbol)
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def loadMcCsv(fileName, dbName, symbol): def loadMcCsv(fileName, dbName, symbol):
"""将Multicharts导出的csv格式的历史数据插入到Mongo数据库中""" """将Multicharts导出的csv格式的历史数据插入到Mongo数据库中"""
import csv import csv
start = time() start = time()
print u'开始读取CSV文件%s中的数据插入到%s%s' %(fileName, dbName, symbol) print(u'开始读取CSV文件%s中的数据插入到%s%s' %(fileName, dbName, symbol))
# 锁定集合,并创建索引 # 锁定集合,并创建索引
host, port, logging = loadMongoSetting() host, port, logging = loadMongoSetting()
@ -395,9 +395,9 @@ def loadMcCsv(fileName, dbName, symbol):
flt = {'datetime': bar.datetime} flt = {'datetime': bar.datetime}
collection.update_one(flt, {'$set':bar.__dict__}, upsert=True) 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): def loadTdxCsv(fileName, dbName, symbol):
@ -405,7 +405,7 @@ def loadTdxCsv(fileName, dbName, symbol):
import csv import csv
start = time() start = time()
print u'开始读取CSV文件%s中的数据插入到%s%s' %(fileName, dbName, symbol) print(u'开始读取CSV文件%s中的数据插入到%s%s' %(fileName, dbName, symbol))
# 锁定集合,并创建索引 # 锁定集合,并创建索引
host, port, logging = loadMongoSetting() host, port, logging = loadMongoSetting()
@ -432,9 +432,9 @@ def loadTdxCsv(fileName, dbName, symbol):
flt = {'datetime': bar.datetime} flt = {'datetime': bar.datetime}
collection.update_one(flt, {'$set':bar.__dict__}, upsert=True) 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): def loadTBCsv(fileName, dbName, symbol):
@ -446,7 +446,7 @@ def loadTBCsv(fileName, dbName, symbol):
import csv import csv
start = time() start = time()
print u'开始读取CSV文件%s中的数据插入到%s%s' %(fileName, dbName, symbol) print(u'开始读取CSV文件%s中的数据插入到%s%s' %(fileName, dbName, symbol))
# 锁定集合,并创建索引 # 锁定集合,并创建索引
host, port, logging = loadMongoSetting() host, port, logging = loadMongoSetting()
@ -477,9 +477,9 @@ def loadTBCsv(fileName, dbName, symbol):
flt = {'datetime': bar.datetime} flt = {'datetime': bar.datetime}
collection.update_one(flt, {'$set':bar.__dict__}, upsert=True) 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__': if __name__ == '__main__':

View File

@ -35,7 +35,7 @@ class DatayesClient(object):
FILENAME = os.path.join(path, FILENAME) FILENAME = os.path.join(path, FILENAME)
f = file(FILENAME) f = file(FILENAME)
except IOError: except IOError:
print u'%s无法打开配置文件' % self.name print(u'%s无法打开配置文件' % self.name)
return return
setting = json.load(f) setting = json.load(f)
@ -44,28 +44,28 @@ class DatayesClient(object):
self.version = str(setting['version']) self.version = str(setting['version'])
self.token = str(setting['token']) self.token = str(setting['token'])
except KeyError: except KeyError:
print u'%s配置文件字段缺失' % self.name print(u'%s配置文件字段缺失' % self.name)
return return
self.header['Connection'] = 'keep_alive' self.header['Connection'] = 'keep_alive'
self.header['Authorization'] = 'Bearer ' + self.token self.header['Authorization'] = 'Bearer ' + self.token
self.settingLoaded = True self.settingLoaded = True
print u'%s配置载入完成' % self.name print(u'%s配置载入完成' % self.name)
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def downloadData(self, path, params): def downloadData(self, path, params):
"""下载数据""" """下载数据"""
if not self.settingLoaded: if not self.settingLoaded:
print u'%s配置未载入' % self.name print(u'%s配置未载入' % self.name)
return None return None
else: else:
url = '/'.join([self.domain, self.version, path]) url = '/'.join([self.domain, self.version, path])
r = requests.get(url=url, headers=self.header, params=params) r = requests.get(url=url, headers=self.header, params=params)
if r.status_code != HTTP_OK: 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 return None
else: else:
result = r.json() result = r.json()
@ -73,9 +73,9 @@ class DatayesClient(object):
return result['data'] return result['data']
else: else:
if 'retMsg' in result: if 'retMsg' in result:
print u'%s查询失败,返回信息%s' %(self.name, result['retMsg']) print(u'%s查询失败,返回信息%s' %(self.name, result['retMsg']))
elif 'message' in result: elif 'message' in result:
print u'%s查询失败,返回信息%s' %(self.name, result['message']) print(u'%s查询失败,返回信息%s' %(self.name, result['message']))
return None return None

View File

@ -32,6 +32,6 @@ for root, subdirs, files in os.walk(path):
v = module.__getattribute__(k) v = module.__getattribute__(k)
STRATEGY_CLASS[k] = v STRATEGY_CLASS[k] = v
except: except:
print '-' * 20 print('-' * 20)
print ('Failed to import strategy file %s:' %moduleName) print('Failed to import strategy file %s:' %moduleName)
traceback.print_exc() traceback.print_exc()

View File

@ -157,7 +157,7 @@ class BacktestEngineMultiTF(BacktestingEngine):
try: try:
self.infobar[info_symbol] = next(self.InfoCursor[info_symbol]) self.infobar[info_symbol] = next(self.InfoCursor[info_symbol])
except StopIteration: 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 raise
temp = {} temp = {}

View File

@ -216,7 +216,7 @@ class Prototype(AtrRsiStrategy):
try: try:
self.initInfobar[info_symbol] = next(initInfoCursorDict[info_symbol]) self.initInfobar[info_symbol] = next(initInfoCursorDict[info_symbol])
except StopIteration: 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 raise
# 若有某一品种的 TimeStamp 和执行报价的 TimeStamp 匹配, 则将"initInfobar"中的数据推送, # 若有某一品种的 TimeStamp 和执行报价的 TimeStamp 匹配, 则将"initInfobar"中的数据推送,
@ -407,4 +407,4 @@ if __name__ == '__main__':
# 显示回测结果 # 显示回测结果
engine.showBacktestingResult() engine.showBacktestingResult()
print 'Time consumed%s' % (time.time() - start) print('Time consumed%s' % (time.time() - start))

View File

@ -113,7 +113,7 @@ class BreakOut(CtaTemplate):
try: try:
self.initInfobar[info_symbol] = next(initInfoCursorDict[info_symbol]) self.initInfobar[info_symbol] = next(initInfoCursorDict[info_symbol])
except StopIteration: 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 raise
# 若有某一品种的 TimeStamp 和执行报价的 TimeStamp 匹配, 则将"initInfobar"中的数据推送, # 若有某一品种的 TimeStamp 和执行报价的 TimeStamp 匹配, 则将"initInfobar"中的数据推送,
@ -314,4 +314,4 @@ if __name__ == '__main__':
# 显示回测结果 # 显示回测结果
engine.showBacktestingResult() engine.showBacktestingResult()
print 'Time consumed%s' % (time.time() - start) print('Time consumed%s' % (time.time() - start))

View File

@ -51,12 +51,12 @@ def test():
for key, value in check_dict.items(): for key, value in check_dict.items():
if len(value)>1: if len(value)>1:
print u'存在重复的常量定义:' + str(key) print(u'存在重复的常量定义:' + str(key))
for name in value: for name in value:
print name print(name)
print '' print('')
print u'测试完毕' print(u'测试完毕')
# 直接运行脚本可以进行测试 # 直接运行脚本可以进行测试

View File

@ -1472,7 +1472,7 @@ def test():
def print_log(event): def print_log(event):
log = event.dict_['data'] log = event.dict_['data']
print ':'.join([log.logTime, log.logContent]) print(':'.join([log.logTime, log.logContent]))
app = QtCore.QCoreApplication(sys.argv) app = QtCore.QCoreApplication(sys.argv)

View File

@ -605,10 +605,10 @@ class FemasTdApi(TdApi):
# 如果登录成功,推送日志信息 # 如果登录成功,推送日志信息
if error['ErrorID'] == 0: if error['ErrorID'] == 0:
for k, v in data.items(): for k, v in data.items():
print k, ':', v print(k, ':', v)
if data['MaxOrderLocalID']: if data['MaxOrderLocalID']:
self.localID = int(data['MaxOrderLocalID']) # 目前最大本地报单号 self.localID = int(data['MaxOrderLocalID']) # 目前最大本地报单号
print 'id now', self.localID print('id now', self.localID)
self.loginStatus = True self.loginStatus = True
self.gateway.mdConnected = True self.gateway.mdConnected = True
@ -960,7 +960,7 @@ def test():
def print_log(event): def print_log(event):
log = event.dict_['data'] log = event.dict_['data']
print ':'.join([log.logTime, log.logContent]) print(':'.join([log.logTime, log.logContent]))
app = QtCore.QCoreApplication(sys.argv) app = QtCore.QCoreApplication(sys.argv)

View File

@ -373,12 +373,12 @@ class HuobiTradeApi(vnhuobi.TradeApi):
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onBuyMarket(self, data, req, reqID): def onBuyMarket(self, data, req, reqID):
"""市价买入回调""" """市价买入回调"""
print data print(data)
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onSellMarket(self, data, req, reqID): def onSellMarket(self, data, req, reqID):
"""市价卖出回调""" """市价卖出回调"""
print data print(data)
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onCancelOrder(self, data, req, reqID): def onCancelOrder(self, data, req, reqID):
@ -396,52 +396,52 @@ class HuobiTradeApi(vnhuobi.TradeApi):
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onGetNewDealOrders(self, data, req, reqID): def onGetNewDealOrders(self, data, req, reqID):
"""查询最新成交回调""" """查询最新成交回调"""
print data print(data)
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onGetOrderIdByTradeId(self, data, req, reqID): def onGetOrderIdByTradeId(self, data, req, reqID):
"""通过成交编号查询委托编号回调""" """通过成交编号查询委托编号回调"""
print data print(data)
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onWithdrawCoin(self, data, req, reqID): def onWithdrawCoin(self, data, req, reqID):
"""提币回调""" """提币回调"""
print data print(data)
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onCancelWithdrawCoin(self, data, req, reqID): def onCancelWithdrawCoin(self, data, req, reqID):
"""取消提币回调""" """取消提币回调"""
print data print(data)
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onGetWithdrawCoinResult(self, data, req, reqID): def onGetWithdrawCoinResult(self, data, req, reqID):
"""查询提币结果回调""" """查询提币结果回调"""
print data print(data)
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onTransfer(self, data, req, reqID): def onTransfer(self, data, req, reqID):
"""转账回调""" """转账回调"""
print data print(data)
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onLoan(self, data, req, reqID): def onLoan(self, data, req, reqID):
"""申请杠杆回调""" """申请杠杆回调"""
print data print(data)
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onRepayment(self, data, req, reqID): def onRepayment(self, data, req, reqID):
"""归还杠杆回调""" """归还杠杆回调"""
print data print(data)
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onLoanAvailable(self, data, req, reqID): def onLoanAvailable(self, data, req, reqID):
"""查询杠杆额度回调""" """查询杠杆额度回调"""
print data print(data)
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onGetLoans(self, data, req, reqID): def onGetLoans(self, data, req, reqID):
"""查询杠杆列表""" """查询杠杆列表"""
print data print(data)
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def connect(self, accessKey, secretKey, market, debug=False): def connect(self, accessKey, secretKey, market, debug=False):
@ -553,7 +553,7 @@ class HuobiDataApi(vnhuobi.DataApi):
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onTick(self, data): def onTick(self, data):
"""实时成交推送""" """实时成交推送"""
print data print(data)
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onQuote(self, data): def onQuote(self, data):

View File

@ -2,6 +2,7 @@
import urllib import urllib
import hashlib import hashlib
import traceback
import json import json
import requests import requests
@ -144,7 +145,7 @@ class TradeApi(object):
# 请求成功 # 请求成功
else: else:
if self.DEBUG: if self.DEBUG:
print callback.__name__ print(callback.__name__)
callback(data, req, reqID) callback(data, req, reqID)
except Empty: except Empty:
@ -428,97 +429,97 @@ class TradeApi(object):
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onError(self, error, req, reqID): def onError(self, error, req, reqID):
"""错误推送""" """错误推送"""
print error, reqID print(error, reqID)
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onGetAccountInfo(self, data, req, reqID): def onGetAccountInfo(self, data, req, reqID):
"""查询账户回调""" """查询账户回调"""
print data print(data)
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onGetOrders(self, data, req, reqID, fuck): def onGetOrders(self, data, req, reqID, fuck):
"""查询委托回调""" """查询委托回调"""
print data print(data)
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onOrderInfo(self, data, req, reqID): def onOrderInfo(self, data, req, reqID):
"""委托详情回调""" """委托详情回调"""
print data print(data)
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onBuy(self, data, req, reqID): def onBuy(self, data, req, reqID):
"""买入回调""" """买入回调"""
print data print(data)
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onSell(self, data, req, reqID): def onSell(self, data, req, reqID):
"""卖出回调""" """卖出回调"""
print data print(data)
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onBuyMarket(self, data, req, reqID): def onBuyMarket(self, data, req, reqID):
"""市价买入回调""" """市价买入回调"""
print data print(data)
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onSellMarket(self, data, req, reqID): def onSellMarket(self, data, req, reqID):
"""市价卖出回调""" """市价卖出回调"""
print data print(data)
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onCancelOrder(self, data, req, reqID): def onCancelOrder(self, data, req, reqID):
"""撤单回调""" """撤单回调"""
print data print(data)
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onGetNewDealOrders(self, data, req, reqID): def onGetNewDealOrders(self, data, req, reqID):
"""查询最新成交回调""" """查询最新成交回调"""
print data print(data)
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onGetOrderIdByTradeId(self, data, req, reqID): def onGetOrderIdByTradeId(self, data, req, reqID):
"""通过成交编号查询委托编号回调""" """通过成交编号查询委托编号回调"""
print data print(data)
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onWithdrawCoin(self, data, req, reqID): def onWithdrawCoin(self, data, req, reqID):
"""提币回调""" """提币回调"""
print data print(data)
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onCancelWithdrawCoin(self, data, req, reqID): def onCancelWithdrawCoin(self, data, req, reqID):
"""取消提币回调""" """取消提币回调"""
print data print(data)
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onGetWithdrawCoinResult(self, data, req, reqID): def onGetWithdrawCoinResult(self, data, req, reqID):
"""查询提币结果回调""" """查询提币结果回调"""
print data print(data)
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onTransfer(self, data, req, reqID): def onTransfer(self, data, req, reqID):
"""转账回调""" """转账回调"""
print data print(data)
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onLoan(self, data, req, reqID): def onLoan(self, data, req, reqID):
"""申请杠杆回调""" """申请杠杆回调"""
print data print(data)
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onRepayment(self, data, req, reqID): def onRepayment(self, data, req, reqID):
"""归还杠杆回调""" """归还杠杆回调"""
print data print(data)
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onLoanAvailable(self, data, req, reqID): def onLoanAvailable(self, data, req, reqID):
"""查询杠杆额度回调""" """查询杠杆额度回调"""
print data print(data)
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onGetLoans(self, data, req, reqID): def onGetLoans(self, data, req, reqID):
"""查询杠杆列表""" """查询杠杆列表"""
print data print(data)
######################################################################## ########################################################################
@ -586,10 +587,11 @@ class DataApi(object):
if r.status_code == 200: if r.status_code == 200:
data = r.json() data = r.json()
if self.DEBUG: if self.DEBUG:
print callback.__name__ print(callback.__name__)
callback(data) callback(data)
except Exception, e: except:
print e traceback.print_exc()
sleep(self.taskInterval) sleep(self.taskInterval)
@ -621,17 +623,17 @@ class DataApi(object):
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onTick(self, data): def onTick(self, data):
"""实时成交推送""" """实时成交推送"""
print data print(data)
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onQuote(self, data): def onQuote(self, data):
"""实时报价推送""" """实时报价推送"""
print data print(data)
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onDepth(self, data): def onDepth(self, data):
"""实时深度推送""" """实时深度推送"""
print data print(data)
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def getKline(self, symbol, period, length=0): def getKline(self, symbol, period, length=0):
@ -647,6 +649,6 @@ class DataApi(object):
if r.status_code == 200: if r.status_code == 200:
data = r.json() data = r.json()
return data return data
except Exception, e: except:
print e traceback.print_exc()
return None return None

View File

@ -372,7 +372,7 @@ class IbWrapper(IbApi):
newtick = copy(tick) newtick = copy(tick)
self.gateway.onTick(newtick) self.gateway.onTick(newtick)
else: else:
print field print(field)
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def tickSize(self, tickerId, field, size): def tickSize(self, tickerId, field, size):
@ -382,7 +382,7 @@ class IbWrapper(IbApi):
key = tickFieldMap[field] key = tickFieldMap[field]
tick.__setattr__(key, size) tick.__setattr__(key, size)
else: else:
print field print(field)
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def tickOptionComputation(self, tickerId, tickType, impliedVol, delta, optPrice, pvDividend, gamma, vega, theta, undPrice): def tickOptionComputation(self, tickerId, tickType, impliedVol, delta, optPrice, pvDividend, gamma, vega, theta, undPrice):

View File

@ -1825,7 +1825,7 @@ def test():
def print_log(event): def print_log(event):
log = event.dict_['data'] log = event.dict_['data']
print ':'.join([log.logTime, log.logContent]) print(':'.join([log.logTime, log.logContent]))
app = QtCore.QCoreApplication(sys.argv) app = QtCore.QCoreApplication(sys.argv)

View File

@ -244,11 +244,11 @@ class LhangApi(vnlhang.LhangApi):
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
def onGetTrades(self, data, req, reqID): def onGetTrades(self, data, req, reqID):
"""查询历史成交""" """查询历史成交"""
print data, reqID print(data, reqID)
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
def onGetKline(self, data, req, reqID): def onGetKline(self, data, req, reqID):
print data, reqID print(data, reqID)
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
def onGetUserInfo(self, data, req, reqID): def onGetUserInfo(self, data, req, reqID):

View File

@ -120,7 +120,7 @@ class LhangApi(object):
# 请求成功 # 请求成功
else: else:
if self.DEBUG: if self.DEBUG:
print callback.__name__ print(callback.__name__)
callback(data, req, reqID) callback(data, req, reqID)
# 流控等待 # 流控等待
@ -149,7 +149,7 @@ class LhangApi(object):
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onError(self, error, req, reqID): 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): def onGetTicker(self, data, req, reqID):
"""查询行情回调""" """查询行情回调"""
print data, reqID print(data, reqID)
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
def onGetDepth(self, data, req, reqID): def onGetDepth(self, data, req, reqID):
"""查询深度回调""" """查询深度回调"""
print data, reqID print(data, reqID)
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
def onGetTrades(self, data, req, reqID): def onGetTrades(self, data, req, reqID):
"""查询历史成交""" """查询历史成交"""
print data, reqID print(data, reqID)
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
def onGetKline(self, data, req, reqID): def onGetKline(self, data, req, reqID):
"""查询K线回报""" """查询K线回报"""
print data, reqID print(data, reqID)
############################################### ###############################################
# 交易接口 # 交易接口
@ -283,25 +283,25 @@ class LhangApi(object):
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
def onGetUserInfo(self, data, req, reqID): def onGetUserInfo(self, data, req, reqID):
"""查询K线回报""" """查询K线回报"""
print data, reqID print(data, reqID)
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
def onCreateOrder(self, data, req, reqID): def onCreateOrder(self, data, req, reqID):
"""委托回报""" """委托回报"""
print data, reqID print(data, reqID)
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
def onCancelOrder(self, data, req, reqID): def onCancelOrder(self, data, req, reqID):
"""撤单回报""" """撤单回报"""
print data, reqID print(data, reqID)
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
def onGetOrdersInfo(self, data, req, reqID): def onGetOrdersInfo(self, data, req, reqID):
"""查询委托回报""" """查询委托回报"""
print data, reqID print(data, reqID)
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
def onGetOrdersInfoHistory(self, data, req, reqID): def onGetOrdersInfoHistory(self, data, req, reqID):
"""撤单回报""" """撤单回报"""
print data, reqID print(data, reqID)

View File

@ -987,7 +987,7 @@ class LtsQryApi(QryApi):
elif data['ProductClass'] == '8': elif data['ProductClass'] == '8':
contract.productClass = PRODUCT_EQUITY contract.productClass = PRODUCT_EQUITY
else: else:
print data['ProductClass'] print(data['ProductClass'])
# 期权类型 # 期权类型
if data['InstrumentType'] == '1': if data['InstrumentType'] == '1':

View File

@ -1,5 +1,6 @@
# encoding: utf-8 # encoding: utf-8
import traceback
import json import json
import requests import requests
from Queue import Queue, Empty from Queue import Queue, Empty
@ -208,8 +209,8 @@ class OandaApi(object):
try: try:
r = self.session.send(pre, stream=stream) r = self.session.send(pre, stream=stream)
except Exception, e: except :
error = e error = traceback.format_exc()
return r, error return r, error
@ -228,10 +229,10 @@ class OandaApi(object):
try: try:
data = r.json() data = r.json()
if self.DEBUG: if self.DEBUG:
print callback.__name__ print(callback.__name__)
callback(data, reqID) callback(data, reqID)
except Exception, e: except :
self.onError(str(e), reqID) self.onError(traceback.format_exc(), reqID)
else: else:
self.onError(error, reqID) self.onError(error, reqID)
except Empty: except Empty:
@ -260,7 +261,7 @@ class OandaApi(object):
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onError(self, error, reqID): def onError(self, error, reqID):
"""错误信息回调""" """错误信息回调"""
print error, reqID print(error, reqID)
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def getInstruments(self, params): def getInstruments(self, params):
@ -526,12 +527,12 @@ class OandaApi(object):
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onPrice(self, data): def onPrice(self, data):
"""行情推送""" """行情推送"""
print data print(data)
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onEvent(self, data): def onEvent(self, data):
"""事件推送(成交等)""" """事件推送(成交等)"""
print data print(data)
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def processStreamPrices(self): def processStreamPrices(self):
@ -546,8 +547,8 @@ class OandaApi(object):
try: try:
data = r.json() data = r.json()
symbols = [d['instrument'] for d in data['instruments']] symbols = [d['instrument'] for d in data['instruments']]
except Exception, e: except :
self.onError(e, -1) self.onError(traceback.format_exc(), -1)
return return
else: else:
self.onError(error, -1) self.onError(error, -1)
@ -570,11 +571,11 @@ class OandaApi(object):
msg = json.loads(line) msg = json.loads(line)
if self.DEBUG: if self.DEBUG:
print self.onPrice.__name__ print(self.onPrice.__name__)
self.onPrice(msg) self.onPrice(msg)
except Exception, e: except :
self.onError(e, -1) self.onError(traceback.format_exc(), -1)
if not self.active: if not self.active:
break break
@ -597,11 +598,11 @@ class OandaApi(object):
msg = json.loads(line) msg = json.loads(line)
if self.DEBUG: if self.DEBUG:
print self.onEvent.__name__ print(self.onEvent.__name__)
self.onEvent(msg) self.onEvent(msg)
except Exception, e: except :
self.onError(e, -1) self.onError(traceback.format_exc(), -1)
if not self.active: if not self.active:
break break

View File

@ -123,25 +123,25 @@ class OkCoinApi(object):
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onMessage(self, ws, evt): def onMessage(self, ws, evt):
"""信息推送""" """信息推送"""
print 'onMessage' print('onMessage')
data = self.readData(evt) data = self.readData(evt)
print data print(data)
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onError(self, ws, evt): def onError(self, ws, evt):
"""错误推送""" """错误推送"""
print 'onError' print('onError')
print evt print(evt)
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onClose(self, ws): def onClose(self, ws):
"""接口断开""" """接口断开"""
print 'onClose' print('onClose')
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def onOpen(self, ws): def onOpen(self, ws):
"""接口打开""" """接口打开"""
print 'onOpen' print('onOpen')
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def connect(self, host, apiKey, secretKey, trace=False): def connect(self, host, apiKey, secretKey, trace=False):

View File

@ -1423,7 +1423,7 @@ def test():
def print_log(event): def print_log(event):
log = event.dict_['data'] log = event.dict_['data']
print ':'.join([log.logTime, log.logContent]) print(':'.join([log.logTime, log.logContent]))
app = QtCore.QCoreApplication(sys.argv) app = QtCore.QCoreApplication(sys.argv)

View File

@ -722,9 +722,9 @@ class ShzdGatewayApi(ShzdApi):
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def printDict(d): def printDict(d):
"""打印字典""" """打印字典"""
print '-' * 50 print('-' * 50)
l = d.keys() l = d.keys()
l.sort() l.sort()
for k in l: for k in l:
print k, ':', d[k] print(k, ':', d[k])

View 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"
}

View 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
View File

@ -0,0 +1,3 @@
#/bin/bash
python /srv/vnpy/vn.trader/vtServer.py --VT_setting /srv/vnpy/vn.trader/tmp/VT_setting.json