[Mod]AlgoEngine的算法加载改为自动扫描目录下算法文件的方式

This commit is contained in:
vn.py 2018-07-23 23:31:17 +08:00
parent 988d432846
commit 04bdbf9f4e
4 changed files with 85 additions and 38 deletions

View File

@ -4,6 +4,8 @@
''' '''
from __future__ import division from __future__ import division
import os
import importlib
from vnpy.event import Event from vnpy.event import Event
from vnpy.trader.vtEvent import EVENT_TIMER, EVENT_TICK, EVENT_ORDER, EVENT_TRADE from vnpy.trader.vtEvent import EVENT_TIMER, EVENT_TICK, EVENT_ORDER, EVENT_TRADE
@ -13,32 +15,26 @@ from vnpy.trader.vtConstant import (DIRECTION_LONG, DIRECTION_SHORT,
OFFSET_CLOSETODAY, OFFSET_CLOSEYESTERDAY) OFFSET_CLOSETODAY, OFFSET_CLOSEYESTERDAY)
from vnpy.trader.vtObject import VtSubscribeReq, VtOrderReq, VtCancelOrderReq, VtLogData from vnpy.trader.vtObject import VtSubscribeReq, VtOrderReq, VtCancelOrderReq, VtLogData
from .twapAlgo import TwapAlgo from .twapAlgo import TwapAlgo
from .dmaAlgo import DmaAlgo from .dmaAlgo import DmaAlgo
from .stopAlgo import StopAlgo from .stopAlgo import StopAlgo
from .stAlgo import StAlgo from .stAlgo import StAlgo
from .mmAlgo import MmAlgo
EVENT_ALGO_LOG = 'eAlgoLog' # 算法日志事件 EVENT_ALGO_LOG = 'eAlgoLog' # 算法日志事件
EVENT_ALGO_PARAM = 'eAlgoParam' # 算法参数事件 EVENT_ALGO_PARAM = 'eAlgoParam' # 算法参数事件
EVENT_ALGO_VAR = 'eAlgoVar' # 算法变量事件 EVENT_ALGO_VAR = 'eAlgoVar' # 算法变量事件
EVENT_ALGO_SETTING = 'eAlgoSetting' # 算法配置事件 EVENT_ALGO_SETTING = 'eAlgoSetting' # 算法配置事件
ALGOTRADING_DB_NAME = 'VnTrader_AlgoTrading_Db' # AlgoTrading数据库名 ALGOTRADING_DB_NAME = 'VnTrader_AlgoTrading_Db' # AlgoTrading数据库名
SETTING_COLLECTION_NAME = 'AlgoSetting' # 算法配置集合名 SETTING_COLLECTION_NAME = 'AlgoSetting' # 算法配置集合名
HISTORY_COLLECTION_NAME = 'AlgoHistory' # 算法历史集合名 HISTORY_COLLECTION_NAME = 'AlgoHistory' # 算法历史集合名
ALGO_DICT = {
TwapAlgo.templateName: TwapAlgo,
DmaAlgo.templateName: DmaAlgo,
StopAlgo.templateName: StopAlgo,
StAlgo.templateName: StAlgo
}
######################################################################## ########################################################################
class AlgoEngine(object): class AlgoEngine(object):
"""算法交易引擎""" """算法交易引擎"""
@ -286,7 +282,6 @@ class AlgoEngine(object):
return contract return contract
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def saveAlgoSetting(self, algoSetting): def saveAlgoSetting(self, algoSetting):
"""保存算法配置""" """保存算法配置"""
@ -334,3 +329,31 @@ class AlgoEngine(object):
event.dict_['data'] = algoSetting event.dict_['data'] = algoSetting
self.eventEngine.put(event) self.eventEngine.put(event)
# 加载目录下的算法模板
ALGO_DICT = {}
WIDGET_DICT = {}
path = os.path.abspath(os.path.dirname(__file__))
for root, subdirs, files in os.walk(path):
for name in files:
# 只有文件名以Algo.py结尾的才是算法文件
if len(name)>7 and name[-7:] == 'Algo.py':
# 模块名称需要模块路径前缀
moduleName = 'vnpy.trader.app.algoTrading.' + name.replace('.py', '')
module = importlib.import_module(moduleName)
# 获取算法类和控件类
for k in dir(module):
# 以Algo结尾的类是算法
if k[-4:] == 'Algo':
algo = module.__getattribute__(k)
# 以Widget结尾的类是控件
if k[-6:] == 'Widget':
widget = module.__getattribute__(k)
# 保存到字典中
ALGO_DICT[algo.templateName] = algo
WIDGET_DICT[algo.templateName] = widget

