Beispiel #1
0
def time_condition(is_more: bool, time: str, is_conjunction: bool = True):
    time_condition = order_condition.Create(
        order_condition.OrderCondition.Time)
    time_condition.isMore = is_more
    time_condition.time = time
    time_condition.isConjunctionConnection = is_conjunction
    return time_condition
Beispiel #2
0
 def TimeCondition(time: str, isMore: bool, isConjunction: bool):
     timeCondition = order_condition.Create(OrderCondition.Time)
     # Before or after...
     timeCondition.isMore = isMore
     # this time..
     timeCondition.time = time
     # AND | OR next condition (will be ignored if no more conditions are added)
     timeCondition.isConjunctionConnection = isConjunction
     return timeCondition
Beispiel #3
0
 def MarginCondition(percent: int, isMore: bool, isConjunction: bool):
     marginCondition = order_condition.Create(OrderCondition.Margin)
     # If margin is above/below
     marginCondition.isMore = isMore
     # given percent
     marginCondition.percent = percent
     # AND | OR next condition (will be ignored if no more conditions are added)
     marginCondition.isConjunctionConnection = isConjunction
     # ! [margin_condition]
     return marginCondition
Beispiel #4
0
    def change_to_ib_order(self, order: Order) -> IBOrder:
        # 市价单和限价单直接提交
        ib_order: IBOrder = IBOrder()
        if isinstance(order, MKTOrder):
            ib_order.orderType = "MKT"
            ib_order.totalQuantity = order.quantity
            ib_order.action = 'BUY' if order.direction == OrderDirection.BUY else 'SELL'
            # 设置自适应算法
            ib_order.algoStrategy = 'Adaptive'
            ib_order.algoParams = [TagValue("adaptivePriority", 'Urgent')]
        elif isinstance(order, LimitOrder):
            ib_order.orderType = "LMT"
            ib_order.totalQuantity = order.quantity
            # 价格调整到两位小数
            ib_order.lmtPrice = round(order.limit_price, 2)
            ib_order.action = 'BUY' if order.direction == OrderDirection.BUY else 'SELL'
        else:
            # 穿越单和延迟单转化为IB的条件单
            if isinstance(order, DelayMKTOrder):
                ib_order.orderType = "MKT"
                ib_order.totalQuantity = order.quantity
                ib_order.action = 'BUY' if order.direction == OrderDirection.BUY else 'SELL'
                cond = order_condition.Create(OrderCondition.Time)
                cond.isMore = True
                time = (Timestamp.now(tz='Asia/Shanghai') + order.delay_time).strftime('%Y%m%d %H:%M:%S')
                cond.time(time)
                ib_order.conditions.append(cond)

            elif isinstance(order, CrossMKTOrder):
                ib_order.orderType = "MKT"
                ib_order.totalQuantity = order.quantity
                ib_order.action = 'BUY' if order.direction == OrderDirection.BUY else 'SELL'
                price_cond = order_condition.Create(OrderCondition.Price)
                contract = self.cli.code_to_contract(order.code)
                price_cond.conId = contract.conId
                price_cond.price = round(order.cross_price, 2)
                price_cond.isMore = True if order.cross_direction == CrossDirection.UP else False
                price_cond.exchange = contract.exchange
                price_cond.triggerMethod = PriceCondition.TriggerMethodEnum.Default
                ib_order.conditions.append(price_cond)

        return ib_order
Beispiel #5
0
 def ExecutionCondition(symbol: str, secType: str, exchange: str,
                        isConjunction: bool):
     execCondition = order_condition.Create(OrderCondition.Execution)
     # When an execution on symbol
     execCondition.symbol = symbol
     # at exchange
     execCondition.exchange = exchange
     # for this secType
     execCondition.secType = secType
     # AND | OR next condition (will be ignored if no more conditions are added)
     execCondition.isConjunctionConnection = isConjunction
     return execCondition
