Пример #1
0
 def send_buy_order(self, sec_instance, price):
     buy_vol = self.determine_buy_volume(price)
     cost = buy_vol * price + buy_vol * IB_TRADE_COST  # m57
     if self.buying_power < cost:
         print(
             f"Total spent limit reached, can't buy {sec_instance.contract.symbol} at {price}."
         )
         return False
     elif self.account_buying_power_usd < cost:
         print(
             f"Account's buying power is insufficient for buying {sec_instance.contract.symbol} at {price}."
         )
         return False
     else:
         self.buying_power -= cost
         sec_instance.buy_vol = buy_vol
         order = Order()
         order.action = "BUY"
         order.totalQuantity = buy_vol  # take the floor
         order.account = ACCOUNT
         order.orderType = "LMT"
         order.lmtPrice = price
         self.placeOrder(self.nextValidOrderId, sec_instance, order)
         self.buying_orders[sec_instance.order_id] = datetime.datetime.now()
         print(
             f"ID: {sec_instance.order_id} -- Buying {sec_instance.contract.symbol} at {order.lmtPrice}"
             f" for {order.totalQuantity}. Buying power available: {self.buying_power}"
         )
         return True
Пример #2
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)
Пример #3
0
 def execute_stploss(self, sec_instance):
     order = Order()
     order.action = "SELL"
     order.totalQuantity = sec_instance.rem_vol  # current holding volume
     order.orderType = "MKT"
     order.account = ACCOUNT
     self.placeOrder(self.nextValidOrderId, sec_instance, order)
     print(
         f"ID: {sec_instance.order_id} -- Stopping loss {sec_instance.contract.symbol} for"
         f" {order.totalQuantity}")
Пример #4
0
 def send_sell_order(self, sec_instance, price):
     order = Order()
     order.action = "SELL"
     order.totalQuantity = sec_instance.rem_vol  # current holding volume
     order.account = ACCOUNT
     order.orderType = "LMT"
     order.lmtPrice = price
     self.placeOrder(self.nextValidOrderId, sec_instance, order)
     print(
         f"ID: {sec_instance.order_id} -- Selling {sec_instance.contract.symbol} at {order.lmtPrice}"
         f" for {order.totalQuantity}")
Пример #5
0
 def create_order(self, action, quantity, type, price=0):
     order = Order()
     order.orderType = type
     if type != 'MKT':
         order.lmtPrice = price
         order.tif = 'GTC'
     order.action = action
     order.totalQuantity = quantity
     order.account = self.account
     print('Parent Order Quantity ' + str(quantity))
     return order
Пример #6
0
    def create_order(self, action, quantity):
        """ Creates an IB order."""

        order = Order()
        order.action = action
        order.totalQuantity = quantity
        order.account = self.account
        order.orderType = 'MKT'
        self.increment_id()
        order.orderId = self.reqID

        return order
Пример #7
0
 def to_order(self) -> Order:
     order = Order()
     order.account = self.acct
     order.orderType = "MIDPRICE"
     qty = abs(self.num_shares)
     order.totalQuantity = Policy.ORDER_QTY.validate(qty)
     order.action = "BUY" if self.num_shares > 0 else "SELL"
     order.lmtPrice = self.limit_price
     order.tif = "GTD"
     order.goodTillDate = self.gtd.strftime(TWS_GTD_FORMAT)
     order.transmit = self.transmit
     return order
Пример #8
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 ""

        ib_contract = generate_ib_contract(req.symbol, req.exchange)
        if not ib_contract:
            return ""

        ib_order = Order()
        ib_order.clientId = self.clientid
        ib_order.action = DIRECTION_VT2IB[req.direction]
        ib_order.orderType = ORDERTYPE_VT2IB[req.type]
        ib_order.totalQuantity = req.volume
        ib_order.outsideRth = True
        ib_order.orderRef = req.orderRef
        ib_order.account = self.account

        if req.type == OrderType.LIMIT:
            ib_order.lmtPrice = req.price
        elif req.type == OrderType.STOP:
            ib_order.auxPrice = req.price

        self.orderLock.acquire()
        self.orderid += 1
        ib_order.orderId = self.orderid
        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.orderLock.release()

        self.gateway.on_order(order)
        return order.vt_orderid