View File

@ -166,6 +166,7 @@ class AlgoTemplate(object):
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def putVarEvent(self, d): def putVarEvent(self, d):
"""更新变量""" """更新变量"""
d['active'] = self.active
self.engine.putVarEvent(self, d) self.engine.putVarEvent(self, d)
#---------------------------------------------------------------------- #----------------------------------------------------------------------

View File

@ -10,12 +10,8 @@ from vnpy.event import Event
from vnpy.trader.uiQt import QtCore, QtWidgets from vnpy.trader.uiQt import QtCore, QtWidgets
from .algoEngine import (EVENT_ALGO_LOG, EVENT_ALGO_PARAM, from .algoEngine import (EVENT_ALGO_LOG, EVENT_ALGO_PARAM,
EVENT_ALGO_VAR, EVENT_ALGO_SETTING) EVENT_ALGO_VAR, EVENT_ALGO_SETTING,
WIDGET_DICT)
from .twapAlgo import TwapWidget
from .dmaAlgo import DmaWidget
from .stopAlgo import StopWidget
from .stAlgo import StWidget
######################################################################## ########################################################################
@ -57,7 +53,6 @@ class StopButton(QtWidgets.QPushButton):
self.setStyleSheet("color:black;background-color:grey") self.setStyleSheet("color:black;background-color:grey")
AlgoCell = QtWidgets.QTableWidgetItem AlgoCell = QtWidgets.QTableWidgetItem
@ -303,11 +298,11 @@ class AlgoSettingMonitor(QtWidgets.QTableWidget):
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def initUi(self): def initUi(self):
"""初始化界面""" """初始化界面"""
labels = [u'', labels = ['',
'',
u'名称', u'名称',
u'算法', u'算法',
u'参数', u'参数']
'']
self.setColumnCount(len(labels)) self.setColumnCount(len(labels))
self.setHorizontalHeaderLabels(labels) self.setHorizontalHeaderLabels(labels)
@ -339,16 +334,16 @@ class AlgoSettingMonitor(QtWidgets.QTableWidget):
self.insertRow(0) self.insertRow(0)
buttonStart = StartButton(self.algoEngine, setting) buttonStart = StartButton(self.algoEngine, setting)
buttonDelete = DeleteButton(self.algoEngine, setting)
cellSettingName = AlgoCell(settingName) cellSettingName = AlgoCell(settingName)
cellTemplateName = AlgoCell(setting['templateName']) cellTemplateName = AlgoCell(setting['templateName'])
cellSettingText = AlgoCell(self.generateText(setting)) cellSettingText = AlgoCell(self.generateText(setting))
buttonDelete = DeleteButton(self.algoEngine, setting)
self.setCellWidget(0, 0, buttonStart) self.setCellWidget(0, 0, buttonStart)
self.setItem(0, 1, cellSettingName) self.setCellWidget(0, 1, buttonDelete)
self.setItem(0, 2, cellTemplateName) self.setItem(0, 2, cellSettingName)
self.setItem(0, 3, cellSettingText) self.setItem(0, 3, cellTemplateName)
self.setCellWidget(0, 4, buttonDelete) self.setItem(0, 4, cellSettingText)
self.cellDict[settingName] = { self.cellDict[settingName] = {
'start': buttonStart, 'start': buttonStart,
@ -383,19 +378,17 @@ class AlgoManager(QtWidgets.QWidget):
"""算法交易管理组件""" """算法交易管理组件"""
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def __init__(self, algoEngine, eventEngine): def __init__(self, algoEngine, eventEngine, parent=None):
"""Constructor""" """Constructor"""
super(AlgoManager, self).__init__() super(AlgoManager, self).__init__(parent)
self.algoEngine = algoEngine self.algoEngine = algoEngine
self.eventEngine = eventEngine self.eventEngine = eventEngine
self.initUi() self.widgetDict = {}
self.addAlgoWidget(TwapWidget)
self.addAlgoWidget(DmaWidget)
self.addAlgoWidget(StopWidget)
self.addAlgoWidget(StWidget)
self.initUi()
self.changeWidget()
self.algoEngine.loadAlgoSetting() # 界面初始化后,再加载算法配置 self.algoEngine.loadAlgoSetting() # 界面初始化后,再加载算法配置
#---------------------------------------------------------------------- #----------------------------------------------------------------------
@ -406,8 +399,19 @@ class AlgoManager(QtWidgets.QWidget):
buttonWidth = 400 buttonWidth = 400
buttonHeight = 60 buttonHeight = 60
self.tab = QtWidgets.QTabWidget() self.comboTemplate = QtWidgets.QComboBox()
self.tab.setMaximumWidth(buttonWidth) self.comboTemplate.setMaximumWidth(buttonWidth)
self.comboTemplate.currentIndexChanged.connect(self.changeWidget)
vbox = QtWidgets.QVBoxLayout()
for templateName, widgetClass in WIDGET_DICT.items():
widget = widgetClass(self.algoEngine)
widget.setMaximumWidth(buttonWidth)
widget.hide()
vbox.addWidget(widget)
self.widgetDict[templateName] = widget
self.comboTemplate.addItem(templateName)
self.buttonStop = StopButton(self.algoEngine) self.buttonStop = StopButton(self.algoEngine)
self.buttonStop.setMaximumWidth(buttonWidth) self.buttonStop.setMaximumWidth(buttonWidth)
@ -423,8 +427,16 @@ class AlgoManager(QtWidgets.QWidget):
self.buttonSaveSetting.clicked.connect(self.saveSettingFromCsv) self.buttonSaveSetting.clicked.connect(self.saveSettingFromCsv)
self.buttonSaveSetting.setFixedHeight(buttonHeight) self.buttonSaveSetting.setFixedHeight(buttonHeight)
label = QtWidgets.QLabel(u'算法类型')
label.setFixedWidth(100)
hbox = QtWidgets.QHBoxLayout()
hbox.addWidget(label)
hbox.addWidget(self.comboTemplate)
vbox1 = QtWidgets.QVBoxLayout() vbox1 = QtWidgets.QVBoxLayout()
vbox1.addWidget(self.tab) vbox1.addLayout(hbox)
vbox1.addLayout(vbox)
vbox1.addStretch() vbox1.addStretch()
vbox1.addWidget(self.buttonStop) vbox1.addWidget(self.buttonStop)
vbox1.addWidget(self.buttonAddAlgo) vbox1.addWidget(self.buttonAddAlgo)
@ -459,6 +471,16 @@ class AlgoManager(QtWidgets.QWidget):
self.setLayout(hbox2) self.setLayout(hbox2)
#----------------------------------------------------------------------
def changeWidget(self):
""""""
for widget in self.widgetDict.values():
widget.hide()
templateName = text_type(self.comboTemplate.currentText())
widget = self.widgetDict[templateName]
widget.show()
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def addAlgoWidget(self, widgetClass): def addAlgoWidget(self, widgetClass):
"""添加算法控制组件 """ """添加算法控制组件 """

View File

@ -6,7 +6,7 @@ from vnpy.trader.uiQt import QtWidgets
######################################################################## ########################################################################
class AlgoWidget(QtWidgets.QWidget): class AlgoWidget(QtWidgets.QFrame):
"""算法启动组件""" """算法启动组件"""
#---------------------------------------------------------------------- #----------------------------------------------------------------------
@ -22,6 +22,7 @@ class AlgoWidget(QtWidgets.QWidget):
#---------------------------------------------------------------------- #----------------------------------------------------------------------
def initUi(self): def initUi(self):
"""""" """"""
self.setFrameShape(self.Box)
algoLayout = self.initAlgoLayout() algoLayout = self.initAlgoLayout()
buttonStart = QtWidgets.QPushButton(u'启动算法') buttonStart = QtWidgets.QPushButton(u'启动算法')