This commit is contained in:
msincenselee 2017-05-10 19:30:36 +08:00
parent 2b0f13069b
commit fe13e89ca9
10 changed files with 108 additions and 40 deletions

View File

@ -1133,7 +1133,6 @@ 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)
@ -1144,6 +1143,7 @@ class BacktestingEngine(object):
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:])

View File

@ -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 *

View File

@ -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):
"""持仓缓存信息(本地维护的持仓数据)"""

View File

@ -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,

View File

@ -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:

View File

@ -3,6 +3,7 @@
import json
import os
# 默认设置
from chinese import text, constant

View File

@ -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'无方向'

View File

@ -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'

View File

@ -7,7 +7,7 @@ import requests
from time import sleep
import execjs
from datetime import datetime, timedelta
from ctaBase import CtaBarData,CtaTickData
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)
#rt = sina.getTicks2(symbol='TF1706', callback=t.addTick)
rt = sina.getTicks3(symbol='TF1709', callback=t.addTick)

View File

@ -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的局部字典中