๐ŸŽ“ Tutorials

IB Python API Connection Timeout: 8 Common Fixes (2026)

โš ๏ธ Disclosure: Some links on this page are affiliate links. If you sign up through them, I may earn a commission โ€” at no extra cost to you. I only review tools I actually use.
# IB Python API Connection Timeout: 8 Common Fixes (2026)

> Disclosure: This guide contains an Interactive Brokers affiliate referral link. If you open an account through it we may earn a referral commission at no extra cost to you. The fixes below are not gated by that link in any way โ€” they apply equally whether you signed up via referral or any other channel.

> Note: The configuration steps below are reconstructed from the official Interactive Brokers TWS API documentation linked inline. The TWS and IB Gateway settings UI has shifted multiple times across releases โ€” verify each menu path against your installed version before relying on it.

You wired up a clean Python script. You called ib.connect('127.0.0.1', 7497, clientId=1). The terminal hangs, then prints something like TimeoutError: API connection failed or Couldn't connect to TWS. Confirm that "Enable ActiveX and Socket EClients" is enabled. Welcome to one of the most-Googled error messages in algorithmic trading.

The Interactive Brokers API is unusual among broker APIs: it does not expose a public cloud REST endpoint that you authenticate against directly. Your Python process opens a local TCP socket to a desktop application โ€” Trader Workstation (TWS) or IB Gateway โ€” that holds the authenticated session, and that desktop application then bridges to IB's servers (Interactive Brokers TWS API documentation, as of 2026-05). When the handshake fails, you generally get a timeout rather than a useful error code, because there is nothing on the wire to send a structured error back.

This guide walks the eight causes that cover almost every timeout reported by users of ib_insync (erdewit/ib_insync, as of 2026-05) and the official IB Campus knowledge base, roughly in the order they should be checked.

If you have not finished installing the API and getting your first script to talk to TWS, the prerequisite is to get a working setup running locally. Our IB Python API live-trading walkthrough covers that install path before troubleshooting begins.

A 30-second diagnostic

Before touching firewall rules, run this checklist top-to-bottom. The first four items resolve the bulk of timeouts that get posted on the IB API forum:

CheckWhat "good" looks like
Is TWS or IB Gateway open and fully logged in?Account number visible in the title bar
Is the API enabled in settings?"Enable ActiveX and Socket EClients" is checked (IB Campus TWS API docs, as of 2026-05)
Are you using the correct port?7496 / 7497 / 4001 / 4002 โ€” see table below
Are you using the correct host?127.0.0.1 (not localhost, not the LAN IP)
Is anything else holding the same clientId?Each connection needs a unique integer per IB's API rules
If those four pass and you still time out, work through the eight fixes below.

Fix 1 โ€” TWS or IB Gateway is not actually running

Sounds trivial. It accounts for a surprising fraction of forum-reported cases, especially after laptop sleep, a Windows update reboot, or the IB nightly maintenance window that knocks Gateway offline. The IB API documentation describes a periodic restart cadence on both TWS and Gateway (Interactive Brokers TWS API documentation, as of 2026-05).

Open the application and confirm:

If you run IB Gateway headless and use cron-like scheduling, allow time after process start before the first API call, since the login flow is multi-step (server discovery โ†’ 2FA โ†’ account load).

Fix 2 โ€” API is enabled but the wrong settings are checked

The TWS API Configuration documentation (Interactive Brokers TWS API documentation, as of 2026-05) describes the panel as File โ†’ Global Configuration โ†’ API โ†’ Settings in TWS, and Configure โ†’ Settings โ†’ API โ†’ Settings in IB Gateway. The settings most relevant to a timing-out connection, all per the same IB doc, are:

After changing API settings, restart TWS or IB Gateway, because several of these settings are read at startup.

Fix 3 โ€” Wrong port number

The single most common timeout cause referenced in community discussion is dialing the wrong default port. There are four possibilities, and they are not interchangeable. Defaults per the IB Campus TWS API documentation (as of 2026-05):

ApplicationModeDefault port
TWSLive7496
TWSPaper7497
IB GatewayLive4001
IB GatewayPaper4002
The defaults are configurable in the same API settings panel. Two trap doors:

1. You opened paper TWS to test, but your script still has port=7496 (live). The connection will time out because nothing is listening on 7496.

2. You migrated from TWS to IB Gateway for stability โ€” Gateway uses a different port range entirely.

Always log the port your script is dialing into. In ib_insync:

ib = IB()
ib.connect('127.0.0.1', 7497, clientId=1)
print(ib.isConnected(), ib.client.host, ib.client.port)

