TWS_API_HANDSHAKE_TIMEOUT.md•5.11 kB
# TWS API Connection Timeout - Diagnosis
## What's Happening
Your diagnostic shows:
```
INFO:ib_async.client:Connecting to 127.0.0.1:7496 with clientId 0...
INFO:ib_async.client:Connected ← Socket connection SUCCESS ✅
ERROR:ib_async.client:API connection failed: TimeoutError() ← API handshake FAIL ❌
```
**This means:**
- ✅ TWS is listening on port 7496
- ✅ Socket connection works (telnet works, ib_async connects)
- ❌ **IB API handshake is failing/timing out**
## Root Cause
The IB API handshake requires TWS to **accept and respond** to the API connection. This is failing, which means TWS API is either:
1. Not fully enabled
2. Blocking the connection
3. Not responding to API requests
## Solution Steps
### Step 1: Check TWS API Settings (CRITICAL)
In TWS:
1. **File → Global Configuration → API → Settings**
2. **Verify these settings:**
```
✅ Enable ActiveX and Socket Clients = CHECKED
✅ Socket port = 7496 (matches your config)
✅ Master API client ID = 0 (or empty)
✅ Read-Only API = UNCHECKED (if you want to place orders)
✅ Download open orders on connection = YOUR CHOICE
```
3. **Check Trusted IPs:**
- If "Allow connections from localhost only" = CHECKED
- Then "Trusted IP Addresses" MUST include `127.0.0.1`
4. **VERY IMPORTANT:** After changing settings:
- Click "OK" to save
- **RESTART TWS COMPLETELY** (not just disconnect/reconnect)
### Step 2: Check for Existing Connections
TWS may reject connections if you have another client connected with the same Client ID.
**In TWS:**
1. Look for a blue/green indicator in the bottom right corner
2. If there's an active API connection, disconnect it first
3. Try again with a different Client ID
### Step 3: Check TWS Version
Some TWS versions have API bugs. Check:
```
Help → About Trader Workstation
```
**Recommended:** Use the latest stable version
### Step 4: Try with a Simple Test Client
Let's verify TWS API is working at all. Try this minimal test:
```python
# test_minimal.py
import asyncio
from ib_async import IB
async def test():
ib = IB()
try:
print("Connecting...")
await ib.connectAsync('127.0.0.1', 7496, clientId=999)
print("SUCCESS!")
print(f"Accounts: {ib.managedAccounts()}")
ib.disconnect()
except Exception as e:
print(f"FAILED: {e}")
asyncio.run(test())
```
Run it:
```bash
uv run python test_minimal.py
```
### Step 5: Check TWS Logs
TWS keeps logs that might show why it's rejecting the API connection:
**Location:**
- Windows: `C:\Users\<username>\Jts\<username>\log`
- Mac: `~/Jts/<username>/log`
- Linux: `~/Jts/<username>/log`
**Look for:**
- Files like `api.<timestamp>.log`
- Error messages about rejected connections
- Security/authentication errors
### Step 6: Check for Common Issues
#### Issue A: "Read-only API" Mode
If TWS is in read-only mode, it might not complete handshakes properly.
**Fix:** Uncheck "Read-Only API" in settings
#### Issue B: Wrong TWS Build
Some TWS builds have API bugs.
**Fix:** Update to latest stable build
#### Issue C: Firewall/Antivirus
Even though telnet works, some security software blocks IB API specifically.
**Fix:** Temporarily disable antivirus and try again
#### Issue D: TWS Needs Clean Restart
Sometimes TWS gets into a bad state.
**Fix:**
```bash
# Completely quit TWS (not just log out)
# Wait 10 seconds
# Start TWS again
# Wait for it to fully load
# Try connection again
```
## Quick Checklist
Before trying again, verify:
- [ ] TWS is running and logged in
- [ ] Edit → Global Configuration → API → Settings
- [ ] "Enable ActiveX and Socket Clients" is CHECKED
- [ ] Socket port = 7496
- [ ] "Read-Only API" is UNCHECKED
- [ ] Trusted IPs includes 127.0.0.1 (if using localhost only)
- [ ] Clicked OK and RESTARTED TWS
- [ ] No other API clients are connected
- [ ] Tried with client ID 0 (master) or 999 (random)
## Alternative: Try IB Gateway Instead
If TWS continues to have issues, try IB Gateway:
1. Download IB Gateway (lighter than full TWS)
2. Configure it for API connections
3. Use port 4001 (live) or 4002 (paper)
4. Update your .env:
```env
TWS_PORT=4001 # or 4002 for paper
```
IB Gateway is specifically designed for API access and often works better than full TWS.
## If All Else Fails
Contact IBKR Support:
- They can check if your account has API access enabled
- They can verify no server-side blocks on your account
- They may have specific configuration for your TWS version
## Next Test
After fixing the TWS settings and restarting:
```bash
# Test with verbose logging
uv run python test_tws_connection.py --client-id 0
# If that works, test with your normal client ID
uv run python test_tws_connection.py --client-id 1
```
## Expected Success Output
When it works, you should see:
```
INFO:ib_async.client:Connecting to 127.0.0.1:7496 with clientId 0...
INFO:ib_async.client:Connected
INFO:ib_async.client:API connection ok ← THIS LINE IS KEY
✅ CONNECTION SUCCESSFUL!
```
The missing `API connection ok` line is why your connection is failing.