diff --git a/vn.trader/ctaStrategy/ctaBacktesting.py b/vn.trader/ctaStrategy/ctaBacktesting.py index e5e0fa92..0c81e9db 100644 --- a/vn.trader/ctaStrategy/ctaBacktesting.py +++ b/vn.trader/ctaStrategy/ctaBacktesting.py @@ -1133,17 +1133,17 @@ class BacktestingEngine(object): self.writeCtaLog(u'加载回测日期:{0}的价差tick'.format(testday)) p = re.compile(r"([A-Z]+)[0-9]+",re.I) - leg1_shortSymbol = p.match(leg1Symbol) leg2_shortSymbol = p.match(leg2Symbol) if leg1_shortSymbol is None or leg2_shortSymbol is None: - self.writeCtaLog(u'{0},{1}不能正则分解'.format(leg1Symbol,leg2Symbol)) + self.writeCtaLog(u'{0},{1}不能正则分解'.format(leg1Symbol, leg2Symbol)) return leg1_shortSymbol = leg1_shortSymbol.group(1) leg2_shortSymbol = leg2_shortSymbol.group(1) + # E:\Ticks\SQ\2014\201401\20140102\ag01_20140102.csv leg1File = u'e:\\ticks\\{0}\\{1}\\{2}\\{3}\\{4}{5}_{3}.csv' \ .format(leg1MainPath, testday.strftime('%Y'), testday.strftime('%Y%m'), testday.strftime('%Y%m%d'), leg1_shortSymbol, leg1Symbol[-2:]) diff --git a/vn.trader/ctaStrategy/ctaBase.py b/vn.trader/ctaStrategy/ctaBase.py index 014b0a95..0bd7e1a7 100644 --- a/vn.trader/ctaStrategy/ctaBase.py +++ b/vn.trader/ctaStrategy/ctaBase.py @@ -7,11 +7,6 @@ from __future__ import division -# 把vn.trader根目录添加到python环境变量中 -import sys -sys.path.append('..') - - # 常量定义 # CTA引擎中涉及到的交易方向类型 CTAORDER_BUY = u'买开' @@ -59,6 +54,13 @@ MINUTE_DB_NAME = 'VnTrader_1Min_Db' ENGINETYPE_BACKTESTING = 'backtesting' # 回测 ENGINETYPE_TRADING = 'trading' # 实盘 +import sys +import os + +trader_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) +if trader_path not in sys.path: + sys.path.append(trader_path) + # CTA引擎中涉及的数据类定义 from vtConstant import * diff --git a/vn.trader/ctaStrategy/ctaEngine.py b/vn.trader/ctaStrategy/ctaEngine.py index 9dcafa95..664c005d 100644 --- a/vn.trader/ctaStrategy/ctaEngine.py +++ b/vn.trader/ctaStrategy/ctaEngine.py @@ -33,6 +33,7 @@ from vtConstant import * from vtGateway import VtSubscribeReq, VtOrderReq, VtCancelOrderReq, VtLogData from vtFunction import todayDate import logging +import re ######################################################################## @@ -646,6 +647,16 @@ class CtaEngine(object): for symbol in self.pendingSubcribeSymbols.keys(): contract = self.mainEngine.getContract(symbol) if contract: + # 获取合约的缩写号 + s = self.getShortSymbol(symbol) + if s == symbol: # 合约缩写提取失败 + continue + + dt = datetime.now() + # 若为中金所的合约,白天才提交订阅请求 + if s in MARKET_ZJ and not(8 < dt.hour < 16): + continue + self.writeCtaLog(u'重新提交合约{0}订阅请求'.format(symbol)) strategy = self.pendingSubcribeSymbols[symbol] self.subscribe(strategy=strategy, symbol=symbol) @@ -869,6 +880,18 @@ class CtaEngine(object): self.posBufferDict = {} self.stopOrderDict = {} + def getShortSymbol(self, symbol): + """取得合约的短号""" + p = re.compile(r"([A-Z]+)[0-9]+", re.I) + shortSymbol = p.match(symbol) + + if shortSymbol is None : + self.writeCtaLog(u'{0}不能正则分解'.format(symbol)) + return symbol + + return shortSymbol.group(1) + + ######################################################################## class PositionBuffer(object): """持仓缓存信息(本地维护的持仓数据)""" diff --git a/vn.trader/ctaStrategy/ctaGridTrade.py b/vn.trader/ctaStrategy/ctaGridTrade.py index 46115218..e563269b 100644 --- a/vn.trader/ctaStrategy/ctaGridTrade.py +++ b/vn.trader/ctaStrategy/ctaGridTrade.py @@ -159,7 +159,6 @@ class CtaGridTrade(object): if len(self.dnGrids) >0: self.writeCtaLog(u'下网格从文件加载完成') else: - for i in range(0, self.maxLots, 1): # 做多,开仓价为下阻力线-网格高度*i,平仓价为开仓价+止盈高度,开仓数量为缺省 @@ -408,13 +407,13 @@ class CtaGridTrade(object): remainLots = len(self.dnGrids) lots = self.maxLots - remainLots - dnline = min(dnline, minPriceInOrder-self.gridHeight) + dnline = min(dnline, minPriceInOrder-self.gridHeight*dnRate) self.writeCtaLog(u'需要重建的网格数量:{0},起点:{1}'.format(lots, dnline)) if lots > 0: for i in range(0, lots, 1): # 做多,开仓价为下阻力线-网格高度*i,平仓价为开仓价+止盈高度,开仓数量为缺省 - open_price = int((dnline - self.gridHeight * (i - 1 + dnRate)* dnRate) / self.minDiff ) * self.minDiff + open_price = int((dnline - self.gridHeight * i * dnRate) / self.minDiff ) * self.minDiff close_price = int((open_price + self.gridWin* dnRate)/self.minDiff) * self.minDiff grid = CtaGrid(direction=DIRECTION_LONG, @@ -443,13 +442,13 @@ class CtaGridTrade(object): # 需要重建的剩余网格数量 remainLots = len(self.upGrids) lots = self.maxLots - remainLots - upline = max(upline, maxPriceInOrder+self.gridHeight) + upline = max(upline, maxPriceInOrder+self.gridHeight*upRate) self.writeCtaLog(u'需要重建的网格数量:{0},起点:{1}'.format(lots, upline)) if lots > 0: # 做空,开仓价为上阻力线+网格高度*i,平仓价为开仓价-止盈高度,开仓数量为缺省 for i in range(0, lots, 1): - open_price = int((upline + self.gridHeight *( i -1 + upRate) * upRate) / self.minDiff) * self.minDiff + open_price = int((upline + self.gridHeight * i * upRate) / self.minDiff) * self.minDiff close_price = int((open_price - self.gridWin * upRate) / self.minDiff) * self.minDiff grid = CtaGrid(direction=DIRECTION_SHORT, diff --git a/vn.trader/ctaStrategy/ctaLineBar.py b/vn.trader/ctaStrategy/ctaLineBar.py index 39cd67c0..05c400c1 100644 --- a/vn.trader/ctaStrategy/ctaLineBar.py +++ b/vn.trader/ctaStrategy/ctaLineBar.py @@ -1412,10 +1412,16 @@ class CtaLineBar(object): def __recountKF(self): """计算卡尔曼过滤器均线""" - min_len = 200 + min_len = 20 if not self.inputKF or self.kf is None: return + if len(self.lineBar) < min_len: + # 数量不足时,不做滤波处理,直接吻合(若改为EMA更好) + if self.mode == self.TICK_MODE and len(self.lineBar)>1: + self.lineStateMean.append(self.lineBar[-2].close) + else: + self.lineStateMean.append(self.lineBar[-1].close) return if len(self.lineStateMean) ==0 or len(self.lineStateCovar) ==0: @@ -1448,7 +1454,7 @@ class CtaLineBar(object): if len(self.lineStateCovar) > min_len: del self.lineStateCovar[0] - self.lineStateMean.append(m ) + self.lineStateMean.append(m) self.lineStateCovar.append(c) # ---------------------------------------------------------------------- diff --git a/vn.trader/language/__init__.py b/vn.trader/language/__init__.py index 696e9d4e..57534826 100644 --- a/vn.trader/language/__init__.py +++ b/vn.trader/language/__init__.py @@ -3,6 +3,7 @@ import json import os + # 默认设置 from chinese import text, constant diff --git a/vn.trader/language/chinese/constant.py b/vn.trader/language/chinese/constant.py index c6bd8d0c..1ee2bcd9 100644 --- a/vn.trader/language/chinese/constant.py +++ b/vn.trader/language/chinese/constant.py @@ -1,15 +1,5 @@ # encoding: UTF-8 -# 默认空值 -EMPTY_STRING = '' -EMPTY_UNICODE = u'' -EMPTY_INT = 0 -EMPTY_FLOAT = 0.0 - -# k线颜色 -COLOR_RED = u'Red' # 上升K线 -COLOR_BLUE = u'Blue' # 下降K线 -COLOR_EQUAL = u'Equal' # 平K线 # 方向常量 DIRECTION_NONE = u'无方向' diff --git a/vn.trader/language/english/constant.py b/vn.trader/language/english/constant.py index 5124169e..0efaa9d2 100644 --- a/vn.trader/language/english/constant.py +++ b/vn.trader/language/english/constant.py @@ -1,16 +1,5 @@ # encoding: UTF-8 -# 默认空值 -EMPTY_STRING = '' -EMPTY_UNICODE = u'' -EMPTY_INT = 0 -EMPTY_FLOAT = 0.0 - -# k线颜色 -COLOR_RED = u'Red' # 上升K线 -COLOR_BLUE = u'Blue' # 下降K线 -COLOR_EQUAL = u'Equal' # 平K线 - # 方向常量 DIRECTION_NONE = u'none' diff --git a/vn.trader/ctaStrategy/utilSinaClient.py b/vn.trader/utilSinaClient.py similarity index 80% rename from vn.trader/ctaStrategy/utilSinaClient.py rename to vn.trader/utilSinaClient.py index b623b024..a995b50d 100644 --- a/vn.trader/ctaStrategy/utilSinaClient.py +++ b/vn.trader/utilSinaClient.py @@ -6,8 +6,8 @@ from __future__ import print_function import requests from time import sleep import execjs -from datetime import datetime,timedelta -from ctaBase import CtaBarData,CtaTickData +from datetime import datetime, timedelta +from ctaStrategy.ctaBase import CtaBarData, CtaTickData class UtilSinaClient(object): @@ -64,10 +64,10 @@ class UtilSinaClient(object): def getTicks2(self, symbol, callback): - # 从sina加载最新的M1数据 + # 从sina加载最新的M1数据(针对中金所) try: - url = url = u'http://stock2.finance.sina.com.cn/futures/api/jsonp.php/var%20t1nf_{0}=/InnerFuturesNewService.getMinLine?symbol={0}'.format(symbol) + #url = u'http://stock2.finance.sina.com.cn/futures/api/jsonp.php/var%20t1nf_{0}=/InnerFuturesNewService.getMinLine?symbol={0}'.format(symbol) self.strategy.writeCtaLog(u'从sina下载{0}Tick数据 {1}'.format(symbol, url)) response_data= self.session.get(url).content @@ -106,6 +106,50 @@ class UtilSinaClient(object): self.strategy.writeCtaLog(u'加载sina历史Tick数据失败:' + str(e)) return False + def getTicks3(self, symbol, callback): + + # 从sina加载最新的5日内M1数据(针对中金所) + try: + url = u'http://stock2.finance.sina.com.cn/futures/api/jsonp.php/var%20t5nf_{0}=/InnerFuturesNewService.getFourDaysLine?symbol={0}'.format(symbol) + + self.strategy.writeCtaLog(u'从sina下载{0}Tick数据 {1}'.format(symbol, url)) + + response_data= self.session.get(url).content + response_data = response_data.decode('gbk').split('=')[-1] + response_data = response_data.replace('(', '') + response_data = response_data.replace(');', '') + responses= execjs.eval(response_data) + datevalue = datetime.now().strftime('%Y-%m-%d') + + for j, day_item in enumerate(responses): + for i, item in enumerate(day_item): + + tick = CtaTickData() + tick.vtSymbol = symbol + tick.symbol = symbol + + if len(item) >= 6: + datevalue = item[6] + + tick.date = datevalue + tick.time = item[0] + u':00' + tick.datetime = datetime.strptime(tick.date + ' ' + tick.time, '%Y-%m-%d %H:%M:%S') + + tick.lastPrice = float(item[1]) + tick.volume = int(item[3]) + + if type(item[4]) == type(None): + tick.openInterest = 0 + else: + tick.openInterest = int(item[4]) + + callback(tick) + + return True + + except Exception as e: + self.strategy.writeCtaLog(u'加载sina历史Tick数据失败:' + str(e)) + return False def getMinBars(self, symbol, minute, callback): """# 从sina加载最新的M5,M15,M30,M60数据""" @@ -256,4 +300,5 @@ if __name__ == '__main__': #rt = sina.getTicks(symbol='RB1705', callback=t.addTick) - rt = sina.getTicks2(symbol='TF1706', callback=t.addTick) \ No newline at end of file + #rt = sina.getTicks2(symbol='TF1706', callback=t.addTick) + rt = sina.getTicks3(symbol='TF1709', callback=t.addTick) \ No newline at end of file diff --git a/vn.trader/vtConstant.py b/vn.trader/vtConstant.py index 03fcdf55..b0a5b9b5 100644 --- a/vn.trader/vtConstant.py +++ b/vn.trader/vtConstant.py @@ -1,6 +1,19 @@ # encoding: UTF-8 print 'laoding vntrader.vtConstant' + +# 默认空值 +EMPTY_STRING = '' +EMPTY_UNICODE = u'' +EMPTY_INT = 0 +EMPTY_FLOAT = 0.0 + +# k线颜色 +COLOR_RED = u'Red' # 上升K线 +COLOR_BLUE = u'Blue' # 下降K线 +COLOR_EQUAL = u'Equal' # 平K线 + + from language import constant # 将常量定义添加到vtConstant.py的局部字典中