Esempio n. 1
0
    def on_order(self, d):
        """"""
        if "ordStatus" not in d:
            return

        sysid = d["orderID"]
        order = self.orders.get(sysid, None)
        if not order:
            if d["clOrdID"]:
                orderid = d["clOrdID"]
            else:
                orderid = sysid

            # time = d["timestamp"][11:19]

            order = OrderData(
                symbol=d["symbol"],
                exchange=Exchange.BITMEX,
                type=ORDERTYPE_BITMEX2VT[d["ordType"]],
                orderid=orderid,
                direction=DIRECTION_BITMEX2VT[d["side"]],
                price=d["price"],
                volume=d["orderQty"],
                time=d["timestamp"][11:19],
                gateway_name=self.gateway_name,
            )
            self.orders[sysid] = order

        order.traded = d.get("cumQty", order.traded)
        order.status = STATUS_BITMEX2VT.get(d["ordStatus"], order.status)

        self.gateway.on_order(copy(order))
Esempio n. 2
0
    def on_order(self, d):
        """"""
        order = OrderData(
            symbol=d["instrument_id"],
            exchange=Exchange.OKEX,
            type=ORDERTYPE_OKEX2VT[d["type"]],
            orderid=d["client_oid"],
            direction=DIRECTION_OKEX2VT[d["side"]],
            price=float(d["price"]),
            volume=float(d["size"]),
            traded=float(d["filled_size"]),
            time=d["timestamp"][11:19],
            status=STATUS_OKEX2VT[d["status"]],
            gateway_name=self.gateway_name,
        )
        self.gateway.on_order(copy(order))

        trade_volume = d.get("last_fill_qty", 0)
        if not trade_volume or float(trade_volume) == 0:
            return

        self.trade_count += 1
        tradeid = f"{self.connect_time}{self.trade_count}"

        trade = TradeData(symbol=order.symbol,
                          exchange=order.exchange,
                          orderid=order.orderid,
                          tradeid=tradeid,
                          direction=order.direction,
                          price=float(d["last_fill_px"]),
                          volume=float(trade_volume),
                          time=d["last_fill_time"][11:19],
                          gateway_name=self.gateway_name)
        self.gateway.on_trade(trade)
Esempio n. 3
0
    def on_query_history_order(self, data, request):
        """"""
        if self.check_error(data, "查询历史委托"):
            return

        for d in data["data"]["orders"]:
            timestamp = d["create_date"]
            dt = datetime.fromtimestamp(timestamp / 1000)
            time = dt.strftime("%H:%M:%S")

            orderid = d["order_id"]

            order = OrderData(
                orderid=orderid,
                symbol=d["contract_code"],
                exchange=Exchange.HUOBI,
                price=d["price"],
                volume=d["volume"],
                type=ORDERTYPE_HBDM2VT[d["order_price_type"]],
                direction=DIRECTION_HBDM2VT[d["direction"]],
                offset=OFFSET_HBDM2VT[d["offset"]],
                traded=d["trade_volume"],
                status=STATUS_HBDM2VT[d["status"]],
                time=time,
                gateway_name=self.gateway_name,
            )
            self.gateway.on_order(order)

        self.gateway.write_log(f"{request.extra}历史委托信息查询成功")
    def on_order_error(self, d):
        """"""
        if d[-2] != "ERROR":
            return

        data = d[4]
        error_info = d[-1]

        # Filter cancel of non-existing order
        orderid = str(data[2])
        if orderid == "None":
            self.gateway.write_log("撤单失败,委托不存在")
            return

        if data[6] > 0:
            direction = Direction.LONG
        else:
            direction = Direction.SHORT

        order = OrderData(
            symbol=str(data[3].replace("t", "")),
            exchange=Exchange.BITFINEX,
            orderid=orderid,
            status=Status.REJECTED,
            direction=direction,
            price=float(data[16]),
            volume=abs(data[6]),
            time=self.generate_date_time(d[0]),
            gateway_name=self.gateway_name,
        )

        self.gateway.on_order(copy(order))

        self.gateway.write_log(f"委托拒单:{error_info}")
