Exemplo n.º 1
0
    def connect(
            self,
            key: str,
            secret: str,
            session_number: int,
            proxy_host: str,
            proxy_port: int,
    ):
        """
        Initialize connection to REST server.
        """
        self.key = key
        self.secret = secret
        self.connect_time = int(datetime.now().strftime("%y%m%d%H%M%S"))

        self.init(REST_HOST_TRADE, proxy_host, proxy_port)
        self.start(session_number)
        self.gateway.write_log("ZB 交易 REST API 启动成功")

        self.query_account()
        # 指定要查询的交易对
        self.query_order(symbol="usdt_qc")

        # 测试接口
        req = OrderRequest(symbol="usdt_qc", exchange=Exchange.ZB, direction=Direction.LONG, type=OrderType.LIMIT,
                           volume=0.01)
        # 价格
        req.price = 6.9
        req.offset = Offset.NONE
        self.send_order(req)
Exemplo n.º 2
0
    def send_order(self, req: OrderRequest):
        """"""
        req.offset = Offset.NONE
        order_id = self._new_order_id()

        symbol = req.symbol
        vol = int(req.volume)
        direction = req.direction
        data = {
            "instrument": symbol,
            # positive for long , negative for short
            "units": vol if direction is Direction.LONG else -vol,
            "clientExtensions": {
                "id": order_id,
            }
        }

        order = req.create_order_data(order_id, self.gateway_name)
        order.time = parse_time(datetime.now().isoformat())

        # Only add price for limit order.
        data["type"] = ORDER_TYPE_VT2OANDA[req.type]
        data["price"] = str(req.price)
        self.gateway.orders[order.orderid] = order
        self.add_request(
            "POST",
            f"/v3/accounts/{self.gateway.account_id}/orders",
            callback=self.on_send_order,
            data={'order': data},
            extra=order,
            on_failed=self.on_send_order_failed,
            on_error=self.on_send_order_error,
        )
        self.gateway.on_order(order)
        return order.vt_orderid
Exemplo n.º 3
0
    def send_order(self, req: OrderRequest) -> str:
        """"""
        cmd = ORDERTYPE_VT2MT.get((req.direction, req.type), None)

        if req.type == OrderType.FOK or req.type == OrderType.FAK or req.type == OrderType.RFQ:
            self.write_log(f"不支持的委托类型:{req.type.value}")
            return ""

        local_id = self.new_orderid()

        mt5_req = {
            "type": FUNCTION_SENDORDER,
            "symbol": req.symbol.replace('-', '.'),
            "cmd": cmd,
            "price": req.price,
            "volume": req.volume,
            "comment": local_id,
        }

        packet = self.client.send_request(mt5_req)
        result = packet["data"]["result"]
        comment = packet["data"]["comment"]

        order = req.create_order_data(local_id, self.gateway_name)
        if result:
            order.status = Status.SUBMITTING
        else:
            order.status = Status.REJECTED
            self.write_log(f"委托{local_id}拒单,原因{comment}")

        self.on_order(order)
        self.orders[local_id] = order

        return order.vt_orderid
Exemplo n.º 4
0
    def send_order(self, req: OrderRequest):
        """"""
        huobi_type = ORDERTYPE_VT2HUOBI.get((req.direction, req.type), "")

        local_orderid = self.order_manager.new_local_orderid()
        order = req.create_order_data(local_orderid, self.gateway_name)
        order.time = datetime.now().strftime("%H:%M:%S")

        data = {
            "account-id": self.account_id,
            "amount": str(req.volume),
            "symbol": req.symbol,
            "type": huobi_type,
            "price": str(req.price),
            "source": "api"
        }

        self.add_request(method="POST",
                         path="/v1/order/orders/place",
                         callback=self.on_send_order,
                         data=data,
                         extra=order,
                         on_error=self.on_send_order_error,
                         on_failed=self.on_send_order_failed)

        self.order_manager.on_order(order)
        return order.vt_orderid
Exemplo n.º 5
0
    def send_order(self, req: OrderRequest):
        """"""
        local_orderid = self.order_manager.new_local_orderid()
        order = req.create_order_data(
            local_orderid,
            self.gateway_name
        )
        order.datetime = datetime.now(UTC_TZ)

        data = {
            "amount": req.volume,
            "price": req.price
        }

        if req.direction == Direction.LONG:
            if req.type == OrderType.LIMIT:
                path = f"/buy/{req.symbol}/"
            elif req.type == OrderType.MARKET:
                path = f"/buy/market/{req.symbol}/"
        else:
            if req.type == OrderType.LIMIT:
                path = f"/sell/{req.symbol}/"
            elif req.type == OrderType.MARKET:
                path = f"/sell/market/{req.symbol}/"

        self.add_request(
            method="POST",
            path=path,
            data=data,
            callback=self.on_send_order,
            extra=order,
        )
        self.order_manager.on_order(order)
        return order.vt_orderid
