ib_insync No Current Event Loop Error: Causes and Fixes
The ib_insync no current event loop error means the thread creating IB() has no asyncio loop, because get_event_loop() only auto-creates one in the main thread. Create a loop in that thread first, or move to ib_async.
- An IB object belongs to exactly one asyncio loop on exactly one thread, and every call on it must run there.
- In a worker thread, call asyncio.set_event_loop(asyncio.new_event_loop()) before creating IB(), then create IB inside that thread.
- In Jupyter or Spyder the loop is already running, so use await ib.connectAsync() or util.startLoop() instead of ib.connect() with asyncio.run().
- ib_insync is unmaintained; pip install ib_async and change the import, since the API is the same and newer Python versions are handled better.
- Use ib.sleep() rather than time.sleep(), and disconnect in a finally block so the clientId is released.
Why do I get the ib_insync no current event loop error?
The ib_insync no current event loop error comes from asyncio, not from Interactive Brokers. ib_insync is built on asyncio. When you create IB(), the library asks asyncio for a loop (util.getLoop(), which calls asyncio.get_event_loop()) and binds its connection, wrapper and event objects to it.
asyncio.get_event_loop() only creates a loop automatically in the main thread. In any other thread it raises RuntimeError: There is no current event loop in thread 'Thread-1'. Nothing is wrong with TWS or your credentials; the failure happens before any socket is opened.
The same call also runs at import time in older versions, because the eventkit dependency grabs a loop when the module loads. That is why importing ib_insync inside a worker thread can fail before you ever write IB().
The one rule that explains every variation: an IB object lives on one loop in one thread. If the thread has no loop, give it one. If the thread already has a running loop, do not start a second one, use the one you have.
Why did my old script break after upgrading Python?
Calling get_event_loop() with no running loop was deprecated in Python 3.10 and tightened in later releases. In 3.12 it emits a DeprecationWarning when no current loop is set, and in 3.14 it raises RuntimeError instead of creating one implicitly. Code that relied on the implicit loop, including old eventkit and ib_insync releases, stops working even in the main thread.
There are two fixes. Upgrade to ib_async, which is maintained against current Python, or create and set the loop yourself before anything binds to it.
ib_insync was left unmaintained after its author passed away in 2024. ib_async is the community fork, and the migration is mechanical.
pip uninstall ib_insync
pip install ib_async
# code change
# before: from ib_insync import *
# after: from ib_async import *Which fix matches my environment?
Find your row, apply the fix, then verify with the checks in the last section.
| Environment | Symptom | Fix |
|---|---|---|
| Plain script, Python 3.12+ | DeprecationWarning or RuntimeError on IB() | Upgrade to ib_async; or write async def main() and asyncio.run(main()) |
| Plain script, any version | Works, but data stops updating | Replace time.sleep() with ib.sleep() |
| Worker thread | There is no current event loop in thread | new_event_loop() + set_event_loop() inside the thread, then create IB() there |
| Jupyter / Spyder / IPython | This event loop is already running | await ib.connectAsync(), or util.startLoop() before ib.connect() |
| Jupyter | asyncio.run() cannot be called from a running event loop | Use top-level await instead of asyncio.run() |
| Streamlit / Flask / FastAPI | No current event loop in ScriptRunner or worker thread | One dedicated IB thread with its own loop, talk to it by queue or run_coroutine_threadsafe |
| Tkinter / Qt | GUI freezes or loop conflicts | util.useQt() for Qt, or run IB in its own thread |
| Reconnect after kernel restart | Error 326, clientId already in use | Disconnect in finally; use a unique clientId |
How do I run ib_insync or ib_async in a plain script?
The cleanest structure is a coroutine with explicit connect and disconnect. asyncio.run() creates and closes the loop for you, so it works on every Python version.
If you prefer synchronous style, ib.connect() and ib.run() still work in the main thread, but never call them from inside a running loop.
import asyncio
from ib_async import IB, Stock
async def main():
ib = IB()
try:
await ib.connectAsync('127.0.0.1', 7497, clientId=11)
contract = Stock('AAPL', 'SMART', 'USD')
await ib.qualifyContractsAsync(contract)
bars = await ib.reqHistoricalDataAsync(
contract, endDateTime='', durationStr='1 D',
barSizeSetting='5 mins', whatToShow='TRADES', useRTH=True)
print(len(bars), ib.isConnected())
finally:
ib.disconnect()
asyncio.run(main())How do I use ib_insync in a separate thread?
The thread must own a loop, and the loop must exist before the IB object does. Create the IB instance inside the thread and never hand it to another thread, because its internals are not thread-safe.
Calling ib methods from another thread touches loop state from the wrong thread. To interact with it safely, submit work to the owning loop with asyncio.run_coroutine_threadsafe(), or loop.call_soon_threadsafe() for plain callbacks, or pass messages through a queue.
import asyncio, threading, queue
from ib_async import IB, Stock
class IBWorker(threading.Thread):
def __init__(self, client_id):
super().__init__(daemon=True)
self.client_id = client_id
self.loop = None
self.ready = threading.Event()
self.ib = None
def run(self):
self.loop = asyncio.new_event_loop()
asyncio.set_event_loop(self.loop) # BEFORE IB()
self.ib = IB()
self.loop.run_until_complete(
self.ib.connectAsync('127.0.0.1', 7497, self.client_id))
self.ready.set()
try:
self.loop.run_forever()
finally:
self.ib.disconnect()
self.loop.close()
def call(self, coro, timeout=30):
fut = asyncio.run_coroutine_threadsafe(coro, self.loop)
return fut.result(timeout)
def stop(self):
self.loop.call_soon_threadsafe(self.loop.stop)
w = IBWorker(client_id=21)
w.start(); w.ready.wait()
c = Stock('MSFT', 'SMART', 'USD')
print(w.call(w.ib.qualifyContractsAsync(c)))
w.stop()Why does Jupyter say this event loop is already running?
Jupyter, Spyder and IPython already run an asyncio loop in the main thread. ib.connect() is a synchronous wrapper that tries to run the loop until the connection completes, and a running loop cannot be re-entered. Likewise asyncio.run() refuses to start inside a running loop.
In a notebook with top-level await, the cleanest option needs no patching. If you want synchronous calls such as ib.connect() and ib.sleep() in a cell, call util.startLoop() once, which applies nest_asyncio-style re-entrancy.
# Option A: top-level await (no patching)
from ib_async import IB
ib = IB()
await ib.connectAsync('127.0.0.1', 7497, clientId=31)
print(ib.isConnected())
# ... work ...
ib.disconnect()
# Option B: synchronous style
from ib_async import IB, util
util.startLoop() # once per kernel, before connect
ib = IB()
ib.connect('127.0.0.1', 7497, clientId=32)How do I run IB inside Streamlit, Flask, FastAPI or a GUI?
These frameworks run your code in threads you do not control, or in their own loop. Streamlit re-executes the script on a ScriptRunner thread with no loop, Flask serves requests from worker threads, and FastAPI already owns a loop for async handlers.
The robust design is the IBWorker above: one long-lived thread, one loop, one IB, one clientId. Request handlers call w.call(...) or push commands onto a queue, and read results from another queue. In Streamlit, keep the worker in st.cache_resource so reruns do not spawn a new connection each time.
In FastAPI async endpoints you can instead share the server's loop: create IB in the startup lifespan, await connectAsync there, and await the Async methods in handlers. In Qt, call util.useQt() so the Qt loop drives asyncio, and in Tkinter keep IB in its own thread.
How do I connect cleanly and verify the loop and thread?
Check these settings first, since a correct loop does not help if TWS refuses the socket.
- In TWS or IB Gateway enable the API socket under Global Configuration, API, Settings (Enable ActiveX and Socket Clients). Untick Read-Only API if you place orders.
- Use the right port: 7497 TWS paper, 7496 TWS live, 4002 Gateway paper, 4001 Gateway live.
- Give every concurrent connection a unique clientId. Reusing one gives error 326, client id already in use, and a killed kernel may keep the id held until TWS notices.
- Wrap work in try/finally and call ib.disconnect() so the id is released.
- Print the loop and thread to confirm the one rule holds.
import asyncio, threading
print(threading.current_thread().name)
try:
print(asyncio.get_running_loop()) # only works inside a coroutine
except RuntimeError:
print('no running loop in this context')
print(ib.isConnected())
print(ib.client.conn.transport.get_extra_info('sockname') if ib.isConnected() else 'offline')Common questions
Is ib_async a drop-in replacement for ib_insync?
Yes for most code. Install it with pip install ib_async, change imports from ib_insync to ib_async, and the IB, Contract, Order and util APIs behave the same. It is the maintained fork, so it tracks newer Python versions.
Should I use util.startLoop() or nest_asyncio?
util.startLoop() is the library's own helper and applies the nest_asyncio patch for notebooks, so use it or await connectAsync, not both. Calling nest_asyncio.apply() directly is fine in Spyder or IPython, but do not stack it with startLoop or patchAsyncio.
Can I call asyncio.set_event_loop in the main thread instead?
You can, and on Python 3.12+ it avoids the deprecation warning, but it is simpler to use asyncio.run(main()). Whatever you choose, the loop must be set before IB() or any eventkit Event objects are created.
Why does the connection hang or drop when my script is idle?
The loop is not being run. With time.sleep() or a long CPU task, API messages are not read and heartbeats go unanswered. Use ib.sleep() or await asyncio.sleep(), and move heavy computation to an executor with loop.run_in_executor.
Can two threads share one IB instance?
No. Its sockets, wrapper state and events all belong to one loop. Use one IB per thread with different clientIds, or a single owner thread and run_coroutine_threadsafe from the others.