Esempio n. 5
0
 def onRtnOrder(self, data: dict):
     """
     Callback of order status update.
     """
     symbol = data["InstrumentID"]
     exchange = symbol_exchange_map.get(symbol, "")
     if not exchange:
         self.order_data.append(data)
         return
     
     frontid = data["FrontID"]
     sessionid = data["SessionID"]
     order_ref = data["OrderRef"]
     orderid = f"{frontid}_{sessionid}_{order_ref}"
     
     order = OrderData(
         symbol=symbol,
         exchange=exchange,
         orderid=orderid,
         type=ORDERTYPE_CTP2VT[data["OrderPriceType"]],
         direction=DIRECTION_CTP2VT[data["Direction"]],
         offset=OFFSET_CTP2VT[data["CombOffsetFlag"]],
         price=data["LimitPrice"],
         volume=data["VolumeTotalOriginal"],
         traded=data["VolumeTraded"],
         status=STATUS_CTP2VT[data["OrderStatus"]],
         time=data["InsertTime"],
         gateway_name=self.gateway_name
     )
     self.gateway.on_order(order)
     
     self.sysid_orderid_map[data["OrderSysID"]] = orderid
    def on_order(self, data):
        """"""
        orderid = str(data[2])

        if data[7] > 0:
            direction = Direction.LONG
        else:
            direction = Direction.SHORT

        order_status = str(data[13].split("@")[0]).replace(" ", "")
        if order_status == "CANCELED":
            order_time = self.generate_date_time(data[5])
        else:
            order_time = self.generate_date_time(data[4])

        order = OrderData(
            symbol=str(data[3].replace("t", "")),
            exchange=Exchange.BITFINEX,
            orderid=orderid,
            status=STATUS_BITFINEX2VT[order_status],
            direction=direction,
            price=float(data[16]),
            volume=abs(data[7]),
            traded=abs(data[7]) - abs(data[6]),
            time=order_time,
            gateway_name=self.gateway_name,
        )

        self.gateway.on_order(copy(order))
Esempio n. 7
0
    def onRtnOrder(self, data: dict):
        """
        Callback of order status update.
        """
        # 更新最大报单编号
        self.localid = max(self.localid, int(
            data["UserOrderLocalID"]))  # 检查并增加本地报单编号

        symbol = data["InstrumentID"]
        exchange = symbol_exchange_map.get(symbol, "")
        if not exchange:
            self.order_data.append(data)
            return

        orderid = data["UserOrderLocalID"]
        order = OrderData(
            symbol=symbol,
            exchange=exchange,
            orderid=orderid,
            direction=DIRECTION_FEMAS2VT[data["Direction"]],
            offset=OFFSET_FEMAS2VT[data["OffsetFlag"]],
            price=data["LimitPrice"],
            volume=data["Volume"],
            traded=data["VolumeTraded"],
            status=STATUS_FEMAS2VT[data["OrderStatus"]],
            time=data["InsertTime"],
            gateway_name=self.gateway_name,
        )
        self.gateway.on_order(order)

        self.sysid_orderid_map[data["OrderSysID"]] = orderid
Esempio n. 8
0
    def openOrder(  # pylint: disable=invalid-name
        self,
        orderId: OrderId,
        ib_contract: Contract,
        ib_order: Order,
        orderState: OrderState,
    ):
        """
        Callback when opening new order.
        """
        super(IbApi, self).openOrder(orderId, ib_contract, ib_order,
                                     orderState)

        orderid = str(orderId)
        order = OrderData(
            symbol=ib_contract.conId,
            exchange=EXCHANGE_IB2VT.get(ib_contract.exchange,
                                        ib_contract.exchange),
            type=ORDERTYPE_IB2VT[ib_order.orderType],
            orderid=orderid,
            direction=DIRECTION_IB2VT[ib_order.action],
            price=ib_order.lmtPrice,
            volume=ib_order.totalQuantity,
            gateway_name=self.gateway_name,
        )

        self.orders[orderid] = order
        self.gateway.on_order(copy(order))
Esempio n. 9
0
    def on_query_order(self, data, request):
        """"""
        if self.check_error(data, "查询委托"):
            return

        for d in data["data"]:
            sys_orderid = d["id"]
            local_orderid = self.order_manager.get_local_orderid(sys_orderid)

            direction, order_type = ORDERTYPE_HUOBI2VT[d["type"]]
            dt = datetime.fromtimestamp(d["created-at"] / 1000)
            time = dt.strftime("%H:%M:%S")

            order = OrderData(
                orderid=local_orderid,
                symbol=d["symbol"],
                exchange=Exchange.HUOBI,
                price=float(d["price"]),
                volume=float(d["amount"]),
                type=order_type,
                direction=direction,
                traded=float(d["filled-amount"]),
                status=STATUS_HUOBI2VT.get(d["state"], None),
                time=time,
                gateway_name=self.gateway_name,
            )

            self.order_manager.on_order(order)

        self.gateway.write_log("委托信息查询成功")