Exemplo n.º 6
0
Arquivo: oes_td.py Projeto: Alyle/vnpy
    def send_order(self, vt_req: OrderRequest):
        """"""
        seq_id = self._get_new_seq_index()
        order_id = seq_id

        oes_req = OesOrdReqT()
        oes_req.clSeqNo = seq_id
        oes_req.mktId = EXCHANGE_VT2OES[vt_req.exchange]
        oes_req.ordType = ORDER_TYPE_VT2OES[(vt_req.exchange, vt_req.type)]
        oes_req.bsType = BUY_SELL_TYPE_VT2OES[(vt_req.exchange, vt_req.offset, vt_req.direction)]
        oes_req.invAcctId = ""
        oes_req.securityId = vt_req.symbol
        oes_req.ordQty = int(vt_req.volume)
        oes_req.ordPrice = int(vt_req.price * 10000)
        oes_req.origClOrdId = order_id

        order = vt_req.create_order_data(str(order_id), self.gateway.gateway_name)
        order.direction = Direction.NET  # fix direction into NET: stock only
        self._order_manager.save_order(order_id, order)

        ret = OesApi_SendOrderReq(self._env.ordChannel,
                                  oes_req
                                  )

        if ret >= 0:
            order.status = Status.SUBMITTING
        else:
            order.status = Status.REJECTED
            self.gateway.write_log(_("下单失败"))  # todo: can I stringify error?
            if is_disconnected(ret):
                self.gateway.write_log(_("下单时连接发现连接已断开,正在尝试重连"))
                self._schedule_reconnect_ord_channel()
        self.gateway.on_order(order)

        return order.vt_orderid
Exemplo n.º 7
0
    def send_order(self, req: OrderRequest):
        """
        Send a new order.
        """
        if not self.status:
            return ""

        if req.exchange not in EXCHANGE_VT2IB:
            self.gateway.write_log(f"不支持的交易所:{req.exchange}")
            return ""

        if req.type not in ORDERTYPE_VT2IB:
            self.gateway.write_log(f"不支持的价格类型:{req.type}")
            return ""

        self.orderid += 1

        ib_contract = Contract()
        ib_contract.conId = str(req.symbol)
        ib_contract.exchange = EXCHANGE_VT2IB[req.exchange]

        ib_order = Order()
        ib_order.orderId = self.orderid
        ib_order.clientId = self.clientid
        ib_order.action = DIRECTION_VT2IB[req.direction]
        ib_order.orderType = ORDERTYPE_VT2IB[req.type]
        ib_order.lmtPrice = req.price
        ib_order.totalQuantity = req.volume

        self.client.placeOrder(self.orderid, ib_contract, ib_order)
        self.client.reqIds(1)

        order = req.create_order_data(str(self.orderid), self.gateway_name)
        self.gateway.on_order(order)
        return order.vt_orderid
Exemplo n.º 8
0
    def send_order(self, req: OrderRequest):
        """"""
        orderid = "NKD8FYX4-" + str(self.connect_time + self._new_order_id())
        order = req.create_order_data(orderid, self.gateway_name)
        self.gateway.on_order(order)

        data = {"security": Security.SIGNED}

        params = {
            "symbol": req.symbol.upper(),
            "timeInForce": "GTC",
            "side": DIRECTION_VT2BINANCE[req.direction],
            "type": ORDERTYPE_VT2BINANCE[req.type],
            "price": str(req.price),
            "quantity": str(req.volume),
            "newClientOrderId": orderid,
            "newOrderRespType": "ACK"
        }

        self.add_request(method="POST",
                         path="/api/v3/order",
                         callback=self.on_send_order,
                         data=data,
                         params=params,
                         extra=order,
                         on_error=self.on_send_order_error,
                         on_failed=self.on_send_order_failed)

        return order.vt_orderid
