我有一个类可以建立几个市场数据流并将它们存储在一个数组中。然后同一类中的另一个函数访问数组并从流中请求数据,但所有值都以 NaN 形式出现。
这是一个例子:
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
因此,当我在解释器中初始化上述类时:
strategy = Trading()
strategy.start()
strategy.start()
将打印NaN
,因为来自流的数据以NaN
. 但是,如果我像这样从策略对象访问数据流数组:
strategy.dataStreams[0].last
它将正确打印最后的价格。
我认为这个问题与 IB api 异步工作的性质有关,但我没有足够的经验来解决这个问题。我需要使用该类创建其他函数,以便能够从流中检索数据并执行计算。
是否可以与上面的逻辑有关?还是我必须将数据流移动到一个单独的类中并单独初始化它才能访问数据?