TL;DR

The Interactive Brokers TWS API lets you place and manage trades programmatically through TWS or IB Gateway on port 7497 (paper) or 7496 (live); most retail traders get a working connection running in under an hour using the free ibapi or ib_async Python libraries, with no subscription fee required beyond a funded brokerage account.

Key Takeaways

  • 1.IBKR's TWS API is free to use once you have a funded or paper trading account; you only pay for optional real-time market data subscriptions.
  • 2.IB Gateway uses roughly 300MB of memory versus 800MB or more for full TWS, making it the better choice for a script that runs unattended on a server.
  • 3.Default socket ports are 7497 for paper TWS, 7496 for live TWS, 4002 for paper Gateway, and 4001 for live Gateway.
  • 4.The API enforces a pacing limit of 50 messages per second per connection; exceeding it triggers a temporary throttle.
  • 5.Paper trading accounts start with $1,000,000 in simulated cash and mirror live market data, making them the safest place to test a new script.

Connecting to the Interactive Brokers API means installing TWS or IB Gateway, enabling API access in the settings, and connecting a Python script through the ibapi or ib_async library on the correct port. Once the socket handshake completes, you can request market data, submit orders, and monitor your account in real time.

I set up my first IBKR API connection in 2023 to automate a simple mean reversion strategy on SPY options, and the hardest part was not the code, it was a handful of small configuration steps IBKR buries inside the TWS settings menu. Miss one checkbox and your socket connection times out with no useful error message. This tutorial walks through the exact setup I use today for both paper and live accounts, including the specific ports, client ID rules, and pacing limits that trip up most first-time users. By the end you will have a working connection that can pull a live quote and submit a test order on your paper account, plus a clear answer on whether TWS or IB Gateway fits a script that runs unattended.

How do you get API access to Interactive Brokers?

You get API access by opening a standard IBKR brokerage account, cash or margin, live or paper, then enabling API connections inside TWS or IB Gateway under Configuration, API, Settings. There is no separate API application, no approval wait, and no extra fee. Paper accounts get API access immediately after activation, which is why most developers build and test there first.

Once you log into TWS or Gateway, open the Configuration menu, select API, then Settings. Check the box labeled Enable ActiveX and Socket Clients. This single toggle is what most first-time users miss, and without it every connection attempt from your script will time out silently. Below that, you will see a Socket Port field (default 7497 for paper TWS) and a list of Trusted IPs. Add 127.0.0.1 if your script runs on the same machine as TWS. Leave Read-Only API checked for now; you will uncheck it later once you are ready to submit real orders.

Start with Read-Only API checked

Leaving Read-Only API enabled lets your script pull quotes and account data with zero risk of accidentally submitting an order while you are still testing the connection.

Enabling API access takes about five minutes inside TWS Configuration and requires no separate approval from IBKR, unlike broker APIs such as Tradier or Alpaca that gate access behind a waitlist.

What do you need before connecting to the IBKR API?

Beyond an active IBKR account, you need four things: TWS or IB Gateway installed and running, Python 3.9 or newer, a client library (ibapi or the community-maintained ib_async), and a unique client ID for each script you plan to run at the same time. Real-time US equity quotes require a small monthly data subscription, but delayed data streams for free through the same API calls.

RequirementWhy it mattersCost
TWS or IB GatewayThe API only works through one of these running locally or on a serverFree
Python 3.9+Both ibapi and ib_async require a modern interpreterFree
ibapi or ib_async libraryHandles the socket protocol so you are not parsing raw messagesFree
Unique client ID per scriptIBKR rejects a second connection reusing an active client IDFree
Real-time data subscriptionDelayed data is free; live US equity quotes run about $10 a monthPaid, optional

Delayed market data is free through the API, but real-time US equity quotes require a Level I data subscription that IBKR bills separately from trading commissions, typically $10 or less per month depending on the exchange.

On the library choice, ib_async wraps the raw ibapi callbacks into request/response style calls that block until a result comes back, which reads far closer to normal Python and cuts the amount of boilerplate roughly in half. The native ibapi package gives you more direct control over the event loop, which matters if you are building a high-frequency system processing thousands of ticks a second, but for most retail strategies checking prices every few seconds, ib_async is the faster path to a working script.

How to set up TWS or IB Gateway for API access

Pros

  • IB Gateway uses about a third of the RAM of full TWS, so it runs cleanly on a $5 to $10 a month cloud VPS
  • Gateway has no charting or order entry UI competing for CPU cycles, which keeps API response times more consistent
  • Both TWS and Gateway share the identical API, so switching later requires no code changes

Cons

  • Gateway has no visual order book or chart, so debugging a bad fill means reading logs instead of looking at a screen
  • TWS still requires a daily restart around midnight Eastern for its own maintenance window, and Gateway inherits the same requirement
  • Neither TWS nor Gateway supports true headless login without a workaround like IBC, since IBKR requires the 2FA prompt to be answered interactively by default