Beispiel #6
0
    def price_condition(self, trigger_method: int, con_id: int, exchange: str,
                        price: float, is_more: bool, is_conjunction: bool):

        priceCondition = order_condition.Create(
            order_condition.OrderCondition.Price)
        priceCondition.conId = con_id
        priceCondition.exchange = exchange
        priceCondition.isMore = is_more
        priceCondition.triggerMethod = trigger_method
        priceCondition.price = price
        priceCondition.isConjunctionConnection = is_conjunction
        return priceCondition
    def decodeConditions(self, fields):
        if self.serverVersion >= MIN_SERVER_VER_PEGGED_TO_BENCHMARK:
            conditionsSize = decode(int, fields)
            if conditionsSize > 0:
                self.order.conditions = []
                for _ in range(conditionsSize):
                    conditionType = decode(int, fields)
                    condition = order_condition.Create(conditionType)
                    condition.decode(fields)
                    self.order.conditions.append(condition)

                self.order.conditionsIgnoreRth = decode(bool, fields)
                self.order.conditionsCancelOrder = decode(bool, fields)
Beispiel #8
0
    def get_ib_order(self, order: Order) -> IBOrder:
        # 市价单和限价单直接提交
        ib_order: IBOrder = IBOrder()
        if order.order_type == OrderType.MKT:
            ib_order.orderType = "MKT"
            ib_order.totalQuantity = order.quantity
            ib_order.action = 'BUY' if order.direction == OrderDirection.BUY else 'SELL'
        elif order.order_type == OrderType.LIMIT:
            ib_order.orderType = "LMT"
            ib_order.totalQuantity = order.quantity
            ib_order.lmtPrice = order.limit_price
            ib_order.action = 'BUY' if order.direction == OrderDirection.BUY else 'SELL'
        else:
            # 穿越单和延迟单转化为IB的条件单
            if order.order_type == OrderType.DELAY_MKT:
                ib_order.orderType = "MKT"
                ib_order.totalQuantity = order.quantity
                ib_order.action = 'BUY' if order.direction == OrderDirection.BUY else 'SELL'
                cond = order_condition.Create(OrderCondition.Time)
                cond.isMore = True
                time = (Timestamp.now(tz='Asia/Shanghai') + order.delay_time).strftime('%Y%m%d %H:%M:%S')
                cond.time(time)
                ib_order.conditions.append(cond)

            elif order.order_type == OrderType.CROSS_MKT:
                ib_order.orderType = "MKT"
                ib_order.totalQuantity = order.quantity
                ib_order.action = 'BUY' if order.direction == OrderDirection.BUY else 'SELL'
                price_cond = order_condition.Create(OrderCondition.Price)
                contract = self.get_contract(order.code)
                price_cond.conId = contract.conId
                price_cond.price = order.cross_price
                price_cond.isMore = True if order.cross_direction == CrossDirection.UP else False
                price_cond.exchange = contract.exchange
                price_cond.triggerMethod = PriceCondition.TriggerMethodEnum.Default
                ib_order.conditions.append(price_cond)

        return ib_order
Beispiel #9
0
 def VolumeCondition(conId: int, exchange: str, isMore: bool, volume: int,
                     isConjunction: bool):
     volCond = order_condition.Create(OrderCondition.Volume)
     # Whenever contract...
     volCond.conId = conId
     # When traded at
     volCond.exchange = exchange
     # reaches a volume higher/lower
     volCond.isMore = isMore
     # than this...
     volCond.volume = volume
     # AND | OR next condition (will be ignored if no more conditions are added)
     volCond.isConjunctionConnection = isConjunction
     return volCond
