Home > Net >  Getting an updated object value inside a Python for loop
Getting an updated object value inside a Python for loop

Time:02-01

I have an object called "ticker" that is collecting streaming data from Interactive Brokers via ib_insync.

I am simply trying to create a list and updated it with new, for example, bid prices from the ticker object every 250 milliseconds or so. When I try to get updated values via the for loop, I am not getting updated values through each iteration, just the original value from the first pass.

I assume I have a lack of understanding around scope inside the for loop which is creating this issue. How can I do this correctly?

Here is the code:

contract = Stock('IBM', 'SMART', 'USD') # this defines the contract
ticker = ib.reqMktData(contract) # this creates the ticker object for the specified contract
vec = [0] * 100
for m in vec:
    vec.pop(0)
    vec.append(ticker.bid)
    print(vec)
    time.sleep(.25)

CodePudding user response:

Need to make a copy of vec and alter the copy in the for loop wih <copy>.append.

ie if you have loop

for i in something: then something must not be changed inside the loop.

CodePudding user response:

In Python you can not change the object you loop over. But given the description of your goal we can work around that. Either update your list a fixed number of times (n_iter) like that:

for _ in range(n_iter):
    vec = vec[:-1]   [ticker.bid]
    print(ticker.bid)
    time.sleep(0.25)

Or use a function that returns True if the updating should continue and False if it should stop like that:

while should_proceed():
    vec = vec[:-1]   [ticker.bid]
    print(ticker.bid)
    time.sleep(0.25)
  •  Tags:  
  • Related