Ejemplo n.º 1
0
 def writeLog(self, content):
     """快速发出日志事件"""
     log = VtLogData()
     log.logContent = content
     event = Event(type_=EVENT_LOG)
     event.dict_['data'] = log
     self.eventEngine.put(event)
Ejemplo n.º 2
0
    def writeLog(self, content):
        """发出日志"""
        log = VtLogData()
        log.logContent = content

        event = Event(EVENT_SPREADTRADING_LOG)
        event.dict_['data'] = log
        self.eventEngine.put(event)
Ejemplo n.º 3
0
 def writeCtaLog(self, content):
     """快速发出CTA模块日志事件"""
     log = VtLogData()
     log.logContent = content
     log.gatewayName = 'CTA_STRATEGY'
     event = Event(type_=EVENT_CTA_LOG)
     event.dict_['data'] = log
     self.eventEngine.put(event)   
Ejemplo n.º 4
0
    def writeRiskLog(self, content):
        """快速发出日志事件"""
        # 发出报警提示音

        if platform.uname() == 'Windows':
            import winsound
            winsound.PlaySound("SystemHand", winsound.SND_ASYNC)

        # 发出日志事件
        log = VtLogData()
        log.logContent = content
        log.gatewayName = self.name
        event = Event(type_=EVENT_LOG)
        event.dict_['data'] = log
        self.eventEngine.put(event)
Ejemplo n.º 5
0
class StLogMonitor(QtWidgets.QTextEdit):
    """价差日志监控"""
    signal = QtCore.Signal(type(Event()))

    #----------------------------------------------------------------------
    def __init__(self, mainEngine, eventEngine, parent=None):
        """Constructor"""
        super(StLogMonitor, self).__init__(parent)

        self.eventEngine = eventEngine

        self.registerEvent()

    #----------------------------------------------------------------------
    def processLogEvent(self, event):
        """处理日志事件"""
        log = event.dict_['data']
        content = '%s:%s' % (log.logTime, log.logContent)
        self.append(content)

    #----------------------------------------------------------------------
    def registerEvent(self):
        """注册事件监听"""
        self.signal.connect(self.processLogEvent)

        self.eventEngine.register(EVENT_SPREADTRADING_LOG, self.signal.emit)
Ejemplo n.º 6
0
    def removeGateway(self, gatewayName):
        newGatewayDetailList = list()
        for gateway in self.gatewayDetailList:
            if gateway['gatewayName'] != gatewayName:
                newGatewayDetailList.append(gateway)

        self.gatewayDetailList = newGatewayDetailList

        if gatewayName in self.gatewayDict.keys():
            del self.gatewayDict[gatewayName]

        event1 = Event(type_=EVENT_GATEWAY + 'ListChanged')
        self.eventEngine.put(event1)
Ejemplo n.º 7
0
    def putSpreadPosEvent(self, spread):
        """发出价差持仓事件"""
        event1 = Event(EVENT_SPREADTRADING_POS + spread.name)
        event1.dict_['data'] = spread
        self.eventEngine.put(event1)

        event2 = Event(EVENT_SPREADTRADING_POS)
        event2.dict_['data'] = spread
        self.eventEngine.put(event2)
Ejemplo n.º 8
0
    def putSpreadTickEvent(self, spread):
        """发出价差行情更新事件"""
        event1 = Event(EVENT_SPREADTRADING_TICK + spread.name)
        event1.dict_['data'] = spread
        self.eventEngine.put(event1)

        event2 = Event(EVENT_SPREADTRADING_TICK)
        event2.dict_['data'] = spread
        self.eventEngine.put(event2)
Ejemplo n.º 9
0
    def addDynamicGateway(self,
                          gatewayModuleStr,
                          gatewayName,
                          gatewayDisplayName,
                          userID,
                          password,
                          brokerID,
                          tdAddress,
                          mdAddress,
                          authCode=None,
                          userProductInfo=None):
        """动态添加底层接口"""
        gatewayModule = importlib.import_module("redtorch.trader.gateway." +
                                                gatewayModuleStr)
        # 创建接口实例
        self.gatewayDict[gatewayName] = gatewayModule.gatewayClass(
            self.eventEngine,
            gatewayName,
            userID,
            password,
            brokerID,
            tdAddress,
            mdAddress,
            authCode=None,
            userProductInfo=None)

        # 设置接口轮询
        if gatewayModule.gatewayQryEnabled:
            self.gatewayDict[gatewayName].setQryEnabled(
                gatewayModule.gatewayQryEnabled)

        # 保存接口详细信息
        d = {
            'gatewayName': gatewayName,
            'gatewayDisplayName': gatewayDisplayName,
            'gatewayType': gatewayModule.gatewayType,
        }
        self.gatewayDetailList.append(d)
        event1 = Event(type_=EVENT_GATEWAY + 'ListChanged')
        self.eventEngine.put(event1)