Esempio n. 10
0
    def on_order(self, order: OrderData):
        """"""
        msg = f"委托号:{order.vt_orderid},委托状态:{order.status.value}"
        self.write_log(msg)

        if not order.is_active():
            self.vt_orderid = ""
            self.put_variables_event()
Esempio n. 11
0
    def update_order(self, order: OrderData):
        """"""
        if order.is_active():
            self.active_orders[order.vt_orderid] = order
        else:
            if order.vt_orderid in self.active_orders:
                self.active_orders.pop(order.vt_orderid)

        self.calculate_frozen()
Esempio n. 12
0
    def update_order(self, order: OrderData):
        """"""
        if self.active:
            if order.is_active():
                self.active_orders[order.vt_orderid] = order
            elif order.vt_orderid in self.active_orders:
                self.active_orders.pop(order.vt_orderid)

            self.on_order(order)
Esempio n. 13
0
    def on_order(self, data: dict):
        """"""
        dt = datetime.fromtimestamp(data["created_at"] / 1000)
        time = dt.strftime("%H:%M:%S")

        if data["client_order_id"]:
            orderid = data["client_order_id"]
        else:
            orderid = data["order_id"]

        order = OrderData(symbol=data["contract_code"],
                          exchange=Exchange.HUOBI,
                          orderid=orderid,
                          type=ORDERTYPE_HBDM2VT[data["order_price_type"]],
                          direction=DIRECTION_HBDM2VT[data["direction"]],
                          offset=OFFSET_HBDM2VT[data["offset"]],
                          price=data["price"],
                          volume=data["volume"],
                          traded=data["trade_volume"],
                          status=STATUS_HBDM2VT[data["status"]],
                          time=time,
                          gateway_name=self.gateway_name)
        self.gateway.on_order(order)

        # Push trade event
        trades = data["trade"]
        if not trades:
            return

        for d in trades:
            dt = datetime.fromtimestamp(d["created_at"] / 1000)
            time = dt.strftime("%H:%M:%S")

            trade = TradeData(
                symbol=order.symbol,
                exchange=Exchange.HUOBI,
                orderid=order.orderid,
                tradeid=str(d["trade_id"]),
                direction=order.direction,
                offset=order.offset,
                price=d["trade_price"],
                volume=d["trade_volume"],
                time=time,
                gateway_name=self.gateway_name,
            )
            self.gateway.on_trade(trade)
Esempio n. 14
0
    def OnOrderEvent(self, order_info: XTPOrderInfo,
                     error_info: XTPRspInfoStruct, session_id: int) -> Any:
        """"""
        self.check_error("委托下单", error_info)

        order = OrderData(symbol=order_info.ticker,
                          exchange=MARKET_XTP2VT[order_info.market],
                          orderid=str(order_info.order_xtp_id),
                          type=ORDERTYPE_XTP2VT[order_info.price_type],
                          direction=DIRECTION_XTP2VT[order_info.side],
                          price=order_info.price,
                          volume=order_info.quantity,
                          traded=order_info.qty_traded,
                          status=STATUS_XTP2VT[order_info.order_status],
                          time=order_info.insert_time,
                          gateway_name=self.gateway_name)

        self.gateway.on_order(order)
Esempio n. 15
0
    def on_query_order(self, data, request):
        """"""
        for order_data in data:
            order = OrderData(
                symbol=order_data["instrument_id"],
                exchange=Exchange.OKEX,
                type=ORDERTYPE_OKEX2VT[order_data["type"]],
                orderid=order_data["client_oid"],
                direction=DIRECTION_OKEX2VT[order_data["side"]],
                price=float(order_data["price"]),
                volume=float(order_data["size"]),
                traded=float(order_data["filled_size"]),
                time=order_data["timestamp"][11:19],
                status=STATUS_OKEX2VT[order_data["status"]],
                gateway_name=self.gateway_name,
            )
            self.gateway.on_order(order)

        self.gateway.write_log("委托信息查询成功")
