Interactive Brokers Python API: contractDetails request prints nicely, but won’t return

  api, interactive-brokers, python, tws

Beginner. Spent a LONG time on this before giving up. Thank you for taking my question.

Writing a program to take input of one or more stock tickers (e.g. GE, EQNR, CCJ) and give information back. First step is, for the list of stocks entered, to get a list of their numerical ID numbers.

Relevant code at flags A, B, C.

Problem seems to be with the contractDetails() function (FLAG B). The instruction "print(contractDetails.contract.conId)" works beautifully, outputting each stock’s ID number to the screen. However, if I try to return the outputted value for storage as a variable (FLAG C) it doesn’t work. It returns nothing. Data type is "None." What am I missing?

from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.contract import Contract

class App(EWrapper, EClient):
    def __init__(self):
        EClient.__init__(self, self)
        EWrapper.__init__(self)

    def error(self, reqId, errorCode, errorString):
        print("Error: ", reqId, " ", errorCode, " ", errorString)

# FLAG B: Ask Interactive Brokers for the ID numbers.  
    def contractDetails(reqID, contract, contractDetails):
        print(contractDetails.contract.conId )
        return int(contractDetails.contract.conId)
        

# FLAG A: Function to call the ID numbers for each ticker.
    def getIDs(self):
        self.contract = Contract()
        self.contract.symbol = i
        self.contract.secType = "STK"
        self.contract.exchange = "SMART"
        self.contract.currency = "USD"
        app.reqContractDetails("", self.contract)

# Function to make a list from user-entered tickers.
def enter_tickers():
    ticker_entry = ""
    while ticker_entry != "done":
        ticker_entry = str(input("Input ticker symbol for reference asset (or type "done"): "))
        if ticker_entry != "done":
            tickerlist.append(ticker_entry)


def main():
    app.connect("127.0.0.1", 4001, 0)

# Instruction to open the data connection and prompt for user entries.
app = App()
tickerlist = []
enter_tickers()
main()

# FLAG C: Store the ID numbers in a list.
listofIDs = []
for i in tickerlist:
    IDnumber = app.getIDs()
    print(IDnumber)

app.run()"""

Source: Python Questions

LEAVE A COMMENT