Howwise RSS
Trading Software7 min read

ibapi Error 502 Couldn't Connect to TWS: Causes and Fixes

Short answer

ibapi error 502 couldn't connect to TWS means the TCP connection to your host and port failed, so the API handshake never began. Start TWS or Gateway, log in, enable socket clients, and match the port.

Key takeaways
  • Error 502 is a failed TCP connection, not a login, permission or clientId problem.
  • Run ss -ltnp or Test-NetConnection first: if nothing listens on the port, no code change will help.
  • Ports are 7496 (TWS live), 7497 (TWS paper), 4001 (Gateway live) and 4002 (Gateway paper), and must match the logged-in account type.
  • Docker, WSL2 and remote hosts need a trusted IP, a reachable bind address and a correct port mapping.
  • A duplicate clientId gives error 326, and requests sent before nextValidId fail even when the socket is open.

What does ibapi error 502 actually mean?

ibapi error 502 comes with the full message "Couldn't connect to TWS. Confirm that API is enabled in TWS/IBG". The client library tried to open a TCP socket to the host and port you gave it and the operating system refused or timed out. The API protocol never started.

That is why 502 is not a login error, not a permissions error and not a clientId error. Python never reached the stage where IB could judge any of those. The question to answer is only: what stops a socket from reaching a listening TWS or Gateway process?

The same failure appears in ib_insync and ib_async as ConnectionRefusedError, or as a timeout. Treat all of them as the same problem.

Which port should my code use: 7497, 7496, 4002 or 4001?

The port in code must match the port in the application's settings and the account type you logged into. A paper login on a live port number will simply find nothing listening.

These are the defaults. Settings can change them, so confirm in the API settings page.

ApplicationAccountDefault port
TWSLive7496
TWSPaper7497
IB GatewayLive4001
IB GatewayPaper4002
Tip: If you logged into paper in Gateway but code uses 7497, you get 502. The number belongs to the application type as well as the account.

How do I fix error 502? A checklist ordered by likelihood

Work down the list. Each step removes one layer, so stop at the first one that fails.

  1. Confirm TWS or IB Gateway is running and fully logged in. The socket opens only after login completes, including any two-factor prompt. The daily auto-restart or auto-logoff closes it, so a script that worked yesterday can fail this morning.
  2. Enable the setting: Global Configuration > API > Settings > tick 'Enable ActiveX and Socket Clients'. Without it the port is never opened.
  3. Read the 'Socket port' field on the same page and use exactly that number. Untick 'Read-Only API' if you intend to place orders, otherwise order requests are rejected after connecting. That is a separate symptom from 502.
  4. Check 'Trusted IPs' and 'Allow connections from localhost only'. 127.0.0.1 is trusted by default. Any other source address must be listed, or the localhost-only box unticked.
  5. Use 127.0.0.1 rather than 'localhost'. localhost can resolve to IPv6 ::1 first, while TWS listens on IPv4 only.
  6. Check for a second TWS or Gateway instance, or another program holding the port. The second one to start may silently pick a different port.
  7. Check firewall, antivirus and VPN software. Windows Firewall must allow the Java process, or the port.
Warning: When a connection arrives from an IP that is not trusted, TWS shows a confirmation popup on the machine running it. Nobody sees it on a headless server, so the client appears to hang or fail until the popup is accepted or the IP is added to Trusted IPs.

How do I verify the port is actually listening?

Prove which layer fails before changing settings. The commands separate three cases: no process listening, listening on the wrong interface, and blocked by the network.

On Linux, ss shows the bind address. 127.0.0.1:7497 means local only. 0.0.0.0 or * means all interfaces.

# Linux: is anything listening, and on which address?
ss -ltnp | grep -E '7496|7497|4001|4002'

# macOS / older Linux / Windows
netstat -an | grep LISTEN | grep 7497
netstat -an | findstr 7497

# Can this machine reach the host and port?
nc -vz 127.0.0.1 7497
nc -vz 192.168.1.50 7497

# Windows PowerShell
Test-NetConnection -ComputerName 127.0.0.1 -Port 7497
Tip: 'Connection refused' means the host answered and nothing listens on that port. A timeout usually means a firewall or routing drop. If nc succeeds but the API still fails, the problem is above the TCP layer, such as an untrusted IP or a clientId conflict.

Why does it fail in Docker, WSL2 or on a remote server?

In these setups 127.0.0.1 inside your script is not the machine running TWS. Three things must all be true: the process binds to an interface the client can reach, the IP is trusted, and the port is published.

