开云体育

ctrl + shift + ? for shortcuts
© 2025 开云体育

Trying to load data asynchronously and struggling with asyncio again


 

I'm trying to load historical data. It takes a while, so I thought I could speed it up with asyncio, but it doesn't work. Instead of data, I'm getting timeouts. Here is what I've tried.:?
?
import asyncio
from datetime import date

from ib_async import IB, Forex


async def load(end):
print(f"Loading {end}")
data = await ib.reqHistoricalDataAsync(
contract, endDateTime=end, durationStr="3 D", barSizeSetting="1 min",
whatToShow="MIDPOINT", useRTH=False, formatDate=2, keepUpToDate=False)
print(data[-1])


async def main():
tasks = [asyncio.create_task(load(date(2024, 12, 1))),
asyncio.create_task(load(date(2024, 12, 2)))]
await asyncio.gather(*tasks)
print('All done')


if __name__ == "__main__":
ib = IB()
ib.connect(host='127.0.0.1', port=4001, clientId=1)
contract = Forex("GBPUSD", 'IDEALPRO')
ib.qualifyContracts(contract)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
I don't understand asyncio well, nor how it works within ib_async. So, I'm stuck here. Could anyone point out where I'm wrong??
?
?


 

I ran your code and got the following output:?
?
Loading 2024-12-01
Loading 2024-12-02
BarData(date=datetime.datetime(2024, 12, 2, 6, 59, tzinfo=datetime.timezone.utc), open=1.270505, high=1.270505, low=1.27045, close=1.27047, volume=-1.0, average=-1.0, barCount=-1)
BarData(date=datetime.datetime(2024, 12, 3, 6, 59, tzinfo=datetime.timezone.utc), open=1.265025, high=1.265035, low=1.26496, close=1.264965, volume=-1.0, average=-1.0, barCount=-1)
All done
?
What errors are you receiving?


 

Hey Christian,?
?
Sorry, I since realized that your issue is with timeouts, not errors. Perhaps one of these settings will solve the problem:
?
ib.connect('127.0.0.1',7497, clientId=1, timeout=0) # 0 seconds=indefinite --- initial connect timeout – If establishing the connection takes longer than timeout seconds then the asyncio.TimeoutError exception is raised. Set to 0 to disable timeout.
?
ib.setTimeout(timeout=600) # --- Set a timeout for receiving messages from TWS/IBG, emitting timeoutEvent if there is no incoming data for too long.


 

ib.reqHistoricalDataAsync takes timeout parameter, set it to 0 and this method will not time out.