Пример #9
0
 def modify_order(self, order_id, modify_price: float):
     """
     亲测可行
     改单子。其实就是把之前的下单动作重新一模一样做了一遍,注意订单编号也要和之前一样哦
     """
     # print("开始执行改单子")
     order = Order()
     order.action = self.sec_instance.active
     order.totalQuantity = self.sec_instance.rem_vol
     order.account = ACCOUNT  # 这个参数在params.py 文件中
     order.orderType = self.sec_instance.order_type  # 改单子一般都是用限价而不是市场价
     order.lmtPrice = modify_price  # 外部设置价格
     # contract = self.create_contract(symbol, 'STK', 'SMART', 'SMART', 'USD')
     self.placeOrder(order_id, self.sec_instance.contract, order)
     # print(f"这单子ID: {order_id}股票{self.sec_instance.symbol}价格被修改为{order.lmtPrice}"
     #       f" for {order.totalQuantity}")
     self.sql = f"INSERT INTO stock_orders(order_id, symbol, price, active,remark,dt) " \
         f"VALUES({order_id},'{self.sec_instance.symbol}',{modify_price},'{self.sec_instance.active}','修改订单','{datetime.datetime.today()}')"
     pg.execute_sql_not_return(self.sql)
Пример #10
0
    def make_order(self, direction, orderType, price, volume):
        """New order."""
        self.reqid += 1
        ib_order = Order()
        ib_order.orderId = self.reqid
        ib_order.clientId = self.clientid
        ib_order.action = direction
        ib_order.orderType = orderType
        if orderType == "LMT":
            ib_order.lmtPrice = float(price)
        ib_order.totalQuantity = float(volume)
        ib_order.account = self.accountid
        self.client.placeOrder(self.reqid, self.contractid, ib_order)
        order = {
            "orderId": ib_order.orderId,
            "orderType": ib_order.orderType,
            "permId": 0,
            "action": ib_order.action,
            "totalQuantity": ib_order.totalQuantity,
            "lmtPrice": ib_order.lmtPrice,
            "auxPrice": ib_order.auxPrice,
            "tif": ib_order.tif,
            "account": ib_order.account,
            "whatIf": ib_order.whatIf,
            "autoCancelDate": ib_order.autoCancelDate,
            "symbol": self.contractid.symbol,
            "exchange": self.contractid.exchange,
            "currency": self.contractid.currency,
            "secType": self.contractid.secType,
            "status": "PendingNew",
            "commission": 0,
            "time": self.maintainer.timer.timestamp(),
            "completedStatus": "",
            "filledQuantity": 0.0,
            "avgFillPrice": 0.0,
        }
        if not self.client.isConnected():
            order["status"] = "Rejected"

        self.ib_orders[str(ib_order.orderId)] = order
        self.client.reqIds(1)
        self.logger(f"make order, {ib_order.orderId}, {order['status']}")
        return self.reqid
Пример #11
0
 def placeOrder(self, contract: Contract, order: Order) -> str:
     order.account = self._account
     super().placeOrder(self.nextOrderId, contract, order)
     self.nextOrderId += 1
     return str(self.nextOrderId - 1)
