I am trying to get market data for multiple stocks using ib_insync and Interactive Brokers. To do this I am using the pendingTickersEvent callback to wait for the data to arrive. However all that happens is that data for the last symbol in the watch_dict (AAPL) is returned multiple times.
If I use ib.sleep(2) instead of ib.pendingTickersEvent += wait_for_market_data it works ok but is too slow.
This is my first time using an asynchronous library so I've probably doe something silly but I can't work out what it is.
from ib_insync import *
watch_dict = {"TSLA": "NYSE",
"MSFT": "NYSE",
"AAPL": "NYSE"}
def wait_for_market_data(tickers):
print(market_data)
print()
# Create connection
ib = IB()
ib.connect('127.0.0.1', 7497, clientId=1)
while True:
# Define stocks
for ticker in list(watch_dict.keys()):
print(ticker)
stock = Stock(ticker, watch_dict[ticker], 'USD')
print(stock)
# Request current prices
market_data = ib.reqMktData(stock, '', False, False)
#ib.sleep(2)
#print(market_data)
ib.pendingTickersEvent += wait_for_market_data
ib.run()