Esempio n. 16
0
 def on_query_order(self, data, request):
     """"""
     for order_data in data["order_info"]:
         offset, direction = TYPE_OKEXF2VT[order_data["type"]]
         order = OrderData(
             symbol=order_data["instrument_id"],
             exchange=Exchange.OKEX,
             type=ORDERTYPE_OKEXF2VT[order_data["order_type"]],
             orderid=order_data["client_oid"],
             direction=direction,
             offset=offset,
             traded=int(order_data["filled_qty"]),
             price=float(order_data["price"]),
             volume=float(order_data["size"]),
             time=utc_to_local(
                 order_data["timestamp"]).strftime("%H:%M:%S"),
             status=STATUS_OKEXF2VT[order_data["status"]],
             gateway_name=self.gateway_name,
         )
         self.gateway.on_order(order)
Esempio n. 17
0
    def onRspOrderInsert(self, data: dict, error: dict, reqid: int, last: bool):
        """"""
        if self.gateway.if_error_write_error("交易委托失败", error):
            return

        orderid = data["UserOrderLocalID"]
        symbol = data["InstrumentID"]
        exchange = symbol_exchange_map[symbol]
        order = OrderData(
            symbol=symbol,
            exchange=exchange,
            orderid=orderid,
            direction=DIRECTION_FEMAS2VT[data["Direction"]],
            offset=OFFSET_FEMAS2VT[data["OffsetFlag"]],
            price=data["LimitPrice"],
            volume=data["Volume"],
            status=Status.REJECTED,
            gateway_name=self.gateway_name,
        )
        self.gateway.on_order(order)
Esempio n. 18
0
    def send_limit_order(self, direction: Direction, offset: Offset,
                         price: float, volume: float):
        """"""
        self.limit_order_count += 1

        order = OrderData(
            symbol=self.symbol,
            exchange=self.exchange,
            orderid=str(self.limit_order_count),
            direction=direction,
            offset=offset,
            price=price,
            volume=volume,
            status=Status.NOTTRADED,
            gateway_name=self.gateway_name,
        )

        self.active_limit_orders[order.vt_orderid] = order
        self.limit_orders[order.vt_orderid] = order

        return order.vt_orderid
Esempio n. 19
0
 def onRspOrderInsert(self, data: dict, error: dict, reqid: int, last: bool):
     """"""
     order_ref = data["OrderRef"]
     orderid = f"{self.frontid}_{self.sessionid}_{order_ref}"
     
     symbol = data["InstrumentID"]
     exchange = symbol_exchange_map[symbol]
     
     order = OrderData(
         symbol=symbol,
         exchange=exchange,
         orderid=orderid,
         direction=DIRECTION_CTP2VT[data["Direction"]],
         offset=OFFSET_CTP2VT[data["CombOffsetFlag"]],
         price=data["LimitPrice"],
         volume=data["VolumeTotalOriginal"],
         status=Status.REJECTED,
         gateway_name=self.gateway_name
     )
     self.gateway.on_order(order)
     
     self.gateway.write_error("交易委托失败", error)
Esempio n. 20
0
    def on_order(self, d):
        """"""
        offset, direction = TYPE_OKEXF2VT[d["type"]]
        order = OrderData(
            symbol=d["instrument_id"],
            exchange=Exchange.OKEX,
            type=ORDERTYPE_OKEXF2VT[d["order_type"]],
            orderid=d["client_oid"],
            offset=offset,
            direction=direction,
            price=float(d["price"]),
            volume=float(d["size"]),
            traded=float(d["filled_qty"]),
            time=utc_to_local(d["timestamp"]).strftime("%H:%M:%S"),
            status=STATUS_OKEXF2VT[d["status"]],
            gateway_name=self.gateway_name,
        )
        self.gateway.on_order(copy(order))

        trade_volume = d.get("last_fill_qty", 0)
        if not trade_volume or float(trade_volume) == 0:
            return

        self.trade_count += 1
        tradeid = f"{self.connect_time}{self.trade_count}"

        trade = TradeData(
            symbol=order.symbol,
            exchange=order.exchange,
            orderid=order.orderid,
            tradeid=tradeid,
            direction=order.direction,
            offset=order.offset,
            price=float(d["last_fill_px"]),
            volume=float(trade_volume),
            time=order.time,
            gateway_name=self.gateway_name,
        )
        self.gateway.on_trade(trade)
Esempio n. 21
0
    def process_order(self, data):
        """
        Process order data for both query and update.
        """
        for ix, row in data.iterrows():
            # Ignore order with status DELETED
            if row["order_status"] == OrderStatus.DELETED:
                continue

            symbol, exchange = convert_symbol_futu2vt(row["code"])
            order = OrderData(
                symbol=symbol,
                exchange=exchange,
                orderid=str(row["order_id"]),
                direction=DIRECTION_FUTU2VT[row["trd_side"]],
                price=float(row["price"]),
                volume=row["qty"],
                traded=row["dealt_qty"],
                status=STATUS_FUTU2VT[row["order_status"]],
                time=row["create_time"].split(" ")[-1],
                gateway_name=self.gateway_name,
            )

            self.on_order(order)