Пример #12
0
    def buildOrders(self, action, price, quantity):
        """ Create Bracket Order with Entry/Profit/Loss """
        console().info("Creating a Bracket Order to {} {}".format(
            action, self.contract.localSymbol))

        if action == "BUY":
            entryPrice = price + config.ENTRY_SPREAD
            profitPrice = entryPrice + config.PROFIT_SPREAD
            lossPrice = entryPrice - self.stopPrice
            bracketAction = "SELL"
        else:
            entryPrice = price - config.ENTRY_SPREAD
            profitPrice = entryPrice - config.PROFIT_SPREAD
            lossPrice = entryPrice + self.stopPrice
            bracketAction = "BUY"

        #Entry Order for High/Low Crossover
        entryOrder = Order()
        entryOrder.orderId = self.account.getOrderId()
        entryOrder.account = self.account.account
        entryOrder.action = action
        entryOrder.orderType = "STP"
        entryOrder.auxPrice = entryPrice
        entryOrder.lmtPrice = 0

        if config.ENABLE_MANAGED:
            entryOrder.faProfile = config.ALLOCATION_PROFILE

        entryOrder.totalQuantity = quantity
        entryOrder.transmit = False

        #Profit Limit
        profitOrder = Order()
        profitOrder.orderId = self.account.getOrderId()
        profitOrder.action = bracketAction
        profitOrder.orderType = "LMT"
        profitOrder.totalQuantity = config.NUM_CONTRACTS
        profitOrder.lmtPrice = profitPrice
        profitOrder.auxPrice = 0
        profitOrder.parentId = entryOrder.orderId

        if config.ENABLE_MANAGED:
            profitOrder.faProfile = config.ALLOCATION_PROFILE

        profitOrder.totalQuantity = quantity
        profitOrder.transmit = False

        #Loss Limit
        lossOrder = Order()
        lossOrder.orderId = self.account.getOrderId()
        lossOrder.action = bracketAction
        lossOrder.orderType = "STP"
        lossOrder.totalQuantity = config.NUM_CONTRACTS
        lossOrder.auxPrice = lossPrice
        lossOrder.lmtPrice = 0
        lossOrder.parentId = entryOrder.orderId

        if config.ENABLE_MANAGED:
            lossOrder.faProfile = config.ALLOCATION_PROFILE

        lossOrder.totalQuantity = quantity
        lossOrder.transmit = True

        return [entryOrder, profitOrder, lossOrder]
Пример #13
0
def submit_trade(conf, connection, main_order_id, symbol_type, symbol, amount, stop_price, action, profit_take,
                 order_purpose, order_ref, lmt_or_market):
    app = connection  # For clarity purpose we call the parameter connection as it will be used with other brokers
    ibcontract = IBContract()
    ibcontract.secType = symbol_type
    ibcontract.symbol = symbol
    ibcontract.currency = "USD"
    ibcontract.exchange = "SMART"
    # ibcontract.PrimaryExchage = "ISLAND"
    resolved_ibcontract, error_code = app.resolve_ib_contract(ibcontract, reqId=conf[Conf.GlobalRequestID])
    conf[Conf.GlobalRequestID] += 1
    print(error_code)
    order_id_main = 0
    order_id_stop = 0
    order_id_profit_take = 0
    if error_code != "OK":
        return 0, 0, app.get_error_queue()
    if order_purpose == MyOrder.Main:  # This happens when we submit stop orders for existing position.
        order_main = Order()
        order_main.action = action
        order_main.account = conf[Conf.AccountNumber]
        order_main.orderRef = f'{MyOrder.Main}_{order_ref}'  # main order
        order_main.orderType = "MKT"
        order_main.totalQuantity = amount
        order_main.tif = 'DAY'
        if (stop_price > 0) or (profit_take > 0):
            order_main.transmit = False  # The order will be transmitted together with its child order, the stop loss
        else:  # This order closes a position or has no stop or profit take defined.
            order_main.transmit = True
        order_id_main = app.place_new_IB_order(resolved_ibcontract, order_main, orderid=main_order_id)
    #  Submit a stop order
    if stop_price > 0:
        order_stop = Order()
        order_stop.account = conf[Conf.AccountNumber]
        if main_order_id != 0:  # Some of the stop order request come without a parent ID to protect an existing position
            order_stop.parentId = main_order_id
        order_stop.action = Dicts.invert_action[action]
        order_stop.auxPrice = stop_price
        order_stop.orderRef = f'{MyOrder.StopLoss}_{order_ref}'
        order_stop.orderType = MyOrder.Stop
        order_stop.tif = 'GTC'  # If we don't put GTC the order is cancelled the next day.
        order_stop.totalQuantity = amount
        if profit_take > 0:
            order_stop.transmit = False
        else:
            order_stop.transmit = True  # The order will be transmitted together with its child order, the stop loss
        order_id_stop = app.place_new_IB_order(resolved_ibcontract, order_stop, orderid=main_order_id + 1)
    if profit_take > 0:
        order_profit_take = Order()
        order_profit_take.account = conf[Conf.AccountNumber]
        if main_order_id != 0:  # Some of the profit take order request come without a parent ID to protect an existing position
            order_profit_take.parentId = order_id_main
        profit_take_order_id = main_order_id + 2
        order_profit_take.action = Dicts.invert_action[action]
        order_profit_take.lmtPrice = profit_take
        order_profit_take.orderRef = f'{MyOrder.ProfitTake}_{order_ref}'
        order_profit_take.orderType = MyOrder.Limit
        order_profit_take.tif = 'GTC'  # If we don't put GTC the order is cancelled the next day.
        order_profit_take.totalQuantity = amount
        order_profit_take.transmit = True  # The order will be transmitted together with its child order, the stop loss
        order_id_profit_take = app.place_new_IB_order(resolved_ibcontract, order_profit_take,
                                                      orderid=profit_take_order_id)
    status_messages = app.get_error_queue()
    return order_id_main, order_id_stop, order_id_profit_take, status_messages