Exemplo n.º 9
0
    def send_order(self, req: OrderRequest):
        """"""
        self.order_count += 1
        orderid = str(self.connect_time + self.order_count)

        data = {
            "symbol": req.symbol,
            "side": DIRECTION_VT2BITMEX[req.direction],
            "ordType": PRICETYPE_VT2BITMEX[req.price_type],
            "price": req.price,
            "orderQty": int(req.volume),
            "clOrdID": orderid,
        }

        # Only add price for limit order.
        if req.price_type == PriceType.LIMIT:
            data["price"] = req.price

        order = req.create_order_data(orderid, self.gateway_name)

        self.add_request(
            "POST",
            "/order",
            callback=self.on_send_order,
            data=data,
            extra=order,
            on_failed=self.on_send_order_failed,
            on_error=self.on_send_order_error,
        )

        self.gateway.on_order(order)
        return order.vt_orderid
Exemplo n.º 10
0
    def send_order(self, req: OrderRequest) -> str:
        """"""
        orderid = "328hhn6c-" + str(self.connect_time + self._new_order_id())
        order = req.create_order_data(orderid, self.gateway_name)
        self.gateway.on_order(order)

        data = {"security": Security.SIGNED}

        params = {
            "symbol": req.symbol,
            "timeInForce": "GTC",
            "side": DIRECTION_VT2BINANCES[req.direction],
            "type": ORDERTYPE_VT2BINANCES[req.type],
            "price": float(req.price),
            "quantity": float(req.volume),
            "newClientOrderId": orderid,
        }
        if req.offset == Offset.CLOSE:
            params["reduceOnly"] = True

        self.add_request(method="POST",
                         path="/fapi/v1/order",
                         callback=self.on_send_order,
                         data=data,
                         params=params,
                         extra=order,
                         on_error=self.on_send_order_error,
                         on_failed=self.on_send_order_failed)

        return order.vt_orderid
    def send_order(self, req: OrderRequest) -> str:
        """"""
        orderid = self.new_orderid()
        order = req.create_order_data(orderid, self.gateway_name)

        data = {
            "symbol": req.symbol,
            "side": DIRECTION_VT2BYBIT[req.direction],
            "qty": int(req.volume),
            "order_link_id": orderid,
            "time_in_force": "GoodTillCancel",
            "reduce_only": False,
            "close_on_trigger": False
        }

        data["order_type"] = ORDER_TYPE_VT2BYBIT[req.type]
        data["price"] = req.price

        if self.usdt_base:
            path = "/private/linear/order/create"
        else:
            path = "/v2/private/order/create"

        self.add_request(
            "POST",
            path,
            callback=self.on_send_order,
            data=data,
            extra=order,
            on_failed=self.on_send_order_failed,
            on_error=self.on_send_order_error,
        )

        self.gateway.on_order(order)
        return order.vt_orderid
Exemplo n.º 12
0
    def send_order(self, req: OrderRequest):
        """"""
        self.order_count += 1
        orderid = str(self.connect_time + self.order_count)

        data = {
            "symbol": req.symbol,
            "side": DIRECTION_VT2BITMEX[req.direction],
            "ordType": PRICETYPE_VT2BITMEX[req.price_type],
            "price": req.price,
            "orderQty": int(req.volume),
            "clOrdID": orderid,
        }

        # Only add price for limit order.
        if req.price_type == PriceType.LIMIT:
            data["price"] = req.price

        order = req.create_order_data(orderid, self.gateway_name)

        self.add_request(
            "POST",
            "/order",
            callback=self.on_send_order,
            data=data,
            extra=order,
            on_failed=self.on_send_order_failed,
            on_error=self.on_send_order_error,
        )

        self.gateway.on_order(order)
        return order.vt_orderid
Exemplo n.º 13
0
    def send_order(self, req: OrderRequest):
        """"""
        side = DIRECTION_VT2FUTU[req.direction]
        price_type = OrderType.NORMAL  # Only limit order is supported.

        # Set price adjustment mode to inside adjustment.
        if req.direction is Direction.LONG:
            adjust_limit = 0.05
        else:
            adjust_limit = -0.05

        futu_symbol = convert_symbol_vt2futu(req.symbol, req.exchange)
        code, data = self.trade_ctx.place_order(
            req.price,
            req.volume,
            futu_symbol,
            side,
            price_type,
            trd_env=self.env,
            adjust_limit=adjust_limit,
        )

        if code:
            self.write_log(f"委托失败:{data}")
            return ""

        for ix, row in data.iterrows():
            orderid = str(row["order_id"])

        order = req.create_order_data(orderid, self.gateway_name)
        self.on_order(order)
        return order.vt_orderid
