完成演示用的双指数均线策略Demo

This commit is contained in:
WOLF 2015-05-26 16:05:04 +08:00
parent 6e622a3e23
commit d20e89c2eb
7 changed files with 388 additions and 1354 deletions

View File

@ -1,11 +1,9 @@
#vn.strategy介绍
##2015/5/21
该模块主要包含了一个适用于CTA类策略时间序列型的策略引擎和策略模板。
目前尚未完成,仅供参考。
##2015/5/26
策略引擎目前主要对接测试用的是CTPLTS的理论上只要稍作修改就可以直接用。
完成了一个演示性的双指数均线策略填入账号、密码等信息后直接运行demoStrategy.py就可以启动。

View File

@ -174,13 +174,20 @@ class StrategyEngine(object):
# 调用函数
self.__connectMongo()
self.createStrategy()
self.__registerEvent()
#----------------------------------------------------------------------
def createStrategy(self):
def createStrategy(self, strategyName, strategySymbol, strategyClass, strategySetting):
"""创建策略"""
pass
strategy = strategyClass(strategyName, strategySymbol, self)
self.dictStrategy[strategyName] = strategy
strategy.loadSetting(strategySetting)
# 订阅合约行情注意这里因为是CTP所以ExchangeID可以忽略
self.mainEngine.subscribe(strategySymbol, None)
# 注册策略监听
self.registerStrategy(strategySymbol, strategy)
#----------------------------------------------------------------------
def __connectMongo(self):
@ -331,7 +338,7 @@ class StrategyEngine(object):
order.orderRef = data['OrderRef']
order.direction = data['Direction']
order.offset = data['ComboOffsetFlag']
order.offset = data['CombOffsetFlag']
order.price = data['LimitPrice']
order.volumeOriginal = data['VolumeTotalOriginal']
@ -353,8 +360,10 @@ class StrategyEngine(object):
#----------------------------------------------------------------------
def __updateTrade(self, event):
"""成交更新"""
print 'updateTrade'
data = event.dict_['data']
orderRef = data['OrderRef']
print 'trade:', orderRef
if orderRef in self.__dictOrderRefStrategy:
@ -396,6 +405,8 @@ class StrategyEngine(object):
offset)
self.__dictOrderRefStrategy[ref] = strategy
print 'ref:', ref
print 'strategy:', strategy.name
return ref
@ -480,17 +491,29 @@ class StrategyEngine(object):
except KeyError:
pass
#----------------------------------------------------------------------
def startAll(self):
"""启动所有策略"""
for strategy in self.dictStrategy.values():
strategy.start()
#----------------------------------------------------------------------
def stopAll(self):
"""停止所有策略"""
for strategy in self.dictStrategy.values():
strategy.stop()
########################################################################
class SimpleStrategyTemplate(object):
"""简易策略模板"""
class StrategyTemplate(object):
"""策略模板"""
#----------------------------------------------------------------------
def __init__(self, name, symbol, engine):
"""Constructor"""
self.name = name # 策略名称(注意唯一性)
self.__engine = engine # 策略引擎对象
self.symbol = symbol # 策略交易的合约
self.engine = engine # 策略引擎对象
self.trading = False # 策略是否启动交易
@ -513,6 +536,11 @@ class SimpleStrategyTemplate(object):
def onStopOrder(self, orderRef):
"""停止单更新"""
raise NotImplementedError
#----------------------------------------------------------------------
def onBar(self, o, h, l, c, volume, time):
"""K线数据更新"""
raise NotImplementedError
#----------------------------------------------------------------------
def start(self):
@ -522,6 +550,7 @@ class SimpleStrategyTemplate(object):
有需要可以重新实现更复杂的操作
"""
self.trading = True
self.engine.writeLog(self.name + u'开始运行')
#----------------------------------------------------------------------
def stop(self):
@ -530,75 +559,84 @@ class SimpleStrategyTemplate(object):
同上
"""
self.trading = False
self.engine.writeLog(self.name + u'停止运行')
#----------------------------------------------------------------------
def __buy(self, price, volume, stopOrder=False):
def loadSetting(self, setting):
"""
载入设置
setting通常是一个包含了参数设置的字典
"""
raise NotImplementedError
#----------------------------------------------------------------------
def buy(self, price, volume, stopOrder=False):
"""买入开仓"""
if self.trading:
if stopOrder:
so = self.__engine.placeStopOrder(self.symbol, DIRECTION_BUY,
so = self.engine.placeStopOrder(self.symbol, DIRECTION_BUY,
OFFSET_OPEN, price, volume, self)
return so
else:
ref = self.__engine.sendOrder(self.symbol, DIRECTION_BUY,
ref = self.engine.sendOrder(self.symbol, DIRECTION_BUY,
OFFSET_OPEN, price, volume, self)
return ref
else:
return None
#----------------------------------------------------------------------
def __cover(self, price, volume, StopOrder=False):
def cover(self, price, volume, StopOrder=False):
"""买入平仓"""
if self.trading:
if stopOrder:
so = self.__engine.placeStopOrder(self.symbol, DIRECTION_BUY,
so = self.engine.placeStopOrder(self.symbol, DIRECTION_BUY,
OFFSET_CLOSE, price, volume, self)
return so
else:
ref = self.__engine.sendOrder(self.symbol, DIRECTION_BUY,
ref = self.engine.sendOrder(self.symbol, DIRECTION_BUY,
OFFSET_CLOSE, price, volume, self)
return ref
else:
return None
#----------------------------------------------------------------------
def __sell(self, price, volume, stopOrder=False):
def sell(self, price, volume, stopOrder=False):
"""卖出平仓"""
if self.trading:
if stopOrder:
so = self.__engine.placeStopOrder(self.symbol, DIRECTION_SELL,
so = self.engine.placeStopOrder(self.symbol, DIRECTION_SELL,
OFFSET_CLOSE, price, volume, self)
return so
else:
ref = self.__engine.sendOrder(self.symbol, DIRECTION_SELL,
ref = self.engine.sendOrder(self.symbol, DIRECTION_SELL,
OFFSET_CLOSE, price, volume, self)
return ref
else:
return None
#----------------------------------------------------------------------
def __short(self, price, volume, stopOrder=False):
def short(self, price, volume, stopOrder=False):
"""卖出开仓"""
if self.trading:
if stopOrder:
so = self.__engine.placeStopOrder(self.symbol, DIRECTION_SELL,
so = self.engine.placeStopOrder(self.symbol, DIRECTION_SELL,
OFFSET_OPEN, price, volume, self)
return so
else:
ref = self.__engine.sendOrder(self.symbol, DIRECTION_SELL,
ref = self.engine.sendOrder(self.symbol, DIRECTION_SELL,
OFFSET_OPEN, price, volume, self)
return ref
else:
return None
#----------------------------------------------------------------------
def __cancelOrder(self, orderRef):
def cancelOrder(self, orderRef):
"""撤单"""
self.__engine.cancelOrder(orderRef)
self.engine.cancelOrder(orderRef)
#----------------------------------------------------------------------
def __cancelStopOrder(self, so):
def cancelStopOrder(self, so):
"""撤销停止单"""
self.__engine.cancelStopOrder(so)
self.engine.cancelStopOrder(so)

View File

@ -82,7 +82,7 @@ class MainEngine:
def sendOrder(self, instrumentid, exchangeid, price, pricetype, volume, direction, offset):
"""发单"""
ref = self.td.sendOrder(instrumentid, exchangeid, price, pricetype, volume, direction, offset)
return ref
return str(ref)
#----------------------------------------------------------------------
def cancelOrder(self, instrumentid, exchangeid, orderref, frontid, sessionid):

View File

@ -1,32 +0,0 @@
# encoding: UTF-8
"""
该文件中包含的是交易平台的主函数
将底层中层上层的功能导入并运行
"""
import ctypes
import sys
from demoEngine import MainEngine
from demoUi import *
#----------------------------------------------------------------------
def main():
"""主程序入口"""
ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID('vn.py demo') # win7以下请注释掉该行
app = QtGui.QApplication(sys.argv)
app.setWindowIcon(QtGui.QIcon('vnpy.ico'))
me = MainEngine()
mw = MainWindow(me.ee, me)
mw.showMaximized()
sys.exit(app.exec_())
if __name__ == '__main__':
main()

View File

@ -1,18 +1,306 @@
# encoding: UTF-8
from strategyEngine import StrategyTemplate
# 首先写系统内置模块
import sys
from datetime import datetime, timedelta, time
from time import sleep
# 然后是第三方库模块如PyQt4等
import sip
from PyQt4 import QtCore
# 然后是自己编写的模块
from demoEngine import MainEngine
from strategyEngine import *
########################################################################
class SimpleEmaStrategy(StrategyTemplate):
"""简单双指数移动均线策略"""
"""简单双指数移动均线EMA策略"""
#----------------------------------------------------------------------
def __init__(self, name, symbol, engine):
"""Constructor"""
super(SimpleEmaStrategy, self).__init__(name, symbol, engine)
# 策略在外部设置的参数
self.fastAlpha = 0.2 # 快速EMA的参数
self.slowAlpha = 0.05 # 慢速EMA的参数
# 最新TICK数据市场报价
self.currentTick = None
# K线缓存对象
self.barOpen = 0
self.barHigh = 0
self.barLow = 0
self.barClose = 0
self.barVolume = 0
self.barTime = None
# 保存K线数据的列表对象
self.listOpen = []
self.listHigh = []
self.listLow = []
self.listClose = []
self.listVolume = []
self.listTime = []
# 持仓
self.pos = 0
# 报单代码列表
self.listOrderRef = [] # 报单号列表
self.listStopOrder = [] # 停止单对象列表
# EMA均线
self.fastEMA = 0 # 快速EMA的数值
self.slowEMA = 0 # 慢速EMA的数值
# 是否完成了初始化
self.initCompleted = False
# 初始化时读取的历史数据的起始日期(可以选择外部设置)
self.startDate = None
#----------------------------------------------------------------------
def loadSetting(self, setting):
"""读取参数设定"""
try:
self.fastAlpha = setting['fastAlpha']
self.slowAlpha = setting['slowAlpha']
self.engine.writeLog(self.name + u'读取参数成功')
except KeyError:
self.engine.writeLog(self.name + u'读取参数设定出错,请检查参数字典')
self.initStrategy()
#----------------------------------------------------------------------
def initStrategy(self):
"""初始化"""
td = timedelta(days=3) # 读取3天的历史TICK数据
today = datetime.today().replace(hour=0, minute=0, second=0, microsecond=0)
cx = self.engine.loadTick(self.symbol, today-td)
if cx:
for data in cx:
tick = Tick(data['InstrumentID'])
tick.openPrice = data['OpenPrice']
tick.highPrice = data['HighestPrice']
tick.lowPrice = data['LowestPrice']
tick.lastPrice = data['LastPrice']
tick.volume = data['Volume']
tick.openInterest = data['OpenInterest']
tick.upperLimit = data['UpperLimitPrice']
tick.lowerLimit = data['LowerLimitPrice']
tick.time = data['UpdateTime']
tick.ms = data['UpdateMillisec']
tick.bidPrice1 = data['BidPrice1']
tick.bidPrice2 = data['BidPrice2']
tick.bidPrice3 = data['BidPrice3']
tick.bidPrice4 = data['BidPrice4']
tick.bidPrice5 = data['BidPrice5']
tick.askPrice1 = data['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.askVolume1 = data['AskVolume1']
tick.askVolume2 = data['AskVolume2']
tick.askVolume3 = data['AskVolume3']
tick.askVolume4 = data['AskVolume4']
tick.askVolume5 = data['AskVolume5']
self.onTick(tick)
self.initCompleted = True
self.engine.writeLog(self.name + u'初始化完成')
#----------------------------------------------------------------------
def onTick(self, tick):
"""行情更新"""
# 保存最新的TICK
self.currentTick = tick
# 首先生成datetime.time格式的时间便于比较
ticktime = self.strToTime(tick.time, tick.ms)
# 假设是收到的第一个TICK
if self.barOpen == 0:
# 初始化新的K线数据
self.barOpen = tick.lastPrice
self.barHigh = tick.lastPrice
self.barLow = tick.lastPrice
self.barClose = tick.lastPrice
self.barVolume = tick.volume
self.barTime = ticktime
else:
# 如果是当前一分钟内的数据
if ticktime.minute == self.barTime.minute:
# 汇总TICK生成K线
self.barHigh = max(self.barHigh, tick.lastPrice)
self.barLow = min(self.barLow, tick.lastPrice)
self.barClose = tick.lastPrice
self.barVolume = self.barVolume + tick.volume
self.barTime = ticktime
# 如果是新一分钟的数据
else:
# 首先推送K线数据
self.onBar(self.barOpen, self.barHigh, self.barLow, self.barClose,
self.barVolume, self.barTime)
# 初始化新的K线数据
self.barOpen = tick.lastPrice
self.barHigh = tick.lastPrice
self.barLow = tick.lastPrice
self.barClose = tick.lastPrice
self.barVolume = tick.volume
self.barTime = ticktime
#----------------------------------------------------------------------
def onTrade(self, trade):
"""交易更新"""
if trade.direction == DIRECTION_BUY:
self.pos = self.pos + trade.volume
else:
self.pos = self.pos - trade.volume
log = self.name + u'当前持仓:' + str(self.pos)
self.engine.writeLog(log)
#----------------------------------------------------------------------
def onOrder(self, order):
"""报单更新"""
pass
#----------------------------------------------------------------------
def onStopOrder(self, orderRef):
"""停止单更新"""
pass
#----------------------------------------------------------------------
def onBar(self, o, h, l, c, volume, time):
"""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(time)
# 计算EMA
if self.fastEMA:
self.fastEMA = c*self.fastAlpha + self.fastEMA*(1-self.fastAlpha)
self.slowEMA = c*self.slowAlpha + self.slowEMA*(1-self.slowAlpha)
else:
self.fastEMA = c
self.slowEMA = c
# 交易逻辑
if self.initCompleted: # 首先检查是否是实盘运行还是数据预处理阶段
# 快速EMA在慢速EMA上方做多
if self.fastEMA > self.slowEMA:
# 如果当前手头无仓位,则直接做多
if self.pos == 0:
# 涨停价买入开仓
self.buy(self.currentTick.upperLimit, 1)
# 手头有空仓,则先平空,再开多
elif self.pos < 0:
self.cover(self.currentTick.upperLimit, 1)
self.buy(self.currentTick.upperLimit, 1)
# 反之,做空
elif self.fastEMA < self.slowEMA:
if self.pos == 0:
self.short(self.currentTick.lowerLimit, 1)
elif self.pos > 0:
self.sell(self.currentTick.lowerLimit, 1)
self.short(self.currentTick.lowerLimit, 1)
# 记录日志
log = self.name + u'当前时间:' + str(time) + \
u'快速EMA' + str(self.fastEMA) + u'慢速EMA' + \
str(self.slowEMA)
self.engine.writeLog(log)
print 'onBar', o, h, l, c, time
print 'fastEMA:', self.fastEMA, '|slowEMA:', self.slowEMA
#----------------------------------------------------------------------
def strToTime(self, t, ms):
"""从字符串时间转化为time格式的时间"""
hh, mm, ss = t.split(':')
tt = time(int(hh), int(mm), int(ss), microsecond=ms)
return tt
#----------------------------------------------------------------------
def print_log(event):
"""打印日志"""
log = event.dict_['log']
print str(datetime.now()), ':', log
#----------------------------------------------------------------------
def main():
"""运行在CMD中的演示程度"""
# 创建PyQt4应用对象
app = QtCore.QCoreApplication(sys.argv)
# 创建主引擎对象
me = MainEngine()
# 注册事件监听
me.ee.register(EVENT_LOG, print_log)
# 登录
userid = ''
password = ''
brokerid = ''
mdAddress = ''
tdAddress = ''
me.login(userid, password, brokerid, mdAddress, tdAddress)
# 等待10秒钟初始化合约数据等
sleep(10)
# 创建策略引擎对象
se = StrategyEngine(me.ee, me)
# 创建策略对象
setting = {}
setting['fastAlpha'] = 0.2
setting['slowAlpha'] = 0.05
se.createStrategy(u'EMA演示策略', 'IF1506', SimpleEmaStrategy, setting)
# 启动所有策略
se.startAll()
# 让程序连续运行
sys.exit(app.exec_())
if __name__ == '__main__':
main()

File diff suppressed because it is too large Load Diff

View File

@ -174,7 +174,6 @@ class StrategyEngine(object):
# 调用函数
self.__connectMongo()
self.createStrategy()
self.__registerEvent()
#----------------------------------------------------------------------
@ -182,7 +181,13 @@ class StrategyEngine(object):
"""创建策略"""
strategy = strategyClass(strategyName, strategySymbol, self)
self.dictStrategy[strategyName] = strategy
strategy.initSetting(strategySetting)
strategy.loadSetting(strategySetting)
# 订阅合约行情注意这里因为是CTP所以ExchangeID可以忽略
self.mainEngine.subscribe(strategySymbol, None)
# 注册策略监听
self.registerStrategy(strategySymbol, strategy)
#----------------------------------------------------------------------
def __connectMongo(self):
@ -333,7 +338,7 @@ class StrategyEngine(object):
order.orderRef = data['OrderRef']
order.direction = data['Direction']
order.offset = data['ComboOffsetFlag']
order.offset = data['CombOffsetFlag']
order.price = data['LimitPrice']
order.volumeOriginal = data['VolumeTotalOriginal']
@ -355,8 +360,10 @@ class StrategyEngine(object):
#----------------------------------------------------------------------
def __updateTrade(self, event):
"""成交更新"""
print 'updateTrade'
data = event.dict_['data']
orderRef = data['OrderRef']
print 'trade:', orderRef
if orderRef in self.__dictOrderRefStrategy:
@ -398,6 +405,8 @@ class StrategyEngine(object):
offset)
self.__dictOrderRefStrategy[ref] = strategy
print 'ref:', ref
print 'strategy:', strategy.name
return ref
@ -504,7 +513,7 @@ class StrategyTemplate(object):
"""Constructor"""
self.name = name # 策略名称(注意唯一性)
self.symbol = symbol # 策略交易的合约
self.__engine = engine # 策略引擎对象
self.engine = engine # 策略引擎对象
self.trading = False # 策略是否启动交易
@ -541,6 +550,7 @@ class StrategyTemplate(object):
有需要可以重新实现更复杂的操作
"""
self.trading = True
self.engine.writeLog(self.name + u'开始运行')
#----------------------------------------------------------------------
def stop(self):
@ -549,83 +559,84 @@ class StrategyTemplate(object):
同上
"""
self.trading = False
self.engine.writeLog(self.name + u'停止运行')
#----------------------------------------------------------------------
def initSetting(self, setting):
def loadSetting(self, setting):
"""
初始化设置
载入设置
setting通常是一个包含了参数设置的字典
"""
raise NotImplementedError
#----------------------------------------------------------------------
def __buy(self, price, volume, stopOrder=False):
def buy(self, price, volume, stopOrder=False):
"""买入开仓"""
if self.trading:
if stopOrder:
so = self.__engine.placeStopOrder(self.symbol, DIRECTION_BUY,
so = self.engine.placeStopOrder(self.symbol, DIRECTION_BUY,
OFFSET_OPEN, price, volume, self)
return so
else:
ref = self.__engine.sendOrder(self.symbol, DIRECTION_BUY,
ref = self.engine.sendOrder(self.symbol, DIRECTION_BUY,
OFFSET_OPEN, price, volume, self)
return ref
else:
return None
#----------------------------------------------------------------------
def __cover(self, price, volume, StopOrder=False):
def cover(self, price, volume, StopOrder=False):
"""买入平仓"""
if self.trading:
if stopOrder:
so = self.__engine.placeStopOrder(self.symbol, DIRECTION_BUY,
so = self.engine.placeStopOrder(self.symbol, DIRECTION_BUY,
OFFSET_CLOSE, price, volume, self)
return so
else:
ref = self.__engine.sendOrder(self.symbol, DIRECTION_BUY,
ref = self.engine.sendOrder(self.symbol, DIRECTION_BUY,
OFFSET_CLOSE, price, volume, self)
return ref
else:
return None
#----------------------------------------------------------------------
def __sell(self, price, volume, stopOrder=False):
def sell(self, price, volume, stopOrder=False):
"""卖出平仓"""
if self.trading:
if stopOrder:
so = self.__engine.placeStopOrder(self.symbol, DIRECTION_SELL,
so = self.engine.placeStopOrder(self.symbol, DIRECTION_SELL,
OFFSET_CLOSE, price, volume, self)
return so
else:
ref = self.__engine.sendOrder(self.symbol, DIRECTION_SELL,
ref = self.engine.sendOrder(self.symbol, DIRECTION_SELL,
OFFSET_CLOSE, price, volume, self)
return ref
else:
return None
#----------------------------------------------------------------------
def __short(self, price, volume, stopOrder=False):
def short(self, price, volume, stopOrder=False):
"""卖出开仓"""
if self.trading:
if stopOrder:
so = self.__engine.placeStopOrder(self.symbol, DIRECTION_SELL,
so = self.engine.placeStopOrder(self.symbol, DIRECTION_SELL,
OFFSET_OPEN, price, volume, self)
return so
else:
ref = self.__engine.sendOrder(self.symbol, DIRECTION_SELL,
ref = self.engine.sendOrder(self.symbol, DIRECTION_SELL,
OFFSET_OPEN, price, volume, self)
return ref
else:
return None
#----------------------------------------------------------------------
def __cancelOrder(self, orderRef):
def cancelOrder(self, orderRef):
"""撤单"""
self.__engine.cancelOrder(orderRef)
self.engine.cancelOrder(orderRef)
#----------------------------------------------------------------------
def __cancelStopOrder(self, so):
def cancelStopOrder(self, so):
"""撤销停止单"""
self.__engine.cancelStopOrder(so)
self.engine.cancelStopOrder(so)