Ejemplo n.º 10
0
    def processTradeEvent(self, event):
        """处理成交推送"""
        # 检查成交是否需要处理
        trade = event.dict_['data']
        if trade.vtSymbol not in self.legDict:
            return

        # 更新腿持仓
        leg = self.legDict[trade.vtSymbol]
        direction = trade.direction
        offset = trade.offset

        if direction == DIRECTION_LONG:
            if offset == OFFSET_OPEN:
                leg.longPos += trade.volume
            else:
                leg.shortPos -= trade.volume
        else:
            if offset == OFFSET_OPEN:
                leg.shortPos += trade.volume
            else:
                leg.longPos -= trade.volume
        leg.netPos = leg.longPos - leg.shortPos

        # 更新价差持仓
        spread = self.vtSymbolSpreadDict[trade.vtSymbol]
        spread.calculatePos()

        # 推送价差持仓更新
        event1 = Event(EVENT_SPREADTRADING_POS + spread.name)
        event1.dict_['data'] = spread
        self.eventEngine.put(event1)

        event2 = Event(EVENT_SPREADTRADING_POS)
        event2.dict_['data'] = spread
        self.eventEngine.put(event2)
Ejemplo n.º 11
0
 def putStrategyEvent(self, name):
     """触发策略状态变化事件(通常用于通知GUI更新)"""
     event = Event(EVENT_CTA_STRATEGY+name)
     self.eventEngine.put(event)
Ejemplo n.º 12
0
class CtaStrategyManager(QtWidgets.QGroupBox):
    """策略管理组件"""
    signal = QtCore.Signal(type(Event()))

    #----------------------------------------------------------------------
    def __init__(self, ctaEngine, eventEngine, name, parent=None):
        """Constructor"""
        super(CtaStrategyManager, self).__init__(parent)

        self.ctaEngine = ctaEngine
        self.eventEngine = eventEngine
        self.name = name

        self.initUi()
        self.updateMonitor()
        self.registerEvent()

    #----------------------------------------------------------------------
    def initUi(self):
        """初始化界面"""
        self.setTitle(self.name)

        self.paramMonitor = CtaValueMonitor(self)
        self.varMonitor = CtaValueMonitor(self)

        height = 65
        self.paramMonitor.setFixedHeight(height)
        self.varMonitor.setFixedHeight(height)

        buttonInit = QtWidgets.QPushButton(text.INIT)
        buttonStart = QtWidgets.QPushButton(text.START)
        buttonStop = QtWidgets.QPushButton(text.STOP)
        buttonInit.clicked.connect(self.init)
        buttonStart.clicked.connect(self.start)
        buttonStop.clicked.connect(self.stop)

        hbox1 = QtWidgets.QHBoxLayout()
        hbox1.addWidget(buttonInit)
        hbox1.addWidget(buttonStart)
        hbox1.addWidget(buttonStop)
        hbox1.addStretch()

        hbox2 = QtWidgets.QHBoxLayout()
        hbox2.addWidget(self.paramMonitor)

        hbox3 = QtWidgets.QHBoxLayout()
        hbox3.addWidget(self.varMonitor)

        vbox = QtWidgets.QVBoxLayout()
        vbox.addLayout(hbox1)
        vbox.addLayout(hbox2)
        vbox.addLayout(hbox3)

        self.setLayout(vbox)

    #----------------------------------------------------------------------
    def updateMonitor(self, event=None):
        """显示策略最新状态"""
        paramDict = self.ctaEngine.getStrategyParam(self.name)
        if paramDict:
            self.paramMonitor.updateData(paramDict)

        varDict = self.ctaEngine.getStrategyVar(self.name)
        if varDict:
            self.varMonitor.updateData(varDict)

    #----------------------------------------------------------------------
    def registerEvent(self):
        """注册事件监听"""
        self.signal.connect(self.updateMonitor)
        self.eventEngine.register(EVENT_CTA_STRATEGY + self.name,
                                  self.signal.emit)

    #----------------------------------------------------------------------
    def init(self):
        """初始化策略"""
        self.ctaEngine.initStrategy(self.name)

    #----------------------------------------------------------------------
    def start(self):
        """启动策略"""
        self.ctaEngine.startStrategy(self.name)

    #----------------------------------------------------------------------
    def stop(self):
        """停止策略"""
        self.ctaEngine.stopStrategy(self.name)
