def makeComboLeg(conId, action): newComboLeg = ComboLeg() newComboLeg.m_conId = conId newComboLeg.m_ratio = 1 newComboLeg.m_action = action newComboLeg.m_exchange = 'SMART' newComboLeg.m_openClose = '0' return newComboLeg
def test_008a(connection, options): c = Contract() c.m_exchange = 'IDEALPRO' c.m_symbol = 'MO' c.m_localSymbol = 'MO1C' c.m_secType = 'BAG' c.m_expiry = '200806' leg1 = ComboLeg() leg1.m_conId = 123 leg1.m_ratio = 1 leg1.m_exchange = 'ONE' leg1.m_action = 'SELL' leg2 = ComboLeg() leg2.m_conId = 125 leg2.m_ratio = 100 leg2.m_exchange = 'NYSE' leg2.m_action = 'BUY' c.m_comboLegs = [leg1, leg2] connection.reqMktData(1, c, generic_tick_keys, False)
def new_option_combo_contract(symbol, id_to_sell, id_to_buy, exchange='SMART', currency='USD'): ''' Make a new stock spread contract, e.g. a long/short pair. The buy:sell ratio is 1 contract:1 contract The function is implemented according to http://interactivebrokers.github.io/tws-api/spread_contracts.html#bag_fut&gsc.tab=0 :param symbol: not used in this function. :param id_to_sell: a int number of stock contract ID (leg) to sell :param id_to_buy: a int number of stock contract ID (leg) to buy :param exchange: the exchange of contracts; string :param currency: the currency of the future contract :return: a new combo contract (stock spread) ''' contract = Contract() contract.m_symbol = currency contract.m_secType = 'BAG' contract.m_currency = currency contract.m_exchange = 'SMART' leg_to_sell = ComboLeg() leg_to_sell.m_conId = id_to_sell # e.g. MCD stock's contract ID leg_to_sell.m_ratio = 1 leg_to_sell.m_action = "SELL" leg_to_sell.m_exchange = exchange leg_to_sell.m_openClose = 0 leg_to_buy = ComboLeg() leg_to_buy.m_conId = id_to_buy # e.g. IBKR stock's contract ID leg_to_buy.m_ratio = 1 leg_to_buy.m_action = "BUY" leg_to_buy.m_exchange = exchange leg_to_buy.m_openClose = 0 contract.m_comboLegs.append(leg_to_buy) contract.m_comboLegs.append(leg_to_sell) return contract
def new_future_spread_contract(symbol, id_to_buy, id_to_sell, exchange, currency='USD'): ''' Make a new future spread contract, e.g. calendar spread. The buy:sell ratio is 1 contract:1 contract The function is implemented according to http://interactivebrokers.github.io/tws-api/spread_contracts.html#bag_fut&gsc.tab=0 :param symbol: symbol of a future contract; e.g. 'VIX' :param id_to_sell: a int number of contract ID (leg) to sell :param id_to_buy: a int number of contract ID (leg) to buy :param exchange: the exchange of contracts; string :param currency: the currency of the future contract :return: a new combo contract (future spread) ''' contract = Contract() contract.m_symbol = symbol # NOTE: do not set it to 'USD' for future spread as for option combo orders contract.m_secType = 'BAG' contract.m_currency = currency contract.m_exchange = 'SMART' # set exchange to 'SMART' in the main order leg_to_sell = ComboLeg() leg_to_sell.m_conId = id_to_sell leg_to_sell.m_ratio = 1 leg_to_sell.m_action = "SELL" leg_to_sell.m_exchange = exchange leg_to_buy = ComboLeg() leg_to_buy.m_conId = id_to_buy leg_to_buy.m_ratio = 1 leg_to_buy.m_action = "BUY" leg_to_buy.m_exchange = exchange contract.m_comboLegs.append(leg_to_buy) contract.m_comboLegs.append(leg_to_sell) return contract
def place_order(order_list): """ Auto-detects which args should be assigned to a new Contract or Order, then use to place order. Makes use of globals to set initial values, but allows args to override (ie clientId) To modify and order, the following parameters are needed (IB won't complain if some of these are missing, but the order update won't succeed): * orderId * exchange * totalQuantity * secType * action * orderType AND related paramters (ie TRAIL needs trailingPercent) * symbol * currency * exchange When an object in `order_list` has secType = 'BAG', it implies an Options combo order will be placed, requiring comboLegs: a JSON list of details required for this function to fetch the conId to then build the ComboLeg. """ log.debug('Starting place_order with args_list: {}'.format(order_list)) client = connection.get_client() if client is None: connection.close_client(client) return g.error_resp[-2] elif client.isConnected() is False: return g.error_resp[-1] # To allow for bracketed orders (or processing a string of orders in a single request), we expect args to be a list if not isinstance(order_list, list): order_list = [order_list] parentId = None order_ids = set() dont_wait_order_ids = set( ) # Some orders aren't worth waiting for responses on for args in order_list: # If an orderId was provided, we'll be updating an existing order, so only send attributes which are updatable: # totalQuantity, orderType, symbol, secType, action # TODO consider casting unicode to utf-8 here. Otherwise we get error(id=1, errorCode=512, errorMsg=Order Sending Error - char format require string of length 1) # log.debug('Processing args from order_list: {}'.format(args)) orderId = args.get('orderId', None) if orderId is None: orderId = g.orderId g.orderId += 1 order_ids.add(orderId) if 'goodAfterTime' in args: dont_wait_order_ids.add(orderId) contract = Contract() order = Order() # Populate contract with appropriate args for attr in dir(contract): if attr[:2] == 'm_' and attr[2:] in args: setattr(contract, attr, args[attr[2:]]) # Populate order with appropriate order.m_clientId = client.clientId for attr in dir(order): if attr[:2] == 'm_' and attr[2:] in args: setattr(order, attr, args[attr[2:]]) # Option Combo Orders need the comboLegs details turned into actual ComboLeg objects comboLegs = args.get('comboLegs', None) if comboLegs: # We need to build ComboLegs by first fetching the conId from the contract details all_legs = [] req_ids = [] # Clear out our global ContractDetails so our handler can repopulate them g.contract_resp['contractDetails'] = dict() g.contract_resp['contractDetailsEnd'] = False # Request new ContractDetails so we can get the conIds needed for our legs for idx, leg in enumerate(comboLegs): # Each leg is a dict of details needed to make a ComboLeg object leg_contract = Contract() # Populate leg_contract with appropriate args for attr in dir(leg_contract): if attr[:2] == 'm_' and attr[2:] in leg: setattr(leg_contract, attr, leg[attr[2:]]) # Fetch conId for leg_contract client.reqContractDetails(idx, leg_contract) req_ids.append(idx) # We've now requested ContractDetails for all legs. Wait to get their async responses. timeout = g.timeout while g.contract_resp[ 'contractDetailsEnd'] is False and client.isConnected( ) is True and timeout > 0: time.sleep(0.25) timeout -= 1 # Create our ComboLegs for our order for idx, leg in enumerate(comboLegs): combo_leg = ComboLeg() # Populate combo_leg with appropriate args for attr in dir(combo_leg): if attr[:2] == 'm_' and attr[2:] in leg: setattr(combo_leg, attr, leg[attr[2:]]) combo_leg.m_conId = g.contract_resp['contractDetails'][idx][ 'm_summary'].m_conId all_legs.append(combo_leg) contract.m_comboLegs = all_legs # If this is a bracketed order, we'll need to add in the parentId for children orders if parentId: order.m_parentId = parentId log.debug( 'Placing order # {} on client # {} (connected={}): {}'.format( orderId, client.clientId, client.isConnected(), args)) client.placeOrder(orderId, contract, order) # Assume our 1st order in the list is the parent. Use this for remaining bracket orders and also error handling if not parentId: parentId = orderId log.debug('Setting child order parentId={}'.format(parentId)) log.debug('Ignoring responses for these orderIds: {}'.format( dont_wait_order_ids)) order_ids = order_ids - dont_wait_order_ids # Don't look for order status or errors until we actually transmit the last order, but then look for status for # all order_ids timeout = g.timeout resp = wait_for_responses(order_ids, client, timeout) connection.close_client(client) return resp
# ----------------- get contract data contractIds = [] for requestId, contract in enumerate(contracts): print(("Requesting ", contract.m_symbol)) tws.reqContractDetails(requestId, contract) sleep(1) # wait for data to come in # safety check that request ids match assert handler.reqId == requestId, "Request and data do not match" contractIds.append(handler.conId) # ------------create contract legs # for simplicity, I just set each leg to buy 1 share legs = [] for conId in contractIds: leg = ComboLeg() leg.m_conId = conId leg.m_ratio = 1 leg.m_action = "BUY" leg.m_exchange = "SMART" legs.append(leg) # -------- create a contract with required legs contract = Contract() contract.m_symbol = "USD" contract.m_secType = "BAG" contract.m_exchange = "SMART" contract.m_currency = "USD" contract.m_comboLegs = legs
def processMsg(self, msgId): """ generated source for method processMsg """ if msgId == -1: return False if msgId == self.TICK_PRICE: version = self.readInt() tickerId = self.readInt() tickType = self.readInt() price = self.readDouble() size = 0 if version >= 2: size = self.readInt() canAutoExecute = 0 if version >= 3: canAutoExecute = self.readInt() self.eWrapper().tickPrice(tickerId, tickType, price, canAutoExecute) if version >= 2: # not a tick sizeTickType = -1 if tickType == 1: # BID sizeTickType = 0 # BID_SIZE elif tickType == 2: # ASK sizeTickType = 3 # ASK_SIZE elif tickType == 4: # LAST sizeTickType = 5 # LAST_SIZE if sizeTickType != -1: self.eWrapper().tickSize(tickerId, sizeTickType, size) elif msgId == self.TICK_SIZE: version = self.readInt() tickerId = self.readInt() tickType = self.readInt() size = self.readInt() self.eWrapper().tickSize(tickerId, tickType, size) elif msgId == self.POSITION: version = self.readInt() account = self.readStr() contract = Contract() contract.m_conId = self.readInt() contract.m_symbol = self.readStr() contract.m_secType = self.readStr() contract.m_expiry = self.readStr() contract.m_strike = self.readDouble() contract.m_right = self.readStr() contract.m_multiplier = self.readStr() contract.m_exchange = self.readStr() contract.m_currency = self.readStr() contract.m_localSymbol = self.readStr() if version >= 2: contract.m_tradingClass = self.readStr() pos = self.readInt() avgCost = 0 if version >= 3: avgCost = self.readDouble() self.eWrapper().position(account, contract, pos, avgCost) elif msgId == self.POSITION_END: version = self.readInt() self.eWrapper().positionEnd() elif msgId == self.ACCOUNT_SUMMARY: version = self.readInt() reqId = self.readInt() account = self.readStr() tag = self.readStr() value = self.readStr() currency = self.readStr() self.eWrapper().accountSummary(reqId, account, tag, value, currency) elif msgId == self.ACCOUNT_SUMMARY_END: version = self.readInt() reqId = self.readInt() self.eWrapper().accountSummaryEnd(reqId) elif msgId == self.TICK_OPTION_COMPUTATION: version = self.readInt() tickerId = self.readInt() tickType = self.readInt() impliedVol = self.readDouble() if impliedVol < 0: # -1 is the "not yet computed" indicator impliedVol = Double.MAX_VALUE delta = self.readDouble() if abs(delta) > 1: # -2 is the "not yet computed" indicator delta = Double.MAX_VALUE optPrice = Double.MAX_VALUE pvDividend = Double.MAX_VALUE gamma = Double.MAX_VALUE vega = Double.MAX_VALUE theta = Double.MAX_VALUE undPrice = Double.MAX_VALUE if version >= 6 or (tickType == TickType.MODEL_OPTION): # introduced in version == 5 optPrice = self.readDouble() if optPrice < 0: # -1 is the "not yet computed" indicator optPrice = Double.MAX_VALUE pvDividend = self.readDouble() if pvDividend < 0: # -1 is the "not yet computed" indicator pvDividend = Double.MAX_VALUE if version >= 6: gamma = self.readDouble() if abs(gamma) > 1: # -2 is the "not yet computed" indicator gamma = Double.MAX_VALUE vega = self.readDouble() if abs(vega) > 1: # -2 is the "not yet computed" indicator vega = Double.MAX_VALUE theta = self.readDouble() if abs(theta) > 1: # -2 is the "not yet computed" indicator theta = Double.MAX_VALUE undPrice = self.readDouble() if undPrice < 0: # -1 is the "not yet computed" indicator undPrice = Double.MAX_VALUE self.eWrapper().tickOptionComputation(tickerId, tickType, impliedVol, delta, optPrice, pvDividend, gamma, vega, theta, undPrice) elif msgId == self.TICK_GENERIC: version = self.readInt() tickerId = self.readInt() tickType = self.readInt() value = self.readDouble() self.eWrapper().tickGeneric(tickerId, tickType, value) elif msgId == self.TICK_STRING: version = self.readInt() tickerId = self.readInt() tickType = self.readInt() value = self.readStr() self.eWrapper().tickString(tickerId, tickType, value) elif msgId == self.TICK_EFP: version = self.readInt() tickerId = self.readInt() tickType = self.readInt() basisPoints = self.readDouble() formattedBasisPoints = self.readStr() impliedFuturesPrice = self.readDouble() holdDays = self.readInt() futureExpiry = self.readStr() dividendImpact = self.readDouble() dividendsToExpiry = self.readDouble() self.eWrapper().tickEFP(tickerId, tickType, basisPoints, formattedBasisPoints, impliedFuturesPrice, holdDays, futureExpiry, dividendImpact, dividendsToExpiry) elif msgId == self.ORDER_STATUS: version = self.readInt() id = self.readInt() status = self.readStr() filled = self.readInt() remaining = self.readInt() avgFillPrice = self.readDouble() permId = 0 if version >= 2: permId = self.readInt() parentId = 0 if version >= 3: parentId = self.readInt() lastFillPrice = 0 if version >= 4: lastFillPrice = self.readDouble() clientId = 0 if version >= 5: clientId = self.readInt() whyHeld = None if version >= 6: whyHeld = self.readStr() self.eWrapper().orderStatus(id, status, filled, remaining, avgFillPrice, permId, parentId, lastFillPrice, clientId, whyHeld) elif msgId == self.ACCT_VALUE: version = self.readInt() key = self.readStr() val = self.readStr() cur = self.readStr() accountName = None if version >= 2: accountName = self.readStr() self.eWrapper().updateAccountValue(key, val, cur, accountName) elif msgId == self.PORTFOLIO_VALUE: version = self.readInt() contract = Contract() if version >= 6: contract.m_conId = self.readInt() contract.m_symbol = self.readStr() contract.m_secType = self.readStr() contract.m_expiry = self.readStr() contract.m_strike = self.readDouble() contract.m_right = self.readStr() if version >= 7: contract.m_multiplier = self.readStr() contract.m_primaryExch = self.readStr() contract.m_currency = self.readStr() if version >= 2: contract.m_localSymbol = self.readStr() if version >= 8: contract.m_tradingClass = self.readStr() position = self.readInt() marketPrice = self.readDouble() marketValue = self.readDouble() averageCost = 0.0 unrealizedPNL = 0.0 realizedPNL = 0.0 if version >= 3: averageCost = self.readDouble() unrealizedPNL = self.readDouble() realizedPNL = self.readDouble() accountName = None if version >= 4: accountName = self.readStr() if version == 6 and self.m_parent.serverVersion() == 39: contract.m_primaryExch = self.readStr() self.eWrapper().updatePortfolio(contract, position, marketPrice, marketValue, averageCost, unrealizedPNL, realizedPNL, accountName) elif msgId == self.ACCT_UPDATE_TIME: version = self.readInt() timeStamp = self.readStr() self.eWrapper().updateAccountTime(timeStamp) elif msgId == self.ERR_MSG: version = self.readInt() if version < 2: msg = self.readStr() self.m_parent.error(msg) else: id = self.readInt() errorCode = self.readInt() errorMsg = self.readStr() self.m_parent.error(id, errorCode, errorMsg) elif msgId == self.OPEN_ORDER: # read version version = self.readInt() # read order id order = Order() order.m_orderId = self.readInt() # read contract fields contract = Contract() if version >= 17: contract.m_conId = self.readInt() contract.m_symbol = self.readStr() contract.m_secType = self.readStr() contract.m_expiry = self.readStr() contract.m_strike = self.readDouble() contract.m_right = self.readStr() if version >= 32: contract.m_multiplier = self.readStr() contract.m_exchange = self.readStr() contract.m_currency = self.readStr() if version >= 2: contract.m_localSymbol = self.readStr() if version >= 32: contract.m_tradingClass = self.readStr() # read order fields order.m_action = self.readStr() order.m_totalQuantity = self.readInt() order.m_orderType = self.readStr() if version < 29: order.m_lmtPrice = self.readDouble() else: order.m_lmtPrice = self.readDoubleMax() if version < 30: order.m_auxPrice = self.readDouble() else: order.m_auxPrice = self.readDoubleMax() order.m_tif = self.readStr() order.m_ocaGroup = self.readStr() order.m_account = self.readStr() order.m_openClose = self.readStr() order.m_origin = self.readInt() order.m_orderRef = self.readStr() if version >= 3: order.m_clientId = self.readInt() if version >= 4: order.m_permId = self.readInt() if version < 18: # will never happen # order.m_ignoreRth = self.readBoolFromInt() else: order.m_outsideRth = self.readBoolFromInt() order.m_hidden = self.readInt() == 1 order.m_discretionaryAmt = self.readDouble() if version >= 5: order.m_goodAfterTime = self.readStr() if version >= 6: # skip deprecated sharesAllocation field self.readStr() if version >= 7: order.m_faGroup = self.readStr() order.m_faMethod = self.readStr() order.m_faPercentage = self.readStr() order.m_faProfile = self.readStr() if version >= 8: order.m_goodTillDate = self.readStr() if version >= 9: order.m_rule80A = self.readStr() order.m_percentOffset = self.readDoubleMax() order.m_settlingFirm = self.readStr() order.m_shortSaleSlot = self.readInt() order.m_designatedLocation = self.readStr() if self.m_parent.serverVersion() == 51: self.readInt() # exemptCode elif version >= 23: order.m_exemptCode = self.readInt() order.m_auctionStrategy = self.readInt() order.m_startingPrice = self.readDoubleMax() order.m_stockRefPrice = self.readDoubleMax() order.m_delta = self.readDoubleMax() order.m_stockRangeLower = self.readDoubleMax() order.m_stockRangeUpper = self.readDoubleMax() order.m_displaySize = self.readInt() if version < 18: # will never happen # order.m_rthOnly = self.readBoolFromInt() order.m_blockOrder = self.readBoolFromInt() order.m_sweepToFill = self.readBoolFromInt() order.m_allOrNone = self.readBoolFromInt() order.m_minQty = self.readIntMax() order.m_ocaType = self.readInt() order.m_eTradeOnly = self.readBoolFromInt() order.m_firmQuoteOnly = self.readBoolFromInt() order.m_nbboPriceCap = self.readDoubleMax() if version >= 10: order.m_parentId = self.readInt() order.m_triggerMethod = self.readInt() if version >= 11: order.m_volatility = self.readDoubleMax() order.m_volatilityType = self.readInt() if version == 11: receivedInt = self.readInt() order.m_deltaNeutralOrderType = ("NONE" if (receivedInt == 0) else "MKT") else: # version 12 and up order.m_deltaNeutralOrderType = self.readStr() order.m_deltaNeutralAuxPrice = self.readDoubleMax() if version >= 27 and not Util.StringIsEmpty( order.m_deltaNeutralOrderType): order.m_deltaNeutralConId = self.readInt() order.m_deltaNeutralSettlingFirm = self.readStr() order.m_deltaNeutralClearingAccount = self.readStr() order.m_deltaNeutralClearingIntent = self.readStr() if version >= 31 and not Util.StringIsEmpty( order.m_deltaNeutralOrderType): order.m_deltaNeutralOpenClose = self.readStr() order.m_deltaNeutralShortSale = self.readBoolFromInt() order.m_deltaNeutralShortSaleSlot = self.readInt() order.m_deltaNeutralDesignatedLocation = self.readStr() order.m_continuousUpdate = self.readInt() if self.m_parent.serverVersion() == 26: order.m_stockRangeLower = self.readDouble() order.m_stockRangeUpper = self.readDouble() order.m_referencePriceType = self.readInt() if version >= 13: order.m_trailStopPrice = self.readDoubleMax() if version >= 30: order.m_trailingPercent = self.readDoubleMax() if version >= 14: order.m_basisPoints = self.readDoubleMax() order.m_basisPointsType = self.readIntMax() contract.m_comboLegsDescrip = self.readStr() if version >= 29: comboLegsCount = self.readInt() if comboLegsCount > 0: contract.m_comboLegs = [] i = 0 while i < comboLegsCount: comboLeg = ComboLeg() comboLeg.m_conId = self.readInt() comboLeg.m_ratio = self.readInt() comboLeg.m_action = self.readStr() comboLeg.m_exchange = self.readStr() comboLeg.m_openClose = self.readInt() comboLeg.m_shortSaleSlot = self.readInt() comboLeg.m_designatedLocation = self.readStr() comboLeg.m_exemptCode = self.readInt() contract.m_comboLegs.append(comboLeg) i += 1 orderComboLegsCount = self.readInt() if orderComboLegsCount > 0: order.m_orderComboLegs = [] i = 0 while i < orderComboLegsCount: price = self.readDoubleMax() orderComboLeg = OrderComboLeg(price) order.m_orderComboLegs.append(orderComboLeg) i += 1 if version >= 26: smartComboRoutingParamsCount = self.readInt() if smartComboRoutingParamsCount > 0: order.m_smartComboRoutingParams = [] i = 0 while i < smartComboRoutingParamsCount: tagValue = TagValue() tagValue.m_tag = self.readStr() tagValue.m_value = self.readStr() order.m_smartComboRoutingParams.append(tagValue) i += 1 if version >= 15: if version >= 20: order.m_scaleInitLevelSize = self.readIntMax() order.m_scaleSubsLevelSize = self.readIntMax() else: # int notSuppScaleNumComponents = self.readIntMax() order.m_scaleInitLevelSize = self.readIntMax() order.m_scalePriceIncrement = self.readDoubleMax() if version >= 28 and order.m_scalePriceIncrement > 0.0 and order.m_scalePriceIncrement != Double.MAX_VALUE: order.m_scalePriceAdjustValue = self.readDoubleMax() order.m_scalePriceAdjustInterval = self.readIntMax() order.m_scaleProfitOffset = self.readDoubleMax() order.m_scaleAutoReset = self.readBoolFromInt() order.m_scaleInitPosition = self.readIntMax() order.m_scaleInitFillQty = self.readIntMax() order.m_scaleRandomPercent = self.readBoolFromInt() if version >= 24: order.m_hedgeType = self.readStr() if not Util.StringIsEmpty(order.m_hedgeType): order.m_hedgeParam = self.readStr() if version >= 25: order.m_optOutSmartRouting = self.readBoolFromInt() if version >= 19: order.m_clearingAccount = self.readStr() order.m_clearingIntent = self.readStr() if version >= 22: order.m_notHeld = self.readBoolFromInt() if version >= 20: if self.readBoolFromInt(): underComp = UnderComp() underComp.m_conId = self.readInt() underComp.m_delta = self.readDouble() underComp.m_price = self.readDouble() contract.m_underComp = underComp if version >= 21: order.m_algoStrategy = self.readStr() if not Util.StringIsEmpty(order.m_algoStrategy): algoParamsCount = self.readInt() if algoParamsCount > 0: order.m_algoParams = [] i = 0 while i < algoParamsCount: tagValue = TagValue() tagValue.m_tag = self.readStr() tagValue.m_value = self.readStr() order.m_algoParams.append(tagValue) i += 1 orderState = OrderState() if version >= 16: order.m_whatIf = self.readBoolFromInt() orderState.m_status = self.readStr() orderState.m_initMargin = self.readStr() orderState.m_maintMargin = self.readStr() orderState.m_equityWithLoan = self.readStr() orderState.m_commission = self.readDoubleMax() orderState.m_minCommission = self.readDoubleMax() orderState.m_maxCommission = self.readDoubleMax() orderState.m_commissionCurrency = self.readStr() orderState.m_warningText = self.readStr() self.eWrapper().openOrder(order.m_orderId, contract, order, orderState) elif msgId == self.NEXT_VALID_ID: version = self.readInt() orderId = self.readInt() self.eWrapper().nextValidId(orderId) elif msgId == self.SCANNER_DATA: contract = ContractDetails() version = self.readInt() tickerId = self.readInt() numberOfElements = self.readInt() ctr = 0 while ctr < numberOfElements: rank = self.readInt() if version >= 3: contract.m_summary.m_conId = self.readInt() contract.m_summary.m_symbol = self.readStr() contract.m_summary.m_secType = self.readStr() contract.m_summary.m_expiry = self.readStr() contract.m_summary.m_strike = self.readDouble() contract.m_summary.m_right = self.readStr() contract.m_summary.m_exchange = self.readStr() contract.m_summary.m_currency = self.readStr() contract.m_summary.m_localSymbol = self.readStr() contract.m_marketName = self.readStr() contract.m_summary.m_tradingClass = self.readStr() distance = self.readStr() benchmark = self.readStr() projection = self.readStr() legsStr = None if version >= 2: legsStr = self.readStr() self.eWrapper().scannerData(tickerId, rank, contract, distance, benchmark, projection, legsStr) ctr += 1 self.eWrapper().scannerDataEnd(tickerId) elif msgId == self.CONTRACT_DATA: version = self.readInt() reqId = -1 if version >= 3: reqId = self.readInt() contract = ContractDetails() contract.m_summary.m_symbol = self.readStr() contract.m_summary.m_secType = self.readStr() contract.m_summary.m_expiry = self.readStr() contract.m_summary.m_strike = self.readDouble() contract.m_summary.m_right = self.readStr() contract.m_summary.m_exchange = self.readStr() contract.m_summary.m_currency = self.readStr() contract.m_summary.m_localSymbol = self.readStr() contract.m_marketName = self.readStr() contract.m_summary.m_tradingClass = self.readStr() contract.m_summary.m_conId = self.readInt() contract.m_minTick = self.readDouble() contract.m_summary.m_multiplier = self.readStr() contract.m_orderTypes = self.readStr() contract.m_validExchanges = self.readStr() if version >= 2: contract.m_priceMagnifier = self.readInt() if version >= 4: contract.m_underConId = self.readInt() if version >= 5: contract.m_longName = self.readStr() contract.m_summary.m_primaryExch = self.readStr() if version >= 6: contract.m_contractMonth = self.readStr() contract.m_industry = self.readStr() contract.m_category = self.readStr() contract.m_subcategory = self.readStr() contract.m_timeZoneId = self.readStr() contract.m_tradingHours = self.readStr() contract.m_liquidHours = self.readStr() if version >= 8: contract.m_evRule = self.readStr() contract.m_evMultiplier = self.readDouble() if version >= 7: secIdListCount = self.readInt() if secIdListCount > 0: contract.m_secIdList = [] i = 0 while i < secIdListCount: tagValue = TagValue() tagValue.m_tag = self.readStr() tagValue.m_value = self.readStr() contract.m_secIdList.append(tagValue) i += 1 self.eWrapper().contractDetails(reqId, contract) elif msgId == self.BOND_CONTRACT_DATA: version = self.readInt() reqId = -1 if version >= 3: reqId = self.readInt() contract = ContractDetails() contract.m_summary.m_symbol = self.readStr() contract.m_summary.m_secType = self.readStr() contract.m_cusip = self.readStr() contract.m_coupon = self.readDouble() contract.m_maturity = self.readStr() contract.m_issueDate = self.readStr() contract.m_ratings = self.readStr() contract.m_bondType = self.readStr() contract.m_couponType = self.readStr() contract.m_convertible = self.readBoolFromInt() contract.m_callable = self.readBoolFromInt() contract.m_putable = self.readBoolFromInt() contract.m_descAppend = self.readStr() contract.m_summary.m_exchange = self.readStr() contract.m_summary.m_currency = self.readStr() contract.m_marketName = self.readStr() contract.m_summary.m_tradingClass = self.readStr() contract.m_summary.m_conId = self.readInt() contract.m_minTick = self.readDouble() contract.m_orderTypes = self.readStr() contract.m_validExchanges = self.readStr() if version >= 2: contract.m_nextOptionDate = self.readStr() contract.m_nextOptionType = self.readStr() contract.m_nextOptionPartial = self.readBoolFromInt() contract.m_notes = self.readStr() if version >= 4: contract.m_longName = self.readStr() if version >= 6: contract.m_evRule = self.readStr() contract.m_evMultiplier = self.readDouble() if version >= 5: secIdListCount = self.readInt() if secIdListCount > 0: contract.m_secIdList = [] i = 0 while i < secIdListCount: tagValue = TagValue() tagValue.m_tag = self.readStr() tagValue.m_value = self.readStr() contract.m_secIdList.append(tagValue) i += 1 self.eWrapper().bondContractDetails(reqId, contract) elif msgId == self.EXECUTION_DATA: version = self.readInt() reqId = -1 if version >= 7: reqId = self.readInt() orderId = self.readInt() contract = Contract() # read contract fields if version >= 5: contract.m_conId = self.readInt() contract.m_symbol = self.readStr() contract.m_secType = self.readStr() contract.m_expiry = self.readStr() contract.m_strike = self.readDouble() contract.m_right = self.readStr() if version >= 9: contract.m_multiplier = self.readStr() contract.m_exchange = self.readStr() contract.m_currency = self.readStr() contract.m_localSymbol = self.readStr() if version >= 10: contract.m_tradingClass = self.readStr() exec_ = Execution() exec_.m_orderId = orderId exec_.m_execId = self.readStr() exec_.m_time = self.readStr() exec_.m_acctNumber = self.readStr() exec_.m_exchange = self.readStr() exec_.m_side = self.readStr() exec_.m_shares = self.readInt() exec_.m_price = self.readDouble() if version >= 2: exec_.m_permId = self.readInt() if version >= 3: exec_.m_clientId = self.readInt() if version >= 4: exec_.m_liquidation = self.readInt() if version >= 6: exec_.m_cumQty = self.readInt() exec_.m_avgPrice = self.readDouble() if version >= 8: exec_.m_orderRef = self.readStr() if version >= 9: exec_.m_evRule = self.readStr() exec_.m_evMultiplier = self.readDouble() self.eWrapper().execDetails(reqId, contract, exec_) elif msgId == self.MARKET_DEPTH: version = self.readInt() id = self.readInt() position = self.readInt() operation = self.readInt() side = self.readInt() price = self.readDouble() size = self.readInt() self.eWrapper().updateMktDepth(id, position, operation, side, price, size) elif msgId == self.MARKET_DEPTH_L2: version = self.readInt() id = self.readInt() position = self.readInt() marketMaker = self.readStr() operation = self.readInt() side = self.readInt() price = self.readDouble() size = self.readInt() self.eWrapper().updateMktDepthL2(id, position, marketMaker, operation, side, price, size) elif msgId == self.NEWS_BULLETINS: version = self.readInt() newsMsgId = self.readInt() newsMsgType = self.readInt() newsMessage = self.readStr() originatingExch = self.readStr() self.eWrapper().updateNewsBulletin(newsMsgId, newsMsgType, newsMessage, originatingExch) elif msgId == self.MANAGED_ACCTS: version = self.readInt() accountsList = self.readStr() self.eWrapper().managedAccounts(accountsList) elif msgId == self.RECEIVE_FA: version = self.readInt() faDataType = self.readInt() xml = self.readStr() self.eWrapper().receiveFA(faDataType, xml) elif msgId == self.HISTORICAL_DATA: version = self.readInt() reqId = self.readInt() startDateStr = "" endDateStr = "" completedIndicator = "finished" if version >= 2: startDateStr = self.readStr() endDateStr = self.readStr() completedIndicator += "-" + startDateStr + "-" + endDateStr itemCount = self.readInt() ctr = 0 while ctr < itemCount: date = self.readStr() open = self.readDouble() high = self.readDouble() low = self.readDouble() close = self.readDouble() volume = self.readInt() WAP = self.readDouble() hasGaps = self.readStr() barCount = -1 if version >= 3: barCount = self.readInt() self.eWrapper().historicalData( reqId, date, open, high, low, close, volume, barCount, WAP, Boolean.valueOf(hasGaps).booleanValue()) ctr += 1 # send end of dataset marker self.eWrapper().historicalData(reqId, completedIndicator, -1, -1, -1, -1, -1, -1, -1, False) elif msgId == self.SCANNER_PARAMETERS: version = self.readInt() xml = self.readStr() self.eWrapper().scannerParameters(xml) elif msgId == self.CURRENT_TIME: # int version = self.readInt() time = self.readLong() self.eWrapper().currentTime(time) elif msgId == self.REAL_TIME_BARS: # int version = self.readInt() reqId = self.readInt() time = self.readLong() open = self.readDouble() high = self.readDouble() low = self.readDouble() close = self.readDouble() volume = self.readLong() wap = self.readDouble() count = self.readInt() self.eWrapper().realtimeBar(reqId, time, open, high, low, close, volume, wap, count) elif msgId == self.FUNDAMENTAL_DATA: # int version = self.readInt() reqId = self.readInt() data = self.readStr() self.eWrapper().fundamentalData(reqId, data) elif msgId == self.CONTRACT_DATA_END: # int version = self.readInt() reqId = self.readInt() self.eWrapper().contractDetailsEnd(reqId) elif msgId == self.OPEN_ORDER_END: # int version = self.readInt() self.eWrapper().openOrderEnd() elif msgId == self.ACCT_DOWNLOAD_END: # int version = self.readInt() accountName = self.readStr() self.eWrapper().accountDownloadEnd(accountName) elif msgId == self.EXECUTION_DATA_END: # int version = self.readInt() reqId = self.readInt() self.eWrapper().execDetailsEnd(reqId) elif msgId == self.DELTA_NEUTRAL_VALIDATION: # int version = self.readInt() reqId = self.readInt() underComp = UnderComp() underComp.m_conId = self.readInt() underComp.m_delta = self.readDouble() underComp.m_price = self.readDouble() self.eWrapper().deltaNeutralValidation(reqId, underComp) elif msgId == self.TICK_SNAPSHOT_END: # int version = self.readInt() reqId = self.readInt() self.eWrapper().tickSnapshotEnd(reqId) elif msgId == self.MARKET_DATA_TYPE: # int version = self.readInt() reqId = self.readInt() marketDataType = self.readInt() self.eWrapper().marketDataType(reqId, marketDataType) elif msgId == self.COMMISSION_REPORT: # int version = self.readInt() commissionReport = CommissionReport() commissionReport.m_execId = self.readStr() commissionReport.m_commission = self.readDouble() commissionReport.m_currency = self.readStr() commissionReport.m_realizedPNL = self.readDouble() commissionReport.m_yield = self.readDouble() commissionReport.m_yieldRedemptionDate = self.readInt() self.eWrapper().commissionReport(commissionReport) else: self.m_parent.error(EClientErrors.NO_VALID_ID, EClientErrors.UNKNOWN_ID.code(), EClientErrors.UNKNOWN_ID.msg()) return False return True