When the test is paper, the port is 7497. When you flip to live, it is 7496. If you forget, the timeout is your reminder.

Fix 4 โ€” Host string and IPv6 quirks

Use 127.0.0.1, not localhost. On some systems โ€” particularly Windows 11 with stricter network stacks, and macOS with certain VPN clients active โ€” localhost may resolve to an IPv6 address (::1) before falling back to IPv4. The IB API installer guidance (Interactive Brokers TWS API documentation, as of 2026-05) documents the loopback connection over IPv4 (127.0.0.1); if your script tries localhost โ†’ IPv6 lookup wins โ†’ the connection is refused โ†’ you see a timeout.

Hard-coding 127.0.0.1 removes the resolver from the path. If you need to connect across machines (a separate algo box dialing into a Gateway-host VM), set the trusted IPs explicitly in the API settings panel and use the LAN IP, but uncheck "Allow connections from localhost only" first โ€” leaving it checked while connecting from a remote host is another silent timeout per the same IB doc.

Fix 5 โ€” Client ID conflict

Each API client must use a unique clientId integer (Interactive Brokers TWS API documentation, as of 2026-05). If two scripts attempt to connect with the same ID, the second connection is rejected.

Common scenarios that trip this:

Fixes: If you run a strategy that auto-restarts on errors, derive each restart's ID from the process PID (modulo a small ceiling) so you do not collide with the previous instance during the brief overlap. Confirm the current cap on simultaneous clients per session in the Interactive Brokers TWS API documentation before relying on a hard number; the limit has changed historically.

Fix 6 โ€” Read-Only API blocking what you thought was a read

This one looks like a timeout but is, per IB's API documentation, actually a silent rejection of the order side of a request. With Read-Only API checked, calls that *attempt to place, modify, or cancel orders* are rejected by TWS (Interactive Brokers TWS API documentation, as of 2026-05). The order method may return an order ID locally but the order does not reach the matching engine, and dependent code (e.g. an ib.openOrders() poll) can hang waiting for an event that never arrives.

๐Ÿ’ก Interactive Brokers

Like what you're reading? Try it yourself โ€” this link supports ChartedTrader at no cost to you.

Open an Interactive Brokers account โ†’

If your script combines reads and writes, decide explicitly. For purely defensive use cases โ€” a portfolio dashboard, a P&L exporter โ€” leave read-only on. For active trading, uncheck it and accept the responsibility. There is no halfway position.

A related symptom: TWS Precautionary Settings โ€” order size limits, percentage-of-average-volume caps โ€” pop a confirmation dialog *in the GUI* when an API order exceeds them. For unattended algo runs, raise or disable these caps in advance per the IB user guide, then restart TWS. The dialog will not auto-dismiss.

Fix 7 โ€” Firewall, antivirus, or VPN intercepting the socket

Loopback traffic on 127.0.0.1 is normally exempt from firewalls, but several pieces of consumer security software intercept loopback as well. Items that recur in community discussion as of 2026-05:

Quickest test: temporarily disconnect the VPN, pause the antivirus, and retry. If the connection succeeds, you have your suspect. The fix is to whitelist the TWS or Gateway executable rather than to leave protections off permanently.

Fix 8 โ€” IB Gateway silently crashed or hit the daily restart

IB enforces a daily restart of TWS and IB Gateway during a maintenance window. The exact window is region-specific and configurable in the application's auto-restart settings, per the Interactive Brokers TWS API documentation (as of 2026-05). The application closes itself unless auto-restart is explicitly enabled in the configuration UI.

If your strategy runs unattended and you have not handled this:

Reconnection logic should treat any disconnect during a known maintenance window as expected, sleep through the documented re-login window, and only then retry. Reconnecting in a tight loop inside the restart window can both fail to connect and spam the client-ID space.

A separate failure mode: the Gateway's underlying Java process can run out of memory after many days of uptime, especially under a wide market-data subscription. The Gateway log directory (typically alongside the install folder) is the canonical place to look for OutOfMemoryError. The cheap mitigation is a scheduled nightly process restart well clear of IB's own restart window.

If you depend on the API for production order flow, add a watchdog: a separate thread that calls ib.reqCurrentTime() on a fixed interval and raises an alert if the call does not return promptly. The IB session can be alive but stale, and the watchdog catches it before the next order does.

A reusable reconnection pattern

Production IB Python code lives or dies on reconnect logic. The shape that follows IB's general disconnection guidance (Interactive Brokers TWS API documentation, as of 2026-05) is:

def connect_with_retry(host, port, client_id, max_attempts=10):
    backoff = 2
    for attempt in range(max_attempts):
        try:
            ib.connect(host, port, clientId=client_id, timeout=15)
            if ib.isConnected():
                return
        except Exception as e:
            print(f'attempt {attempt+1} failed: {e}')
        time.sleep(backoff)
        backoff = min(backoff * 2, 60)
    raise RuntimeError('IB connection failed after retries')

Two principles:

1. Cap the backoff at ~60 seconds so retries do not balloon to multi-minute waits during a fast-recovering blip.

2. Use a non-zero connect timeout so the call does not hang the entire process if Gateway is in a half-state. Fifteen seconds is plenty for a healthy local connection.

Pair this with the Flex Query Python pipeline for end-of-day reconciliation โ€” Flex Queries run against a separate IB endpoint and survive API socket outages, which makes them a useful independent ground truth for fills and positions.

When the timeout is actually a market data permission issue

Most of this guide treats timeouts as *connection* failures. There is a closely related class of errors where the connection succeeds but a specific call hangs forever โ€” reqMktData(), reqHistoricalData(), reqContractDetails(). Per the Interactive Brokers TWS API documentation (as of 2026-05), these typically indicate a missing or unsubscribed market-data permission rather than a transport problem; the errorEvent carries the explanation, but novice scripts often ignore it. The diagnosis path is covered in TWS API "Market Data Not Subscribed" โ€” different root cause, similar surface symptom.

If you have been chasing a connection timeout for an hour and it turns out to be a permissions issue, that piece is the next stop.

Library choice and the deprecation footnote

Two Python libraries dominate:

The eight fixes above apply to both libraries โ€” the timeouts originate on the TWS or Gateway side of the wire, not the Python side. Switching libraries hoping a different connect() will succeed is rarely effective.

Practical checklist before you ship

If you are about to run unattended for the first time, walk this list once:

1. Daily auto-restart configured (or your watchdog handles the gap).

2. Distinct clientId per process, documented somewhere. 3. Reconnection logic with bounded backoff. 4. A heartbeat call (e.g. reqCurrentTime) on a 30s timer with alerting. 5. Logs that include the host, port, and clientId on every connect attempt. 6. Read-Only API setting matches your intent. 7. Firewall and VPN tested in the actual production environment, not just on a dev laptop. 8. A paper-account dry-run that mirrors the live config except for the port.

For a worked example of these moving parts wired together with an actual trading strategy, see our IBKR Python momentum strategy walkthrough and the broader IBKR systematic trading review where we trace a year of live P&L on the same setup.

Closing

A connection timeout is rarely a Python problem. It is a TWS state problem, a port problem, or a process-lifecycle problem. Treat the eight fixes above as a triage tree, log every connect attempt with the full tuple (host, port, clientId), and the silent timeouts stop being silent โ€” they tell you which fix to reach for next.

๐Ÿงฎ Free IBKR calculator

IBKR Margin Calculator โ†’
Reg-T initial / maintenance / margin call price + IBKR Pro interest cost
Interactive Brokers

Ready to get started? Use the link below โ€” it helps support ChartedTrader at no cost to you.

Open an Interactive Brokers account โ†’
๐Ÿ“ˆ

About the author

I'm a systematic trader running live strategies on IB (USDJPY momentum) and Hyperliquid (crypto perps). Every tool reviewed here is something I've used with real capital. Questions? Reach out.

๐Ÿ“š Related Articles

๐ŸŽ“ Tutorials

Hyperliquid Python SDK Tutorial: Build a Bot (2026)

Wire the official Hyperliquid Python SDK to a perp bot in 2026: API wallet model, signed orders, WebSocket reconciliation, rate limits, and the 10 pitfalls that drain accounts.

May 6, 2026 โฑ 13 min read
๐ŸŽ“ Tutorials

TradingView Paper Trading Without Real Money (2026)

Practice trading on TradingView with $100K paper money โ€” setup, realistic commissions, common beginner mistakes, when to switch to real cash.

May 5, 2026 โฑ 12 min read
๐ŸŽ“ Tutorials

IBKR Python API Error Handling: Codes & Fixes (2026)

A code-by-code map of the IBKR TWS API error surface with paper-account-tested dispatch patterns for 1100, 110, 103, 100, 162, 354, 10090 and more.

May 3, 2026 โฑ 16 min read

๐Ÿ“ฌ Get weekly trading insights

Real trades, honest reviews, no fluff. One email per week.