Пример #14
0
    def processOpenOrder(self, fields):

        sMsgId = next(fields)
        version = decode(int, fields)

        order = Order()
        order.orderId = decode(int, fields)

        contract = Contract()

        contract.conId = decode(int, fields) # ver 17 field
        contract.symbol = decode(str, fields) 
        contract.secType = decode(str, fields) 
        contract.lastTradeDateOrContractMonth = decode(str, fields) 
        contract.strike = decode(float, fields)
        contract.right = decode(str, fields) 
        if version >= 32:
            contract.multiplier = decode(str, fields) 
        contract.exchange = decode(str, fields) 
        contract.currency = decode(str, fields) 
        contract.localSymbol = decode(str, fields)  # ver 2 field
        if version >= 32:
            contract.tradingClass = decode(str, fields) 

        # read order fields
        order.action = decode(str, fields)  

        if self.serverVersion >= MIN_SERVER_VER_FRACTIONAL_POSITIONS:
            order.totalQuantity = decode(float, fields)  
        else:
            order.totalQuantity = decode(int, fields)

        order.orderType = decode(str, fields) 
        if version < 29:
            order.lmtPrice = decode(float, fields)
        else:
            order.lmtPrice = decode(float, fields, SHOW_UNSET)
        if version < 30:
            order.auxPrice = decode(float, fields)
        else:
            order.auxPrice = decode(float, fields, SHOW_UNSET)
        order.tif = decode(str, fields)
        order.ocaGroup = decode(str, fields)
        order.account = decode(str, fields)
        order.openClose = decode(str, fields)

        order.origin = decode(int, fields)

        order.orderRef = decode(str, fields)
        order.clientId = decode(int, fields) # ver 3 field
        order.permId = decode(int, fields)   # ver 4 field

        order.outsideRth = decode(bool, fields) # ver 18 field
        order.hidden = decode(bool, fields) # ver 4 field
        order.discretionaryAmt = decode(float, fields) # ver 4 field
        order.goodAfterTime = decode(str, fields) # ver 5 field

        order.sharesAllocation = decode(str, fields) # deprecated ver 6 field

        order.faGroup = decode(str, fields) # ver 7 field
        order.faMethod = decode(str, fields) # ver 7 field
        order.faPercentage = decode(str, fields) # ver 7 field
        order.faProfile = decode(str, fields) # ver 7 field

        if self.serverVersion >= MIN_SERVER_VER_MODELS_SUPPORT:
            order.modelCode = decode(str, fields)

        order.goodTillDate = decode(str, fields) # ver 8 field

        order.rule80A = decode(str, fields) # ver 9 field
        order.percentOffset = decode(float, fields, SHOW_UNSET) # ver 9 field
        order.settlingFirm = decode(str, fields) # ver 9 field
        order.shortSaleSlot = decode(int, fields) # ver 9 field
        order.designatedLocation = decode(str, fields) # ver 9 field
        if self.serverVersion == MIN_SERVER_VER_SSHORTX_OLD:
            exemptCode = decode(int, fields)
        elif version >= 23:
            order.exemptCode = decode(int, fields)
        order.auctionStrategy = decode(int, fields) # ver 9 field
        order.startingPrice = decode(float, fields, SHOW_UNSET) # ver 9 field
        order.stockRefPrice = decode(float, fields, SHOW_UNSET) # ver 9 field
        order.delta = decode(float, fields, SHOW_UNSET) # ver 9 field
        order.stockRangeLower = decode(float, fields, SHOW_UNSET) # ver 9 field
        order.stockRangeUpper = decode(float, fields, SHOW_UNSET) # ver 9 field
        order.displaySize = decode(int, fields) # ver 9 field

        #if( version < 18) {
        #		# will never happen
        #		/* order.rthOnly = */ readBoolFromInt()
        #}

        order.blockOrder = decode(bool, fields) # ver 9 field
        order.sweepToFill = decode(bool, fields) # ver 9 field
        order.allOrNone = decode(bool, fields) # ver 9 field
        order.minQty = decode(int, fields, SHOW_UNSET) # ver 9 field
        order.ocaType = decode(int, fields) # ver 9 field
        order.eTradeOnly = decode(bool, fields) # ver 9 field
        order.firmQuoteOnly = decode(bool, fields) # ver 9 field
        order.nbboPriceCap = decode(float, fields, SHOW_UNSET) # ver 9 field

        order.parentId = decode(int, fields) # ver 10 field
        order.triggerMethod = decode(int, fields) # ver 10 field

        order.volatility = decode(float, fields, SHOW_UNSET) # ver 11 field
        order.volatilityType = decode(int, fields) # ver 11 field
        order.deltaNeutralOrderType = decode(str, fields) # ver 11 field (had a hack for ver 11)
        order.deltaNeutralAuxPrice = decode(float, fields, SHOW_UNSET) # ver 12 field

        if version >= 27 and order.deltaNeutralOrderType:
            order.deltaNeutralConId = decode(int, fields)
            order.deltaNeutralSettlingFirm = decode(str, fields)
            order.deltaNeutralClearingAccount = decode(str, fields)
            order.deltaNeutralClearingIntent = decode(str, fields)

        if version >= 31 and order.deltaNeutralOrderType:
            order.deltaNeutralOpenClose = decode(str, fields)
            order.deltaNeutralShortSale = decode(bool, fields)
            order.deltaNeutralShortSaleSlot = decode(int, fields)
            order.deltaNeutralDesignatedLocation = decode(str, fields)

        order.continuousUpdate = decode(bool, fields) # ver 11 field

        # will never happen
        #if( self.serverVersion == 26) {
        #	order.stockRangeLower = readDouble()
        #	order.stockRangeUpper = readDouble()
        #}

        order.referencePriceType = decode(int, fields) # ver 11 field

        order.trailStopPrice = decode(float, fields, SHOW_UNSET) # ver 13 field

        if version >= 30:
            order.trailingPercent = decode(float, fields, SHOW_UNSET)

        order.basisPoints = decode(float, fields, SHOW_UNSET) # ver 14 field
        order.basisPointsType = decode(int, fields, SHOW_UNSET) # ver 14 field
        contract.comboLegsDescrip = decode(str, fields) # ver 14 field

        if version >= 29:
            contract.comboLegsCount = decode(int, fields)

            if contract.comboLegsCount > 0:
                contract.comboLegs = []
                for idxLeg in range(contract.comboLegsCount):
                    comboLeg = ComboLeg()
                    comboLeg.conId = decode(int, fields)
                    comboLeg.ratio = decode(int, fields)
                    comboLeg.action = decode(str, fields)
                    comboLeg.exchange = decode(str, fields)
                    comboLeg.openClose = decode(int, fields)
                    comboLeg.shortSaleSlot = decode(int, fields)
                    comboLeg.designatedLocation = decode(str, fields)
                    comboLeg.exemptCode = decode(int, fields)
                    contract.comboLegs.append(comboLeg)

            order.orderComboLegsCount = decode(int, fields)
            if order.orderComboLegsCount > 0:
                order.orderComboLegs = []
                for idxOrdLeg in range(order.orderComboLegsCount):
                    orderComboLeg = OrderComboLeg()
                    orderComboLeg.price = decode(float, fields, SHOW_UNSET)
                    order.orderComboLegs.append(orderComboLeg)

        if version >= 26:
            order.smartComboRoutingParamsCount = decode(int, fields)
            if order.smartComboRoutingParamsCount > 0:
                order.smartComboRoutingParams = []
                for idxPrm in range(order.smartComboRoutingParamsCount):
                    tagValue = TagValue()
                    tagValue.tag = decode(str, fields)
                    tagValue.value = decode(str, fields)
                    order.smartComboRoutingParams.append(tagValue)

        if version >= 20:
            order.scaleInitLevelSize = decode(int, fields, SHOW_UNSET)
            order.scaleSubsLevelSize = decode(int, fields, SHOW_UNSET)
        else:
            # ver 15 fields
            order.notSuppScaleNumComponents = decode(int, fields, SHOW_UNSET)
            order.scaleInitLevelSize = decode(int, fields, SHOW_UNSET) # scaleComponectSize

        order.scalePriceIncrement = decode(float, fields, SHOW_UNSET) # ver 15 field

        if version >= 28 and order.scalePriceIncrement != UNSET_DOUBLE \
                and order.scalePriceIncrement > 0.0:
            order.scalePriceAdjustValue = decode(float, fields, SHOW_UNSET)
            order.scalePriceAdjustInterval = decode(int, fields, SHOW_UNSET)
            order.scaleProfitOffset = decode(float, fields, SHOW_UNSET)
            order.scaleAutoReset = decode(bool, fields)
            order.scaleInitPosition = decode(int, fields, SHOW_UNSET)
            order.scaleInitFillQty = decode(int, fields, SHOW_UNSET)
            order.scaleRandomPercent = decode(bool, fields)

        if version >= 24:
            order.hedgeType = decode(str, fields)
            if order.hedgeType:
                order.hedgeParam = decode(str, fields)

        if version >= 25:
            order.optOutSmartRouting = decode(bool, fields)

        order.clearingAccount = decode(str, fields) # ver 19 field
        order.clearingIntent = decode(str, fields) # ver 19 field

        if version >= 22:
            order.notHeld = decode(bool, fields)

        if version >= 20:
            contract.underCompPresent = decode(bool, fields)
            if contract.underCompPresent:
                contract.underComp = UnderComp()
                contract.underComp.conId = decode(int, fields)
                contract.underComp.delta = decode(float, fields)
                contract.underComp.price = decode(float, fields)

        if version >= 21:
            order.algoStrategy = decode(str, fields)
            if order.algoStrategy:
                order.algoParamsCount = decode(int, fields)
                if order.algoParamsCount > 0:
                    order.algoParams = []
                    for idxAlgoPrm in range(order.algoParamsCount):
                        tagValue = TagValue()
                        tagValue.tag = decode(str, fields)
                        tagValue.value = decode(str, fields)
                        order.algoParams.append(tagValue)

        if version >= 33:
            order.solicited = decode(bool, fields)

        orderState = OrderState()

        order.whatIf = decode(bool, fields) # ver 16 field

        orderState.status = decode(str, fields) # ver 16 field
        orderState.initMargin = decode(str, fields) # ver 16 field
        orderState.maintMargin = decode(str, fields) # ver 16 field
        orderState.equityWithLoan = decode(str, fields) # ver 16 field
        orderState.commission = decode(float, fields, SHOW_UNSET) # ver 16 field
        orderState.minCommission = decode(float, fields, SHOW_UNSET) # ver 16 field
        orderState.maxCommission = decode(float, fields, SHOW_UNSET) # ver 16 field
        orderState.commissionCurrency = decode(str, fields) # ver 16 field
        orderState.warningText = decode(str, fields) # ver 16 field

        if version >= 34:
            order.randomizeSize = decode(bool, fields)
            order.randomizePrice = decode(bool, fields)

        if self.serverVersion >= MIN_SERVER_VER_PEGGED_TO_BENCHMARK:
            if order.orderType == "PEG BENCH":
                order.referenceContractId = decode(int, fields)
                order.isPeggedChangeAmountDecrease = decode(bool, fields)
                order.peggedChangeAmount = decode(float, fields)
                order.referenceChangeAmount = decode(float, fields)
                order.referenceExchangeId = decode(str, fields)

            order.conditionsSize = decode(int, fields)
            if order.conditionsSize > 0:
                order.conditions = []
                for idxCond in range(order.conditionsSize):
                    order.conditionType = decode(int, fields)
                    condition = order_condition.Create(order.conditionType)
                    condition.decode(fields)
                    order.conditions.append(condition)

                order.conditionsIgnoreRth = decode(bool, fields)
                order.conditionsCancelOrder = decode(bool, fields)

            order.adjustedOrderType = decode(str, fields)
            order.triggerPrice = decode(float, fields)
            order.trailStopPrice = decode(float, fields)
            order.lmtPriceOffset = decode(float, fields)
            order.adjustedStopPrice = decode(float, fields)
            order.adjustedStopLimitPrice = decode(float, fields)
            order.adjustedTrailingAmount = decode(float, fields)
            order.adjustableTrailingUnit = decode(int, fields)

        if self.serverVersion >= MIN_SERVER_VER_SOFT_DOLLAR_TIER:
            name = decode(str, fields)
            value = decode(str, fields)
            displayName = decode(str, fields)
            order.softDollarTier = SoftDollarTier(name, value, displayName)

        self.wrapper.openOrder(order.orderId, contract, order, orderState)
