예제 #1
0
 def subscribe(self):
     ss = SubscribeRequest()
     ss.sym_type = SYMBOL_TYPE.CTP
     ss.content = str(self.sym.text())
     m = Event(EventType.SUBSCRIBE)
     m.msg_type = MSG_TYPE.MSG_TYPE_SUBSCRIBE_MARKET_DATA
     m.data = ss
     self.subscribe_signal.emit(m)
예제 #2
0
 def write_log(self, msg: str):
     """"""
     if self.event_engine:
         event = Event(type=EventType.BACKTEST_LOG)
         event.data = msg
         self.event_engine.put(event)
     else:
         print(str)
예제 #3
0
    def run_optimization(self,
                         class_name: str,
                         full_symbol: str,
                         interval: str,
                         start: datetime,
                         end: datetime,
                         rate: float,
                         slippage: float,
                         size: int,
                         pricetick: float,
                         capital: int,
                         optimization_setting: OptimizationSetting,
                         use_ga: bool,
                         datasource: str = 'DataBase'):
        """"""
        if use_ga:
            self.write_log("开始遗传算法参数优化")
        else:
            self.write_log("开始多进程参数优化")

        self.result_values = None

        engine = self.backtesting_engine
        engine.clear_data()

        engine.set_parameters(full_symbol=full_symbol,
                              interval=interval,
                              start=start,
                              end=end,
                              rate=rate,
                              slippage=slippage,
                              size=size,
                              pricetick=pricetick,
                              capital=capital)

        strategy_class = self.classes[class_name]
        engine.add_strategy(strategy_class, {})

        if use_ga:
            self.result_values = engine.run_ga_optimization(
                optimization_setting, output=False, datasource=datasource)
        else:
            self.result_values = engine.run_optimization(optimization_setting,
                                                         output=False,
                                                         datasource=datasource)

        # Clear thread object handler.
        self.thread = None
        self.write_log("多进程参数优化完成")

        # Put optimization done event
        if self.event_engine:
            event = Event(type=EventType.OPTIMIZATION_FINISH)
            self.event_engine.put(event)
예제 #4
0
    def run_batch_bt(self,
                     class_name: str,
                     settinglist: dict,
                     interval: str,
                     rate: float,
                     slippage: float,
                     size: int,
                     pricetick: float,
                     capital: int,
                     setting: dict,
                     datasource: str = "DataBase"):
        """"""
        self.result_df = None
        self.result_statistics = None

        engine = self.backtesting_engine
        engine.clear_data()
        strategy_class = self.classes[class_name]

        fsmlist = settinglist['full_symbol']
        startlist = settinglist['start']
        endlist = settinglist['end']

        for i in range(len(fsmlist)):
            full_symbol = fsmlist[i]
            start = startlist[i]
            end = endlist[i]
            engine.set_parameters(full_symbol=full_symbol,
                                  interval=interval,
                                  start=start,
                                  end=end,
                                  rate=rate,
                                  slippage=slippage,
                                  size=size,
                                  pricetick=pricetick,
                                  capital=capital)

            engine.add_strategy(strategy_class, setting)

            engine.load_data(datasource)
            engine.run_backtesting()

        self.result_df = engine.calculate_result()
        self.result_statistics = engine.calculate_statistics(output=False)
        self.result_trades = engine.get_all_trades()
        self.result_dailys = engine.get_all_daily_results()
        # Clear thread object handler.
        self.thread = None

        # Put backtesting done event
        if self.event_engine:
            event = Event(type=EventType.BACKTEST_FINISH)
            self.event_engine.put(event)
예제 #5
0
 def qry(self):
     qry = Event(EventType.QRY)
     if (self.qry_type.currentText() == 'Account'):
         qry.msg_type = MSG_TYPE.MSG_TYPE_QRY_ACCOUNT
     if (self.qry_type.currentText() == 'Position'):
         qry.msg_type = MSG_TYPE.MSG_TYPE_QRY_POS
     if (self.qry_type.currentText() == 'Contract'):
         qc = QryContractRequest()
         qc.sym_type = SYMBOL_TYPE.CTP
         qc.content = self.qry_content.text()
         qry.msg_type = MSG_TYPE.MSG_TYPE_QRY_CONTRACT
         qry.data = qc
     if (self.qry_type.currentText() == 'Order'):
         qry.msg_type = MSG_TYPE.MSG_TYPE_QRY_ORDER
     if (self.qry_type.currentText() == 'Trade'):
         qry.msg_type = MSG_TYPE.MSG_TYPE_QRY_TRADE
     if (self.qry_type.currentText() == 'PositionDetail'):
         qry.msg_type = MSG_TYPE.MSG_TYPE_QRY_POSDETAIL
     self.qry_signal.emit(qry)