Exemplo n.º 14
0
    def send_order(self, req: OrderRequest):
        """"""
        orderid = f"a{self.connect_time}{self._new_order_id()}"

        data = {
            "client_oid": orderid,
            "type": ORDERTYPE_VT2OKEX[req.type],
            "side": DIRECTION_VT2OKEX[req.direction],
            "instrument_id": req.symbol
        }

        if req.type == OrderType.MARKET:
            if req.direction == Direction.LONG:
                data["notional"] = req.volume
            else:
                data["size"] = req.volume
        else:
            data["price"] = req.price
            data["size"] = req.volume

        order = req.create_order_data(orderid, self.gateway_name)

        self.add_request(
            "POST",
            "/api/spot/v3/orders",
            callback=self.on_send_order,
            data=data,
            extra=order,
            on_failed=self.on_send_order_failed,
            on_error=self.on_send_order_error,
        )

        self.gateway.on_order(order)
        return order.vt_orderid
Exemplo n.º 15
0
    def send_order(self, req: OrderRequest) -> str:
        """"""
        if self.usdt_base:
            path = "/linear-swap-api/v1/swap_cross_order"
        else:
            path = "/swap-api/v1/swap_order"

        local_orderid = self.new_local_orderid()
        order = req.create_order_data(local_orderid, self.gateway_name)
        order.datetime = datetime.now(CHINA_TZ)

        data = {
            "contract_code": req.symbol,
            "client_order_id": int(local_orderid),
            "price": req.price,
            "volume": int(req.volume),
            "direction": DIRECTION_VT2HUOBIS.get(req.direction, ""),
            "offset": OFFSET_VT2HUOBIS.get(req.offset, ""),
            "order_price_type": ORDERTYPE_VT2HUOBIS.get(req.type, ""),
            "lever_rate": 20
        }

        self.add_request(method="POST",
                         path=path,
                         callback=self.on_send_order,
                         data=data,
                         extra=order,
                         on_error=self.on_send_order_error,
                         on_failed=self.on_send_order_failed)

        self.gateway.on_order(order)
        return order.vt_orderid
Exemplo n.º 16
0
    def send_order(self, req: OrderRequest):
        """"""
        local_orderid = self.new_local_orderid()
        order = req.create_order_data(local_orderid, self.gateway_name)
        order.time = datetime.now().strftime("%H:%M:%S")

        data = {
            "contract_code": req.symbol,
            "client_order_id": int(local_orderid),
            "price": req.price,
            "volume": int(req.volume),
            "direction": DIRECTION_VT2HBDM.get(req.direction, ""),
            "offset": OFFSET_VT2HBDM.get(req.offset, ""),
            "order_price_type": ORDERTYPE_VT2HBDM.get(req.type, ""),
            "lever_rate": 20
        }

        self.add_request(method="POST",
                         path="/api/v1/contract_order",
                         callback=self.on_send_order,
                         data=data,
                         extra=order,
                         on_error=self.on_send_order_error,
                         on_failed=self.on_send_order_failed)

        self.gateway.on_order(order)
        return order.vt_orderid
Exemplo n.º 17
0
    def send_order(self, req: OrderRequest):
        """
        Send new order.
        """
        self.local_no += 1

        currency = symbol_currency_map[req.symbol]
        account_no = currency_account_map[currency]

        da_req = {
            "UserId": self.userid,
            "AccountNo": account_no,
            "LocalNo": str(self.local_no),
            "TradePwd": self.password,
            "ExchangeCode": EXCHANGE_VT2DA[req.exchange],
            "TreatyCode": req.symbol,
            "BuySale": DIRECTION_VT2DA[req.direction],
            "OrderPrice": str(req.price),
            "OrderNumber": str(int(req.volume)),
            "PriceType": ORDERTYPE_VT2DA[req.type]
        }

        self.reqid += 1
        self.reqOrderInsert(da_req, self.reqid)

        order = req.create_order_data(str(self.local_no), self.gateway_name)

        self.orders[order.orderid] = order
        self.gateway.on_order(order)

        return order.vt_orderid
Exemplo n.º 18
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)
Exemplo n.º 19
0
    def send_order(self, req: OrderRequest):
        """"""
        order_id = self.order_manager.new_local_orderid()

        symbol = req.symbol
        data = {
            "symbol": symbol,
            "side": DIRECTION_VT2BYBIT[req.direction],
            "qty": int(req.volume),
            "order_link_id": order_id,
            "time_in_force": "GoodTillCancel"
        }

        order = req.create_order_data(order_id, self.gateway_name)

        # Only add price for limit order.
        data["order_type"] = ORDER_TYPE_VT2BYBIT[req.type]
        data["price"] = req.price
        self.add_request(
            "POST",
            "/open-api/order/create",
            callback=self.on_send_order,
            data=data,
            extra=order,
            on_failed=self.on_send_order_failed,
            on_error=self.on_send_order_error,
        )

        self.order_manager.on_order(order)
        return order.vt_orderid