Пример #15
0
    def buy(self,
            quantity,
            contract,
            open_position,
            take_profit_price=0,
            stop_loss_price=0,
            limit_orders_lot=0,
            is_combined=False,
            reduce_lot=False,
            order_type='MKT',
            price=0):
        total_orders = []
        parent_id = self.reqIds()
        sleep(0.7)
        print('Apo to buy to ID einai : ' + str(parent_id))
        other_id = parent_id
        order = self.create_order('BUY',
                                  quantity + abs(open_position),
                                  order_type,
                                  price=price)
        order.orderId = parent_id
        total_orders.append(order)
        if take_profit_price != 0:

            take_profit_order = Order()

            other_id += 1
            take_profit_order.orderId = other_id
            if reduce_lot:
                take_profit_order.action = 'BUY'
            else:
                take_profit_order.action = 'SELL'
            take_profit_order.lmtPrice = take_profit_price
            take_profit_order.orderType = 'LMT'
            take_profit_order.totalQuantity = limit_orders_lot
            take_profit_order.tif = 'GTC'
            take_profit_order.ocaType = 1
            take_profit_order.account = self.account
            take_profit_order.ocaGroup = contract.symbol + contract.currency + str(
                parent_id)
            total_orders.append(take_profit_order)
        if stop_loss_price != 0:

            stop_loss_order = Order()

            other_id += 1
            stop_loss_order.orderId = other_id
            if reduce_lot:
                stop_loss_order.action = 'BUY'
            else:
                stop_loss_order.action = 'SELL'
            stop_loss_order.auxPrice = stop_loss_price
            stop_loss_order.orderType = 'STP'
            stop_loss_order.totalQuantity = limit_orders_lot
            stop_loss_order.tif = 'GTC'
            stop_loss_order.ocaType = 1
            stop_loss_order.account = self.account
            stop_loss_order.ocaGroup = contract.symbol + contract.currency + str(
                parent_id)
            total_orders.append(stop_loss_order)
        orders = self.getOpenOrders()
        if is_combined == False:
            for open_order in orders:
                if contract.symbol + contract.currency in orders[open_order][
                        1].ocaGroup:
                    self.cancelOrder(open_order)
        for every_order in total_orders:
            self.placeOrder(every_order.orderId, contract, every_order)

        return self.wrapper_dict[
            EWrapper.openOrder.__name__], self.wrapper_dict[
                EWrapper.orderStatus.__name__]