ib_insync vs ib_async: Python 3.14 Error and Migration
Updated: 3 hours ago

AI Summary: ib_insync vs ib_async on Python 3.14: ib_insync is archived and no longer updated, and in our clean-environment tests on Python 3.14 even importing it fails with “There is no current event loop in thread 'MainThread'”. Setting an event loop before the import is a stopgap. ib_async, the maintained continuation, connects normally on 3.14 and for most code the migration is a package swap, an import rename and a paper-account retest. After you migrate, handle TWS API disconnects around the IB Gateway daily logoff or auto restart, throttle historical data to avoid an IBKR pacing violation, and treat error 162, 200, 354 and 10197 as distinct fixes. A Client Portal API session times out unless you call /tickle regularly; the IBKR Web API still offers OAuth 1.0a and OAuth 2.0 for different account types. ib_async can also request an options chain with reqSecDefOptParams and place a bracket order or trailing stop. |
If you run Python against Interactive Brokers’ TWS API, you’ve probably used ib_insync. It was the default IBKR Python library for years. It is no longer maintained, and on Python 3.14 the classic script that imports it and calls IB().connect(...) now crashes before it reaches the Gateway. This post covers ib_insync vs ib_async: what breaks, why, a stopgap if you can’t migrate today, and the migration itself. Everything below was tested on real versions, not copied from changelogs.
Running IB Gateway unattended as well? Read our headless IB Gateway in Docker guide next.
Tested on (22 November 2026) | Version |
Python | 3.14.7 and 3.14.10 (Linux, clean virtual environments) |
ib_insync / eventkit | 0.9.86 / 1.0.3 |
ib_async / aeventkit | 2.1.0 / 2.1.0 |
The error: “There is no current event loop in thread 'MainThread'”
This is the minimal script that used to work everywhere:
from ib_insync import IB
ib = IB()
ib.connect("127.0.0.1", 4002, clientId=1) # paper IB GatewayOn Python 3.14 it fails on the very first line, before it ever reaches the Gateway:
File ".../ib_insync/__init__.py", line 6, in <module>
File ".../eventkit/__init__.py", line 3, in <module>
File ".../eventkit/event.py", line 9, in <module>
File ".../eventkit/util.py", line 24, in <module>
File ".../eventkit/util.py", line 21, in get_event_loop
File ".../asyncio/events.py", line 718, in get_event_loop
RuntimeError: There is no current event loop in thread 'MainThread'.Two things are worth knowing before you debug it:
It fails at import, not at connect. ib_insync imports eventkit, and eventkit 1.0.3 asks asyncio for an event loop the moment it loads. On Python 3.14 there is no loop yet, so from ib_insync import IB raises. On Python 3.13 the same script only prints a DeprecationWarning (“There is no current event loop”) and keeps working, which is why this error often shows up right after a Python upgrade in production.
Async code works if the import happens inside the loop. If you move the import inside an async function started with asyncio.run(...) and use await ib.connectAsync(...), it connects normally, because a loop exists by then. Importing at the top of the module, before asyncio.run, still fails.
Why it happens on Python 3.14
ib_insync and eventkit find the event loop through asyncio.get_event_loop_policy().get_event_loop(). Older Python versions quietly created a loop if none existed. Python 3.12 started warning about this (on 3.13 you get a DeprecationWarning: There is no current event loop). Python 3.14 stops creating one and raises RuntimeError instead. Because ib_insync and the original eventkit are archived on GitHub, they won’t be patched.
Heads-up for Python 3.16. Python 3.14 also deprecates the asyncio policy system, including asyncio.get_event_loop_policy(), which is “slated for removal in Python 3.16”. In our tests ib_async 2.1.0 still calls it and prints that DeprecationWarning, even though it works today. Pin your version, watch the ib_async releases, and run your test suite with warnings visible (python -W default) before moving to 3.16.
Which Python library are you migrating to after the ib_insync compatibility issues with Python 3.14?
ib_async – Migrating to the actively maintained alternative
ib_insync – Staying with the existing library
Custom solution – Building my own Interactive Brokers integr
Still evaluating – Need to understand the migration process
Stopgap: make ib_insync work on 3.14 today
If you can’t migrate this week, either of these gets you running again. We tested both: each one got past the import and reached the Gateway socket.
# Option 1: create and set a loop BEFORE importing ib_insync
import asyncio
asyncio.set_event_loop(asyncio.new_event_loop())
from ib_insync import IB
ib = IB()
ib.connect("127.0.0.1", 4002, clientId=1)# Option 2: go async, and import inside the running loop
import asyncio
async def main():
from ib_insync import IB
ib = IB()
await ib.connectAsync("127.0.0.1", 4002, clientId=1)
...
asyncio.run(main())These are stopgaps, not fixes. Both still trigger the 3.16 deprecation warning, and you’re still on an unmaintained library that won’t get new TWS API features or bug fixes.
Is ib_insync still maintained? No. Use ib_async
ib_async is the community-maintained continuation of ib_insync, published by the ib-api-reloaded project (github.com/ib-api-reloaded/ib_async). The original ib_insync repository is archived. Interactive Brokers’ own TWS API documentation says ib_insync is no longer updated and points users who want that structure to ib_async, while noting that IBKR doesn’t provide coding support for either package. The API is almost identical. In our test, the same synchronous script connects normally on Python 3.14 after switching the import.
Migrating from ib_insync to ib_async in three steps
1. Swap the dependency. Pin an exact version you have tested. ib_async 2.1.0 needs Python 3.10 or newer.
# requirements.txt
- ib_insync==0.9.86
+ ib_async==2.1.0 # pin what you tested2. Rename the imports. For most code this is the whole change.
- from ib_insync import IB, Stock, Option, LimitOrder, util
+ from ib_async import IB, Stock, Option, LimitOrder, util3. Retest the parts that differ.
Event-loop patches. ib_async uses aeventkit instead of eventkit. If you call util.startLoop() or util.patchAsyncio() (common in Jupyter), or use nest_asyncio, retest those paths.
Warning vs error codes. The two libraries don’t treat exactly the same IBKR message codes as warnings. In ib_async 2.1.0, codes 105, 321 and 329 are logged as warnings, and 202 (order cancelled) is no longer in the warning list as it was in ib_insync 0.9.86. If your code reacts to any of these, check that it still sees them the way it expects.
A full order cycle on paper. Against a paper IB Gateway (port 4002): connect, contract lookup, quote, place order, fill, cancel, reconnect. Only then deploy.
On the trading system we migrated, the code change took minutes. Most of the hour went on re-running integration tests against the paper Gateway.
ib_insync vs ib_async at a glance
ib_insync | ib_async | |
Maintained | No (repository archived) | Yes (ib-api-reloaded) |
Import and sync connect() on Python 3.14 | Fails at import: “no current event loop” | Works (tested on 2.1.0) |
Async connectAsync() on 3.14 | Works only if imported after a loop exists | Works |
Event library | eventkit | aeventkit |
API surface | Original | Nearly identical; imports renamed |
Python 3.16 readiness | Will not be updated | Still calls a deprecated asyncio API in 2.1.0; watch releases |
Handling TWS API disconnects in ib_async
A TWS API disconnect is not one event. Your Python client can lose its socket to TWS or IB Gateway, or the Gateway can stay up while IBKR’s servers drop away and come back. ib_async exposes both: disconnectedEvent when the client socket closes, and errorEvent for the system codes IBKR sends on the still-open connection.
IBKR documents three system codes you should handle explicitly:
1100 — Connectivity between IB and TWS has been lost. This can be an internet issue, a nightly reset of IBKR’s servers, or a competing session.
1101 — Connectivity has been restored, but market data subscriptions were lost and must be submitted again.
1102 — Connectivity has been restored and market data subscriptions were maintained, so you do not need to resubscribe.
When the socket itself drops — which is what happens during an IB Gateway auto restart — subscribe to disconnectedEvent and start a reconnect loop with connectAsync. ib_async’s docs warn that placing new requests inside an event handler can recurse, so schedule the reconnect as a separate task:
import asyncio
from ib_async import IB
HOST, PORT, CLIENT_ID = "127.0.0.1", 4002, 1 # paper IB Gateway
ib = IB()
async def connect_with_retry():
while not ib.isConnected():
try:
await ib.connectAsync(HOST, PORT, clientId=CLIENT_ID)
# Re-subscribe to market data after a clean reconnect.
break
except Exception:
await asyncio.sleep(5)
def on_disconnected():
# Do not call connectAsync directly inside the handler.
asyncio.get_running_loop().create_task(connect_with_retry())
def on_error(reqId, errorCode, errorString, contract):
if errorCode == 1101:
# Data lost after a server-side reset: resubscribe.
pass
elif errorCode == 1102:
# Data maintained: no resubscribe needed.
pass
ib.disconnectedEvent += on_disconnected
ib.errorEvent += on_errorIB Gateway auto restart and daily logoff
IB Gateway and TWS are configured to log off each day at 11:45 PM local time. You can change that time under Configure (or Global Configuration in TWS) → Lock and Exit, using the Auto Logoff Timer. For API use, IBKR recommends Never lock Trader Workstation and Auto restart, so the application comes back without a fresh login. That auto-restart is a local Gateway setting, not the same event as IBKR’s nightly server reset (the 1100 / 1101 / 1102 sequence above).
You still have to plan for weekly reauthentication. IBKR says the weekly authentication cycle starts every Monday, and a failed login with a message about a soft token instead of a permanent one means you need to log in manually again. Auto restart does not remove that weekly step. See IBKR’s daily and weekly reauthentication notes and its IB Gateway auto logoff FAQ.
IBC IB Gateway headless and IB Gateway Docker
IBC, the usual tool for a headless IB Gateway login, was retired and its repository archived on 1 September 2026. Releases can still be downloaded, but there is no new development. We cover how to run a headless IB Gateway in Docker, auto restart, 2FA and reconnects in a separate guide, so we will not repeat that setup here: Headless IB Gateway in Docker. Your ib_async client still has to reconnect on its own after each restart, using the pattern above.
IBKR pacing violation for historical data
If you pull historical bars with ib_async’s reqHistoricalData and suddenly get a failed request, check whether you hit an IBKR pacing violation. IBKR documents these limits for historical bars of 30 seconds or less; they apply to all clients and cannot be changed:
Do not make identical historical data requests within 15 seconds.
Do not make six or more historical data requests for the same contract, exchange and tick type within two seconds.
Do not make more than 60 requests within any ten-minute period.
BID_ASK historical data is counted twice.
Those rules are in IBKR’s historical market data limitations. A pacing problem is usually reported as error 162 (historical market data service error), with the reason in the message text. Queue requests through one place, space out identical retries, and cache bars you already have so you are not asking for the same window again.
from ib_async import IB, Stock
ib = IB()
ib.connect("127.0.0.1", 4002, clientId=1)
contract = ib.qualifyContracts(Stock("IBM", "SMART", "USD"))[0]
# Small bars (30 secs or less) are the ones IBKR paces as above.
bars = ib.reqHistoricalData(
contract,
endDateTime="",
durationStr="1800 S",
barSizeSetting="5 secs",
whatToShow="TRADES",
useRTH=False,
formatDate=1,
)IBKR API error 162, 200, 354 and 10197
Subscribe to ib.errorEvent and branch on the numeric code. These four come up constantly once you are past the import error. Meanings below are from IBKR’s TWS API error codes:
Code | IBKR message | What to do |
162 | Historical market data Service error message. | Read the message text. If it is a pacing violation, wait and retry; if it is permissions or no data for that period, fix the request or the account instead. |
200 | No security definition has been found, or the contract description is ambiguous. | Check symbol, expiry, strike, right and exchange. For stocks that share a symbol, set primaryExchange. For futures with more than one multiplier, set multiplier. |
354 | Requested market data is not subscribed. | The account does not have live market data for that instrument. Check Market Data Subscription Manager, or enable delayed data if that is enough. |
10197 | No market data during competing session. | You are logged into a paper account and a live account at the same time and both are asking for live data. IBKR gives priority to the live session. Log out of the competing live session, or use a separate username with its own market data subscription. |
Error 10197 is easy to misread as a broken ib_async install. It is a session conflict, documented by IBKR, not a Python 3.14 issue. See also IBKR’s notes on logging into multiple applications.
ib_insync not working? A short checklist
If ib_insync is not working, walk the list in order. Most failures after a Python upgrade are the import error at the top of this article; the rest are connection, contract or data issues that ib_async will hit in the same way.
Confirm the Python version. On 3.14, from ib_insync import IB fails before it reaches the Gateway. Use the stopgap above or migrate to ib_async.
Confirm you are importing ib_async, not ib_insync, after the package swap, and that the environment you run is the one you installed into.
Confirm TWS or IB Gateway is running, API connections are enabled, and the port matches: 4001 live / 4002 paper for IB Gateway, 7496 live / 7497 paper for TWS.
Use a unique clientId. A second client with the same id will not connect cleanly.
If connect() itself fails, check the daily logoff and auto-restart window, then reconnect with the disconnectedEvent loop above.
If you are connected but quotes or history fail, check errors 162, 200, 354 and 10197 rather than assuming the library is broken.
The ib_async vs ib_insync comparison in the table above still holds after these fixes: the API is nearly identical, ib_async is the maintained package, and you should retest event-loop patches and a full paper-account order cycle before you deploy.
Client Portal API session timeout and IBKR Web API OAuth
The TWS API (ib_async talking to TWS or IB Gateway) is not the only IBKR interface. The Web API, also called the Client Portal API, is a REST interface with its own session rules. If you mix the two, or you keep a Web API session open for account and model calls, the timeout behaviour is different from a Gateway socket.
IBKR’s authentication FAQ says a brokerage session can remain authenticated for up to 24 hours, resetting at midnight in New York, Zug or Hong Kong depending on your nearest connection. It will time out sooner after approximately six minutes with no new requests, or if you do not call /tickle at least every five minutes. In the same note, IBKR says a Web API brokerage session times out if no requests arrive within five minutes, and it recommends calling /tickle about once a minute. Daily server maintenance can also disconnect you earlier than the 24-hour mark.
If the session has timed out but is still connected to IBKR’s backend, GET /iserver/auth/status returns connected: true and authenticated: false. Re-initialise the brokerage session with POST /iserver/auth/ssodh/init (IBKR’s documented body uses compete: true and publish: true). A typical keep-alive looks like this:
import requests
# Production host; the Client Portal Gateway uses https://localhost:5000
base = "https://api.ibkr.com/v1/api"
headers = {"Authorization": f"Bearer {bearer_token}"}
requests.post(f"{base}/tickle", headers=headers)
status = requests.get(f"{base}/iserver/auth/status", headers=headers).json()
if status.get("connected") and not status.get("authenticated"):
requests.post(
f"{base}/iserver/auth/ssodh/init",
headers={**headers, "Content-Type": "application/json"},
json={"compete": True, "publish": True},
)On OAuth, the IBKR Web API has three authentication methods, and they are not interchangeable. Per IBKR’s Web API authentication introduction:
Client Portal Gateway — the standard path for individual accounts, a Java client that reverse-proxies SSO.
OAuth 1.0a — the only supported authentication method IBKR lists for third-party developers. It is also available to advisor, broker, proprietary trading, hedge and mutual fund, and institutional accounts.
OAuth 2.0 — a programmatic flow for advisor, broker and FCM, proprietary trading, hedge and mutual fund, and institutional hedge fund investor accounts. IBKR notes that account-management endpoints are only available through OAuth 2.0 for advisor and broker account types. Individual accounts are not in the OAuth 2.0 list.
OAuth 2.0 has not replaced OAuth 1.0a. Choose the method that matches the account type; third-party developers should follow OAuth 1.0a unless IBKR has onboarded them on a different path.
Options chain with the IBKR API
To request an options chain, do not pull every contract with reqContractDetails. IBKR says that path is throttled for large, incomplete option definitions, and recommends reqSecDefOptParams instead. In ib_async the same call is ib.reqSecDefOptParams(underlyingSymbol, futFopExchange, underlyingSecType, underlyingConId). Pass an empty string for futFopExchange to include all exchanges. The result is a list of OptionChain objects, each with an exchange, trading class, multiplier, expirations and strikes. IBKR notes that some strike and expiry combinations still will not be a valid contract, so qualify the option before you use it.
from ib_async import IB, Stock, Option
ib = IB()
ib.connect("127.0.0.1", 4002, clientId=1)
underlying = ib.qualifyContracts(Stock("IBM", "SMART", "USD"))[0]
chains = ib.reqSecDefOptParams(
underlying.symbol,
"", # all exchanges
underlying.secType,
underlying.conId,
)
chain = next(c for c in chains if c.tradingClass == underlying.symbol)
expiry = sorted(chain.expirations)[0]
strike = sorted(chain.strikes, key=lambda s: abs(s - 100))[0]
option = Option(underlying.symbol, expiry, strike, "C", "SMART")
option = ib.qualifyContracts(option)[0]The strike in the sample is just a picker; use the underlying price you actually care about. Official request details are in IBKR’s option chain documentation. For a multi-account options desk that also uses FA allocation, see our IBKR FA allocation guide and the options trading automation case study.
Bracket order and trailing stop with the IBKR API
A bracket order is a parent limit order plus a take-profit limit and a stop-loss, linked so that filling the parent activates the children and one child cancels the other. IBKR’s important detail is the transmit flag: set it to false on the parent and the take-profit, and true on the last child, so TWS sends the whole bracket together and no leg can fill before the others are in place. ib_async wraps that in ib.bracketOrder(), which returns a parent LimitOrder, a take-profit LimitOrder and a StopOrder:
from ib_async import IB, Stock
ib = IB()
ib.connect("127.0.0.1", 4002, clientId=1)
contract = ib.qualifyContracts(Stock("IBM", "SMART", "USD"))[0]
bracket = ib.bracketOrder(
action="BUY",
quantity=100,
limitPrice=50,
takeProfitPrice=55,
stopLossPrice=48,
)
for order in bracket:
ib.placeOrder(contract, order)A trailing stop is a different order type. IBKR’s TWS API trailing-stop docs require a trail offset: trailingPercent for a percentage (for example 2 means 2%, not 0.02) or auxPrice for an absolute offset, and optionally trailStopPrice for the initial stop. You can also use a trailing stop as the stop-loss child of a bracket by building the third order yourself, with parentId set and transmit=True:
from ib_async import IB, Stock, LimitOrder, Order
parent = LimitOrder("BUY", 100, 50, orderId=ib.client.getReqId(), transmit=False)
take_profit = LimitOrder(
"SELL", 100, 55,
orderId=ib.client.getReqId(),
transmit=False,
parentId=parent.orderId,
)
trailing_stop = Order(
action="SELL",
orderType="TRAIL",
totalQuantity=100,
trailingPercent=2, # 2%
trailStopPrice=48,
orderId=ib.client.getReqId(),
parentId=parent.orderId,
transmit=True, # last child transmits the whole bracket
)
for order in (parent, take_profit, trailing_stop):
ib.placeOrder(contract, order)Test bracket and trailing-stop orders on a paper account first. Official samples are in IBKR’s bracket order and trailing stop documentation.
FAQ
Is ib_insync still maintained?
No. ib_insync is no longer updated and its repository is archived. Its maintained continuation is ib_async, published by the ib-api-reloaded project, and Interactive Brokers’ own API documentation points ib_insync users to it. For new code, start with ib_async.
Does ib_insync work on Python 3.14?
Not out of the box. In our tests on Python 3.14.7 and 3.14.10, ib_insync 0.9.86 with eventkit 1.0.3 fails as soon as it is imported, with “RuntimeError: There is no current event loop in thread 'MainThread'”. It only runs if an event loop already exists when you import it.
How do I fix “There is no current event loop” in ib_insync?
Migrate to ib_async, which connects normally on Python 3.14. As a short-term stopgap, create and set an event loop before importing ib_insync, with asyncio.set_event_loop(asyncio.new_event_loop()), or import it inside an async function started with asyncio.run and use connectAsync.
Is ib_async a drop-in replacement for ib_insync?
Almost. For most code you change the package name and the imports. Retest anything that patches the event loop, anything that depends on which IBKR error codes are treated as warnings, and run a full order cycle against a paper account before deploying.
Why do TWS API disconnects happen, and how do I reconnect with ib_async?
The client socket can drop when IB Gateway logs off or auto-restarts, and IBKR also sends 1100, then 1101 or 1102, when connectivity between the Gateway and IBKR’s servers is lost and restored (for example during a nightly reset). Subscribe to ib.disconnectedEvent and start a reconnect task that calls connectAsync in a loop; do not place that request inside the event handler itself. After a 1101 message, resubscribe to market data.
What is an IBKR pacing violation for historical data?
IBKR documents pacing violations for historical bars of 30 seconds or less: do not repeat an identical request within 15 seconds, do not make six or more requests for the same contract, exchange and tick type within two seconds, and do not make more than 60 requests in any ten-minute period. BID_ASK requests count twice, and these limits cannot be raised. A pacing problem usually arrives as error 162; read the message text before you retry.
What do IBKR API errors 162, 200, 354 and 10197 mean?
Error 162 is IBKR’s general historical market data service error; the message text tells you whether the cause is pacing, permissions or missing data. Error 200 means no security definition was found, or the contract is ambiguous — add primaryExchange or multiplier. Error 354 means you are not subscribed to the requested market data. Error 10197 means there is no market data during a competing session, typically when a paper session and a live session both request live data and the live session takes priority.
How do I stop a Client Portal API session timeout?
IBKR says a Web API brokerage session times out after about five to six minutes with no requests, unless you call the /tickle endpoint at least every five minutes (they recommend about once a minute). A session can otherwise last up to 24 hours, resetting at midnight in New York, Zug or Hong Kong depending on your nearest connection. If /iserver/auth/status returns connected: true and authenticated: false, re-initialise the brokerage session with POST /iserver/auth/ssodh/init.
How do I request an options chain or place a bracket order with the IBKR API in ib_async?
Qualify the underlying, then call ib.reqSecDefOptParams(symbol, "", secType, conId). That returns expirations and strikes per exchange; not every combination is a valid contract, so qualify the option before you quote or trade it. For a bracket order, use ib.bracketOrder() and place the parent, take-profit and stop with placeOrder, which sets transmit=False until the last child. A trailing stop uses orderType "TRAIL" with trailingPercent or auxPrice.
Conclusion
If your IBKR code still imports ib_insync, Python 3.14 is the push to move. The stopgaps work, but ib_async is a near drop-in replacement with active maintenance, and the migration is mostly a rename plus a paper-account test run. Next, make sure the Gateway you connect to stays up: headless IB Gateway in Docker: daily restarts, 2FA and reconnects. For the wider picture of building on IBKR, see our guide to integrating the Interactive Brokers API with a fintech or trading platform.
We build and run production trading systems on Interactive Brokers. Our IBKR options trading automation case study shows one of them, built on ib_async. If you want a second pair of eyes on your migration, book a call with our team.