Exemplo n.º 20
0
    def send_order(self, req: OrderRequest):
        """"""
        side = DIRECTION_VT2FUTU[req.direction]
        futu_order_type = OrderType.NORMAL  # Only limit order is supported.

        # Set price adjustment mode to inside adjustment.
        if req.direction is Direction.LONG:
            adjust_limit = 0.05
        else:
            adjust_limit = -0.05

        futu_symbol = convert_symbol_vt2futu(req.symbol, req.exchange)
        code, data = self.trade_ctx.place_order(
            req.price,
            req.volume,
            futu_symbol,
            side,
            futu_order_type,
            trd_env=self.env,
            adjust_limit=adjust_limit,
        )

        if code:
            self.write_log(f"委托失败:{data}")
            return ""

        for ix, row in data.iterrows():
            orderid = str(row["order_id"])

        order = req.create_order_data(orderid, self.gateway_name)
        self.on_order(order)
        return order.vt_orderid
Exemplo n.º 21
0
    def send_order(self, req: OrderRequest):
        """"""
        local_orderid = self.order_manager.new_local_orderid()
        order = req.create_order_data(local_orderid, self.gateway_name)
        order.datetime = datetime.now(UTC_TZ)

        if req.direction == Direction.SHORT:
            volume = -int(req.volume)
        else:
            volume = int(req.volume)

        request_body = {
            "contract": req.symbol,
            "size": volume,
            "price": str(req.price),
            "close": False,
            "tif": "gtc",
            "text": f"t-{local_orderid}"
        }

        data = json.dumps(request_body)

        self.add_request(method="POST",
                         path="/api/v4/futures/orders",
                         callback=self.on_send_order,
                         data=data,
                         extra=order,
                         on_error=self.on_send_order_error,
                         on_failed=self.on_send_order_failed)

        self.order_manager.on_order(order)
        return order.vt_orderid
Exemplo n.º 22
0
    def send_order(self, req: OrderRequest):
        """
        Send a new order.
        """
        if not self.status:
            return ""

        if req.exchange not in EXCHANGE_VT2IB:
            self.gateway.write_log(f"不支持的交易所:{req.exchange}")
            return ""

        if req.type not in ORDERTYPE_VT2IB:
            self.gateway.write_log(f"不支持的价格类型:{req.type}")
            return ""

        self.orderid += 1

        ib_contract = Contract()
        ib_contract.conId = str(req.symbol)
        ib_contract.exchange = EXCHANGE_VT2IB[req.exchange]

        ib_order = Order()
        ib_order.orderId = self.orderid
        ib_order.clientId = self.clientid
        ib_order.action = DIRECTION_VT2IB[req.direction]
        ib_order.orderType = ORDERTYPE_VT2IB[req.type]
        ib_order.lmtPrice = req.price
        ib_order.totalQuantity = req.volume

        self.client.placeOrder(self.orderid, ib_contract, ib_order)
        self.client.reqIds(1)

        order = req.create_order_data(str(self.orderid), self.gateway_name)
        self.gateway.on_order(order)
        return order.vt_orderid
Exemplo n.º 23
0
    def send_order(self, req: OrderRequest):
        """"""
        local_orderid = str(self.connect_time + self._new_order_id())

        data = {
            "symbol": req.symbol,
            "qty": str(req.volume),
            "side": DIRECTION_VT2ALPACA[req.direction],
            "type": ORDERTYPE_VT2ALPACA[req.type],
            "time_in_force": "day",
            "client_order_id": local_orderid
        }

        if data["type"] == "limit":
            data["limit_price"] = str(req.price)

        order = req.create_order_data(local_orderid, self.gateway_name)
        self.gateway.on_order(order)

        self.add_request(
            "POST",
            "/v2/orders",
            callback=self.on_send_order,
            data=data,
            extra=order,
            on_failed=self.on_send_order_failed,
            on_error=self.on_send_order_error,
        )

        return order.vt_orderid
