Пример #1
0
def _constructContractAndOrder(aat_order):
    contract = _constructContract(aat_order.instrument)
    order = Order()
    order.action = aat_order.side.value

    if aat_order.order_type == OrderType.MARKET:
        order.orderType = "MKT"
        order.totalQuantity = aat_order.volume

    elif aat_order.order_type == OrderType.LIMIT:
        order.orderType = "LMT"
        order.totalQuantity = aat_order.volume
        order.lmtPrice = aat_order.price

    elif aat_order.order_type == OrderType.STOP:
        if aat_order.stop_target.order_type == OrderType.MARKET:
            order.orderType = "STP"
            order.auxPrice = aat_order.price
            order.totalQuantity = aat_order.stop_target.volume

        elif aat_order.stop_target.order_type == OrderType.LIMIT:
            order.orderType = "STP LMT"
            order.totalQuantity = aat_order.stop_target.volume
            order.lmtPrice = aat_order.stop_target.price
            order.auxPrice = aat_order.price

        else:
            raise NotImplementedError()

    else:
        raise NotImplementedError()

    return contract, order
Пример #2
0
 def MarketIfTouched(action: str, quantity: float, price: float):
     order = Order()
     order.action = action
     order.orderType = "MIT"
     order.totalQuantity = quantity
     order.auxPrice = price
     return order
Пример #3
0
def order_stop(symbol, action, qty, stp_price):
    order = Order()
    order.action = action
    order.orderType = "STP"
    order.totalQuantity = qty

    return order
Пример #4
0
def create_order(qty, order_type):
    order = Order()
    order.orderId = get_next_order_id()
    order.totalQuantity = qty
    order.action = "BUY" if order_type == OrderType.BUY else "SELL"
    order.transmit = True
    return order
Пример #5
0
 def MarketOnOpen(action: str, quantity: float):
     order = Order()
     order.action = action
     order.orderType = "MKT"
     order.totalQuantity = quantity
     order.tif = "OPG"
     return order
Пример #6
0
 def LimitOnClose(action: str, quantity: float, limitPrice: float):
     order = Order()
     order.action = action
     order.orderType = "LOC"
     order.totalQuantity = quantity
     order.lmtPrice = limitPrice
     return order
Пример #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
Пример #8
0
 def my_send_order(self):
     """
     亲测可用
     下订单的程序,可买卖
     """
     print("开始执行下单函数my_send_order")
     self.valid_id = self.nextValidOrderId
     print('|- Place order. ID 数值是: %d' % self.valid_id)
     # 这里Order()开始下订单了,是重点
     order = Order()
     order.action = self.sec_instance.active  # BUY 或者 SELL
     order.account = ACCOUNT
     order.orderType = self.sec_instance.order_type  # MKT市场价格  LMT限价
     if order.orderType == "LMT":
         order.lmtPrice = self.last_price  # 自己试一试加价买
         order.totalQuantity = self.buy_vol
     else:
         order.totalQuantity = 1  # 不知道怎么拿到市场价格,只好写死
     self.placeOrder(self.valid_id, self.sec_instance.contract, order)
     print(f"订单执行完毕了,你能在客户端软件上看到订单了")
     if order.orderType == "LMT":
         self.sql = f"INSERT INTO stock_orders(order_id, symbol, price, active,remark,dt) " \
             f"VALUES({self.valid_id},'{self.sec_instance.symbol}',{order.lmtPrice},"\
             f"'{self.sec_instance.active}','LMT','{datetime.datetime.today()}')"
     else:
         self.sql = f"INSERT INTO stock_orders(order_id, symbol, price, active,remark,dt) " \
                    f"VALUES({self.valid_id},'{self.sec_instance.symbol}',null," \
                    f"'{self.sec_instance.active}','MkT','{datetime.datetime.today()}')"
     pg.execute_sql_not_return(self.sql)
Пример #9
0
    def placeSampleOrder(self):
        oid = self.next_valid_id()

        contract = Contract()
        contract.symbol = "MSFT"
        contract.secType = "STK"
        contract.currency = "USD"
        contract.exchange = "SMART"
        contract.primaryExchange = "ISLAND"

        order = Order()
        order.action = "BUY"
        order.orderType = "MKT"
        order.totalQuantity = 5

        queue = self.wrapper.init_order_status()
        self.placeOrder(oid, contract, order)
        MAX_WAIT_SECONDS = 10
        try:
            queue.get(timeout=MAX_WAIT_SECONDS)
        except queue.Empty:
            print("Exceeded maximum wait for wrapper to respond")

        if self.wrapper.is_error():
            print("An error occurred")
        pass
Пример #10
0
    def orderStock(self, type, shares, symbol):
        oid = self.next_valid_id()

        contract = Contract()
        contract.symbol = symbol
        contract.secType = "STK"
        contract.currency = "USD"
        contract.exchange = "ARCA"
        contract.primaryExchange = "ARCA"

        order = Order()
        order.action = type
        order.orderType = "MKT"
        order.totalQuantity = shares

        queue = self.wrapper.init_order_status()
        self.placeOrder(oid, contract, order)
        MAX_WAIT_SECONDS = 10
        try:
            queue.get(timeout=MAX_WAIT_SECONDS)
        except queue.Empty:
            print("Exceeded maximum wait for wrapper to respond")

        if self.wrapper.is_error():
            print("An error occurred")
        pass
