Search code examples
pythonpython-3.xdelay

Time lag when collecting data and using datetime.sleep()


I'm trying to collect data of cotizations through an API each minute, and for this I have used a loop that pauses 60 seconds, actually all this works but I have some troubles.

For example, when I send a petition at the time 12:00, it receives the data of the 11:59 but I want to receive the data of 12:00. This only happens when I use time.sleep() and the delay it is proportional to the seconds that I put inside of the time.sleep() function

This is my code:

from iqoptionapi.api import IQOptionAPI
from datetime import datetime
import time

candles = None
contador = 1
while True:
    if candles is None:
        api = IQOptionAPI("iqoption.com", "user", "pass") # Data for conection
        api.connect()
        api.getcandles(1,1) # (id_active, time)
        candles = api.candles.candles_data # List with candles
        print ("Try....\n")
    else:
        print ("Candle petition:", contador, "-", datetime.now(), "\n")
        api.getcandles(1, 1)
        candles = api.candles.candles_data
        print (candles, "\n")
        print ("First list:", datetime.fromtimestamp(candles[0][0]),
               "Second list:", datetime.fromtimestamp(candles[1][0]), "\n")
        contador += 1

    time.sleep(60)

and these are my results:

Candle petition: 2 - 2017-01-25 10:14:05.554242

[[1485360784, 1073590, 1073600, 1073600, 1073590], [1485360785,
1073600, 1073595, 1073600, 1073595]]

First list: 2017-01-25 10:13:04 Second list: 2017-01-25 10:13:05

What is happening? Why the delay?


Solution

  • It looks like IQOptionAPI uses websocket-client, which is asynchronous. Sending a request will return immediately, without waiting for a response from the server. You are checking for the response before you have received it. As a result, what you are getting is actually the result of the previous request. That's why it corresponds to the length of the sleep you use.

    I don't immediately see a way within IQOptionAPI to make a synchronous request or get any sort of feedback when the response comes in, but it would be best to look a little closer and see if there is indeed a way. As a workaround, try inserting a couple of seconds of delay between the request and checking the response:

    api.getcandles(1, 1)
    time.sleep(2)
    candles = api.candles.candles_data