Exemplo n.º 24
0
    def send_order(self, req: OrderRequest) -> str:
        """"""
        local_orderid = self.order_manager.new_local_orderid()
        order = req.create_order_data(local_orderid, self.gateway_name)
        order.datetime = datetime.now(CHINA_TZ)

        data = {
            "channelType": "I",
            "exchangeCode": EXCHANGE_VT2KAISA[req.exchange],
            "accountCode": self.user_id,
            "productCode": req.symbol,
            "price": req.price,
            "qty": int(req.volume),
            "bsFlag": DIRECTION_VT2KAISA[req.direction],
            "orderType": ORDERTYPE_VT2KAISA[req.type],
        }

        self.add_request(method="POST",
                         path="/v1/order/orders/place",
                         callback=self.on_send_order,
                         data=data,
                         extra=order,
                         on_error=self.on_send_order_error,
                         on_failed=self.on_send_order_failed)

        self.order_manager.on_order(order)
        return order.vt_orderid
Exemplo n.º 25
0
    def send_order(self, req: OrderRequest):
        """"""
        # Need both offset and direction for sending order.
        if (req.offset, req.direction) not in TYPE_VT2OKEXS:
            return ""

        orderid = f"a{self.connect_time}{self._new_order_id()}"

        data = {
            "client_oid": orderid,
            "type": TYPE_VT2OKEXS[(req.offset, req.direction)],
            "instrument_id": req.symbol,
            "price": str(req.price),
            "size": str(int(req.volume)),
        }

        if req.type == OrderType.MARKET:
            data["match_price"] = "1"
        else:
            data["match_price"] = "0"

        order = req.create_order_data(orderid, self.gateway_name)

        self.add_request(
            "POST",
            "/api/swap/v3/order",
            callback=self.on_send_order,
            data=data,
            extra=order,
            on_failed=self.on_send_order_failed,
            on_error=self.on_send_order_error,
        )

        self.gateway.on_order(order)
        return order.vt_orderid
Exemplo n.º 26
0
    def send_order(self, req: OrderRequest):
        """"""
        orderid = str(self.connect_time + self._new_order_id())

        data = {
            "contract": self.exchange + "/" + req.symbol,
            "price": float(req.price),
            "bs": DIRECTION_VT2ONETOKEN[req.direction],
            "amount": float(req.volume),
            "client_oid": orderid
        }

        if req.offset == Offset.CLOSE:
            data["options"] = {"close": True}
        data = json.dumps(data)
        order = req.create_order_data(orderid, self.gateway_name)

        self.add_request(method="POST",
                         path="/v1/trade/{}/{}/orders".format(
                             self.exchange, self.account),
                         callback=self.on_send_order,
                         data=data,
                         params={},
                         extra=order,
                         on_failed=self.on_send_order_failed,
                         on_error=self.on_send_order_error)

        self.gateway.on_order(order)
        return order.vt_orderid
Exemplo n.º 27
0
    def send_order(self, req: OrderRequest):
        """"""
        orderid = str(uuid.uuid1())
        order = req.create_order_data(orderid, self.gateway_name)
        self.gateway.on_order(order)

        data = {
            "size": req.volume,
            "product_id": req.symbol,
            "side": DIRECTION_VT2COINBASE[req.direction],
            "type": ORDERTYPE_VT2COINBASE[req.type],
            "client_oid": orderid,
        }

        if req.type == OrderType.LIMIT:
            data["price"] = req.price

        self.add_request(
            "POST",
            "/orders",
            callback=self.on_send_order,
            data=json.dumps(data),
            params={},
            extra=order,
            on_failed=self.on_send_order_failed,
            on_error=self.on_send_order_error,
        )

        return order.vt_orderid
Exemplo n.º 28
0
    def send_order(self, req: OrderRequest) -> str:
        """
        Send new order.
        """
        if req.offset not in OFFSET_VT2KSGOLD:
            self.gateway.write_log("请选择开平方向")
            return ""

        self.order_ref += 1

        ksgold_req = {
            "SeatID": self.seat_no,
            "ClientID": self.userid,
            "TradeCode": self.trade_code,
            "InstID": req.symbol,
            "BuyOrSell": DIRECTION_VT2KSGOLD.get(req.direction, ""),
            "OffsetFlag": OFFSET_VT2KSGOLD.get(req.offset, ""),
            "Amount": int(req.volume),
            "Price": req.price,
            "MarketID": symbol_market_map[req.symbol],
            "OrderRef": str(self.order_ref),
            "SessionID": self.sessionid,
        }

        self.reqid += 1
        self.reqOrderInsert(ksgold_req, self.reqid)

        orderid = f"{self.frontid}_{self.sessionid}_{self.order_ref}"
        order = req.create_order_data(orderid, self.gateway_name)
        self.gateway.on_order(order)

        return order.vt_orderid
