2 years ago

#15544

test-img

micastik

IB API: Retrieving the prices for multiple stocks simultaneously

Based on stock news I would like to retrieve and store prices of specific stocks which have been identified. When news comes in, I would like to retrieve the price for a certain amount of time.

The issue here is, that during the time prices are retrieved for one stock, new stock news can come in and for this new stock, the prices shall be retrieved simultaneously. The code I have written for this task is the following:

while True:

    new_news_symbol = x # Will be set prior to this code by searching for new stock news
    contract = Contract()
    contract.symbol = new_news_symbol
    contract.secType = 'STK'
    contract.exchange = 'SMART'
    contract.currency = "EUR"
    contract.primaryExchange = "SMART"

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

            self.last = 0

        def nextValidId(self, orderId: int):
            random_id = random.randint(0, 9999)
            self.reqMarketDataType(3)  # or DELAYED
            self.reqMktData(random_id, contract, "", False, False, [])

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

        def tickPrice(self, reqId, tickType, price, attrib):
            if str(format(datetime.now(), '%H:%M:%S')) <= timer:
                if tickType == 2:
                    time_.append(str(datetime.now(tz).time())[:8])
                    prices.append(price)
            else:
                df = pd.DataFrame(np.column_stack([time_, prices]), columns=['Time', 'Prices'])
                pd.DataFrame(df).to_csv("Prices/%s.csv" % new_news_symbol)
                print("Price data retrieval sucessfull")
                self.disconnect()
                sys.exit()

    def main():
        app = TestApp()
        random_id = random.randint(0, 999)
        app.connect('127.0.0.1', 7497, random_id)
        app.run()


    a = threading.Thread(target=main)
    a.start()

    continue # While the price for the current stock news is retrieved, new stock news is searched for

My problem here is that every time the price is retrieved for new stock news, the current retrieval is stopped. I thought I could solve this by threading but it didn't work.

So in summary, how can I retrieve stock prices for multiple stocks simultaneously with IB Python API?

python

multithreading

algorithmic-trading

interactive-brokers

0 Answers

Your Answer

Accepted video resources