0

I have a class that establishes several market data streams and stores them in an array. Then another function within the same class accesses the array and requests data from the streams, but all the values are coming out as NaN.

Here is an example:

 from ib_insync import *

 class Trading:
     def __init__(...):
         self.dataStreams = []
         self.conn = IB()  #establish connecting to the api
         self.tickers = [('BMW', 'IBIS'), ('BAYN', 'IBIS'),  .. ]

     def _stream_data(self): # this function established the data stream and appends it to an array
         for contract in self.tickers:
              stock = Stock(contract[0], contract[1], 'EUR')
              stream = self.conn.reqMktData(stock, '', False, False)
              self.dataStreams.append(stream)
              self.conn.sleep(1)

    def start(self):
        self._stream_data()  # fill the datastream array
        print(self.dataStreams[0].last + self.dataStreams[1].last)  # so this should return the sum of two prices, but it does not

So when I initialize the above class in the interpreter:

 strategy = Trading()
 strategy.start()

strategy.start() will print NaN because the data from the streams are coming as NaN. However if I access the datastreams array from the strategy object like so:

strategy.dataStreams[0].last 

it will print the last price correctly.

I think that this issue is related to the nature of IB api working asynchronously, but I do not have enough experience to figure a work around. I need to make other functions withing the class to be able to retrieve data from the streams and perform calculations.

Is it possible to do with the logic above? or do i have to move the data streams in to a separate class and initialize it separately in order to be able to access the data?

Artem Korol
  • 191
  • 1
  • 2
  • 11

0 Answers0