The short answer
Almost every failed TWS API connection is one of six settings, and they fail in a predictable order: the API is not enabled, the port is wrong, the connection is waiting on a dialog you have not noticed, Read-Only API is still ticked, a precaution is rejecting the order, or TWS restarted overnight and is sitting at a login screen. Fix them in that order. Enable ActiveX and Socket Clients is the first checkbox under Global Configuration, API, Settings. TWS listens on 7496 for live and 7497 for paper; IB Gateway on 4001 and 4002. Add 127.0.0.1 to Trusted IPs for anything running on the same machine. Untick Read-Only API or nothing you send will become an order. Then set Auto Restart under Lock and Exit and expect to log in by hand once a week.
Why can't my app connect to TWS at all?
Because a fresh TWS does not accept API connections. Open Edit (File, in Mosaic), Global Configuration, API, Settings. The first checkbox is "Enable ActiveX and Socket Clients". IBKR's description of it is dry: "Check to enable integration with TWS using ActiveX or socket clients including Java and C++." Without it, your client gets error 502, whose text tells you exactly this: "Couldn't connect to TWS. Confirm that 'Enable ActiveX and Socket Clients' is enabled and connection port is the same as 'Socket Port' on the TWS 'Edit->Global Configuration...->API->Settings' menu."
An illustration, not a screenshot. TWS's window looks different.
The other half of 502 is the obvious one. The API is an interface to a running TWS or IB Gateway. If neither is open and logged in, there is nothing to connect to.
Which port: 7496, 7497, 4001 or 4002?
IBKR's numbers, from its own setup lesson: "By default, TWS uses socket port 7496 for live sessions and 7497 for paper sessions. IB Gateway by contrast uses 4001 for live sessions and 4002 for paper sessions." The port can be changed to anything open, as long as the client and the Socket port field match.
Two traps. First, the API docs warn, in bold, that when you run paper and live TWS on the same computer you must make sure your client application is connecting to the right TWS. A client pointed at 7497 while you meant 7496 is trading a paper account with total confidence. Second, one TWS session accepts up to 32 client applications, told apart by client ID, so each piece of software needs its own. If you want one client to see every order regardless of who placed it, that is the Master API client ID field: "The API client with the specified client ID will receive all orders, even those placed by other API clients."
Why does TWS keep asking me to accept the connection?
Because the address is not trusted. From the API docs: "For security reasons, by default the API is not configured to automatically accept connection requests from API applications. After a connection attempt, a dialogue will appear in TWS asking the user to manually confirm that a connection can be made." The Trusted IPs list is the fix. IBKR's guide: "If you connect to the API through a trusted IP address, the connection is not questioned. Otherwise, you will get a verification message asking if you are sure you want to make the connection."
For software on the same machine, the address is 127.0.0.1. The docs also note TWS can be set to accept connections from the local machine automatically. If your helper, the small program an app installs to talk to TWS, is stuck at "connecting", look for the dialog behind another window before you look anywhere else.
Why do I connect fine but every order is rejected?
Read-Only API. It is on by default, on purpose. The API docs: "By default, 'Read Only' is enabled as an additional precautionary measure." The setup lesson is blunter: "The setting 'Read-Only' is enabled by default and will block all API orders. It must be unchecked to allow any orders from the API." This is the checkbox nobody mentions, and it is the reason a working connection can place nothing. Leave it ticked if all you want is fills and positions flowing into a journal. Untick it the day you want software to place or manage an order for you, and understand what you have just allowed. If only some orders are refused, the message says who refused them: what each IBKR rejection message means. If the order is a stop, what makes one hold at IBKR is in setting a stop loss on IBKR that actually fires.
An illustration, not a screenshot. The position is invented.
What are the precautions, and should I bypass them?
TWS runs sanity checks on orders. In Presets they are called Precautionary Settings: Percentage, Size Limit, Total Value Limit and Number of Ticks. IBKR describes Percentage as "a safety net to prevent you from transmitting a limit order that has a mistyped limit price", and Size Limit as something you can override with a click. When you type an order by hand, a warning appears and you decide. When software sends the order, the same check produces an error instead.
There is a switch for that, under Global Configuration, API, Precautions: "Bypass Order Precautions for API Orders", which IBKR describes as "Check to allow orders that fall outside the size or value limits to be submitted without a warning." Before ticking it, consider the alternative: set the precaution values to your actual maximum size and value, so a fat finger in the software is still caught while your normal orders pass. Bypass is the right answer only when you have already put the limit somewhere else.
Why did the API die overnight?
Because TWS is designed to restart every day and to make you log in every week. The API docs say it in one line: "Both TWS and IBGW were designed to be restarted daily." The settings live under Global Configuration, Lock and Exit: "Lock trading system after ___ minutes of inactivity", "Never lock trading system", "Set Auto Log Off Time" and "Set Auto Restart Time". IBKR's guide describes the last one as a restart "without authentication requirements", and its API guidance for people running software is to choose "Never lock Trader Workstation" and "Auto restart".
Auto Restart is not a full escape. IBKR's Auto Restart Considerations page: "This procedure will require manual authentication once a week, the first time you log into the platform after the security tokens have been invalidated," and "This security process occurs each Sunday at 1:00 am ET." The failure you see on Monday morning reads "Login failed = Soft token=0 received instead of expected permanent." IBKR also lists what stops the restart working at all: a machine asleep or without power at the scheduled time, an operating system update forcing a reboot, and, in rare cases, a revoked token. On a Mac that means checking the sleep settings before you trust the restart.
Paper or live: which one am I actually connected to?
The port tells you, and nothing else does. Beyond that, IBKR's guide says a paper account's "trading permissions, market data subscriptions, base currency, and other account configurations are the same as specified for your regular account", starting with USD 1,000,000 of simulated equity, and that "trades entered into a paper trading account will not actually execute on any exchange". IBKR recommends testing there first: "Paper accounts are compatible to use with the TWS API, and it is recommended to test all programs in a paper environment before moving to production trading."
Market data is where paper surprises people. Unsubscribed data in a paper account is delayed: 15 minutes for US stocks and options, 10 minutes for US futures, according to IBKR's delayed-data page, which also says "You can only subscribe to real-time market data from an approved, fully-funded account." The API docs add that your paper user can receive live data only if you have shared your subscriptions with it, and only if "You are NOT logged in with your live user name at the same time on a different computer." Error 10197, "No market data during competing session", is what that looks like from the API.
Do I need market data subscriptions for the API?
For real-time data, yes: "In order to receive real time top-of-book, depth-of-book, or historical market data from the API it is necessary have live market data subscriptions for the requested instruments in TWS." Placing orders and reading fills and positions does not need a data subscription.
Where Degen Pro fits
Degen Pro is a Mac app for Interactive Brokers, and the connection this guide sets up is what its stop, its keys and its lock run on: its helper looks for Trader Workstation and IB Gateway on their usual ports, 7497, 7496, 4002 and 4001, and needs Read-Only API off, since with Read-Only on nothing it sends can become an order. With it working, the app keeps your stop from sitting wider than the rule you wrote down and will not loosen it; the exit keys act through it, one key each to PROTECT, peel a runner, put the stop on a trail that only moves up, and flatten everything; and when the day is spent it can close Trader Workstation and TradingView, and IB Gateway or IBKR Desktop if they are open, and hold them shut until the next morning. Options fills arrive from Interactive Brokers as they happen; futures come in from a Tradovate or TradingView export instead. Without Interactive Brokers the journal, the limits and the grades still work from an export, and the stop, the keys and the lock do not. It can place an entry you choose — calls and puts on SPX and SPY — and gives no signals. macOS 14 or later; it lives in the menu bar. What the app asks of Trader Workstation, in order, is on the setup page.
The order to check things in
- TWS or IB Gateway is open and logged in.
- Enable ActiveX and Socket Clients is ticked.
- The client's port matches the Socket port field: 7496 or 7497 for TWS, 4001 or 4002 for Gateway.
- 127.0.0.1 is in Trusted IPs, or you have answered the dialog.
- Read-Only API is off, if you expect orders to go through.
- Precautionary values fit your real sizes, or Bypass Order Precautions for API Orders is on and you know why.
- Lock and Exit is set to Never lock and Auto Restart, the Mac does not sleep at that time, and Monday's manual login is in the calendar.
- You have looked at the port one more time, because it is the paper account.