ibapi Error 502 Couldn't Connect to TWS: Causes and Fixes
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.
- 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.
| Application | Account | Default port |
|---|---|---|
| TWS | Live | 7496 |
| TWS | Paper | 7497 |
| IB Gateway | Live | 4001 |
| IB Gateway | Paper | 4002 |
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.
- 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.
- Enable the setting: Global Configuration > API > Settings > tick 'Enable ActiveX and Socket Clients'. Without it the port is never opened.
- 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.
- 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.
- Use 127.0.0.1 rather than 'localhost'. localhost can resolve to IPv6 ::1 first, while TWS listens on IPv4 only.
- 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.
- Check firewall, antivirus and VPN software. Windows Firewall must allow the Java process, or the port.
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 7497Why 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.
| Setup | Typical mistake | Fix |
|---|---|---|
| Docker | Port not published, or using 4002 instead of the socat port | Publish the mapped port (for example 4004:4004) and connect to it |
| WSL2 | Using 127.0.0.1 to reach Windows TWS | Use the Windows host IP, trust it, allow the firewall |
| Remote host | Localhost-only on, or IP not trusted | Add the client IP, or use an SSH tunnel to 127.0.0.1 |
| VM | NAT address differs from what TWS sees | Trust the address TWS sees as the source |
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()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.
| Code | Meaning | Typical cause and action |
|---|---|---|
| 502 | Couldn't connect to TWS | Nothing reachable on host and port. Follow the checklist above |
| 504 | Not connected | A request was sent on a client with no live socket, often after 502 or a disconnect |
| 326 | Client ID already in use | Another connection uses the same clientId. Choose a unique one |
| 507 | Bad message | The socket closed or the data was malformed, often a version mismatch or a dropped connection |
| 1100 | Connectivity between IB and TWS lost | TWS lost its link to IB servers. The API socket stays open |
| 1101 | Connectivity restored, data lost | Resubscribe market data and requests |
| 1102 | Connectivity restored, data maintained | No 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.