From decec65092c201beda7a470dbb530717a27832b4 Mon Sep 17 00:00:00 2001 From: msincenselee Date: Sat, 24 Oct 2015 08:01:02 +0800 Subject: [PATCH] daily --- vn.strategy/strategydemo/backtestingEngine.py | 66 +++++--- vn.strategy/strategydemo/demoStrategy.py | 144 +++++++++--------- vn.strategy/strategydemo/strategyEngine.py | 107 ++++++------- 3 files changed, 156 insertions(+), 161 deletions(-) diff --git a/vn.strategy/strategydemo/backtestingEngine.py b/vn.strategy/strategydemo/backtestingEngine.py index d30f0aa2..fb4f9634 100644 --- a/vn.strategy/strategydemo/backtestingEngine.py +++ b/vn.strategy/strategydemo/backtestingEngine.py @@ -132,6 +132,7 @@ class BacktestingEngine(object): self.writeLog(u'历史TICK数据从Cache载入') return + # 每次获取日期周期 intervalDays = 10 for i in range (0,(endDate - startDate).days +1, intervalDays): @@ -142,47 +143,58 @@ class BacktestingEngine(object): else: d2 = endDate + # 从Mysql 提取数据 self.loadMysqlDataHistory(symbol, d1, d2) self.writeLog(u'历史TICK数据共载入{0}条'.format(len(self.listDataHistory))) + + # 保存本地cache文件 self.__saveDataHistoryToLocalCache(symbol, startDate, endDate) def __loadDataHistoryFromLocalCache(self, symbol, startDate, endDate): """看本地缓存是否存在""" + # 运行路径下cache子目录 cacheFolder = os.getcwd()+'\/cache' - - cacheFile = u'{0}\/{1}_{2}_{3}.pickle'.format(cacheFolder,symbol, startDate.strftime('%Y-%m-%d'), endDate.strftime('%Y-%m-%d')) + # cache文件 + cacheFile = u'{0}\/{1}_{2}_{3}.pickle'.\ + format(cacheFolder, symbol, startDate.strftime('%Y-%m-%d'), endDate.strftime('%Y-%m-%d')) if not os.path.isfile(cacheFile): return False else: + # 从cache文件加载 cache = open(cacheFile,mode='r') self.listDataHistory = cPickle.load(cache) + cache.close() return True def __saveDataHistoryToLocalCache(self, symbol, startDate, endDate): """保存本地缓存""" + + # 运行路径下cache子目录 cacheFolder = os.getcwd()+'\/cache' + # 创建cache子目录 if not os.path.isdir(cacheFolder): os.mkdir(cacheFolder) - cacheFile = u'{0}\/{1}_{2}_{3}.pickle'.format(cacheFolder,symbol, startDate.strftime('%Y-%m-%d'), endDate.strftime('%Y-%m-%d')) + # cache 文件名 + cacheFile = u'{0}\/{1}_{2}_{3}.pickle'.\ + format(cacheFolder, symbol, startDate.strftime('%Y-%m-%d'), endDate.strftime('%Y-%m-%d')) + # 重复存在 返回 if os.path.isfile(cacheFile): return False else: - cache= open(cacheFile, mode='w') - + # 写入cache文件 + cache = open(cacheFile, mode='w') cPickle.dump(self.listDataHistory,cache) - cache.close() - return True #---------------------------------------------------------------------- @@ -194,40 +206,48 @@ class BacktestingEngine(object): if self.__mysqlConnected: - #获取指针 + # 获取指针 cur = self.__mysqlConnection.cursor(MySQLdb.cursors.DictCursor) if endDate: - sqlstring = ' select \'{0}\' as InstrumentID, str_to_date(concat(ndate,\' \', ntime),' \ + # 开始日期 ~ 结束日期 + sqlstring = ' select \'{0}\' as InstrumentID, str_to_date(concat(ndate,\' \', ntime),' \ '\'%Y-%m-%d %H:%i:%s\') as UpdateTime,price as LastPrice,vol as Volume,' \ 'position_vol as OpenInterest,bid1_price as BidPrice1,bid1_vol as BidVolume1, ' \ 'sell1_price as AskPrice1, sell1_vol as AskVolume1 from TB_{0}MI ' \ - 'where ndate between cast(\'{1}\' as date) and cast(\'{2}\' as date)'.format(symbol, startDate, endDate) + 'where ndate between cast(\'{1}\' as date) and cast(\'{2}\' as date)'.\ + format(symbol, startDate, endDate) elif startDate: - sqlstring = ' select \'{0}\' as InstrumentID,str_to_date(concat(ndate,\' \', ntime),' \ + # 开始日期 - 当前 + sqlstring = ' select \'{0}\' as InstrumentID,str_to_date(concat(ndate,\' \', ntime),' \ '\'%Y-%m-%d %H:%i:%s\') as UpdateTime,price as LastPrice,vol as Volume,' \ 'position_vol as OpenInterest,bid1_price as BidPrice1,bid1_vol as BidVolume1, ' \ 'sell1_price as AskPrice1, sell1_vol as AskVolume1 from TB__{0}MI ' \ - 'where ndate > cast(\'{1}\' as date)'.format( symbol, startDate) + 'where ndate > cast(\'{1}\' as date)'.\ + format( symbol, startDate) else: - sqlstring =' select \'{0}\' as InstrumentID,str_to_date(concat(ndate,\' \', ntime),' \ + # 所有数据 + sqlstring =' select \'{0}\' as InstrumentID,str_to_date(concat(ndate,\' \', ntime),' \ '\'%Y-%m-%d %H:%i:%s\') as UpdateTime,price as LastPrice,vol as Volume,' \ 'position_vol as OpenInterest,bid1_price as BidPrice1,bid1_vol as BidVolume1, ' \ - 'sell1_price as AskPrice1, sell1_vol as AskVolume1 from TB__{0}MI '.format(symbol) + 'sell1_price as AskPrice1, sell1_vol as AskVolume1 from TB__{0}MI '.\ + format(symbol) - self.writeLog(sqlstring) + # self.writeLog(sqlstring) + # 执行查询 count = cur.execute(sqlstring) #self.writeLog(u'历史TICK数据共{0}条'.format(count)) - # 将TICK数据读入内存 + # 将TICK数据一次性读入内存 #self.listDataHistory = cur.fetchall() + # 分批次读取 fetch_counts = 0 fetch_size = 1000 @@ -240,7 +260,6 @@ class BacktestingEngine(object): fetch_counts = fetch_counts + len(results) if not self.listDataHistory: - self.listDataHistory =results else: @@ -251,7 +270,9 @@ class BacktestingEngine(object): else: self.writeLog(u'MysqlDB未连接,请检查') + except MySQLdb.Error, e: + self.writeLog(u'MysqlDB载入数据失败,请检查.Error {0}'.format(e)) #---------------------------------------------------------------------- @@ -260,18 +281,19 @@ class BacktestingEngine(object): try: if self.__mysqlConnected: - #获取指针 + # 获取mysql指针 cur = self.__mysqlConnection.cursor() sqlstring='select distinct ndate from TB_{0}MI where ndate < ' \ 'cast(\'{1}\' as date) order by ndate desc limit {2},1'.format(symbol, startDate, decreaseDays-1) - self.writeLog(sqlstring) + # self.writeLog(sqlstring) count = cur.execute(sqlstring) if count > 0: + # 提取第一条记录 result = cur.fetchone() return result[0] @@ -283,11 +305,11 @@ class BacktestingEngine(object): self.writeLog(u'MysqlDB未连接,请检查') except MySQLdb.Error, e: + self.writeLog(u'MysqlDB载入数据失败,请检查.Error {0}: {1}'.format(e.arg[0],e.arg[1])) - td = timedelta(days=3) - - return startDate-td; + # 出错后缺省返回 + return startDate-timedelta(days=3) #---------------------------------------------------------------------- def processLimitOrder(self): diff --git a/vn.strategy/strategydemo/demoStrategy.py b/vn.strategy/strategydemo/demoStrategy.py index 1e4e990a..a8d654c8 100644 --- a/vn.strategy/strategydemo/demoStrategy.py +++ b/vn.strategy/strategydemo/demoStrategy.py @@ -31,10 +31,10 @@ class SimpleEmaStrategy(StrategyTemplate): super(SimpleEmaStrategy, self).__init__(name, symbol, engine) # 策略在外部设置的参数 - #self.fastAlpha = 0.2 # 快速EMA的参数 + # self.fastAlpha = 0.2 # 快速EMA的参数 self.fastAlpha = 0.2 - #self.slowAlpha = 0.05 # 慢速EMA的参数 - self.fastAlpha = 0.05 + # self.slowAlpha = 0.05 # 慢速EMA的参数 + self.slowAlpha = 0.05 # 最新TICK数据(市场报价) self.currentTick = None @@ -48,12 +48,12 @@ class SimpleEmaStrategy(StrategyTemplate): self.barTime = None # 保存K线数据的列表对象 - #self.listOpen = [] - #self.listHigh = [] - #self.listLow = [] - #self.listClose = [] - #self.listVolume = [] - #s#elf.listTime = [] + # self.listOpen = [] + # self.listHigh = [] + # self.listLow = [] + # self.listClose = [] + # self.listVolume = [] + # s#elf.listTime = [] # 持仓 self.pos = 0 @@ -102,71 +102,61 @@ class SimpleEmaStrategy(StrategyTemplate): self.engine.writeLog(u'读取3天的历史TICK数据') td = timedelta(days=1) - if startDate: - #读取历史Tick数据 - #cx = self.engine.loadTickFromMongo(self.symbol, startDate-td) - historyStartDate=self.engine.getMysqlDeltaDate(self.symbol,startDate,3) + # 读取历史Tick数据 + # cx = self.engine.loadTickFromMongo(self.symbol, startDate-td) + historyStartDate = self.engine.getMysqlDeltaDate(self.symbol,startDate,3) cx = self.engine.loadTickFromMysql(self.symbol, historyStartDate, startDate-td) else: today = datetime.today().replace(hour=0, minute=0, second=0, microsecond=0) - #cx = self.engine.loadTickFromMongo(self.symbol, today-td) - historyStartDate=self.engine.getMysqlDeltaDate(self.symbol,today,3) + # cx = self.engine.loadTickFromMongo(self.symbol, today-td) + historyStartDate = self.engine.getMysqlDeltaDate(self.symbol,today,3) cx = self.engine.loadTickFromMysql(self.symbol, historyStartDate,today-td) if cx: for data in cx: - #InstrumentID, UpdateTime, LastPrice, Volume, OpenInterest, BidPrice1, BidVolume1, AskPrice1, AskVolume1 = data tick = Tick(data['InstrumentID']) - #tick = Tick(InstrumentID) + # tick = Tick(InstrumentID) - #tick.openPrice = data['OpenPrice'] - #tick.highPrice = data['HighestPrice'] - #tick.lowPrice = data['LowestPrice'] + # tick.openPrice = data['OpenPrice'] + # tick.highPrice = data['HighestPrice'] + # tick.lowPrice = data['LowestPrice'] tick.lastPrice = float(data['LastPrice']) - #tick.lastPrice = LastPrice - + tick.volume = data['Volume'] tick.openInterest = data['OpenInterest'] - #tick.volume = Volume - #tick.openInterest = OpenInterest - #tick.upperLimit = data['UpperLimitPrice'] - #tick.lowerLimit = data['LowerLimitPrice'] + # tick.upperLimit = data['UpperLimitPrice'] + # tick.lowerLimit = data['LowerLimitPrice'] tick.time = data['UpdateTime'] - #tick.ms = data['UpdateMillisec'] - #tick.time = UpdateTime + # tick.ms = data['UpdateMillisec'] - tick.bidPrice1 =float(data['BidPrice1']) - #tick.bidPrice2 = data['BidPrice2'] - #tick.bidPrice3 = data['BidPrice3'] - #tick.bidPrice4 = data['BidPrice4'] - #tick.bidPrice5 = data['BidPrice5'] - #tick.bidPrice1 = BidPrice1 + tick.bidPrice1 = float(data['BidPrice1']) + # tick.bidPrice2 = data['BidPrice2'] + # tick.bidPrice3 = data['BidPrice3'] + # tick.bidPrice4 = data['BidPrice4'] + # tick.bidPrice5 = data['BidPrice5'] tick.askPrice1 = float(data['AskPrice1']) - #tick.askPrice2 = data['AskPrice2'] - #tick.askPrice3 = data['AskPrice3'] - #tick.askPrice4 = data['AskPrice4'] - #tick.askPrice5 = data['AskPrice5'] - #tick.askPrice1 = AskPrice1 - + # tick.askPrice2 = data['AskPrice2'] + # tick.askPrice3 = data['AskPrice3'] + # tick.askPrice4 = data['AskPrice4'] + # tick.askPrice5 = data['AskPrice5'] + tick.bidVolume1 = data['BidVolume1'] - #tick.bidVolume2 = data['BidVolume2'] - #tick.bidVolume3 = data['BidVolume3'] - #tick.bidVolume4 = data['BidVolume4'] - #tick.bidVolume5 = data['BidVolume5'] - #tick.bidVolume1 = BidVolume1 + # tick.bidVolume2 = data['BidVolume2'] + # tick.bidVolume3 = data['BidVolume3'] + # tick.bidVolume4 = data['BidVolume4'] + # tick.bidVolume5 = data['BidVolume5'] tick.askVolume1 = data['AskVolume1'] - #tick.askVolume2 = data['AskVolume2'] - #tick.askVolume3 = data['AskVolume3'] - #tick.askVolume4 = data['AskVolume4'] - #tick.askVolume5 = data['AskVolume5'] - #tick.askVolume1 = AskVolume1 + # tick.askVolume2 = data['AskVolume2'] + # tick.askVolume3 = data['AskVolume3'] + # tick.askVolume4 = data['AskVolume4'] + # tick.askVolume5 = data['AskVolume5'] self.onTick(tick) @@ -176,12 +166,14 @@ class SimpleEmaStrategy(StrategyTemplate): #---------------------------------------------------------------------- def onTick(self, tick): - """行情更新""" + """行情更新 + :type tick: object + """ # 保存最新的TICK self.currentTick = tick # 首先生成datetime.time格式的时间(便于比较) - #ticktime = self.strToTime(tick.time, tick.ms) + # ticktime = self.strToTime(tick.time, tick.ms) ticktime = tick.time # 假设是收到的第一个TICK @@ -201,7 +193,8 @@ class SimpleEmaStrategy(StrategyTemplate): self.barLow = min(self.barLow, tick.lastPrice) self.barClose = tick.lastPrice self.barVolume = self.barVolume + tick.volume - self.barTime = ticktime + self.barTime = ticktime + # 如果是新一分钟的数据 else: # 首先推送K线数据 @@ -242,12 +235,12 @@ class SimpleEmaStrategy(StrategyTemplate): def onBar(self, o, h, l, c, volume, t): """K线数据更新,同时进行策略的买入、卖出逻辑计算""" # 保存K线序列数据 - #self.listOpen.append(o) - #self.listHigh.append(h) - #self.listLow.append(l) - #self.listClose.append(c) - #self.listVolume.append(volume) - #self.listTime.append(t) + # self.listOpen.append(o) + # self.listHigh.append(h) + # self.listLow.append(l) + # self.listClose.append(c) + # self.listVolume.append(volume) + # self.listTime.append(t) # 保存K线数据 bar = Bar() @@ -260,7 +253,6 @@ class SimpleEmaStrategy(StrategyTemplate): bar.date = t.strftime('%Y-%m-%d') bar.time = t.strftime('%H:%M:%S') bar.datetime = t - self.lineBar.append(bar) # 计算EMA @@ -296,26 +288,27 @@ class SimpleEmaStrategy(StrategyTemplate): if self.pos == 0: # 涨停价买入开仓 # Modified by Incense Lee :回测时,Tick数据中没有涨停价,只能使用当前价 - #self.buy(self.currentTick.upperLimit, 1) + # self.buy(self.currentTick.upperLimit, 1) self.buy(self.currentTick.lastPrice, 1, t) # 价格,数量,下单时间 + # 手头有空仓,则先平空,再开多 elif self.pos < 0: - #self.cover(self.currentTick.upperLimit, 1) + # self.cover(self.currentTick.upperLimit, 1) self.cover(self.currentTick.lastPrice, 1, t) # 价格,数量, 下单时间 - #self.buy(self.currentTick.upperLimit, 1) + # self.buy(self.currentTick.upperLimit, 1) self.buy(self.currentTick.lastPrice, 1, t) - + # 反之,做空 elif self.fastEMA < self.slowEMA: if self.pos == 0: # Modified by Incense Lee :回测时,Tick数据中没有最低价价,只能使用当前价 - #self.short(self.currentTick.lowerLimit, 1) + # self.short(self.currentTick.lowerLimit, 1) self.short(self.currentTick.lastPrice, 1, t) elif self.pos > 0: - #self.sell(self.currentTick.lowerLimit, 1) + # self.sell(self.currentTick.lowerLimit, 1) self.sell(self.currentTick.lastPrice, 1, t) - #self.short(self.currentTick.lowerLimit, 1) + # self.short(self.currentTick.lowerLimit, 1) self.short(self.currentTick.lastPrice, 1, t) # 记录日志 @@ -333,13 +326,13 @@ class SimpleEmaStrategy(StrategyTemplate): #---------------------------------------------------------------------- def saveData(self, id): - """保存过程数据""" - # 保存K线 - print u'{0}保存K线'.format(self.name) - self.engine.saveBarToMysql(id, self.lineBar) + """保存过程数据""" + # 保存K线 + print u'{0}保存K线'.format(self.name) + self.engine.saveBarToMysql(id, self.lineBar) - # 保存快速EMA和慢速EMA - self.engine.saveEmaToMysql(id, self.lineEMA) + # 保存快速EMA和慢速EMA + self.engine.saveEmaToMysql(id, self.lineEMA) #---------------------------------------------------------------------- @@ -360,7 +353,6 @@ def main(): me = MainEngine() print u'demoStrategy.py Main call MainEngine() success' - # 注册事件监听 me.ee.register(EVENT_LOG, print_log) @@ -383,7 +375,7 @@ def main(): setting = {} setting['fastAlpha'] = 0.2 setting['slowAlpha'] = 0.09 - #se.createStrategy(u'EMA演示策略', 'IF1506', SimpleEmaStrategy, setting) + # se.createStrategy(u'EMA演示策略', 'IF1506', SimpleEmaStrategy, setting) se.createStrategy(u'EMA演示策略', 'a', SimpleEmaStrategy, setting) # 启动所有策略 @@ -392,7 +384,7 @@ def main(): # 让程序连续运行 sys.exit(app.exec_()) - + if __name__ == '__main__': main() diff --git a/vn.strategy/strategydemo/strategyEngine.py b/vn.strategy/strategydemo/strategyEngine.py index de98a0da..56bccfdb 100644 --- a/vn.strategy/strategydemo/strategyEngine.py +++ b/vn.strategy/strategydemo/strategyEngine.py @@ -461,7 +461,10 @@ class StrategyEngine(object): self.__connectMysql() if self.__mysqlConnected: - sql='insert into BackTest.TB_Bar (Id, symbol ,open ,high ,low ,close ,date ,time ,datetime, volume, openInterest) values ' + sql = 'insert into BackTest.TB_Bar ' \ + '(Id, symbol, open,high, low,close,date,time,datetime, volume, openInterest) ' \ + 'values ' + values = '' print u'共{0}条Bar记录.'.format(len(barList)) @@ -523,17 +526,17 @@ class StrategyEngine(object): os.mkdir(resultPath) resultFile = u'{0}\\{1}_Ema.pickle'.format(resultPath, id) - cache= open(resultFile, mode='w') - cPickle.dump(emaList,cache) - cache.close() self.__connectMysql() if self.__mysqlConnected: - sql='insert into BackTest.TB_Ema (Id, symbol ,fastEMA,slowEMA ,date ,time ,datetime) values ' + sql = 'insert into BackTest.TB_Ema ' \ + '(Id, symbol ,fastEMA,slowEMA ,date ,time ,datetime) ' \ + 'values ' + values = '' print u'共{0}条EMA记录.'.format(len(emaList)) @@ -578,61 +581,50 @@ class StrategyEngine(object): def updateMarketData(self, event): """行情更新""" data = event.dict_['data'] - #InstrumentID, UpdateTime, LastPrice, Volume, OpenInterest, BidPrice1, BidVolume1, AskPrice1, AskVolume1 = data symbol = data['InstrumentID'] - #symbol = InstrumentID # 检查是否存在交易该合约的策略 if symbol in self.__dictSymbolStrategy: # 创建TICK数据对象并更新数据 tick = Tick(symbol) - #tick.openPrice = data['OpenPrice'] - #tick.highPrice = data['HighestPrice'] - #tick.lowPrice = data['LowestPrice'] + # tick.openPrice = data['OpenPrice'] + # tick.highPrice = data['HighestPrice'] + # tick.lowPrice = data['LowestPrice'] tick.lastPrice = float(data['LastPrice']) - #tick.lastPrice = LastPrice tick.volume = data['Volume'] tick.openInterest = data['OpenInterest'] - #tick.volume = Volume - #tick.openInterest = OpenInterest - #tick.upperLimit = data['UpperLimitPrice'] - #tick.lowerLimit = data['LowerLimitPrice'] + # tick.upperLimit = data['UpperLimitPrice'] + # tick.lowerLimit = data['LowerLimitPrice'] tick.time = data['UpdateTime'] - #tick.time = UpdateTime - #tick.ms = data['UpdateMillisec'] tick.bidPrice1 = float(data['BidPrice1']) - #tick.bidPrice2 = data['BidPrice2'] - #tick.bidPrice3 = data['BidPrice3'] - #tick.bidPrice4 = data['BidPrice4'] - #tick.bidPrice5 = data['BidPrice5'] - #tick.bidPrice1 = BidPrice1 + # tick.bidPrice2 = data['BidPrice2'] + # tick.bidPrice3 = data['BidPrice3'] + # tick.bidPrice4 = data['BidPrice4'] + # tick.bidPrice5 = data['BidPrice5'] tick.askPrice1 = float(data['AskPrice1']) - #tick.askPrice2 = data['AskPrice2'] - #tick.askPrice3 = data['AskPrice3'] - #tick.askPrice4 = data['AskPrice4'] - #tick.askPrice5 = data['AskPrice5'] - #tick.askPrice1 = AskPrice1 + # tick.askPrice2 = data['AskPrice2'] + # tick.askPrice3 = data['AskPrice3'] + # tick.askPrice4 = data['AskPrice4'] + # tick.askPrice5 = data['AskPrice5'] tick.bidVolume1 = data['BidVolume1'] - #tick.bidVolume2 = data['BidVolume2'] - #tick.bidVolume3 = data['BidVolume3'] - #tick.bidVolume4 = data['BidVolume4'] - #tick.bidVolume5 = data['BidVolume5'] - #tick.bidVolume1 = BidVolume1 + # tick.bidVolume2 = data['BidVolume2'] + # tick.bidVolume3 = data['BidVolume3'] + # tick.bidVolume4 = data['BidVolume4'] + # tick.bidVolume5 = data['BidVolume5'] tick.askVolume1 = data['AskVolume1'] - #tick.askVolume2 = data['AskVolume2'] - #tick.askVolume3 = data['AskVolume3'] - #tick.askVolume4 = data['AskVolume4'] - #tick.askVolume5 = data['AskVolume5'] - #tick.askVolume1 = AskVolume1 + # tick.askVolume2 = data['AskVolume2'] + # tick.askVolume3 = data['AskVolume3'] + # tick.askVolume4 = data['AskVolume4'] + # tick.askVolume5 = data['AskVolume5'] # 首先检查停止单是否需要发出 self.__processStopOrder(tick) @@ -643,7 +635,7 @@ class StrategyEngine(object): # 将数据插入MongoDB/Mysql数据库,实盘建议另开程序记录TICK数据 if not self.backtesting: - #self.__recordTickToMongo(data) + # self.__recordTickToMongo(data) self.__recordTickToMysql(data) #---------------------------------------------------------------------- @@ -657,8 +649,6 @@ class StrategyEngine(object): # 如果当前有该合约上的止损单 if symbol in self.__dictStopOrder: - #print u'strategyEngine.py __processStopOrder() has stop order.' - # 获取止损单列表 listSO = self.__dictStopOrder[symbol] # SO:stop order @@ -704,8 +694,6 @@ class StrategyEngine(object): def updateOrder(self, event): """事件响应:报单更新""" - #print u'strategyEngine.py updateOrder() begin.' - data = event.dict_['data'] orderRef = data['OrderRef'] @@ -736,13 +724,10 @@ class StrategyEngine(object): # 记录该Order的数据 self.__dictOrder[orderRef] = data - #print u'strategyEngine.py updateOrder() end.' - #---------------------------------------------------------------------- def updateTrade(self, event): """事件响应:成交更新""" - #print u'strategyEngine.py updateTrade() begin.' data = event.dict_['data'] orderRef = data['OrderRef'] @@ -765,8 +750,6 @@ class StrategyEngine(object): strategy = self.__dictOrderRefStrategy[orderRef] strategy.onTrade(trade) - #print u'strategyEngine.py updateTrade() end.' - #---------------------------------------------------------------------- def sendOrder(self, symbol, direction, offset, price, volume, ordertime, strategy): """ @@ -780,7 +763,6 @@ class StrategyEngine(object): strategy:策略对象 """ - #print u'strategyEngine.py sendOrder() begin.' contract = self.mainEngine.selectInstrument(symbol) if contract: @@ -797,7 +779,6 @@ class StrategyEngine(object): # 添加报单编号及其映射的策略 self.__dictOrderRefStrategy[ref] = strategy - #print u'strategyEngine.py sendOrder() end.' return ref @@ -825,13 +806,13 @@ class StrategyEngine(object): def __registerEvent(self): """注册事件监听""" - #注册订阅行情数据更新事件 + # 注册 订阅行情数据更新事件 self.__eventEngine.register(EVENT_MARKETDATA, self.updateMarketData) - #注册订阅订单更新事件 + # 注册 订阅订单更新事件 self.__eventEngine.register(EVENT_ORDER, self.updateOrder) - #注册订阅交易响应事件 + # 注册 订阅交易响应事件 self.__eventEngine.register(EVENT_TRADE ,self.updateTrade) #---------------------------------------------------------------------- @@ -865,7 +846,8 @@ class StrategyEngine(object): 注意这里的price是停止单的触发价 """ # 创建止损单对象 - print u'strategyEngine.py placeStopOrder() symbol:{0}, direction:{1}, offset:{2}, price:{3}, volume:{4}.'.format(symbol, direction, offset, price, volume) + print u'strategyEngine.py placeStopOrder() symbol:{0}, direction:{1}, offset:{2}, price:{3}, volume:{4}.'\ + .format(symbol, direction, offset, price, volume) so = StopOrder(symbol, direction, offset, price, volume, strategy) @@ -879,16 +861,12 @@ class StrategyEngine(object): # 将该止损单插入列表中 listSO.append(so) - #print u'strategyEngine.py placeStopOrder() end.' - return so #---------------------------------------------------------------------- def cancelStopOrder(self, so): """撤销停止单""" - print u'strategyEngine.py cancelStopOrder() begin.' - symbol = so.symbol try: @@ -902,7 +880,6 @@ class StrategyEngine(object): except KeyError: pass - print u'strategyEngine.py cancelStopOrder() end.' #---------------------------------------------------------------------- def startAll(self): @@ -1000,7 +977,8 @@ class StrategyTemplate(object): def buy(self, price, volume, orderTime, stopOrder=False ): """买入开仓""" - print u'strategyEngine.py StrategyTemplate({3}) buy() begin. symbol:{0}, price:{1},volume:{2},time:{4}'.format(self.symbol, price, volume, self.name,orderTime) + print u'strategyEngine.py StrategyTemplate({3}) buy(symbol:{0}, price:{1},volume:{2},time:{4})'.\ + format(self.symbol, price, volume, self.name,orderTime) if self.trading: if stopOrder: @@ -1022,7 +1000,8 @@ class StrategyTemplate(object): def cover(self, price, volume,orderTime, stopOrder=False): """买入平仓""" - print u'strategyEngine.py StrategyTemplate({3}) cover() begin. symbol:{0}, price:{1},volume:{2},time:{4}'.format(self.symbol, price, volume, self.name, orderTime) + print u'strategyEngine.py StrategyTemplate({3}) cover(symbol:{0}, price:{1},volume:{2},time:{4})'.\ + format(self.symbol, price, volume, self.name, orderTime) if self.trading: if stopOrder: @@ -1044,7 +1023,8 @@ class StrategyTemplate(object): def sell(self, price, volume, orderTime, stopOrder=False): """卖出平仓""" - print u'strategyEngine.py StrategyTemplate({3}) sell() begin. symbol:{0}, price:{1},volume:{2},time:{4}'.format(self.symbol, price, volume, self.name, orderTime) + print u'strategyEngine.py StrategyTemplate({3}) sell(symbol:{0}, price:{1},volume:{2},time:{4})'.\ + format(self.symbol, price, volume, self.name, orderTime) if self.trading: if stopOrder: @@ -1064,7 +1044,8 @@ class StrategyTemplate(object): #---------------------------------------------------------------------- def short(self, price, volume, orderTime, stopOrder=False): """卖出开仓""" - print u'strategyEngine.py StrategyTemplate({3}) short() begin. symbol:{0}, price:{1},volume:{2},time:{4}'.format(self.symbol, price, volume, self.name, orderTime) + print u'strategyEngine.py StrategyTemplate({3}) short(symbol:{0}, price:{1},volume:{2},time:{4})'.\ + format(self.symbol, price, volume, self.name, orderTime) if self.trading: if stopOrder: # 止损单 @@ -1078,7 +1059,7 @@ class StrategyTemplate(object): return ref else: return None - #print u'strategyEngine.py short() end.' + #---------------------------------------------------------------------- def cancelOrder(self, orderRef):