Docker images for IB Gateway, including IBC based ones, usually run socat because Gateway itself only accepts local connections. The container then exposes a forwarded port such as 4004 mapped to Gateway's 4002 (and 4003 to 4001). Connect to the exposed port, not to 4002. Publish it with -p 4004:4004 or an equivalent mapping, and make sure the host side is reachable from your client.

On WSL2, 127.0.0.1 is the Linux VM. Use the Windows host IP, which you can read from the default route (ip route show default), and add it to Trusted IPs in TWS or untick localhost-only. Windows Firewall must also permit inbound traffic on the port.

For a remote server, prefer an SSH tunnel or a private network to exposing the port publicly. The API has no encryption or authentication beyond the trusted IP list.

SetupTypical mistakeFix
DockerPort not published, or using 4002 instead of the socat portPublish the mapped port (for example 4004:4004) and connect to it
WSL2Using 127.0.0.1 to reach Windows TWSUse the Windows host IP, trust it, allow the firewall
Remote hostLocalhost-only on, or IP not trustedAdd the client IP, or use an SSH tunnel to 127.0.0.1
VMNAT address differs from what TWS seesTrust the address TWS sees as the source
Warning: Do not open an API port to the internet. Anyone who can reach it and passes the trusted IP check can send orders on a live account.

What is a minimal working connection in ibapi and ib_insync?

With ibapi, connect() only opens the socket. You must run the message loop in a thread and wait for nextValidId before sending any request. Sending earlier produces errors or silently dropped requests, which is the usual timing bug after a successful connect.

In ib_insync and ib_async, connect() performs the handshake and waits for the initial data, and accepts a timeout.

# --- ibapi ---
import threading, time
from ibapi.client import EClient
from ibapi.wrapper import EWrapper

class App(EWrapper, EClient):
    def __init__(self):
        EClient.__init__(self, self)
        self.ready = threading.Event()
    def nextValidId(self, orderId):
        self.next_id = orderId
        self.ready.set()
    def error(self, reqId, errorCode, errorString, *args):
        print(reqId, errorCode, errorString)

app = App()
app.connect('127.0.0.1', 7497, clientId=7)
threading.Thread(target=app.run, daemon=True).start()
if not app.ready.wait(10):
    raise TimeoutError('No nextValidId: socket or handshake failed')
print('connected, next id', app.next_id)
# send requests only after this point
app.disconnect()

# --- ib_insync / ib_async ---
from ib_insync import IB   # or: from ib_async import IB
ib = IB()
ib.connect('127.0.0.1', 7497, clientId=7, timeout=10)
print(ib.isConnected(), ib.managedAccounts())
ib.disconnect()
Tip: Use a different clientId for each simultaneous connection. clientId 0 is special: only that client can bind and see manual TWS orders, so keep it for a single dedicated process.

Which related errors look like 502 but are not?

Once the socket opens, the failures change code. Reading the number tells you which layer to inspect.

CodeMeaningTypical cause and action
502Couldn't connect to TWSNothing reachable on host and port. Follow the checklist above
504Not connectedA request was sent on a client with no live socket, often after 502 or a disconnect
326Client ID already in useAnother connection uses the same clientId. Choose a unique one
507Bad messageThe socket closed or the data was malformed, often a version mismatch or a dropped connection
1100Connectivity between IB and TWS lostTWS lost its link to IB servers. The API socket stays open
1101Connectivity restored, data lostResubscribe market data and requests
1102Connectivity restored, data maintainedNo resubscription needed

Common questions

Why does error 502 appear only in the morning?

TWS and Gateway restart or log off daily, and the API socket closes while the application is not logged in. Check that the application is running and logged in, and consider IBC or the auto-restart setting to keep it alive. Add reconnect logic with a back-off to your script.

Does error 502 mean my account lacks API permission?

No. Permissions and market data subscriptions are checked after the handshake, so they cannot cause 502. A 502 means the TCP connection failed before any account logic ran.

Why do I get 326 when I fix the port?

Error 326 means the socket now works, but another connection, perhaps a stale script or a notebook kernel, still holds that clientId. Close the old process or use a different number. The message is a sign of progress.

Can I connect to paper and live at the same time?

Yes, if they run as separate TWS or Gateway instances with different socket ports, each logged into its own account. Use the matching port for each in code, and avoid sharing a clientId on the same instance.

Why does connect succeed but requests return nothing?

With ibapi, requests sent before nextValidId arrives can be lost. Wait for that callback, and also check the error callback for codes such as 354 or 10089 that indicate missing market data subscriptions.

Related topics:interactive brokersibapiibinsynctwstroubleshooting