예제 #6
0
 def unsubscribe(self):
     cell = self.currentItem()
     if not cell:
         return
     tick = cell.get_data()
     if not tick:
         return
     req = SubscribeRequest(sym_type=SYMBOL_TYPE.FULL,
                            content=tick.full_symbol)
     m = Event(type=EventType.GENERAL_REQ,
               data=req,
               des=tick.gateway_name,
               src='0',
               msgtype=MSG_TYPE.MSG_TYPE_UNSUBSCRIBE)
     self.event_engine.put(m)
예제 #7
0
 def place_order_ctp(self, of):
     try:
         m = Event(EventType.ORDER)
         m.msg_type = MSG_TYPE.MSG_TYPE_ORDER_CTP
         m.destination = self.gateway.currentText()
         m.source = '0'
         ot = OrderType.DEFAULT
         if (of.OrderPriceType == THOST_FTDC_OPT_AnyPrice) and (
                 of.ContingentCondition
                 in [THOST_FTDC_CC_Touch, THOST_FTDC_CC_TouchProfit]):
             ot = OrderType.STP
         elif (of.OrderPriceType == THOST_FTDC_OPT_LimitPrice) and (
                 of.ContingentCondition
                 in [THOST_FTDC_CC_Touch, THOST_FTDC_CC_TouchProfit]):
             ot = OrderType.STPLMT
         elif (of.OrderPriceType == THOST_FTDC_OPT_AnyPrice) and (
                 of.ContingentCondition
                 == THOST_FTDC_CC_Immediately) and (of.TimeCondition
                                                    == THOST_FTDC_TC_GFD):
             ot = OrderType.MKT
         elif (of.OrderPriceType == THOST_FTDC_OPT_LimitPrice) and (
                 of.ContingentCondition
                 == THOST_FTDC_CC_Immediately) and (of.TimeCondition
                                                    == THOST_FTDC_TC_GFD):
             ot = OrderType.LMT
         elif (of.ContingentCondition == THOST_FTDC_CC_Immediately) and (
                 of.TimeCondition
                 == THOST_FTDC_TC_IOC) and (of.VolumeCondition
                                            == THOST_FTDC_VC_AV):
             ot = OrderType.FAK
         elif (of.ContingentCondition == THOST_FTDC_CC_Immediately) and (
                 of.TimeCondition
                 == THOST_FTDC_TC_IOC) and (of.VolumeCondition
                                            == THOST_FTDC_VC_CV):
             ot = OrderType.FOK
         o = OrderData(api="CTP.TD",
                       account=m.destination[7:],
                       clientID=0,
                       client_order_id=self.manualorderid,
                       type=ot,
                       orderfield=of)
         # o.api = "CTP.TD"       #self.gateway.currentText()
         # o.account = m.destination[7:]
         # o.clientID = 0
         # o.client_order_id = self.manualorderid
         # # o.create_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')
         # o.orderfield = of
         m.data = o
         self.order_signal.emit(m)
         self.manualorderid = self.manualorderid + 1
     except:
         print('place ctp order error')
예제 #8
0
 def cancel_order(self, cell):
     data = cell.get_data()
     oid = data.__getattribute__(self.data_key)
     row_cells = self.cells[oid]
     cell2 = row_cells['status']
     order = cell2.get_data()
     if not order:
         return
     if order.status not in ACTIVE_STATUSES:
         QtWidgets.QMessageBox().information(None, 'Error',
                                             'Order not active!',
                                             QtWidgets.QMessageBox.Ok)
         return
     req = order.create_cancel_request()
     dest = order.api + '.' + order.account  # gateway_name
     m = Event(type=EventType.GENERAL_REQ,
               data=req,
               des=dest,
               src='0',
               msgtype=MSG_TYPE.MSG_TYPE_CANCEL_ORDER)
     self.event_engine.put(m)
예제 #9
0
 def place_order_paper(self, of):
     try:
         m = Event(EventType.ORDER)
         m.msg_type = MSG_TYPE.MSG_TYPE_ORDER_PAPER
         m.destination = self.gateway.currentText()
         m.source = '0'
         o = OrderData()
         o.api = "PAPER.TD"  # self.api_type.currentText()
         o.account = "manual"
         o.clientID = 0
         o.client_order_id = self.manualorderid
         self.manualorderid = self.manualorderid + 1
         # o.create_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')
         o.orderfield = of
         m.data = o
         self.order_signal.emit(m)
     except:
         print('place paper order error')
