Exemple #1
0
    def send_order(self) -> None:
        """"""
        symbol = self.symbol_line.text()
        contract = self.contracts.get(symbol, None)
        if not contract:
            return

        price_text = self.price_line.text()
        volume_text = self.volume_line.text()

        if not price_text or not volume_text:
            return

        price = float(price_text)
        volume = int(volume_text)
        direction = Direction(self.direction_combo.currentText())
        offset = Offset(self.offset_combo.currentText())

        req = OrderRequest(symbol=contract.symbol,
                           exchange=contract.exchange,
                           direction=direction,
                           type=OrderType.LIMIT,
                           offset=offset,
                           volume=volume,
                           price=price)
        self.main_engine.send_order(req, contract.gateway_name)
Exemple #2
0
    def __init__(self, algo_engine: BaseEngine, algo_name: str, setting: dict):
        """"""
        super().__init__(algo_engine, algo_name, setting)

        # Parameters
        self.vt_symbol = setting["vt_symbol"]
        self.direction = Direction(setting["direction"])
        self.price = setting["price"]
        self.volume = setting["volume"]
        self.time = setting["time"]
        self.interval = setting["interval"]
        self.offset = Offset(setting["offset"])

        # Variables
        self.order_volume = self.volume / (self.time / self.interval)
        contract = self.get_contract(self.vt_symbol)
        if contract:
            self.order_volume = round_to(self.order_volume,
                                         contract.min_volume)

        self.timer_count = 0
        self.total_count = 0
        self.traded = 0

        self.last_tick = None

        self.subscribe(self.vt_symbol)
        self.put_parameters_event()
        self.put_variables_event()
Exemple #3
0
 def to_investment(self):
     investment = InvestmentData(
         id=self.id,
         exchange=Exchange(self.exchange),
         product_code=self.product_code,
         symbol=self.symbol,
         open_price=self.open_price,
         finish_price=self.finish_price,
         volume=self.volume,
         close_volume=self.close_volume,
         direction=Direction(self.direction),
         money_lock=self.money_lock,
         profit=self.profit,
         profit_rate=self.profit_rate,
         net_profit=self.net_profit,
         cost_fee=self.cost_fee,
         strategy=self.strategy,
         start_datetime=self.start_datetime,
         end_datetime=self.end_datetime,
         open_trade_id=self.open_trade_id,
         close_trade_ids=self.close_trade_ids.split(",")
         if self.close_trade_ids is not None else None,
         state=InvestmentState(self.state),
         engine_type=EngineType(self.engine_type))
     return investment
Exemple #4
0
    def __init__(
        self,
        algo_engine: BaseEngine,
        algo_name: str,
        setting: dict
    ):
        """"""
        super().__init__(algo_engine, algo_name, setting)

        # Parameters
        self.vt_symbol = setting["vt_symbol"]
        self.direction = Direction(setting["direction"])
        self.stop_price = setting["stop_price"]
        self.volume = setting["volume"]
        self.price_add = setting["price_add"]
        self.offset = Offset(setting["offset"])

        # Variables
        self.vt_orderid = ""
        self.traded = 0
        self.order_status = ""

        self.subscribe(self.vt_symbol)
        self.put_parameters_event()
        self.put_variables_event()
Exemple #5
0
    def load_data(self) -> None:
        """"""
        position_data = load_json(self.data_filename)

        for d in position_data:
            vt_symbol = d["vt_symbol"]
            direction = Direction(d["direction"])

            position = self.get_position(vt_symbol, direction)
            position.volume = d["volume"]
            position.price = d["price"]
Exemple #6
0
 def to_trade(self):
     trade = TradeDataExt(id=self.id,
                          product_code=self.product_code,
                          symbol=self.symbol,
                          exchange=Exchange(self.exchange),
                          datetime=self.datetime,
                          direction=Direction(self.direction),
                          offset=Offset(self.offset),
                          price=self.price,
                          volume=self.volume,
                          rest_volume=self.rest_volume,
                          strategy=self.strategy,
                          engine_type=EngineType(self.engine_type))
     return trade
