Understanding threading in Interactive Brokers Python API

I read a few tutorials about threading in Python to get better understanding of Interactive Brokers API. But I still do not understand why below code does not work:

from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.contract import Contract
from ibapi.ticktype import TickTypeEnum
import time
import threading


class TestApp(EWrapper, EClient):
    def __init__(self):
        EClient.__init__(self, self)
        self.last_price_list = []

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

    def tickPrice(self, reqId, tickType, price, attrib):
        self.last_price_list = self.last_price_list + [price]
        print("Tick Price. Ticker Id:", reqId, "tickType:", TickTypeEnum.to_str(tickType), "Price:", price, end=' ')
        print("_______________________")
    


   

 app = TestApp()
    
 app.connect("127.0.0.1", 4002, 0)
        
 # allow time to connect to server
 time.sleep(1)
 
 contract = Contract()
 contract.symbol = "AAPL"
 contract.secType = "STK"
 contract.exchange = "SMART"
 contract.currency = "USD"
 contract.primaryExchange = "NASDAQ"
 
 app.reqMarketDataType(4)  # switch to delayed-frozen data if live is not available
 app.reqMktData(1, contract, "", False, False, [])
 
 api_thread = threading.Thread(target=app.run())
 api_thread.start()
 
 while True:
     print(len(app.last_price_list))
        time.sleep(2)
    

Here is what it produced before I interrupted it. :

Error:  -1   2104   Market data farm connection is OK:usfarm
Error:  -1   2107   HMDS data farm connection is inactive but should be available upon demand.ushmds
Error:  -1   2158   Sec-def data farm connection is OK:secdefil
Error:  1   10167   Requested market data is not subscribed. Displaying delayed market data.
Tick Price. Ticker Id: 1 tickType: DELAYED_BID Price: 152.41 _______________________
Tick Price. Ticker Id: 1 tickType: DELAYED_ASK Price: 152.46 _______________________
Tick Price. Ticker Id: 1 tickType: DELAYED_LAST Price: 152.44 _______________________
Tick Price. Ticker Id: 1 tickType: DELAYED_HIGH Price: 155.04 _______________________
Tick Price. Ticker Id: 1 tickType: DELAYED_LOW Price: 152.28 _______________________
Tick Price. Ticker Id: 1 tickType: DELAYED_CLOSE Price: 154.09 _______________________
Tick Price. Ticker Id: 1 tickType: DELAYED_OPEN Price: 154.04 _______________________

I do not understand why this line does not print anything print(len(app.last_price_list))

>Solution :

(target=app.run) No brackets after run, you are supposed to give the name of the method being called, don’t actually call it.

Leave a Reply