Ejemplo n.º 13
0
class CtaEngineManager(QtWidgets.QWidget):
    """CTA引擎管理组件"""
    signal = QtCore.Signal(type(Event()))

    #----------------------------------------------------------------------
    def __init__(self, ctaEngine, eventEngine, parent=None):
        """Constructor"""
        super(CtaEngineManager, self).__init__(parent)

        self.ctaEngine = ctaEngine
        self.eventEngine = eventEngine

        self.strategyLoaded = False

        self.initUi()
        self.registerEvent()

        # 记录日志
        self.ctaEngine.writeCtaLog(text.CTA_ENGINE_STARTED)

    #----------------------------------------------------------------------
    def initUi(self):
        """初始化界面"""
        self.setWindowTitle(text.CTA_STRATEGY)

        # 按钮
        loadButton = QtWidgets.QPushButton(text.LOAD_STRATEGY)
        initAllButton = QtWidgets.QPushButton(text.INIT_ALL)
        startAllButton = QtWidgets.QPushButton(text.START_ALL)
        stopAllButton = QtWidgets.QPushButton(text.STOP_ALL)

        loadButton.clicked.connect(self.load)
        initAllButton.clicked.connect(self.initAll)
        startAllButton.clicked.connect(self.startAll)
        stopAllButton.clicked.connect(self.stopAll)

        # 滚动区域,放置所有的CtaStrategyManager
        self.scrollArea = QtWidgets.QScrollArea()
        self.scrollArea.setWidgetResizable(True)

        # CTA组件的日志监控
        self.ctaLogMonitor = QtWidgets.QTextEdit()
        self.ctaLogMonitor.setReadOnly(True)
        self.ctaLogMonitor.setMaximumHeight(200)

        # 设置布局
        hbox2 = QtWidgets.QHBoxLayout()
        hbox2.addWidget(loadButton)
        hbox2.addWidget(initAllButton)
        hbox2.addWidget(startAllButton)
        hbox2.addWidget(stopAllButton)
        hbox2.addStretch()

        vbox = QtWidgets.QVBoxLayout()
        vbox.addLayout(hbox2)
        vbox.addWidget(self.scrollArea)
        vbox.addWidget(self.ctaLogMonitor)
        self.setLayout(vbox)

    #----------------------------------------------------------------------
    def initStrategyManager(self):
        """初始化策略管理组件界面"""
        w = QtWidgets.QWidget()
        vbox = QtWidgets.QVBoxLayout()

        for name in self.ctaEngine.strategyDict.keys():
            strategyManager = CtaStrategyManager(self.ctaEngine,
                                                 self.eventEngine, name)
            vbox.addWidget(strategyManager)

        vbox.addStretch()

        w.setLayout(vbox)
        self.scrollArea.setWidget(w)

    #----------------------------------------------------------------------
    def initAll(self):
        """全部初始化"""
        self.ctaEngine.initAll()

    #----------------------------------------------------------------------
    def startAll(self):
        """全部启动"""
        self.ctaEngine.startAll()

    #----------------------------------------------------------------------
    def stopAll(self):
        """全部停止"""
        self.ctaEngine.stopAll()

    #----------------------------------------------------------------------
    def load(self):
        """加载策略"""
        if not self.strategyLoaded:
            self.ctaEngine.loadSetting()
            self.initStrategyManager()
            self.strategyLoaded = True
            self.ctaEngine.writeCtaLog(text.STRATEGY_LOADED)

    #----------------------------------------------------------------------
    def updateCtaLog(self, event):
        """更新CTA相关日志"""
        log = event.dict_['data']
        content = '\t'.join([log.logTime, log.logContent])
        self.ctaLogMonitor.append(content)

    #----------------------------------------------------------------------
    def registerEvent(self):
        """注册事件监听"""
        self.signal.connect(self.updateCtaLog)
        self.eventEngine.register(EVENT_CTA_LOG, self.signal.emit)
