def make_combo_Switch(underlying: Contract, call: Contract, put: Contract): underlyingleg = ComboLeg() underlyingleg.conId = underlying.conId underlyingleg.ratio = 100 underlyingleg.action = 'BUY' underlyingleg.exchange = 'SMART' Pleg = ComboLeg() Pleg.ratio = 1 Pleg.action = 'BUY' Pleg.exchange = 'SMART' Pleg.conId = put.conId Cleg = ComboLeg() Cleg.ratio = 1 Cleg.action = 'SELL' Cleg.exchange = 'SMART' Cleg.conId = call.conId contract = Contract() contract.symbol = underlying.symbol contract.secType = 'BAG' contract.currency = 'USD' contract.exchange = 'SMART' contract.comboLegs = [] contract.comboLegs.append(underlyingleg) contract.comboLegs.append(Pleg) contract.comboLegs.append(Cleg) return contract
def combo_generator_Switch(symbol: str, abovedays=7, lessdays =120): specpath = r'E:\newdata\IB data\Option Specs' file = specpath + os.sep + symbol + '-specs.json' jf = open(file, 'r') jdict = json.load(jf) jf.close() underlyingfile = r'E:\newdata\IB data\Underlying_Contract_Details.csv' underlying = pd.read_csv(underlyingfile) syms = list(underlying['symbol']) idx = syms.index(symbol) last = underlying['Last'][idx] underlyingleg = ComboLeg() underlyingleg.conId = underlying['conID'][idx] underlyingleg.ratio = 100 underlyingleg.action = 'BUY' underlyingleg.exchange = 'SMART' Pleg = ComboLeg() Pleg.ratio = 1 Pleg.action = 'BUY' Pleg.exchange = 'SMART' Cleg = ComboLeg() Cleg.ratio = 1 Cleg.action = 'SELL' Cleg.exchange = 'SMART' contract = Contract() contract.symbol = symbol contract.secType = 'BAG' contract.currency = 'USD' contract.exchange = 'SMART' Combos = [] for mi, di in jdict.items(): jm = IBdate_to_Date(mi) today = date.today() if abovedays < (jm - today).days <= lessdays: stricks = list(di['C'].keys()) stricks_1 = [float(i) for i in stricks] print(symbol) ps = pick_stricks_2(last, stricks_1, 2) for si in ps: Pleg.conId = di['P'][str(si)]['conID'] Cleg.conId = di['C'][str(si)]['conID'] contract.comboLegs = [] contract.comboLegs.append(underlyingleg) contract.comboLegs.append(Pleg) contract.comboLegs.append(Cleg) Combos.append([deepcopy(contract), si]) return Combos
def decodeComboLegs(self, fields): self.contract.comboLegsDescrip = decode(str, fields) if self.version >= 29: comboLegsCount = decode(int, fields) if comboLegsCount > 0: self.contract.comboLegs = [] for _ in range(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) self.contract.comboLegs.append(comboLeg) orderComboLegsCount = decode(int, fields) if orderComboLegsCount > 0: self.order.orderComboLegs = [] for _ in range(orderComboLegsCount): orderComboLeg = OrderComboLeg() orderComboLeg.price = decode(float, fields, SHOW_UNSET) self.order.orderComboLegs.append(orderComboLeg)
def make_combo_Box(call_H: Contract, put_H: Contract, call_L: Contract, put_L: Contract): Pleg_H = ComboLeg() Pleg_H.ratio = 1 Pleg_H.action = 'SELL' Pleg_H.exchange = 'SMART' Pleg_H.conId = put_H.conId Cleg_H = ComboLeg() Cleg_H.ratio = 1 Cleg_H.action = 'BUY' Cleg_H.exchange = 'SMART' Cleg_H.conId = call_H.conId Pleg_L = ComboLeg() Pleg_L.ratio = 1 Pleg_L.action = 'BUY' Pleg_L.exchange = 'SMART' Pleg_L.conId = put_L.conId Cleg_L = ComboLeg() Cleg_L.ratio = 1 Cleg_L.action = 'SELL' Cleg_L.exchange = 'SMART' Cleg_L.conId = call_L.conId contract = Contract() contract.symbol = call_H.symbol contract.secType = 'BAG' contract.currency = 'USD' contract.exchange = 'SMART' contract.comboLegs = [] contract.comboLegs.append(Cleg_H) contract.comboLegs.append(Pleg_H) contract.comboLegs.append(Cleg_L) contract.comboLegs.append(Pleg_L) return contract
def InterCmdtyFuturesContract(): contract = Contract() contract.symbol = "CL.BZ" # symbol is 'local symbol' of intercommodity spread. contract.secType = "BAG" contract.currency = "USD" contract.exchange = "NYMEX" leg1 = ComboLeg() leg1.conId = 47207310 # CL Dec'16 @NYMEX leg1.ratio = 1 leg1.action = "BUY" leg1.exchange = "NYMEX" leg2 = ComboLeg() leg2.conId = 47195961 # BZ Dec'16 @NYMEX leg2.ratio = 1 leg2.action = "SELL" leg2.exchange = "NYMEX" contract.comboLegs = [] contract.comboLegs.append(leg1) contract.comboLegs.append(leg2) return contract
def SmartFutureComboContract(): contract = Contract() contract.symbol = "WTI" # WTI,COIL spread. Symbol can be defined as first leg symbol ("WTI") or currency ("USD") contract.secType = "BAG" contract.currency = "USD" contract.exchange = "SMART" leg1 = ComboLeg() leg1.conId = 55928698 # WTI future June 2017 leg1.ratio = 1 leg1.action = "BUY" leg1.exchange = "IPE" leg2 = ComboLeg() leg2.conId = 55850663 # COIL future June 2017 leg2.ratio = 1 leg2.action = "SELL" leg2.exchange = "IPE" contract.comboLegs = [] contract.comboLegs.append(leg1) contract.comboLegs.append(leg2) return contract
def FutureComboContract(): contract = Contract() contract.symbol = "VIX" contract.secType = "BAG" contract.currency = "USD" contract.exchange = "CFE" leg1 = ComboLeg() leg1.conId = 256038899 # VIX FUT 201708 leg1.ratio = 1 leg1.action = "BUY" leg1.exchange = "CFE" leg2 = ComboLeg() leg2.conId = 260564703 # VIX FUT 201709 leg2.ratio = 1 leg2.action = "SELL" leg2.exchange = "CFE" contract.comboLegs = [] contract.comboLegs.append(leg1) contract.comboLegs.append(leg2) return contract
def StockComboContract(): contract = Contract() contract.symbol = "IBKR,MCD" contract.secType = "BAG" contract.currency = "USD" contract.exchange = "SMART" leg1 = ComboLeg() leg1.conId = 43645865 # IBKR STK leg1.ratio = 1 leg1.action = "BUY" leg1.exchange = "SMART" leg2 = ComboLeg() leg2.conId = 9408 # MCD STK leg2.ratio = 1 leg2.action = "SELL" leg2.exchange = "SMART" contract.comboLegs = [] contract.comboLegs.append(leg1) contract.comboLegs.append(leg2) return contract
def OptionComboContract(): contract = Contract() contract.symbol = "DBK" contract.secType = "BAG" contract.currency = "EUR" contract.exchange = "DTB" leg1 = ComboLeg() leg1.conId = 197397509 # DBK JUN 15 2018 C leg1.ratio = 1 leg1.action = "BUY" leg1.exchange = "DTB" leg2 = ComboLeg() leg2.conId = 197397584 # DBK JUN 15 2018 P leg2.ratio = 1 leg2.action = "SELL" leg2.exchange = "DTB" contract.comboLegs = [] contract.comboLegs.append(leg1) contract.comboLegs.append(leg2) return contract
def createSpreadContract(ticker1, ticker2, conids): contract = Contract() contract.symbol = 'ANZ,WBC' contract.secType = "BAG" contract.currency = "AUD" contract.exchange = "SMART" leg1 = ComboLeg() leg1.conId = conids[ticker1] leg1.ratio = 1 leg1.action = "BUY" leg1.exchange = "SMART" leg2 = ComboLeg() leg2.conId = conids[ticker2] leg2.ratio = 1 leg2.action = "SELL" leg2.exchange = "SMART" contract.comboLegs = [] contract.comboLegs.append(leg1) contract.comboLegs.append(leg2) return contract
def from_string(cls, contract_str: str) -> "IBContract": """ Create IBContract object from the corresponding string. """ params, combo_legs = contract_str.split("combo:") ib_contract = Contract() [ib_contract.conId, ib_contract.symbol, ib_contract.secType, ib_contract.lastTradeDateOrContractMonth, ib_contract.strike, ib_contract.right, ib_contract.multiplier, ib_contract.exchange, ib_contract.primaryExchange, ib_contract.currency, ib_contract.localSymbol, ib_contract.tradingClass, ib_contract.includeExpired, ib_contract.secIdType, ib_contract.secId] = params.split(",") ib_contract.conId = int(ib_contract.conId) ib_contract.strike = float(ib_contract.strike) ib_contract.includeExpired = bool(ib_contract.includeExpired == "True") combo_legs = combo_legs.split(";") combo_legs = [c for c in combo_legs if len(c) > 0] if len(combo_legs) > 0: if len(combo_legs[-1].split(",")) == 3: delta_neutral_contract = combo_legs[-1].split(",") combo_legs = combo_legs[:-1] ib_contract.deltaNeutralContract = DeltaNeutralContract() ib_contract.deltaNeutralContract.conId = int(delta_neutral_contract[0]) ib_contract.deltaNeutralContract.delta = float(delta_neutral_contract[1]) ib_contract.deltaNeutralContract.price = float(delta_neutral_contract[2]) ib_contract.comboLegs = [] if len(combo_legs) > 0 else None if ib_contract.comboLegs is not None: for params in combo_legs: params = params.split(",") combo_leg = ComboLeg() combo_leg.conId = int(params[0]) combo_leg.ratio = int(params[1]) combo_leg.action = params[2] combo_leg.exchange = params[3] combo_leg.openClose = int(params[4]) combo_leg.shortSaleSlot = int(params[5]) combo_leg.designatedLocation = params[6] combo_leg.exemptCode = int(params[7]) ib_contract.comboLegs.append(combo_leg) return cls.from_ib_contract(ib_contract)
def buy6030(self, sym, direction="Bull", exp="", budget=500): if direction == "Bull": right = "Put" else: right = "Call" if exp == "": d = datetime.date.today() d += datetime.timedelta(10) while d.weekday() != 4: d += datetime.timedelta(1) exp = d.strftime("%Y%m%d") contract1 = IBcontract() contract1.secType = "STK" contract1.symbol = sym contract1.exchange = "ISLAND" contract2 = IBcontract() contract2.secType = "OPT" contract2.symbol = sym contract2.exchange = "SMART" contract2.lastTradeDateOrContractMonth = exp contract2.right = right contract2.multiplier = 100 self.reqMktData(1032, contract1, "", False, False, []) contract1.exchange = "SMART" self.reqMktData(1033, contract1, "", False, False, []) d = self.reqContractDetails(1202, contract2) time.sleep(1) #print(d) print("=" * 40) print() print("{} Price Details:".format(sym)) lastPrice = None try: for k in list(self._my_price_details[1032].queue): t = dict(k) if t['tickType'] == 4: lastPrice = t['price'] if t['tickType'] == 9 and lastPrice == None: lastPrice = t['price'] print(t) except: try: for k in list(self._my_price_details[1033].queue): t = dict(k) if t['tickType'] == 4: lastPrice = t['price'] if t['tickType'] == 9 and lastPrice == None: lastPrice = t['price'] print(t) except: print("No stock prices available for {} at this time.".format( sym)) return if lastPrice == None: print("No stock prices available for {} at this time.".format(sym)) return # print() # print("{0} Last Price: ${1:4.2f}".format(sym, lastPrice)) # print() rID = 1100 df = DataFrame() print("Contract Details:") try: cDetails = self._my_contract_details[1202].queue except: print("Contract details for {} are not available at this time.". format(sym)) return for k in list(cDetails): t = list(str(k).split(',')) # print(t) try: if lastPrice * 1.10 > float(t[4]) > lastPrice * 0.90: df[rID] = t contract3 = IBcontract() contract3.secType = "OPT" contract3.symbol = sym contract3.exchange = "CBOE2" contract3.lastTradeDateOrContractMonth = exp contract3.strike = float(t[4]) contract3.right = right contract3.multiplier = 100 self.reqMarketDataType(2) self.reqMktData(rID, contract3, "", False, False, []) rID = rID + 1 except: pass if rID == 1100: print( "No option prices available for {} at this time.".format(sym)) return df = df.transpose() # print(df) # print("Getting option details for {0:2d} strikes:".format(len(df))) # print() time.sleep(1) df['undPrice'] = [""] * len(df) df['optPrice'] = [""] * len(df) df['delta'] = [""] * len(df) df['strike'] = [""] * len(df) df['delta60'] = [""] * len(df) for s in df.index: #self.cancelMktData(s) try: for k in list(self._my_option_data[s].queue): t = dict(k) #print(s,t) if t['delta']: try: df.loc[s, 'conId'] = int(df.loc[s, 0]) df.loc[s, 'strike'] = float(df.loc[s, 4]) df.loc[s, 'undPrice'] = t['undPrice'] df.loc[s, 'optPrice'] = t['optPrice'] df.loc[s, 'delta'] = abs(t['delta']) df.loc[s, 'delta60'] = abs(abs(t['delta']) - 0.60) except: pass except: print("No option prices available for {} at this time.".format( sym)) return # print(df.loc[:,['conId',3,'strike','undPrice','delta','delta60']].sort_values(['strike'])) # print() d60 = df.loc[df['delta60'] == df['delta60'].min()].index.min() # print("Sell a {} with the {:7.2f} strike".format(right,df.strike[d60])) t30 = (df.delta[d60] - 0.3) p = df.loc[df.delta > t30].delta.min() d30plus = df.loc[df.delta == p].index.min() m = df.loc[df.delta < t30].delta.max() d30min = df.loc[df.delta == m].index.min() if abs(df.delta[d30plus] - t30) > abs(df.delta[d30min] - t30): d30 = d30min else: d30 = d30plus # Order variables ##### cdelta = df.delta[d60] - df.delta[d30] lim = abs(df.strike[d60] - df.strike[d30]) * 0.35 try: cOptPrice = df.optPrice[d60] - df.optPrice[d30] if abs(cOptPrice) < abs(lim * 0.95): print("Spread Combo price for {} is too low.".format(sym)) return True quantity = int(budget / 100 / cOptPrice) if quantity == 0: print("Spread Combo for {} is above the budget of ${}".format( sym, budget)) return True except: quantity = 1 takeProfitLimitPrice = lim * 0. stopLossPrice = lim * 1.50 action = "SELL" #parentOrderId = 101 # print("Buy a {} with the {:7.2f} strike ".format(right,df.strike[d30])) # print("Combo delta is {:5.3f}".format(cdelta)) # print("Combo limit price is ${:7.2f}".format(lim)) # print("Combo Expiry is {}".format(exp)) # print() print( "{} - Price: ${:7.2f} - Sell a {} {:7.2f}/{:7.2f} {} Spread - Limit price: ${:5.2f} - Combo delta: {:5.3f}" .format(sym, lastPrice, exp, df.strike[d60], df.strike[d30], right, lim, cdelta)) # # Send order for the Spread above #### contract3 = IBcontract() contract3.secType = "BAG" contract3.symbol = sym contract3.exchange = "SMART" contract3.currency = "USD" leg1 = IBcomboLeg() leg1.conId = int(df.conId[d60]) # Sell the delta 60 option leg1.ratio = 1 leg1.action = "SELL" if action == "BUY" else "BUY" leg1.exchange = "SMART" leg2 = IBcomboLeg() leg2.conId = int( df.conId[d30]) # Buy the delta 30 option as protection leg2.ratio = 1 leg2.action = "BUY" if action == "BUY" else "SELL" leg2.exchange = "SMART" contract3.comboLegs = [] contract3.comboLegs.append(leg1) contract3.comboLegs.append(leg2) order3 = Order() order3.action = action order3.orderType = "LMT" order3.totalQuantity = quantity order3.lmtPrice = lim order3.tif = 'DAY' order3.transmit = False parentOrderId = self.place_new_IB_order(contract3, order3, orderid=None) takeProfit = Order() takeProfit.action = "SELL" if action == "BUY" else "BUY" takeProfit.orderType = "LMT" takeProfit.totalQuantity = quantity takeProfit.lmtPrice = takeProfitLimitPrice takeProfit.parentId = parentOrderId takeProfit.tif = 'GTC' takeProfit.transmit = False self.place_new_IB_order(contract3, takeProfit, orderid=None) stopLoss = Order() stopLoss.action = "SELL" if action == "BUY" else "BUY" stopLoss.orderType = "STP" # Stop trigger price stopLoss.auxPrice = stopLossPrice stopLoss.totalQuantity = quantity stopLoss.parentId = parentOrderId stopLoss.tif = 'GTC' # In this case, the low side order will be the last child being sent. Therefore, it needs to set this attribute to True # to activate all its predecessors stopLoss.transmit = True self.place_new_IB_order(contract3, stopLoss, orderid=None) time.sleep(1) return True
def _constructContract(instrument): '''Construct an IB contract and order from an Order object''' contract = Contract() if instrument.type == InstrumentType.EQUITY: contract.symbol = instrument.name contract.secType = "STK" contract.currency = (instrument.currency.name if instrument.currency else '') or "USD" contract.exchange = instrument.brokerExchange or "SMART" elif instrument.type == InstrumentType.BOND: # enter CUSIP as symbol contract.symbol = instrument.name # cusip e.g. 912828C57 contract.secType = "BOND" contract.exchange = instrument.brokerExchange or "SMART" contract.currency = instrument.currency.name or "USD" elif instrument.type == InstrumentType.OPTION: # contract.symbol = "GOOG" contract.secType = "OPT" contract.exchange = instrument.brokerExchange or "SMART" contract.currency = (instrument.currency.name if instrument.currency else '') or "USD" # contract.lastTradeDateOrContractMonth = "20170120" # contract.strike = 615 # contract.right = "C" # contract.multiplier = "100" contract.localSymbol = instrument.name # e.g. "P BMW JUL 20 4650" # can swap name for the above # commented out stuff elif instrument.type == InstrumentType.FUTURE: # contract.symbol = "ES"; contract.secType = "FUT" contract.exchange = instrument.brokerExchange or "SMART" contract.currency = (instrument.currency.name if instrument.currency else '') or "USD" # contract.lastTradeDateOrContractMonth = "201803"; # contract.Multiplier = "5"; contract.localSymbol = instrument.name # e.g. "ESU6" # swap for commented elif instrument.type == InstrumentType.PAIR: contract.symbol = instrument.leg1 # "EUR" contract.secType = "CASH" contract.currency = instrument.leg2 # "GBP" contract.exchange = instrument.brokerExchange or "IDEALPRO" elif instrument.type == InstrumentType.FUTURESOPTION: # contract.symbol = instrument.symbol contract.secType = "FOP" contract.exchange = instrument.brokerExchange contract.currency = (instrument.currency.name if instrument.currency else '') or "USD" # contract.lastTradeDateOrContractMonth = instrument.contractDate.strftime('%Y%m%d') # contract.strike = instrument.strike # contract.right = instrument.callOrPut # contract.multiplier = instrument.multiplier or "100" contract.localSymbol = instrument.name # e.g. "ESU6" elif instrument.type == InstrumentType.MUTUALFUND: contract.symbol = instrument.name # "VINIX" contract.secType = "FUND" contract.exchange = instrument.brokerExchange or "FUNDSERV" contract.currency = (instrument.currency.name if instrument.currency else '') or "USD" elif instrument.type == InstrumentType.COMMODITIES: contract.symbol = instrument.name # "XAUUSD" contract.secType = "CMDTY" contract.exchange = instrument.brokerExchange or "SMART" contract.currency = (instrument.currency.name if instrument.currency else '') or "USD" elif instrument.type == InstrumentType.SPREAD: if instrument.leg1 and \ instrument.leg1.type == InstrumentType.FUTURE and \ instrument.leg1.underlying and \ instrument.leg1.underlying.type == InstrumentType.COMMODITIES and \ instrument.leg2 and \ instrument.leg2.type == InstrumentType.FUTURE and \ instrument.leg2.underlying and \ instrument.leg2.underlying.type == InstrumentType.COMMODITIES and \ instrument.leg1 != instrument.leg2: # Intercommodity futures use A.B contract.symbol = '{}.{}'.format(instrument.leg1.underlying.name, instrument.leg2.underlying.name) elif instrument.leg1 and instrument.leg1.underlying and \ instrument.leg2 and instrument.leg2.underlying and \ (instrument.leg1.underlying == instrument.leg2.underlying): # most other spreads just use the underlying contract.symbol = instrument.leg1.underlying.name elif instrument.leg1 and instrument.leg2 and \ (instrument.leg1.type == InstrumentType.EQUITY and instrument.leg2.type == InstrumentType.EQUITY): # Stock spreads use A,B contract.symbol = '{},{}'.format(instrument.leg1.name, instrument.leg2.name) else: contract.symbol = instrument.name contract.secType = "BAG" contract.currency = (instrument.currency.name if instrument.currency else '') or "USD" contract.exchange = instrument.brokerExchange or "SMART" leg1 = ComboLeg() leg1.conId = instrument.brokerId leg1.ratio = 1 # TODO leg1.action = instrument.leg1_side leg1.exchange = instrument.brokerExchange or "SMART" leg2 = ComboLeg() leg2.conId = instrument.brokerId # MCD STK leg2.ratio = 1 # TODO leg2.action = instrument.leg2_side leg2.exchange = instrument.brokerExchange or "SMART" contract.comboLegs = [leg1, leg2] elif instrument.type == InstrumentType.CURRENCY: raise NotImplementedError() elif instrument.type == InstrumentType.INDEX: raise NotImplementedError() else: raise NotImplementedError() return contract
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 _constructContractAndOrder(aat_order): '''Construct an IB contract and order from an Order object''' contract = Contract() instrument = aat_order.instrument if instrument.type == InstrumentType.EQUITY: contract.symbol = instrument.name contract.secType = "STK" contract.currency = instrument.currency.name or "USD" contract.exchange = instrument.brokerExchange or "SMART" elif instrument.type == InstrumentType.BOND: # enter CUSIP as symbol contract.symbol = instrument.name # cusip e.g. 912828C57 contract.secType = "BOND" contract.exchange = instrument.brokerExchange or "SMART" contract.currency = instrument.currency.name or "USD" elif instrument.type == InstrumentType.OPTION: # contract.symbol = "GOOG" contract.secType = "OPT" contract.exchange = instrument.brokerExchange or "SMART" contract.currency = instrument.currency.name or "USD" # contract.lastTradeDateOrContractMonth = "20170120" # contract.strike = 615 # contract.right = "C" # contract.multiplier = "100" contract.localSymbol = instrument.name # e.g. "P BMW JUL 20 4650" # can swap name for the above # commented out stuff elif instrument.type == InstrumentType.FUTURE: # contract.symbol = "ES"; contract.secType = "FUT" contract.exchange = instrument.brokerExchange or "SMART" contract.currency = instrument.currency.name or "USD" # contract.lastTradeDateOrContractMonth = "201803"; # contract.Multiplier = "5"; contract.localSymbol = instrument.name # e.g. "ESU6" # swap for commented elif instrument.type == InstrumentType.PAIR: contract.symbol = instrument.leg1 # "EUR" contract.secType = "CASH" contract.currency = instrument.leg2 # "GBP" contract.exchange = instrument.brokerExchange or "IDEALPRO" elif instrument.type == InstrumentType.FUTURESOPTION: contract.symbol = "ES" contract.secType = "FOP" contract.exchange = instrument.brokerExchange contract.currency = instrument.currency.name or "USD" contract.lastTradeDateOrContractMonth = "20180316" contract.strike = 2800 contract.right = "C" contract.multiplier = "50" elif instrument.type == InstrumentType.MUTUALFUND: contract.symbol = instrument.name # "VINIX" contract.secType = "FUND" contract.exchange = instrument.brokerExchange or "FUNDSERV" contract.currency = instrument.currency.name or "USD" elif instrument.type == InstrumentType.COMMODITIES: contract.symbol = instrument.name # "XAUUSD" contract.secType = "CMDTY" contract.exchange = instrument.brokerExchange or "SMART" contract.currency = instrument.currency.name or "USD" elif instrument.type == InstrumentType.SPREAD: contract.symbol = instrument.name contract.secType = "BAG" contract.currency = instrument.currency.name or "USD" contract.exchange = instrument.brokerExchange or "SMART" leg1 = ComboLeg() leg1.conId = 43645865 # IBKR STK # TODO leg1.ratio = 1 # TODO leg1.action = instrument.leg1_side leg1.exchange = instrument.brokerExchange or "SMART" leg2 = ComboLeg() leg2.conId = 9408 # MCD STK # TODO leg2.ratio = 1 # TODO leg2.action = instrument.leg2_side leg2.exchange = instrument.brokerExchange or "SMART" contract.comboLegs = [leg1, leg2] elif instrument.type == InstrumentType.CURRENCY: raise NotImplementedError() elif instrument.type == InstrumentType.INDEX: raise NotImplementedError() else: raise NotImplementedError() 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