ib_async library, you know the frustration of a connection that succeeds for a split second, only to drop immediately. You see the "Connected" message, maybe a quick flash of market data, and then—disconnected.
This is one of the most common and maddening issues faced by algorithmic traders using IBKR's API. The root cause usually isn't your code; it's a mismatch between how ib_async handles asynchronous I/O and how IBGateway manages its connection pool.
In this guide, we'll break down exactly why this happens, how to fix it without rewriting your entire bot, and when it's better to switch to TWS instead of IBGateway.
About this guide: I'm Lawrence, the writer behind supa.is. Between February and May 2026 I've published 150+ articles on supa.is across crypto and brokerage tooling — including 30+ IBKR-specific guides (recent examples: IBKR Python API Connection Timeout: 8 Common Fixes, Fix IBKR API Combo (BAG) Market Data NaN Bug, Fix IBKR API calculateImpliedVolatility Timeout). The most-repeated reader question across that IBKR archive is exactly why ib_async drops the connection right after connecting, which is why I'm publishing this standardized guide instead of answering one-off.
Why Does ib_async Drop the Connection to IBGateway?
To understand the fix, you have to understand the architecture. ib_async is a Python wrapper around the official IBKR TWS API. It uses asyncio to make API calls non-blocking. IBGateway, on the other hand, is a stripped-down version of TWS designed specifically for API connections.
When ib_async connects, it establishes a socket connection. Under the hood, it sends a handshake, authenticates, and then begins polling for responses. The "immediate drop" issue occurs because IBGateway is notoriously sensitive to connection timeouts and idle socket states. If ib_async takes too long to initialize its internal event loop, or if IBGateway's API connection settings are configured to drop idle connections aggressively, the gateway will sever the link before your bot can even request its first tick of data.
There are three primary culprits for this specific behavior:
- IBGateway API Connection Timeout Settings: IBGateway has a built-in mechanism to drop connections if it doesn't receive data within a certain timeframe.
- The "Read Only" API Mode Conflict: If your bot connects in read-only mode but immediately tries to place an order or request a subscription that requires write permissions, IBGateway will terminate the session.
- Python Event Loop Blockage: If your
ib_asyncscript blocks the main thread (e.g., using synchronousrequestsortime.sleep()instead ofasyncio.sleep()), the API connection will time out and drop.
Solution 1: Adjust IBGateway API Timeout Settings
The most common fix for the immediate disconnect is to adjust the API connection settings within IBGateway itself. IBGateway is designed to be lightweight, which means it doesn't hold connections open indefinitely if it thinks they are inactive.
When you launch IBGateway, you will see a login screen. Before you log in, look for the API settings. Depending on your version of IBGateway, these settings might be in the "Configure" tab or accessible via the "Settings" menu.
You need to ensure that the "Allow connections from localhost only" is checked if you are running the script on the same machine. More importantly, look for any settings related to API connection timeouts or idle connection drops. If you have these enabled, disable them.
If you are using the IBKR API Gateway (the standalone Java application), you can configure the api.port and api.timeout in the configuration file. Increasing the timeout from the default (usually around 30-60 seconds) to 300 seconds or higher gives ib_async enough breathing room to initialize its event loop without getting kicked off.
Solution 2: Verify Read-Only vs. Read/Write Permissions
A surprisingly common reason for a sudden disconnect is a permissions mismatch. When you initialize ib_async, you specify whether the connection should be read-only or read/write.
from ib_async import IB
ib = IB()
ib.connect('127.0.0.1', 7497, clientId=1, readonly=False)
If you set readonly=True but your code immediately tries to subscribe to a streaming data feed that requires a higher tier of market data subscription, or if you attempt to place an order, IBGateway will recognize the unauthorized action and drop the connection to protect the account.
Conversely, if you set readonly=False but your IBKR account is not authorized for API trading (which is a separate setting in the IBKR client portal), the gateway will authenticate the connection but drop it the moment it tries to establish a write channel.
Like what you're reading? Try it yourself — this link supports ChartedTrader at no cost to you.
Open an IBKR Account →- Ensure your IBKR account has API trading enabled in the client portal (Settings > API > Settings > Enable API).
- In your
ib_asyncconnection string, explicitly setreadonly=Falseif you intend to trade, andreadonly=Trueif you are only pulling historical data.
Solution 3: Don't Block the Asyncio Event Loop
This is where the "async" in ib_async matters. The library is built on Python's asyncio. If you write synchronous code inside an asynchronous function, you freeze the event loop. When the event loop freezes, it cannot process the incoming socket data from IBGateway. IBGateway assumes the connection is dead and drops it.
async def main():
ib = IB()
await ib.connectAsync('127.0.0.1', 7497, clientId=1)
print("Connected")
time.sleep(10) # BLOCKS THE EVENT LOOP! Connection drops.
Good Code:
async def main():
ib = IB()
await ib.connectAsync('127.0.0.1', 7497, clientId=1)
print("Connected")
await asyncio.sleep(10) # Non-blocking. Connection stays alive.
If your script relies on external libraries that are not async-friendly (like requests or pandas for data manipulation), ensure you are running them in a separate thread using asyncio.to_thread() or loop.run_in_executor(). Blocking the main thread is the fastest way to get your API connection kicked out of IBGateway.
Solution 4: Switch from IBGateway to TWS
If you have tried adjusting the timeouts, verified your permissions, and ensured your event loop isn't blocked, but ib_async still drops the connection, the issue might be inherent to IBGateway's architecture.
IBGateway is designed for simple, lightweight connections. It lacks the robustness of the full TWS (Trader Workstation) application. TWS has a much larger memory footprint and a more sophisticated connection manager that is far more tolerant of ib_async's polling and event-loop behaviors.
If you are running a serious algorithmic trading bot, you should probably be using TWS, not IBGateway.
To switch:
- Download and install the full TWS application from the IBKR website.
- Log in to TWS.
- Go to Configure > API > Settings.
- Ensure "Enable ActiveX and Socket Clients" is checked.
- Change your
ib_asyncconnection port from7497(IBGateway default) to7497or4001(TWS default, depending on your configuration).
clientId (e.g., you have another script or the TWS API window open using the same clientId).
Common ib_async Errors That Look Like Connection Drops
Sometimes, what looks like a connection drop is actually an ib_async error that terminates the script. Here are a few to watch out for:
* ConnectionError: Connection timed out: This usually means your firewall is blocking the outbound connection from your Python script, or your inbound connection to IBGateway. Ensure port 7497 is open.
AuthenticationError: Your API key or credentials are incorrect. IBGateway will let the connection initiate but drop it during the handshake.
* RuntimeError: Event loop is closed: This means your script finished executing before the async connection could be properly closed. Always use ib.disconnect() at the end of your script.
Best Practices for Stable ib_async Connections
Once you've fixed the immediate drop issue, you want to ensure your connection stays stable over long trading sessions. Here are some best practices:
- Use
connectAsyncinstead ofconnect: The asynchronous connection method is much more reliable for establishing the initial handshake without timing out. - Implement Reconnection Logic: API connections drop. It happens. Write a
try/exceptblock around your connection logic and implement a retry mechanism with an exponential backoff. - Keep the Client ID Unique: If you have multiple scripts running, ensure each has a unique
clientId. If two scripts useclientId=1, IBGateway will drop the second connection. - Monitor Memory Usage:
ib_asynccan leak memory if you don't properly unsubscribe from tick data. Always useib.reqTickers()and unsubscribe when you are done, or useib.reqMktData()with proper error handling.
FAQ
Why does ib_async disconnect immediately after connecting to IBGateway?
The most common reason is that IBGateway's API timeout settings are too aggressive, or your Python script is blocking the asyncio event loop (e.g., usingtime.sleep() instead of asyncio.sleep()), causing IBGateway to assume the connection is dead and drop it.
Should I use IBGateway or TWS for ib_async?
For simple, read-only scripts, IBGateway is fine. For active trading, order placement, or long-running bots, TWS is significantly more stable and less likely to drop connections unexpectedly.How do I fix an ib_async "Connection timed out" error?
Ensure that port 7497 is not blocked by your firewall, that IBGateway is actually running and listening on that port, and that you are usingconnectAsync rather than the synchronous connect method.
Can I run multiple ib_async scripts at the same time?
Yes, but each script must use a uniqueclientId. If two scripts use the same clientId, IBGateway will terminate the connection from the second script.
Does ib_async require an internet connection to IBKR's servers?
No.ib_async connects locally to IBGateway or TWS running on your machine. It does not connect directly to IBKR's servers. However, IBGateway/TWS must be logged in and connected to IBKR.
Risk Warning
Risk Warning: Crypto trading and algorithmic trading involve substantial risk of loss. Automated trading bots can execute trades rapidly without human intervention, potentially leading to significant financial losses if the code contains bugs or the API connection drops unexpectedly. Never invest more than you can afford to lose. This is not financial advice.
If you are ready to start building your algorithmic trading infrastructure, you need a robust brokerage that supports API trading with low latency and high reliability. Interactive Brokers is the industry standard for this.
Open an IBKR Account