Getting your first connection live

  1. 1

    Step 1: Install TWS or IB Gateway

    Download the standalone installer from IBKR's site. Gateway is a lighter option with no charting or order entry screen, built specifically for scripts.

  2. 2

    Step 2: Log in with your paper trading credentials first

    Never test a new script against a live account. IBKR issues a separate paper trading username automatically when you open a real account.

  3. 3

    Step 3: Open Configuration, then API, then Settings

    This is the panel that controls whether outside programs can talk to TWS at all.

  4. 4

    Step 4: Check Enable ActiveX and Socket Clients

    Without this box checked, every connection attempt from your script fails silently with no error in TWS itself.

  5. 5

    Step 5: Confirm the socket port

    7497 for paper TWS, 7496 for live TWS, 4002 for paper Gateway, 4001 for live Gateway. Your script's connect call must match exactly.

  6. 6

    Step 6: Add 127.0.0.1 to Trusted IPs

    If your script runs on a remote server instead, add that server's IP address here rather than localhost.

  7. 7

    Step 7: Set a client ID

    Pick a number like 1 for your first script. Every simultaneous connection needs a different client ID or IBKR will reject the second one.

  8. 8

    Step 8: Restart TWS or Gateway

    Settings changes to the API panel only take effect after a restart, which is the second most common cause of a stuck connection.

Once your script's connect call returns without a timeout, you have a live socket to TWS. That is the entire setup; there is no OAuth flow, no API key to generate, and no callback URL to register, which is a meaningfully lower barrier than most broker APIs launched after 2020.

How to place your first automated trade with the IBKR API

With a connection open, the workflow for any trade is the same four calls: define a contract, request its current price or historical bars, build an order, and submit it. The ib_async library wraps the raw ibapi callbacks into a simpler request/response pattern, which is why most retail developers start there instead of the native library.

MethodPurpose
reqMktDataStream live or delayed quotes for a contract
reqHistoricalDataPull OHLCV bars for backtesting or signal generation
placeOrderSubmit a new order, market or limit
reqPositionsCheck current holdings across the account
reqAccountSummaryPull cash balance, net liquidation value, and buying power

A minimal script defines a Stock contract, for example AAPL on the SMART exchange in USD, requests a snapshot quote, builds a market or limit order for a small share size, and calls placeOrder against that contract. On a paper account this whole sequence, from connection to filled order, typically completes in two or three seconds.

Order type matters more than most tutorials admit. A market order fills fast but at whatever price is available, which can slip badly on a thin options contract right at the open. A limit order protects your entry price but might never fill if the market moves away from you. IBKR's API also supports bracket orders, a parent order paired with an automatic take-profit and stop-loss, submitted as one unit. For any strategy that runs unattended overnight, a bracket order is the difference between a defined risk trade and a position nobody is watching if the connection drops.

Test order size matters

Always submit your first live order for 1 share or the minimum contract size. It is far cheaper to discover a bug in your quantity calculation with $150 at risk than with $15,000.

A working ib_async script, connect, define a Stock contract, and call placeOrder, can submit a filled paper trade in under 30 lines of code, which is roughly a third the length of the equivalent script using the raw ibapi callbacks.

What are the most common IBKR API connection errors?

Most first connections fail for one of four reasons, and all four show up as a specific numbered error IBKR logs to the TWS API tab, which makes debugging faster once you know what to look for.

ErrorCauseFix
Error 502: Couldn't connect to TWSTWS or Gateway is not running, or the API toggle is offConfirm the app is open and Enable ActiveX and Socket Clients is checked
Error 326: Client id already in useTwo scripts are trying to use the same client ID at onceAssign a unique client ID per connection
Error 200: No security definition foundContract details are incomplete or the exchange is wrongSpecify exchange as SMART and set currency explicitly
Pacing violationMore than 50 messages per second, or too many historical data requests for the same contractAdd a short delay between calls and batch historical requests

Historical data requests carry a separate limit: no more than roughly 6 requests per 10 minutes for the same contract and bar size, a restriction that catches most people the first time they try to backfill several years of daily bars in a loop.

A less obvious cause of connection failures is local firewall or antivirus software blocking the loopback socket, even when it is only talking to 127.0.0.1. If TWS shows no errors at all but your script still times out after enabling the API toggle, temporarily disabling third-party firewall software is a faster diagnostic step than re-reading your connection code.

Is the Interactive Brokers API free to use?

Yes, in the sense that matters most: IBKR does not charge a separate fee to enable or call the TWS API. What you pay for is the same as trading manually through the desktop platform, standard commissions per trade plus optional real-time data subscriptions.

As of 2026, IBKR Pro charges $0.0035 per share with a $1 minimum commission on US stock trades, and API access itself carries zero incremental fee beyond that standard schedule. IBKR Lite offers $0 commissions on US stocks but routes orders differently, which can matter if your strategy depends on execution quality.

What to do next

Get a paper account connected first, confirm you can pull a quote and submit a test order, then let the script run unattended for a few days before you fund it with real money. Most of the bugs that matter, a bad pacing loop, a contract that resolves to the wrong exchange, a client ID collision, show up within the first 48 hours of continuous operation.

  • Confirm the paper account API connection works before touching live money
  • Add a short delay between requests to stay under the 50 messages per second pacing limit
  • Log every order submission and fill to a file for later review
  • Set a daily loss limit inside your script's logic, not only inside TWS
  • Restart Gateway on a nightly schedule via cron to avoid memory creep during multi-day runs

A connection that survives a full week of unattended operation without a manual restart is the real benchmark for whether your IBKR API setup is production ready, not whether it works once in a five-minute test.

Get smarter trades, weekly

One short email every Sunday. AI workflows, tool reviews, and trader productivity tips.