Ejemplo n.º 14
0
class DrEngineManager(QtWidgets.QWidget):
    """行情数据记录引擎管理组件"""
    signal = QtCore.Signal(type(Event()))

    #----------------------------------------------------------------------
    def __init__(self, drEngine, eventEngine, parent=None):
        """Constructor"""
        super(DrEngineManager, self).__init__(parent)

        self.drEngine = drEngine
        self.eventEngine = eventEngine

        self.initUi()
        self.updateSetting()
        self.registerEvent()

    #----------------------------------------------------------------------
    def initUi(self):
        """初始化界面"""
        self.setWindowTitle(text.DATA_RECORDER)

        # 记录合约配置监控
        tickLabel = QtWidgets.QLabel(text.TICK_RECORD)
        self.tickTable = QtWidgets.QTableWidget()
        self.tickTable.setColumnCount(2)
        self.tickTable.verticalHeader().setVisible(False)
        self.tickTable.setEditTriggers(QtWidgets.QTableWidget.NoEditTriggers)
        self.tickTable.setAlternatingRowColors(True)
        self.tickTable.setHorizontalHeaderLabels(
            [text.CONTRACT_SYMBOL, text.GATEWAY])

        barLabel = QtWidgets.QLabel(text.BAR_RECORD)
        self.barTable = QtWidgets.QTableWidget()
        self.barTable.setColumnCount(2)
        self.barTable.verticalHeader().setVisible(False)
        self.barTable.setEditTriggers(QtWidgets.QTableWidget.NoEditTriggers)
        self.barTable.setAlternatingRowColors(True)
        self.barTable.setHorizontalHeaderLabels(
            [text.CONTRACT_SYMBOL, text.GATEWAY])

        activeLabel = QtWidgets.QLabel(text.DOMINANT_CONTRACT)
        self.activeTable = QtWidgets.QTableWidget()
        self.activeTable.setColumnCount(2)
        self.activeTable.verticalHeader().setVisible(False)
        self.activeTable.setEditTriggers(QtWidgets.QTableWidget.NoEditTriggers)
        self.activeTable.setAlternatingRowColors(True)
        self.activeTable.setHorizontalHeaderLabels(
            [text.DOMINANT_SYMBOL, text.CONTRACT_SYMBOL])

        # 日志监控
        self.logMonitor = QtWidgets.QTextEdit()
        self.logMonitor.setReadOnly(True)
        self.logMonitor.setMinimumHeight(600)

        # 设置布局
        grid = QtWidgets.QGridLayout()

        grid.addWidget(tickLabel, 0, 0)
        grid.addWidget(barLabel, 0, 1)
        grid.addWidget(activeLabel, 0, 2)
        grid.addWidget(self.tickTable, 1, 0)
        grid.addWidget(self.barTable, 1, 1)
        grid.addWidget(self.activeTable, 1, 2)

        vbox = QtWidgets.QVBoxLayout()
        vbox.addLayout(grid)
        vbox.addWidget(self.logMonitor)
        self.setLayout(vbox)

    #----------------------------------------------------------------------
    def updateLog(self, event):
        """更新日志"""
        log = event.dict_['data']
        content = '\t'.join([log.logTime, log.logContent])
        self.logMonitor.append(content)

    #----------------------------------------------------------------------
    def registerEvent(self):
        """注册事件监听"""
        self.signal.connect(self.updateLog)
        self.eventEngine.register(EVENT_DATARECORDER_LOG, self.signal.emit)

    #----------------------------------------------------------------------
    def updateSetting(self):
        """显示引擎行情记录配置"""
        setting, activeSetting = self.drEngine.getSetting()

        for d in setting.values():
            if 'tick' in d and d['tick']:
                self.tickTable.insertRow(0)
                self.tickTable.setItem(0, 0, TableCell(d['symbol']))
                self.tickTable.setItem(0, 1, TableCell(d['gateway']))

            if 'bar' in d and d['bar']:
                self.barTable.insertRow(0)
                self.barTable.setItem(0, 0, TableCell(d['symbol']))
                self.barTable.setItem(0, 1, TableCell(d['gateway']))

        for vtSymbol, activeSymbol in activeSetting.items():
            self.activeTable.insertRow(0)
            self.activeTable.setItem(0, 0, TableCell(activeSymbol))
            self.activeTable.setItem(0, 1, TableCell(vtSymbol))

        self.tickTable.resizeColumnsToContents()
        self.barTable.resizeColumnsToContents()
        self.activeTable.resizeColumnsToContents()
Ejemplo n.º 15
0
 def putAlgoEvent(self, algo):
     """发出算法状态更新事件"""
     event = Event(EVENT_SPREADTRADING_ALGO + algo.name)
     self.eventEngine.put(event)