Пример #11
0
def default_order():
    order = Order()
    order.action = "BUY"
    order.orderType = "LMT"
    order.totalQuantity = 100
    order.lmtPrice = 100
    return order
Пример #12
0
    def put_order_with_condition(self, order_id: int):
        order1 = Order()
        order1.orderId = order_id
        order1.action = "buy"
        order1.orderType = "LMT"
        order1.totalQuantity = 1
        order1.lmtPrice = 160
        current_time = datetime.today()
        cancel_time = current_time + timedelta(minutes=3)
        cancel_time_str = cancel_time.strftime("%Y%m%d %H:%M:%S")

        order1.conditions.append(self.time_condition(False, cancel_time_str))
        order1.conditions.append(
            self.price_condition(
                order_condition.PriceCondition.TriggerMethodEnum.Last, 265598,
                "SMART", 150, False, True))
        contract_aapl = self.contract_aapl()

        # order2 = Order()
        # order2.orderId = order_id
        # order2.action = "buy"
        # order2.orderType = "MKT"
        # order2.totalQuantity = 1
        # order2.conditions.append(self.time_condition(False, "20190226 12:18:00"))
        # contract_es = self.contract_es()

        self.placeOrder(order_id, contract_aapl, order1)
Пример #13
0
    def put_oca_order(self, order_id: int):
        contract_opt = self.contract_spx()
        parent = Order()
        parent.orderId = order_id
        parent.action = "buy"
        parent.orderType = "LMT"
        parent.totalQuantity = 1
        parent.lmtPrice = 32.5
        parent.transmit = False

        self.placeOrder(order_id, contract_opt, parent)

        pp33_bracket = PP33BracketOrderBuilder(parent, contract_opt.symbol)

        order_id += 1
        self.take_profit_order = pp33_bracket.take_profit_order
        self.take_profit_order.orderId = order_id

        order_id += 1
        self.stop_loss_order = pp33_bracket.stop_loss_order
        self.stop_loss_order.orderId = order_id

        order_id += 1
        self.quit_before_close_order = pp33_bracket.quit_before_close_order
        self.quit_before_close_order.orderId = order_id

        self.placeOrder(self.take_profit_order.orderId, contract_opt,
                        self.take_profit_order)
        self.placeOrder(self.stop_loss_order.orderId, contract_opt,
                        self.stop_loss_order)
        self.placeOrder(self.quit_before_close_order.orderId, contract_opt,
                        self.quit_before_close_order)
Пример #14
0
    def basic_order(self, order_id: int):
        contract_aapl = self.contract_aapl()

        parent = Order()
        parent.orderId = order_id
        parent.action = "buy"
        parent.orderType = "LMT"
        parent.totalQuantity = 1
        parent.lmtPrice = 8
        parent.transmit = False

        option_contract = Contract()
        option_contract.symbol = 'TSLA'
        option_contract.secType = "OPT"
        option_contract.exchange = "SMART"
        option_contract.primaryExchange = "SMART"
        option_contract.currency = "USD"
        option_contract.strike = 310.0
        option_contract.lastTradeDateOrContractMonth = "20190315"
        option_contract.right = "P"

        pp33_order_builder = PP33BracketOrderBuilder(order_id, parent)

        for order_in_bracket in pp33_order_builder.bracket_order_list():
            self.placeOrder(order_in_bracket.orderId, option_contract,
                            order_in_bracket)
Пример #15
0
 def create_order(sAction, iTotalQuantity, sOrderType, sLmtPrice):
     order = Order()
     order.action = sAction
     order.totalQuantity = iTotalQuantity
     order.orderType = sOrderType
     order.lmtPrice = sLmtPrice
     return order
Пример #16
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
Пример #17
0
    def process_order_request(self, order):
        with self.lock:
            ibcontract = Contract()
            ibcontract.symbol = order.symbol
            ibcontract.secType = "STK"
            ibcontract.currency = "USD"
            ibcontract.exchange = "SMART"

            iborder = Order()

            iborder.action = 'BUY' if order.order_type == Type.BUY else 'SELL' if order.order_type == Type.SELL else None

            if isinstance(order, orders.MarketOrder):
                iborder.orderType = "MKT"
            elif isinstance(order, orders.LimitOrder):
                iborder.orderType = "LMT"
                order.lmtPrice = order.price
            elif isinstance(order, orders.StopMarketOrder):
                iborder.orderType = "STP"
                order.auxPrice = order.price
            elif isinstance(order, orders.StopLimitOrder):
                iborder.orderType = "STP LMT"
                order.lmtPrice = order.limit_price
                order.auxPrice = order.stop_price

            iborder.totalQuantity = order.quantity

            self._has_valid_id.wait()

            self._pending_orders[self.next_valid_order_id] = order

            self.placeOrder(self.next_valid_order_id, ibcontract, iborder)

            self.next_valid_order_id += 1