예제 #10
0
 def place_local_order_ctp(self, of):
     try:
         m = Event(EventType.ORDER)
         m.msg_type = MSG_TYPE.MSG_TYPE_ORDER_CTP
         m.destination = self.gateway.currentText()
         m.source = '0'
         ot = OrderType.LPT
         if of.ContingentCondition in [
                 THOST_FTDC_CC_Touch, THOST_FTDC_CC_TouchProfit
         ]:
             of.ContingentCondition = THOST_FTDC_CC_Immediately
         o = OrderData(api="CTP.TD",
                       account=m.destination[7:],
                       clientID=0,
                       client_order_id=self.manualorderid,
                       type=ot,
                       orderfield=of)
         m.data = o
         self.order_signal.emit(m)
         self.manualorderid = self.manualorderid + 1
     except:
         print('place ctp local order error')
예제 #11
0
    def generate_request(self):
        print("ctp request at ", datetime.now())
        if (self.request_type.currentText() == 'Order'):
            of = CtpOrderField()
            of.InstrumentID = self.sym.text()
            of.OrderPriceType = self.orderfielddict['pricetype'][
                self.order_price_type.currentIndex()]
            of.Direction = self.orderfielddict['direction'][
                self.direction_type.currentIndex()]
            of.CombOffsetFlag = self.orderfielddict['orderflag'][
                self.order_flag_type.currentIndex()]
            of.CombHedgeFlag = self.orderfielddict['hedge'][
                self.hedge_type.currentIndex()]
            of.TimeCondition = self.orderfielddict['timecondition'][
                self.time_condition_type.currentIndex()]
            of.GTDDate = self.time_condition_time.text()
            of.VolumeCondition = self.orderfielddict['volumecondition'][
                self.volume_condition_type.currentIndex()]
            of.ContingentCondition = self.orderfielddict['condition'][
                self.order_condition_type.currentIndex()]
            of.ForceCloseReason = THOST_FTDC_FCC_NotForceClose
            try:
                of.LimitPrice = float(self.limit_price.text())
                of.VolumeTotalOriginal = int(self.order_quantity.text())
                of.MinVolume = int(self.order_minquantity.text())
                of.StopPrice = float(self.stop_price.text())
            except:
                print('ctp request error,please check numerical field')
                return

            self.orderfield_signal.emit(of)
        elif (self.request_type.currentText() == 'LocalOrder'):
            of = CtpOrderField()
            of.InstrumentID = self.sym.text()
            of.OrderPriceType = self.orderfielddict['pricetype'][
                self.order_price_type.currentIndex()]
            of.Direction = self.orderfielddict['direction'][
                self.direction_type.currentIndex()]
            of.CombOffsetFlag = self.orderfielddict['orderflag'][
                self.order_flag_type.currentIndex()]
            of.CombHedgeFlag = self.orderfielddict['hedge'][
                self.hedge_type.currentIndex()]
            of.TimeCondition = self.orderfielddict['timecondition'][
                self.time_condition_type.currentIndex()]
            of.GTDDate = self.time_condition_time.text()
            of.VolumeCondition = self.orderfielddict['volumecondition'][
                self.volume_condition_type.currentIndex()]
            of.ContingentCondition = self.orderfielddict['condition'][
                self.order_condition_type.currentIndex()]
            of.ForceCloseReason = THOST_FTDC_FCC_NotForceClose
            try:
                of.LimitPrice = float(self.limit_price.text())
                of.VolumeTotalOriginal = int(self.order_quantity.text())
                of.MinVolume = int(self.order_minquantity.text())
                of.StopPrice = float(self.stop_price.text())
            except:
                print('ctp request error,please check numerical field')
                return
            if of.StopPrice <= 0:
                QtWidgets.QMessageBox().information(
                    None, 'Error', 'Stop Price must be positive number !',
                    QtWidgets.QMessageBox.Ok)
                return
            self.local_orderfield_signal.emit(of)

        elif (self.request_type.currentText() == 'CancelAll'):
            ss = CancelAllRequest()
            ss.sym_type = SYMBOL_TYPE.CTP
            ss.content = str(self.sym.text())
            m = Event(EventType.CANCEL)
            m.msg_type = MSG_TYPE.MSG_TYPE_CANCEL_ALL
            m.data = ss
            self.cancelall_signal.emit(m)