def FillBalanceImpactRiskParams(baseOrder: Order, maxPctVol: float, riskAversion: str, forceCompletion: bool): baseOrder.algoStrategy = "BalanceImpactRisk" baseOrder.algoParams = [] baseOrder.algoParams.append(TagValue("maxPctVol", maxPctVol)) baseOrder.algoParams.append(TagValue("riskAversion", riskAversion)) baseOrder.algoParams.append( TagValue("forceCompletion", int(forceCompletion)))
def FillPctVolParams(baseOrder: Order, pctVol: float, startTime: str, endTime: str, noTakeLiq: bool, monetaryValue: float): baseOrder.algoStrategy = "PctVol" baseOrder.algoParams = [] baseOrder.algoParams.append(TagValue("pctVol", pctVol)) baseOrder.algoParams.append(TagValue("startTime", startTime)) baseOrder.algoParams.append(TagValue("endTime", endTime)) baseOrder.algoParams.append(TagValue("noTakeLiq", int(noTakeLiq))) baseOrder.algoParams.append(TagValue("monetaryValue", monetaryValue))
def create_adaptive_order(action, order_type, quantity): order = Order() order.action = action order.orderType = order_type order.totalQuantity = quantity order.algoStrategy = "Adaptive" order.algoParams = [] order.algoParams.append(TagValue("adaptivePriority", "Normal")) return order
def FillClosePriceParams(baseOrder: Order, maxPctVol: float, riskAversion: str, startTime: str, forceCompletion: bool, monetaryValue: float): baseOrder.algoStrategy = "ClosePx" baseOrder.algoParams = [] baseOrder.algoParams.append(TagValue("maxPctVol", maxPctVol)) baseOrder.algoParams.append(TagValue("riskAversion", riskAversion)) baseOrder.algoParams.append(TagValue("startTime", startTime)) baseOrder.algoParams.append(TagValue("forceCompletion", int(forceCompletion))) baseOrder.algoParams.append(TagValue("monetaryValue", monetaryValue))
def FillDarkIceParams(baseOrder: Order, displaySize: int, startTime: str, endTime: str, allowPastEndTime: bool, monetaryValue: float): baseOrder.algoStrategy = "DarkIce" baseOrder.algoParams = [] baseOrder.algoParams.append(TagValue("displaySize", displaySize)) baseOrder.algoParams.append(TagValue("startTime", startTime)) baseOrder.algoParams.append(TagValue("endTime", endTime)) baseOrder.algoParams.append( TagValue("allowPastEndTime", int(allowPastEndTime))) baseOrder.algoParams.append(TagValue("monetaryValue", monetaryValue))
def FillTwapParams(baseOrder: Order, strategyType: str, startTime: str, endTime: str, allowPastEndTime: bool, monetaryValue: float): baseOrder.algoStrategy = "Twap" baseOrder.algoParams = [] baseOrder.algoParams.append(TagValue("strategyType", strategyType)) baseOrder.algoParams.append(TagValue("startTime", startTime)) baseOrder.algoParams.append(TagValue("endTime", endTime)) baseOrder.algoParams.append( TagValue("allowPastEndTime", int(allowPastEndTime))) baseOrder.algoParams.append(TagValue("monetaryValue", monetaryValue))
def FillVwapParams(baseOrder: Order, maxPctVol: float, startTime: str, endTime: str, allowPastEndTime: bool, noTakeLiq: bool, monetaryValue: float): baseOrder.algoStrategy = "Vwap" baseOrder.algoParams = [] baseOrder.algoParams.append(TagValue("maxPctVol", maxPctVol)) baseOrder.algoParams.append(TagValue("startTime", startTime)) baseOrder.algoParams.append(TagValue("endTime", endTime)) baseOrder.algoParams.append( TagValue("allowPastEndTime", int(allowPastEndTime))) baseOrder.algoParams.append(TagValue("noTakeLiq", int(noTakeLiq))) baseOrder.algoParams.append(TagValue("monetaryValue", monetaryValue))
def FillQBAlgoInLineParams(baseOrder: Order, startTime: str, endTime: str, duration: float, benchmark: str, percentVolume: float, noCleanUp: bool): # must be direct-routed to "QBALGO" baseOrder.algoStrategy = "STROBE" baseOrder.algoParams = [] baseOrder.algoParams.append(TagValue("StartTime", startTime)) baseOrder.algoParams.append(TagValue("EndTime", endTime)) #This example uses endTime instead of duration #baseOrder.algoParams.append(TagValue("Duration", str(duration))) baseOrder.algoParams.append(TagValue("Benchmark", benchmark)) baseOrder.algoParams.append( TagValue("PercentVolume", str(percentVolume))) baseOrder.algoParams.append(TagValue("NoCleanUp", int(noCleanUp)))
def FillPriceVariantPctVolParams(baseOrder: Order, pctVol: float, deltaPctVol: float, minPctVol4Px: float, maxPctVol4Px: float, startTime: str, endTime: str, noTakeLiq: bool, monetaryValue: float): baseOrder.algoStrategy = "PctVolPx" baseOrder.algoParams = [] baseOrder.algoParams.append(TagValue("pctVol", pctVol)) baseOrder.algoParams.append(TagValue("deltaPctVol", deltaPctVol)) baseOrder.algoParams.append(TagValue("minPctVol4Px", minPctVol4Px)) baseOrder.algoParams.append(TagValue("maxPctVol4Px", maxPctVol4Px)) baseOrder.algoParams.append(TagValue("startTime", startTime)) baseOrder.algoParams.append(TagValue("endTime", endTime)) baseOrder.algoParams.append(TagValue("noTakeLiq", int(noTakeLiq))) baseOrder.algoParams.append(TagValue("monetaryValue", monetaryValue))
def FillArrivalPriceParams(baseOrder: Order, maxPctVol: float, riskAversion: str, startTime: str, endTime: str, forceCompletion: bool, allowPastTime: bool, monetaryValue: float): baseOrder.algoStrategy = "ArrivalPx" baseOrder.algoParams = [] baseOrder.algoParams.append(TagValue("maxPctVol", maxPctVol)) baseOrder.algoParams.append(TagValue("riskAversion", riskAversion)) baseOrder.algoParams.append(TagValue("startTime", startTime)) baseOrder.algoParams.append(TagValue("endTime", endTime)) baseOrder.algoParams.append( TagValue("forceCompletion", int(forceCompletion))) baseOrder.algoParams.append( TagValue("allowPastEndTime", int(allowPastTime))) baseOrder.algoParams.append(TagValue("monetaryValue", monetaryValue))
def FillAccumulateDistributeParams(baseOrder: Order, componentSize: int, timeBetweenOrders: int, randomizeTime20: bool, randomizeSize55: bool, giveUp: int, catchUp: bool, waitForFill: bool, startTime: str, endTime: str): baseOrder.algoStrategy = "AD" baseOrder.algoParams = [] baseOrder.algoParams.append(TagValue("componentSize", componentSize)) baseOrder.algoParams.append(TagValue("timeBetweenOrders", timeBetweenOrders)) baseOrder.algoParams.append(TagValue("randomizeTime20", int(randomizeTime20))) baseOrder.algoParams.append(TagValue("randomizeSize55", int(randomizeSize55))) baseOrder.algoParams.append(TagValue("giveUp", giveUp)) baseOrder.algoParams.append(TagValue("catchUp", int(catchUp))) baseOrder.algoParams.append(TagValue("waitForFill", int(waitForFill))) baseOrder.algoParams.append(TagValue("activeTimeStart", startTime)) baseOrder.algoParams.append(TagValue("activeTimeEnd", endTime))
def MarketOrder(action: str, quantity: float, adaptive=False, priority="Normal"): #! [market] order = Order() order.action = action order.orderType = "MKT" order.totalQuantity = quantity if adaptive: order.algoStrategy = "Adaptive" order.algoParams = [] order.algoParams.append(TagValue("adaptivePriority", priority)) #! [market] return order
def order(self, asset, amount, style): ib_symbol = self._asset_symbol(asset) contract = Contract() contract.symbol = ib_symbol contract.exchange = 'SMART' primaryExchange = 'ISLAND' contract.secType = 'STK' contract.currency = self.currency order = Order() order.totalQuantity = int(fabs(amount)) order.action = "BUY" if amount > 0 else "SELL" is_buy = (amount > 0) order.lmtPrice = style.get_limit_price(is_buy) or 0 order.auxPrice = style.get_stop_price(is_buy) or 0 if isinstance(style, MarketOrder): order.orderType = "MKT" order.tif = "DAY" order.algoStrategy = "Adaptive" order.algoParams = [] order.algoParams.append(TagValue("adaptivePriority", "Patient")) elif isinstance(style, LimitOrder): order.orderType = "LMT" order.tif = "GTC" elif isinstance(style, StopOrder): order.orderType = "STP" order.tif = "GTC" elif isinstance(style, StopLimitOrder): order.orderType = "STP LMT" order.tif = "GTC" order.orderRef = self._create_order_ref(order) ib_order_id = self._tws.next_order_id zp_order = self._get_or_create_zp_order(ib_order_id, order, contract) self.log_order(contract, ib_order_id, order) self._tws.placeOrder(ib_order_id, contract, order) return zp_order
def create_order_pct(sAction="SELL", iPercent="-100", sOrderType="MKT", iTotalQuantity=0.0, bTransmit=True, sTif='DAY', sPriority="Normal"): order = Order() order.action = sAction order.faGroup = GROUP_NAME order.faMethod = "PctChange" order.faPercentage = iPercent order.orderType = sOrderType if sOrderType == "MKT": order.algoStrategy = "Adaptive" order.algoParams = [TagValue("adaptivePriority", sPriority)] order.totalQuantity = iTotalQuantity order.tif = sTif order.transmit = bTransmit return order
def LimitOrder(action: str, quantity: float, limitPrice: float, adaptive=False, priority="Normal"): """ priority values: Urgent, Normal, Patient """ order = Order() order.action = action order.orderType = "LMT" order.totalQuantity = quantity order.lmtPrice = limitPrice if adaptive: order.algoStrategy = "Adaptive" order.algoParams = [] order.algoParams.append(TagValue("adaptivePriority", priority)) return order
def FillCSFBInlineParams(baseOrder: Order, startTime: str, endTime: str, execStyle: str, minPercent: int, maxPercent: int, displaySize: int, auction: str, blockFinder: bool, blockPrice: float, minBlockSize: int, maxBlockSize: int, iWouldPrice: float): # must be direct-routed to "CSFBALGO" baseOrder.algoStrategy = "INLINE" baseOrder.algoParams = [] baseOrder.algoParams.append(TagValue("StartTime", startTime)) baseOrder.algoParams.append(TagValue("EndTime", endTime)) baseOrder.algoParams.append(TagValue("ExecStyle", execStyle)) baseOrder.algoParams.append(TagValue("MinPercent", minPercent)) baseOrder.algoParams.append(TagValue("MaxPercent", maxPercent)) baseOrder.algoParams.append(TagValue("DisplaySize", displaySize)) baseOrder.algoParams.append(TagValue("Auction", auction)) baseOrder.algoParams.append(TagValue("BlockFinder", int(blockFinder))) baseOrder.algoParams.append(TagValue("BlockPrice", blockPrice)) baseOrder.algoParams.append(TagValue("MinBlockSize", minBlockSize)) baseOrder.algoParams.append(TagValue("MaxBlockSize", maxBlockSize)) baseOrder.algoParams.append(TagValue("IWouldPrice", iWouldPrice))
def FillJefferiesVWAPParams(baseOrder: Order, startTime: str, endTime: str, relativeLimit: float, maxVolumeRate: float, excludeAuctions: str, triggerPrice: float, wowPrice: float, minFillSize: int, wowOrderPct: float, wowMode: str, isBuyBack: bool, wowReference: str): # must be direct-routed to "JEFFALGO" baseOrder.algoStrategy = "VWAP" baseOrder.algoParams = [] baseOrder.algoParams.append(TagValue("StartTime", startTime)) baseOrder.algoParams.append(TagValue("EndTime", endTime)) baseOrder.algoParams.append(TagValue("RelativeLimit", relativeLimit)) baseOrder.algoParams.append(TagValue("MaxVolumeRate", maxVolumeRate)) baseOrder.algoParams.append(TagValue("ExcludeAuctions", excludeAuctions)) baseOrder.algoParams.append(TagValue("TriggerPrice", triggerPrice)) baseOrder.algoParams.append(TagValue("WowPrice", wowPrice)) baseOrder.algoParams.append(TagValue("MinFillSize", minFillSize)) baseOrder.algoParams.append(TagValue("WowOrderPct", wowOrderPct)) baseOrder.algoParams.append(TagValue("WowMode", wowMode)) baseOrder.algoParams.append(TagValue("IsBuyBack", int(isBuyBack))) baseOrder.algoParams.append(TagValue("WowReference", wowReference))
def placing_final_orders(action_final, order_id, ordersPriority, transmit): class TestApp(EWrapper, EClient): def __init__(self): EClient.__init__(self, self) def error(self, reqId: TickerId, errorCode: int, errorString: str): if reqId > -1: print("Error. Id: ", reqId, " Code: ", errorCode, " Msg: ", errorString) app = TestApp() app.connect('127.0.0.1', 7497, 0) for ticker in action_final.index: contract = Contract() contract.symbol = ticker contract.secType = 'STK' contract.exchange = 'SMART' #contract.primaryExchange = 'ISLAND' contract.currency = 'USD' order = Order() order.orderType = 'MKT' order.transmit = transmit order.totalQuantity = np.abs(action_final.loc[ticker])[0] if action_final.loc[ticker][0] > 0: order.action = 'BUY' order.algoStrategy = 'Adaptive' order.algoParams = [] order.algoParams.append( TagValue("adaptivePriority", ordersPriority)) app.placeOrder(orderId=order_id, contract=contract, order=order) sleep(sleeptime) order_id = order_id + 1 print('buy order quantity placed for {} is: {} '.format( contract.symbol, order.totalQuantity)) elif action_final.loc[ticker][0] < 0: order.action = 'SELL' order.algoStrategy = 'Adaptive' order.algoParams = [] order.algoParams.append( TagValue("adaptivePriority", ordersPriority)) app.placeOrder(orderId=order_id, contract=contract, order=order) sleep(sleeptime) order_id = order_id + 1 print('sell order quantity placed for {} is: {} '.format( contract.symbol, order.totalQuantity)) app.disconnect()
def rebalancing_to_leverage(action_balance, order_id, ordersPriority, transmit): class TestApp(EWrapper, EClient): def __init__(self): EClient.__init__(self, self) def error(self, reqId: TickerId, errorCode: int, errorString: str): if reqId > -1: print("Error. Id: ", reqId, " Code: ", errorCode, " Msg: ", errorString) app = TestApp() app.connect('127.0.0.1', 7497, 0) if app.isConnected(): print('app is running ...') print('balancing {} positions'.format(len(action_balance.index))) # Closing Position for i in action_balance.index: contract = Contract() contract.symbol = i contract.secType = 'STK' contract.exchange = 'SMART' contract.currency = 'USD' order = Order() order.orderType = 'MKT' order.totalQuantity = np.abs(action_balance.loc[i, 'shares']) order.transmit = transmit if action_balance.loc[i, 'shares'] > 0: order.action = 'BUY' order.algoStrategy = 'Adaptive' order.algoParams = [] order.algoParams.append( TagValue("adaptivePriority", ordersPriority)) app.placeOrder(orderId=order_id, contract=contract, order=order) sleep(sleeptime) order_id = order_id + 1 print(' buy order quantity placed for {} is: {} '.format( contract.symbol, order.totalQuantity)) elif action_balance.loc[i, 'shares'] < 0: order.action = 'SELL' order.algoStrategy = 'Adaptive' order.algoParams = [] order.algoParams.append( TagValue("adaptivePriority", ordersPriority)) app.placeOrder(orderId=order_id, contract=contract, order=order) sleep(sleeptime) order_id = order_id + 1 print(' sell order quantity placed for {} is: {} '.format( contract.symbol, order.totalQuantity)) else: print('app not connected') app.disconnect()
def closing_positions(stock_to_close, portfolio, order_id, ordersPriority, transmit): class TestApp(EWrapper, EClient): def __init__(self): EClient.__init__(self, self) def error(self, reqId: TickerId, errorCode: int, errorString: str): if reqId > -1: print("Error. Id: ", reqId, " Code: ", errorCode, " Msg: ", errorString) app = TestApp() app.connect('127.0.0.1', 7497, 0) if app.isConnected(): print('app is running ...') print( 'closing {} positions which are not present in action'.format( len(stock_to_close))) # Closing Position for i in stock_to_close: contract = Contract() contract.symbol = i contract.secType = 'STK' contract.exchange = 'SMART' #contract.primaryExchange = 'ISLAND' contract.currency = 'USD' order = Order() order.orderType = 'MKT' order.totalQuantity = int(np.abs(portfolio.loc[i, 'Position'])) order.transmit = transmit if portfolio.loc[i, 'Position'] > 0: order.action = 'SELL' #order.cashQty = weigth * 1.5 * net_liq order.algoStrategy = 'Adaptive' order.algoParams = [] order.algoParams.append( TagValue("adaptivePriority", ordersPriority)) app.placeOrder(orderId=order_id, contract=contract, order=order) sleep(sleeptime) order_id = order_id + 1 print('closing position for {} is: {} '.format( contract.symbol, order.totalQuantity)) elif portfolio.loc[i, 'Position'] < 0: order.action = 'BUY' #order.cashQty = weigth * 1.5 * net_liq order.algoStrategy = 'Adaptive' order.algoParams = [] order.algoParams.append( TagValue("adaptivePriority", ordersPriority)) app.placeOrder(orderId=order_id, contract=contract, order=order) sleep(sleeptime) order_id = order_id + 1 print('closing position for {} is: {} '.format( contract.symbol, order.totalQuantity)) else: print('app not connected') app.disconnect() return order_id + 1
def fill_adaptive_params(self, baseOrder: Order, priority: str): baseOrder.algoStrategy = "Adaptive" baseOrder.algoParams = [] baseOrder.algoParams.append(TagValue("adaptivePriority", priority))
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)
def main(): # Create the client and connect to TWS client = AdvOrder('127.0.0.1', 7497, 0) time.sleep(0.5) # Define the contract con = Contract() con.symbol = 'IBM' con.secType = 'STK' con.currency = 'USD' con.exchange = 'SMART' # Get unique ID for contract client.reqContractDetails(0, con) time.sleep(3) # Create a volume condition vol_condition = Create(OrderCondition.Volume) vol_condition.conId = client.con_id vol_condition.exchange = client.exch vol_condition.isMore = True vol_condition.volume = 20000 # Obtain an ID for the main order client.reqIds(1000) time.sleep(2) # Create the bracket order main_order = Order() main_order.orderId = client.order_id main_order.action = 'BUY' main_order.orderType = 'MKT' main_order.totalQuantity = 100 main_order.transmit = False main_order.conditions.append(vol_condition) # Set the algorithm for the order main_order.algoStrategy = 'Adaptive' main_order.algoParams = [] main_order.algoParams.append(TagValue('adaptivePriority', 'Patient')) # First child order - limit order first_child = Order() first_child.orderId = client.order_id + 1 first_child.action = 'SELL' first_child.orderType = 'LMT' first_child.totalQuantity = 100 first_child.lmtPrice = 170 first_child.parentId = client.order_id first_child.transmit = False # Stop order child second_child = Order() second_child.orderId = client.order_id + 2 second_child.action = 'SELL' second_child.orderType = 'STP' second_child.totalQuantity = 100 second_child.auxPrice = 120 second_child.parentId = client.order_id second_child.transmit = False # Submit each order client.placeOrder(client.order_id, con, main_order) client.placeOrder(client.order_id + 1, con, first_child) client.placeOrder(client.order_id + 2, con, second_child) # Sleep while the request is processed time.sleep(5) client.disconnect()
def FillMinImpactParams(baseOrder: Order, maxPctVol: float): baseOrder.algoStrategy = "MinImpact" baseOrder.algoParams = [] baseOrder.algoParams.append(TagValue("maxPctVol", maxPctVol))
def FillAdaptiveParams(baseOrder: Order, priority: str): baseOrder.algoStrategy = "Adaptive" baseOrder.algoParams = [] baseOrder.algoParams.append(TagValue("adaptivePriority", priority))