Exemple #7
0
    def load_trade_from_excel(self, gateway_name: str):
        """"""

        total_row = self.trade_sheet.max_row
        # total_column = trade_sheet.max_column

        for i in range(2, total_row + 1):
            trade_datetime = self.trade_sheet.cell(i, 8).value
            trade_datetime = trade_datetime.split("+")[0]

            vt_symbol = self.trade_sheet.cell(i, 1).value
            symbol, exchange_str = vt_symbol.split(".")
            exchange = Exchange(exchange_str)

            direction = self.trade_sheet.cell(i, 5).value
            if direction == "Direction.LONG":
                direction = "多"
            elif direction == "Direction.SHORT":
                direction = "空"
            elif direction == "Direction.NET":
                direction = "净"

            offset = self.trade_sheet.cell(i, 4).value
            if offset == "Offset.NONE":
                offset = ""
            elif offset == "Offset.OPEN":
                offset = "开"
            elif offset == "Offset.CLOSE":
                offset = "平"
            elif offset == "Offset.CLOSETODAY":
                offset = "平今"
            elif offset == "Offset.CLOSEYESTERDAY":
                offset = "平昨"

            trade = TradeData(symbol=symbol,
                              exchange=exchange,
                              orderid=self.trade_sheet.cell(i, 2).value,
                              tradeid=self.trade_sheet.cell(i, 3).value,
                              direction=Direction(direction),
                              offset=Offset(offset),
                              price=self.trade_sheet.cell(i, 6).value,
                              volume=self.trade_sheet.cell(i, 7).value,
                              datetime=CHINA_TZ.localize(
                                  datetime.strptime(trade_datetime,
                                                    "%Y-%m-%d %H:%M:%S.%f")),
                              gateway_name=gateway_name)

            self.trades.append(trade)

        self.output(f"已从excel表格加载{len(self.trades)}条交易记录")
Exemple #8
0
    def to_trade(self):
        trade = TradeData(symbol=self.symbol,
                          exchange=Exchange(self.exchange),
                          orderid=self.orderid,
                          tradeid=self.tradeid,
                          direction=Direction(self.direction),
                          offset=Offset(self.offset),
                          price=self.price,
                          volume=self.volume,
                          datetime=self.datetime.replace(tzinfo=DB_TZ),
                          orderRef=self.orderRef,
                          gateway_name="DB")
        trade.strategy = self.strategy

        return trade
Exemple #9
0
    def start_algo(self):
        """"""
        name = self.name_line.text()
        direction = Direction(self.direction_combo.currentText())
        price = float(self.price_line.text())
        volume = float(self.volume_line.text())
        payup = int(self.payup_line.text())
        interval = int(self.interval_line.text())

        lock_str = self.lock_combo.currentText()
        if lock_str == "是":
            lock = True
        else:
            lock = False

        self.spread_engine.start_algo(name, direction, price, volume, payup,
                                      interval, lock)
Exemple #10
0
        def to_trade(self):
            """
            Generate ContractData object from DbContractData.
            """
            trade = TradeData(accountid=self.accountid,
                              symbol=self.symbol,
                              exchange=Exchange(self.exchange),
                              orderid=self.orderid,
                              tradeid=self.tradeid,
                              direction=Direction(self.direction),
                              offset=Offset(self.offset),
                              price=self.price,
                              volume=self.volume,
                              datetime=self.datetime,
                              gateway_name="DB")

            return trade
Exemple #11
0
    def send_order(self):
        """"""
        name = self.name_combo.currentText()

        price_text = self.price_line.text()
        volume_text = self.volume_line.text()

        if not price_text or not volume_text:
            return

        price = float(price_text)
        volume = float(volume_text)
        direction = Direction(self.direction_combo.currentText())
        offset = Offset(self.offset_combo.currentText())

        self.portfolio_engine.send_order(name, price, volume, direction,
                                         offset)