Пример #18
0
    def orderStatus(self, orderId: OrderId, status: str, filled: float,
                    remaining: float, avgFillPrice: float, permId: int,
                    parentId: int, lastFillPrice: float, clientId: int,
                    whyHeld: str, mktCapPrice: float):
        print("OrderStatus. Id: ", orderId, ", Status: ", status, ", Filled: ",
              filled)
        #print(time.time()-self.playBuyOrderTime)
        global buyCount

        if (filled == buyCount and self.hasBuy == True):

            self.reqGlobalCancel()
            self.Close()

            self.oID = self.oID + 1

            contract = Contract()
            contract.symbol = "TSLA"
            contract.secType = "STK"
            contract.currency = "USD"
            contract.exchange = "ISLAND"

            order = Order()
            order.action = "SELL"
            order.orderType = "LMT"
            order.totalQuantity = 10

            order.lmtPrice = avgFillPrice + 0.5
Пример #19
0
 def LMT_order(action, quantity, price):
     order = Order()
     order.action = action
     order.orderType = "LMT"
     order.lmtPrice = price
     order.totalQuantity = quantity
     return order
Пример #20
0
 def PeggedToMarket(action: str, quantity: float, marketOffset: float):
     order = Order()
     order.action = action
     order.orderType = "PEG MKT"
     order.totalQuantity = quantity
     order.auxPrice = marketOffset  # Offset price
     return order
Пример #21
0
 def order(action, quantity, limitPrice):
     order = Order()
     order.action = action
     order.orderType = "LMT"
     order.totalQuantity = quantity
     order.lmtPrice = limitPrice
     return order
Пример #22
0
def market_order(action, size):
    order = Order()
    order.action = action
    order.orderType = "MKT"
    order.totalQuantity = size
    app.placeOrder(app.nextValidOrderId, contract(), order)
    log(f'market order placed, {action, size}', LOG_PATH)
Пример #23
0
 def PeggedToBenchmark(action: str, quantity: float, startingPrice: float,
                       peggedChangeAmountDecrease: bool,
                       peggedChangeAmount: float,
                       referenceChangeAmount: float, referenceConId: int,
                       referenceExchange: str, stockReferencePrice: float,
                       referenceContractLowerRange: float,
                       referenceContractUpperRange: float):
     order = Order()
     order.orderType = "PEG BENCH"
     # BUY or SELL
     order.action = action
     order.totalQuantity = quantity
     # Beginning with price...
     order.startingPrice = startingPrice
     # increase/decrease price..
     order.isPeggedChangeAmountDecrease = peggedChangeAmountDecrease
     # by... (and likewise for price moving in opposite direction)
     order.peggedChangeAmount = peggedChangeAmount
     # whenever there is a price change of...
     order.referenceChangeAmount = referenceChangeAmount
     # in the reference contract...
     order.referenceContractId = referenceConId
     # being traded at...
     order.referenceExchange = referenceExchange
     # starting reference price is...
     order.stockRefPrice = stockReferencePrice
     # Keep order active as long as reference contract trades between...
     order.stockRangeLower = referenceContractLowerRange
     # and...
     order.stockRangeUpper = referenceContractUpperRange
     return order
Пример #24
0
 def StopWithProtection(action: str, quantity: float, stopPrice: float):
     order = Order()
     order.totalQuantity = quantity
     order.action = action
     order.orderType = "STP PRT"
     order.auxPrice = stopPrice
     return order
Пример #25
0
 def Stop(action: str, quantity: float, stopPrice: float):
     order = Order()
     order.action = action
     order.orderType = "STP"
     order.auxPrice = stopPrice
     order.totalQuantity = quantity
     return order
Пример #26
0
 def PassiveRelative(action: str, quantity: float, offset: float):
     order = Order()
     order.action = action
     order.orderType = "PASSV REL"
     order.totalQuantity = quantity
     order.auxPrice = offset
     return order
Пример #27
0
 def MarketOrder(action, quantity):
     # ! [market]
     order = Order()
     order.action = action
     order.orderType = "MKT"
     order.totalQuantity = quantity
     # ! [market]
     return order
Пример #28
0
def order_limit(symbol, action, qty, lim_price, dis_lim_price):
    order = Order()
    order.action = action
    order.orderType = "LMT"
    order.totalQuantity = qty
    order.lmtPrice = lim_price
    order.discretionaryAmt = dis_lim_price
    return order
Пример #29
0
    def create_order(self, order_type, quantity, action):
        order = Order()
        order.orderType = order_type
        order.totalQuantity = quantity
        order.action = action
        order.transmit = True

        return order
Пример #30
0
def MarketOrder(action: str, quantity: float):

    order = Order()
    order.action = action
    order.orderType = "MKT"
    order.totalQuantity = quantity

    return order
Пример #31
0
 def LimitOnOpen(action: str, quantity: float, limitPrice: float):
     order = Order()
     order.action = action
     order.tif = "OPG"
     order.orderType = "LMT"
     order.totalQuantity = quantity
     order.lmtPrice = limitPrice
     return order