Beispiel #10
0
 def PercentageChangeCondition(pctChange: float, conId: int, exchange: str,
                               isMore: bool, isConjunction: bool):
     pctChangeCondition = order_condition.Create(
         OrderCondition.PercentChange)
     # If there is a price percent change measured against last close price above or below...
     pctChangeCondition.isMore = isMore
     # this amount...
     pctChangeCondition.changePercent = pctChange
     # on this contract
     pctChangeCondition.conId = conId
     # when traded on this exchange...
     pctChangeCondition.exchange = exchange
     # AND | OR next condition (will be ignored if no more conditions are added)
     pctChangeCondition.isConjunctionConnection = isConjunction
     # ! [percentage_condition]
     return pctChangeCondition
Beispiel #11
0
 def PriceCondition(triggerMethod: int, conId: int, exchange: str,
                    price: float, isMore: bool, isConjunction: bool):
     # Conditions have to be created via the OrderCondition.create
     priceCondition = order_condition.Create(OrderCondition.Price)
     # When this contract...
     priceCondition.conId = conId
     # traded on this exchange
     priceCondition.exchange = exchange
     # has a price above/below
     priceCondition.isMore = isMore
     priceCondition.triggerMethod = triggerMethod
     # this quantity
     priceCondition.price = price
     # AND | OR next condition (will be ignored if no more conditions are added)
     priceCondition.isConjunctionConnection = isConjunction
     return priceCondition
    def wrapper_price_update(self, set_price):
        """
        Updates the prices of the order structure
        :param set_price:
        :return:
        """
        # TODO Add time conditioned close. time in format 20181126 09:40:32 EET
        # Market orders don't work outside RTH?
        t = datetime.datetime.now() + timedelta(seconds=self.kill_time)
        time_condition = order_condition.Create(
            order_condition.OrderCondition.Time)
        time_condition.isMore = True
        time_condition.time = t.strftime("%y%m%d %H:%M:%S %Z")

        self.logger.log("Setting order structure around price " +
                        str(set_price))
        self.set_price = set_price

        self.long_entry.lmtPrice = set_price + self.entry_spread
        self.long_entry.auxPrice = set_price + self.entry_spread
        self.long_tgt.auxPrice = set_price + self.tgt_spread
        # self.long_trail.trailStopPrice = set_price - self.trail_spread
        # self.long_trail.lmtPriceOffset = self.trail_spread
        self.long_trail.auxPrice = self.trail_spread  # Trailing amount
        # self.long_time.conditionsCancelOrder = True
        self.long_time.conditions.clear()
        self.long_time.conditions.append(time_condition)

        self.short_entry.lmtPrice = set_price - self.entry_spread
        self.short_entry.auxPrice = set_price - self.entry_spread
        self.short_tgt.auxPrice = set_price - self.tgt_spread
        # self.short_trail.trailStopPrice = set_price + self.trail_spread
        # self.short_trail.lmtPriceOffset = self.trail_spread
        self.short_trail.auxPrice = self.trail_spread  # Trailing amount
        # self.short_time.conditionsCancelOrder = True
        self.short_time.conditions.clear()
        self.short_time.conditions.append(time_condition)
Beispiel #13
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)
    resolved_ibcontract = app.resolve_ib_contract(ibcontract)
    print(resolved_ibcontract)

    conContract = IBcontract()
    conContract.symbol = "SPY"
    conContract.secType = "STK"
    #conContract.exchange = "SMART"
    conContract.exchange = "BATS"

    resolved_conContract = app.resolve_ib_contract(conContract)

    print(resolved_conContract)
    print(resolved_conContract.conId)

    #Conditions have to be created via the OrderCondition.create
    priceCondition = order_condition.Create(OrderCondition.Price)
    priceCondition.conId = resolved_conContract.conId
    #has a price above/below
    priceCondition.isMore = True
    priceCondition.triggerMethod = PriceCondition.TriggerMethodEnum.Last
    priceCondition.price = 150

    order = Order()
    order.action = "BUY"
    order.orderType = "LMT"
    order.totalQuantity = 1
    order.lmtPrice = 17
    order.conditionsCancelOrder = True
    #order.conditions.append(priceCondition)
    order.conditions.append(priceCondition)
    #order.conditions = priceCondition