Exemple #12
0
    def __init__(
        self,
        algo_engine: BaseEngine,
        algo_name: str,
        setting: dict
    ):
        """"""
        super().__init__(algo_engine, algo_name, setting)

        # Parameters
        self.vt_symbol = setting["vt_symbol"]
        self.direction = Direction(setting["direction"])
        self.volume = setting["volume"]
        self.offset = Offset(setting["offset"])

        self.min_volume = setting["min_volume"]
        self.max_volume = setting["max_volume"]

        if "." in setting["volume_change"]:
            self.volume_change = float(setting["volume_change"])
        else:
            self.volume_change = int(setting["volume_change"])

        # Variables
        self.vt_orderid = ""
        self.traded = 0
        self.last_tick = None
        self.order_price = 0

        self.put_parameters_event()
        self.put_variables_event()

        # Check if min/max volume met
        if self.min_volume <= 0:
            self.write_log("最小挂单量必须大于0,算法启动失败")
            self.stop()
            return

        if self.max_volume < self.min_volume:
            self.write_log("最大挂单量必须不小于最小委托量,算法启动失败")
            self.stop()
            return

        self.subscribe(self.vt_symbol)
Exemple #13
0
        def to_order(self):
            """
            Generate ContractData object from DbContractData.
            """
            order = OrderData(accountid=self.accountid,
                              symbol=self.symbol,
                              exchange=Exchange(self.exchange),
                              orderid=self.orderid,
                              type=self.type,
                              direction=Direction(self.direction),
                              offset=Offset(self.offset),
                              price=self.price,
                              volume=self.volume,
                              traded=self.traded,
                              status=self.status,
                              time=self.time,
                              gateway_name="DB")

            return order
Exemple #14
0
    def __init__(self, algo_engine: BaseEngine, algo_name: str, setting: dict):
        """"""
        super().__init__(algo_engine, algo_name, setting)

        # Parameters
        self.vt_symbol = setting["vt_symbol"]
        self.direction = Direction(setting["direction"])
        self.price = setting["price"]
        self.volume = setting["volume"]
        self.display_volume = setting["display_volume"]
        self.interval = setting["interval"]
        self.offset = Offset(setting["offset"])

        # Variables
        self.timer_count = 0
        self.vt_orderid = ""
        self.traded = 0

        self.last_tick = None

        self.subscribe(self.vt_symbol)
        self.put_parameters_event()
        self.put_variables_event()
Exemple #15
0
    def send_parent_order(self, setting: dict):
        """"""
        vt_symbol = setting["vt_symbol"]
        volume = setting["volume"]
        price = setting["price"]
        order_type = OrderType(setting["order_type"])
        direction = Direction(setting["direction"])
        offset = Offset(setting["offset"])
        template_name = setting["template_name"]
        algo_type = template_name.replace("Genus", "")

        message = new_message(fix.MsgType_NewOrderSingle)

        symbol, exchange = extract_vt_symbol(vt_symbol)
        genus_exchange = EXCHANGE_VT2GNS[exchange]
        genus_symbol = f"{symbol}.{genus_exchange}"

        side = DIRECTION_VT2GNS[direction]
        genus_type = ORDERTYPE_VT2GNS[order_type]

        self.parent_orderid += 1
        parent_orderid = f"{template_name}_{self.parent_orderid}"
        message.setField(fix.ClOrdID(parent_orderid))

        message.setField(fix.HandlInst("2"))
        message.setField(fix.Currency("CNY"))

        message.setField(fix.ExDestination(genus_exchange))
        message.setField(fix.Symbol(genus_symbol))
        message.setField(fix.Side(side))
        message.setField(fix.OrdType(genus_type))
        message.setField(fix.OrderQty(volume))
        message.setField(526, parent_orderid)
        message.setField(fix.Text("vnpy"))

        if order_type == OrderType.LIMIT:
            message.setField(fix.Price(price))

        seconds = setting["time"]
        dt = datetime.now() + timedelta(seconds=seconds)
        local_dt = CHINA_TZ.localize(dt)
        utc_dt = local_dt.astimezone(pytz.utc)
        utc_end = utc_dt.strftime("%Y%m%d-%H:%M:%S")

        parameters = f"EndTime;{utc_end}"

        message.setField(847, algo_type)
        message.setField(848, parameters)

        fix.Session.sendToTarget(message, self.session_id)

        self.algo_settings[parent_orderid] = {
            "symbol": genus_symbol,
            "side": side,
            "algo_type": algo_type
        }

        self.client.set_parent_offset(parent_orderid, offset)
        self.client.put_parameters_event(parent_orderid, setting)

        return parent_orderid