Esempio n. 22
0
    def cross_stop_order(self):
        """
        Cross stop order with last bar/tick data.
        """
        if self.mode == BacktestingMode.BAR:
            long_cross_price = self.bar.high_price
            short_cross_price = self.bar.low_price
            long_best_price = self.bar.open_price
            short_best_price = self.bar.open_price
        else:
            long_cross_price = self.tick.last_price
            short_cross_price = self.tick.last_price
            long_best_price = long_cross_price
            short_best_price = short_cross_price

        for stop_order in list(self.active_stop_orders.values()):
            # Check whether stop order can be triggered.
            long_cross = (stop_order.direction == Direction.LONG
                          and stop_order.price <= long_cross_price)

            short_cross = (stop_order.direction == Direction.SHORT
                           and stop_order.price >= short_cross_price)

            if not long_cross and not short_cross:
                continue

            # Create order data.
            self.limit_order_count += 1

            order = OrderData(
                symbol=self.symbol,
                exchange=self.exchange,
                orderid=str(self.limit_order_count),
                direction=stop_order.direction,
                offset=stop_order.offset,
                price=stop_order.price,
                volume=stop_order.volume,
                status=Status.ALLTRADED,
                gateway_name=self.gateway_name,
            )

            self.limit_orders[order.vt_orderid] = order

            # Create trade data.
            if long_cross:
                trade_price = max(stop_order.price, long_best_price)
                pos_change = order.volume
            else:
                trade_price = min(stop_order.price, short_best_price)
                pos_change = -order.volume

            self.trade_count += 1

            trade = TradeData(
                symbol=order.symbol,
                exchange=order.exchange,
                orderid=order.orderid,
                tradeid=str(self.trade_count),
                direction=order.direction,
                offset=order.offset,
                price=trade_price,
                volume=order.volume,
                time=self.datetime.strftime("%H:%M:%S"),
                gateway_name=self.gateway_name,
            )
            trade.datetime = self.datetime

            self.trades[trade.vt_tradeid] = trade

            # Update stop order.
            stop_order.vt_orderid = order.vt_orderid
            stop_order.status = StopOrderStatus.TRIGGERED

            self.active_stop_orders.pop(stop_order.stop_orderid)

            # Push update to strategy.
            self.strategy.on_stop_order(stop_order)
            self.strategy.on_order(order)

            self.strategy.pos += pos_change
            self.strategy.on_trade(trade)
Esempio n. 23
0
    def processQueueOrder(self, data, historyFlag):
        for d in data['data']:
            # self.gateway.localID += 1
            # localID = str(self.gateway.localID)

            order = OrderData()
            order.gateway_name = self.gateway_name

            order.symbol = d['symbol']
            order.exchange = 'IDCM'
            order.vtSymbol = '.'.join([order.exchange, order.symbol])

            order.orderID = d['orderid']
            # order.vtOrderID = '.'.join([self.gateway_name, localID])
            order.vtOrderID = '.'.join([self.gateway_name, order.orderID])

            #order.price = float(d['price'])  # 委托价格
            order.price = float(d['price'])  # 委托价格
            order.avgprice = float(d['avgprice'])  # 平均成交价
            order.volume = float(d['amount']) + float(
                d['executedamount'])  # 委托数量
            order.tradedVolume = float(d['executedamount'])  # 成交数量
            order.status = orderStatusMapReverse[d['status']]  # 订单状态
            order.direction = directionMapReverse[
                d['side']]  # 交易方向   0 买入 1 卖出
            order.orderType = orderTypeMapReverse[
                d['type']]  # 订单类型  0	市场价  1	 限价

            dt = datetime.fromtimestamp(d['timestamp'])
            order.orderTime = dt.strftime('%Y-%m-%d %H:%M:%S')

            if order.status == STATUS_ALLTRADED:
                # order.vtTradeID =  '.'.join([self.gateway_name, order.orderID])
                if historyFlag:
                    self.onTrade(order)
                else:
                    self.onOrder(order)  # 普通推送更新委托列表
            else:
                self.onOrder(order)
Esempio n. 24
0
 def on_order(self, order: OrderData):
     """"""
     if not order.is_active():
         self.vt_orderid = ""
         self.put_variables_event()