def FutureWithLocalSymbol(): contract = Contract() contract.secType = "FUT" contract.exchange = "GLOBEX" contract.currency = "USD" contract.localSymbol = "ESU6" return contract
def future_contract(symbol, exchange='NYMEX'): C = IBcontract() C.secType = 'FUT' C.exchange = exchange C.currency = 'USD' C.localSymbol = symbol return C
def DutchWarrant(): contract = Contract() contract.localSymbol = "B881G" contract.secType = "IOPT" contract.exchange = "SBF" contract.currency = "EUR" return contract
def processPositionDataMsg(self, fields): sMsgId = next(fields) version = decode(int, fields) account = decode(str, fields) # decode contract fields contract = Contract() contract.conId = decode(int, fields) 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) contract.multiplier = decode(str, fields) contract.exchange = decode(str, fields) contract.currency = decode(str, fields) contract.localSymbol = decode(str, fields) if version >= 2: contract.tradingClass = decode(str, fields) if self.serverVersion >= MIN_SERVER_VER_FRACTIONAL_POSITIONS: position = decode(float, fields) else: position = decode(int, fields) avgCost = 0. if version >= 3: avgCost = decode(float, fields) self.wrapper.position(account, contract, position, avgCost)
def contract(self) -> Contract: _contract = Contract() _contract.secType = "FUT" _contract.exchange = self.exchange _contract.currency = "USD" _contract.localSymbol = self.local_symbol return _contract
def make_contract(symbol='', conID=0, secType='STK', currency='USD', exchange='', primaryExchange='', multiplier=100, tradingClass='', localSymbol='', right='', lastTradeDateOrContractMonth='', strike=0): contract = Contract() contract.symbol = symbol contract.conId = conID contract.secType = secType contract.currency = currency contract.exchange = exchange contract.primaryExchange = primaryExchange contract.multiplier = multiplier contract.tradingClass = tradingClass if tradingClass == '': contract.tradingClass = symbol contract.localSymbol = localSymbol contract.right = right contract.lastTradeDateOrContractMonth = lastTradeDateOrContractMonth contract.strike = strike return contract
def contractDetails(self, reqId: int, contractDetails: ContractDetails): super(IbApp, self).contractDetails(reqId, contractDetails) self.Logger.info('contractDetails received %s ' % contractDetails.summary) if reqId not in self.requestedContracts: self.Logger.warning('Unknown contractDetails reqId: %s' % reqId) return contract = self.requestedContracts[reqId] if contract.symbol == contractDetails.summary.symbol or contract.symbol == contractDetails.marketName: validated = Contract() validated.symbol = contractDetails.summary.symbol validated.secType = contractDetails.summary.secType validated.exchange = contractDetails.summary.exchange validated.tradingClass = contractDetails.summary.tradingClass validated.lastTradeDateOrContractMonth = contractDetails.summary.lastTradeDateOrContractMonth validated.localSymbol = contractDetails.summary.localSymbol if self.__subRealMD: cId = self.nextReqId() self.marketDataLookup[cId] = validated.localSymbol self.requestedMarketData[cId] = validated self.reqMktData(cId, contract, "", True, False, []) if self.__subHistMD: hId = self.nextReqId() self.historicalLookup[hId] = validated.localSymbol self.requestedHistoricalData[hId] = validated self.reqHistoricalData(hId, validated, '', "2 D", "1 day", "TRADES", 1, 1, False, list("XYZ")) else: self.Logger.warning('Unknown contract received %s' % contractDetails.summary)
def processPositionMultiMsg(self, fields): sMsgId = next(fields) version = decode(int, fields) reqId = decode(int, fields) account = decode(str, fields) # decode contract fields contract = Contract() contract.conId = decode(int, fields) 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) contract.multiplier = decode(str, fields) contract.exchange = decode(str, fields) contract.currency = decode(str, fields) contract.localSymbol = decode(str, fields) contract.tradingClass = decode(str, fields) position = decode(float, fields) avgCost = decode(float, fields) modelCode = decode(str, fields) self.wrapper.positionMulti(reqId, account, modelCode, contract, position, avgCost)
def processExecutionDataMsg(self, fields): sMsgId = next(fields) version = decode(int, fields) reqId = -1 if version >= 7: reqId = decode(int, fields) orderId = decode(int, fields) # decode contract fields contract = Contract() contract.conId = decode(int, fields) # ver 5 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 >= 9: contract.multiplier = decode(str, fields) contract.exchange = decode(str, fields) contract.currency = decode(str, fields) contract.localSymbol = decode(str, fields) if version >= 10: contract.tradingClass = decode(str, fields) # decode execution fields exec = Execution() exec.orderId = orderId exec.execId = decode(str, fields) exec.time = decode(str, fields) exec.acctNumber = decode(str, fields) exec.exchange = decode(str, fields) exec.side = decode(str, fields) if self.serverVersion >= MIN_SERVER_VER_FRACTIONAL_POSITIONS: exec.shares = decode(float, fields) else: exec.shares = decode(int, fields) exec.price = decode(float, fields) exec.permId = decode(int, fields) # ver 2 field exec.clientId = decode(int, fields) # ver 3 field exec.liquidation = decode(int, fields) # ver 4 field if version >= 6: exec.cumQty = decode(float, fields) exec.avgPrice = decode(float, fields) if version >= 8: exec.orderRef = decode(str, fields) if version >= 9: exec.evRule = decode(str, fields) exec.evMultiplier = decode(float, fields) if self.serverVersion >= MIN_SERVER_VER_MODELS_SUPPORT: exec.modelCode = decode(str, fields) self.wrapper.execDetails(reqId, contract, exec)
def OptionWithLocalSymbol(): contract = Contract() # Watch out for the spaces within the local symbol! contract.localSymbol = "C DBK DEC 20 1600" contract.secType = "OPT" contract.exchange = "DTB" contract.currency = "EUR" return contract
def futures_contract(ticker: str, exchange: str): # ! [futcontract_local_symbol] contract = Contract() contract.secType = "FUT" contract.exchange = exchange contract.currency = "USD" contract.localSymbol = ticker # ! [futcontract_local_symbol] return contract
def OptionWithLocalSymbol(): contract = Contract() contract.localSymbol = "C SPX JAN 16 2450" contract.secType = "OPT" contract.exchange = "SMART" contract.primaryExchange = "SMART" contract.currency = "USD" return contract
def _get_stock_contract(ticker: str, exchange="SMART", currency="USD", **_): """ Helper function for creating a contract object for use in querying data for stocks """ contract = Contract() contract.secType = "STK" contract.localSymbol = ticker contract.exchange = exchange contract.currency = currency return contract
def test_futures_ibcontract_from_ib_contract_2(self): contract = Contract() contract.secType = "FUT" contract.exchange = "GLOBEX" contract.currency = "USD" contract.localSymbol = "ESU6" ibcontract = IBContract.from_ib_contract(contract) self.assertEqual(ibcontract.secType, "FUT") self.assertEqual(ibcontract.security_type, SecurityType.FUTURE) self.assertEqual(ibcontract.exchange, "GLOBEX") self.assertEqual(ibcontract.currency, "USD") self.assertEqual(ibcontract.localSymbol, "ESU6")
def Dict_to_Contract(data: dict): con = Contract() con.symbol = data['symbol'] con.conId = data['conID'] con.secType = data['secType'] con.currency = data['currency'] con.exchange = data['exchange'] con.primaryExchange = data['primaryExchange'] con.multiplier = data['multiplier'] con.tradingClass = data['tradingClass'] con.localSymbol = data['localSymbol'] con.right = data['right'] con.lastTradeDateOrContractMonth = data['lastTradeDateOrContractMonth'] con.strike = data['strike'] return con
def GetTicks(): app = TickFeed(export_func=q_to_list) app.connect("127.0.0.1", 4002, 0) contract = Contract() contract.secType = "FUT" contract.exchange = "GLOBEX" contract.currency = "USD" contract.localSymbol = "ESH0" app.reqMarketDataType(1) app.reqTickByTickData(1, contract, "BidAsk", 0, False) app.reqTickByTickData(2, contract, "AllLast", 0, False) app.run()
def processPortfolioValueMsg(self, fields): sMsgId = next(fields) version = decode(int, fields) # read contract fields contract = Contract() contract.conId = decode(int, fields) # ver 6 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 >= 7: contract.multiplier = decode(str, fields) contract.primaryExchange = decode(str, fields) contract.currency = decode(str, fields) contract.localSymbol = decode(str, fields) # ver 2 field if version >= 8: contract.tradingClass = decode(str, fields) if self.serverVersion >= MIN_SERVER_VER_FRACTIONAL_POSITIONS: position = decode(float, fields) else: position = decode(int, fields) marketPrice = decode(float, fields) marketValue = decode(float, fields) averageCost = decode(float, fields) # ver 3 field unrealizedPNL = decode(float, fields) # ver 3 field realizedPNL = decode(float, fields) # ver 3 field accountName = decode(str, fields) # ver 4 field if version == 6 and self.serverVersion == 39: contract.primaryExchange = decode(str, fields) self.wrapper.updatePortfolio( contract, position, marketPrice, marketValue, averageCost, unrealizedPNL, realizedPNL, accountName)
def start(self): items = [('VIX', 'IND', 'CBOE', '', '', 'VIX')] nxt = self.__start while nxt < self.__end: contract = self.GetContract(nxt) items.append(contract) nxt = nxt + relativedelta(months=1) for sym, typ, exch, tc, exp, loc in items: validated = Contract() validated.symbol = sym validated.secType = typ validated.exchange = exch validated.tradingClass = tc validated.lastTradeDateOrContractMonth = exp if typ == 'FUT': validated.includeExpired = True validated.localSymbol = loc hId = self.nextReqId() self.historicalLookup[hId] = validated.localSymbol self.requestedHistoricalData[hId] = validated if exp != '': expiry = datetime.datetime.strptime(exp, '%Y%m%d') end = expiry.strftime('%Y%m%d %H:%M:%S') duration = "30 D" else: end = self.__end.strftime('%Y%m%d %H:%M:%S') duration = "%s M" % self.months self.Logger.info( 'ReqId: %s. Requesting Historical %s %s %s %s %s %s' % (hId, sym, typ, exch, tc, exp, loc)) self.reqHistoricalData(hId, validated, end, duration, "1 day", "TRADES", 1, 1, False, list("XYZ"))
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
# right = "C", # local="EW2M8 C2775", # multiplier = 50) from ibapi.contract import Contract as IBcontract ibcontract = IBcontract() ibcontract.secType = "FOP" ibcontract.symbol = "ES" ibcontract.exchange = "GLOBEX" #ibcontract.primaryExchange = "CME" ibcontract.currency = "USD" ibcontract.lastTradeDateOrContractMonth = "20180608" ibcontract.strike = 2775 ibcontract.right = "C" ibcontract.multiplier = "50" ibcontract.conId = 317012336 ibcontract.localSymbol = "EW2M8 C2775" ## resolve the contract resolved_ibcontract = app.resolve_ib_contract(ibcontract) tickerid = app.start_getting_IB_market_data(resolved_ibcontract) time.sleep(10) ## What have we got so far? market_data1 = app.get_IB_market_data(tickerid) print(market_data1[0]) market_data1_as_df = market_data1.as_pdDataFrame() print(market_data1_as_df)
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
# asset = Contract() # asset.symbol = 'IBM' # asset.secType = 'STK' # asset.exchange = 'SMART' # asset.currency = 'USD' # id only asset # vix_contract = app.req_contract_details_futures('VIX', exchange='CFE', # summary_only=True) asset = Contract() asset.symbol = 'VIX' asset.secType = 'FUT' asset.currency = 'USD' asset.exchange = 'CFE' asset.localSymbol = 'VXU0' asset.multiplier = '1000' asset.lastTradeDateOrContractMonth = '20200916' # asset = gen_contract( # 'SPX', 'IND', 'CBOE', 'USD') # non blocking app.req_mkt_data(asset, snapshot=False) # app.req_tick_by_tick_data(contract, TickType.mid) # app.req_mkt_depth(asset, 10, True, []) # app.req_real_time_bars(asset, 1, 'TRADES', True, []) # app.req_account_updates(True, 'DU1589832') # result = app.req_historical_data_non_blocking(contract, "1 D", '1 min', 'MIDPOINT', 1, 1, []) # app.req_account_summary('All', AccountSummaryTags.AllTags)