Exemplo n.º 29
0
    def send_order(self, req: OrderRequest):
        orderid = self._gen_unqiue_cid()

        if req.direction == Direction.LONG:
            amount = req.volume
        else:
            amount = -req.volume

        order_type = ORDERTYPE_VT2BITFINEX[req.type]
        if self.margin:
            order_type = order_type.replace("EXCHANGE ", "")

        o = {
            "cid": orderid,
            "type": order_type,
            "symbol": "t" + req.symbol,
            "amount": str(amount),
            "price": str(req.price),
        }

        request = [0, "on", None, o]

        order = req.create_order_data(orderid, self.gateway_name)
        self.send_packet(request)

        self.gateway.on_order(order)
        return order.vt_orderid
Exemplo n.º 30
0
    def send_order(self, req: OrderRequest):
        """"""
        self.reqid += 1
        order_ref = self._get_new_order_id()

        opt, tc, vc = ORDER_TYPE_VT2TORA[req.type]

        info = CTORATstpSPInputOrderField()
        info.ShareholderID = self.shareholder_ids[req.exchange]
        info.SecurityID = req.symbol
        info.ExchangeID = EXCHANGE_VT2TORA[req.exchange]
        info.OrderRef = order_ref
        info.OrderPriceType = opt
        info.Direction = DIRECTION_VT2TORA[req.direction]
        info.CombOffsetFlag = OFFSET_VT2TORA[req.offset]
        info.CombHedgeFlag = TORA_TSTP_SP_HF_Speculation
        info.LimitPrice = req.price
        info.VolumeTotalOriginal = int(req.volume)
        info.TimeCondition = tc
        info.VolumeCondition = vc

        order_id = f"{self.frontid}_{self.sessionid}_{order_ref}"

        self.orders[order_id] = OrderInfo(
            order_ref,
            EXCHANGE_VT2TORA[req.exchange],
            self.sessionid,
            self.frontid,
        )
        self.gateway.on_order(
            req.create_order_data(order_id, self.gateway.gateway_name)
        )
        self.api.ReqOrderInsert(info, self.reqid)

        return f"{self.gateway_name}.{order_id}"
Exemplo n.º 31
0
    def send_order(
        self,
        vt_symbol: str,
        price: float,
        volume: float,
        direction: Direction,
        offset: Offset,
        order_type: OrderType
    ) -> str:
        """"""
        contract = self.get_contract(vt_symbol)
        if not contract:
            return ""

        req = OrderRequest(
            symbol=contract.symbol,
            exchange=contract.exchange,
            direction=direction,
            type=order_type,
            volume=volume,
            price=price,
            offset=offset
        )

        vt_orderid = self.main_engine.send_order(req, contract.gateway_name)
        return vt_orderid
Exemplo n.º 32
0
    def send_order(self, vt_req: OrderRequest):
        """"""
        seq_id = self._get_new_seq_index()
        order_id = seq_id

        oes_req = OesOrdReqT()
        oes_req.clSeqNo = seq_id
        oes_req.mktId = EXCHANGE_VT2OES[vt_req.exchange]
        oes_req.ordType = ORDER_TYPE_VT2OES[(vt_req.exchange, vt_req.type)]
        oes_req.bsType = BUY_SELL_TYPE_VT2OES[(vt_req.exchange, vt_req.offset, vt_req.direction)]
        oes_req.invAcctId = ""
        oes_req.securityId = vt_req.symbol
        oes_req.ordQty = int(vt_req.volume)
        oes_req.ordPrice = int(vt_req.price * 10000)
        oes_req.origClOrdId = order_id

        order = vt_req.create_order_data(str(order_id), self.gateway.gateway_name)
        order.direction = Direction.NET  # fix direction into NET: stock only
        self._order_manager.save_order(order_id, order)

        ret = OesApi_SendOrderReq(self._env.ordChannel,
                                  oes_req
                                  )

        if ret >= 0:
            order.status = Status.SUBMITTING
        else:
            order.status = Status.REJECTED
            self.gateway.write_log(_("下单失败"))  # todo: can I stringify error?
            if is_disconnected(ret):
                self.gateway.write_log(_("下单时连接发现连接已断开,正在尝试重连"))
                self._schedule_reconnect_ord_channel()
        self.gateway.on_order(order)

        return order.vt_orderid
