erdewit / ib_insync

Python sync/async framework for Interactive Brokers API
BSD 2-Clause "Simplified" License
2.76k stars 726 forks source link

RuntimeError: This event loop is already running #619

Closed ascripter closed 11 months ago

ascripter commented 11 months ago

I'm aware of this issue with the same, but mine is different. This code:

from ib_insync import *
ib = IB()
ib.connect('127.0.0.1', 4001, clientId=1)  # IB gateway

raises this traceback

Traceback (most recent call last):

  Cell In[3], line 1
    ib.connect('127.0.0.1', 4001, clientId=1)  # IB gateway

  File ~\.conda\envs\ib\lib\site-packages\ib_insync\ib.py:279 in connect
    return self._run(self.connectAsync(

  File ~\.conda\envs\ib\lib\site-packages\ib_insync\ib.py:318 in _run
    return util.run(*awaitables, timeout=self.RequestTimeout)

  File ~\.conda\envs\ib\lib\site-packages\ib_insync\util.py:341 in run
    result = loop.run_until_complete(task)

  File ~\.conda\envs\ib\lib\asyncio\base_events.py:623 in run_until_complete
    self._check_running()

  File ~\.conda\envs\ib\lib\asyncio\base_events.py:583 in _check_running
    raise RuntimeError('This event loop is already running')

RuntimeError: This event loop is already running

I'm using python 3.9.17 on windows 10, ib_insync version 0.9.86 from pip install ib_insync. I was suspecting maybe some parallel thread spawned from a previous call was responsible, but it happens already after rebooting the PC, removing and re-installing conda env, launching spyder, then running this code. Even the IB Gateway was not opened in this case, so ~2 seconds later I get an additional output after the traceback:

API connection failed: ConnectionRefusedError(10061, "Connect call failed ('127.0.0.1', 4001)")
Make sure API port on TWS/IBG is open

That means something still happens even though I get the RuntimeError. Also when calling other methods like ib.reqScannerData (when IB Gateway is active), I also get the same RuntimeError with additional print out:

Error 162, reqId 3: Historical Market Data Service error message:API scanner subscription cancelled: 3

The peculiar thing is: I think in the beginning I got it working once to get a valid connection; but I wouldn't bet on it.

Any ideas what's wrong here?

erdewit commented 11 months ago

There might be multiple threads with multiple event loops running.