Exemplo n.º 33
0
    def send_order(self, req: OrderRequest) -> str:
        """"""
        huobi_type = ORDERTYPE_VT2HUOBI.get((req.direction, req.type), "")

        orderid = self.new_orderid()
        order = req.create_order_data(orderid, self.gateway_name)
        order.datetime = datetime.now(CHINA_TZ)

        data = {
            "account-id": self.account_id,
            "amount": str(req.volume),
            "symbol": req.symbol,
            "type": huobi_type,
            "price": str(req.price),
            "source": "api",
            "client-order-id": orderid
        }

        self.add_request(method="POST",
                         path="/v1/order/orders/place",
                         callback=self.on_send_order,
                         data=data,
                         extra=order,
                         on_error=self.on_send_order_error,
                         on_failed=self.on_send_order_failed)

        self.gateway.on_order(order)
        return order.vt_orderid
Exemplo n.º 34
0
    def send_order(self, req: OrderRequest):
        """
        Send new order to TAP server.
        """
        contract_info = contract_infos.get((req.symbol, req.exchange), None)
        if not contract_info:
            self.write_log(f"找不到匹配的合约:{req.symbol}和{req.exchange.value}")
            return ""

        if req.type not in ORDERTYPE_VT2TAP:
            self.write_log(f"不支持的委托类型: {req.type.value}")
            return ""

        order_req = TapAPINewOrder()
        order_req.ExchangeNo = contract_info.exchange_no
        order_req.CommodityNo = contract_info.commodity_no
        order_req.CommodityType = contract_info.commodity_type
        order_req.ContractNo = contract_info.contract_no
        order_req.OrderType = ORDERTYPE_VT2TAP[req.type]
        order_req.OrderSide = DIRECTION_VT2TAP[req.direction]
        order_req.OrderPrice = req.price
        order_req.OrderQty = int(req.volume)
        order_req.AccountNo = self.account_no

        retv, session_id, order_id = self.api.InsertOrder(order_req)

        order = req.create_order_data(order_id, self.gateway_name)
        self.gateway.on_order(order)

        return order.vt_orderid
Exemplo n.º 35
0
    def send_order(self, req: OrderRequest):
        """"""
        local_id = self.get_new_local_id()
        order = req.create_order_data(local_id, self.gateway_name)

        self.on_order(order)
        self.add_task(self._send_order, req, local_id)
        return order.vt_orderid
Exemplo n.º 36
0
 def send_order(self, req: OrderRequest):
     """
     Send new order.
     """
     self.order_ref += 1
     
     ctp_req = {
         "InstrumentID": req.symbol,
         "LimitPrice": req.price,
         "VolumeTotalOriginal": int(req.volume),
         "OrderPriceType": ORDERTYPE_VT2CTP.get(req.type, ""),
         "Direction": DIRECTION_VT2CTP.get(req.direction, ""),
         "CombOffsetFlag": OFFSET_VT2CTP.get(req.offset, ""),
         "OrderRef": str(self.order_ref),
         "InvestorID": self.userid,
         "UserID": self.userid,
         "BrokerID": self.brokerid,
         "CombHedgeFlag": THOST_FTDC_HF_Speculation,
         "ContingentCondition": THOST_FTDC_CC_Immediately,
         "ForceCloseReason": THOST_FTDC_FCC_NotForceClose,
         "IsAutoSuspend": 0,
         "TimeCondition": THOST_FTDC_TC_GFD,
         "VolumeCondition": THOST_FTDC_VC_AV,
         "MinVolume": 1
     }
     
     if req.type == OrderType.FAK:
         ctp_req["OrderPriceType"] = THOST_FTDC_OPT_LimitPrice
         ctp_req["TimeCondition"] = THOST_FTDC_TC_IOC
         ctp_req["VolumeCondition"] = THOST_FTDC_VC_AV
     elif req.type == OrderType.FOK:
         ctp_req["OrderPriceType"] = THOST_FTDC_OPT_LimitPrice
         ctp_req["TimeCondition"] = THOST_FTDC_TC_IOC
         ctp_req["VolumeCondition"] = THOST_FTDC_VC_CV            
     
     self.reqid += 1
     self.reqOrderInsert(ctp_req, self.reqid)
     
     orderid = f"{self.frontid}_{self.sessionid}_{self.order_ref}"
     order = req.create_order_data(orderid, self.gateway_name)
     self.gateway.on_order(order)
     
     return order.vt_orderid
Exemplo n.º 37
0
    def update_order_request(self, req: OrderRequest, vt_orderid: str):
        """"""
        gateway_name, orderid = vt_orderid.split(".")

        order = req.create_order_data(orderid, gateway_name)
        self.update_order(order)