An Interactive Brokers (IBKR) API bot connects through the TWS API to a running, logged-in copy of Trader Workstation (TWS) or IB Gateway. Turn on Enable ActiveX and Socket Clients, point the bot at the matching socket port (7497 for TWS paper, 4002 for IB Gateway paper) and give it a unique client ID. IB Gateway uses about 40% fewer resources than TWS, so it is the usual choice for a bot that runs all day.
Automated trading bots execute trades based on rules you set, without emotions. IBKR adds a few chores of its own: a daily restart, a weekly login with two-factor authentication (2FA), and API settings that must match the bot. Here is what you need to know:
- Which API: the TWS API suits most retail bots; the Web API and FIX serve other needs.
- TWS or IB Gateway: both work with the TWS API. IB Gateway is lighter, while TWS has the full trading screen.
- Python: use IBKR's official ibapi library or the community ib_async library.
- No-code route: TradingView alerts can also reach IBKR; see connecting TradingView to Interactive Brokers.
- Hosting: a VPS keeps TWS or IB Gateway and the bot running on a remote server; order execution still depends on IBKR and the market.

Which IBKR API to Use: TWS API, Web API or FIX
For most retail trading bots, the TWS API is the right choice: IBKR says it has nearly full parity with TWS's functionality, order types and market data, and it comes in Python, Java, C++, C# and VB.NET. The Web API suits apps that prefer REST calls over HTTPS, and FIX is for professional traders and institutions. IBKR requires an IBKR Pro account to use the TWS API (checked on 10 Oct 2026).
| API | How it connects | Best for | What must be running |
|---|---|---|---|
| TWS API | TCP socket to TWS or IB Gateway | Retail and professional bots, third-party platforms | TWS or IB Gateway, logged in |
| Web API | REST and WebSocket over HTTPS | Web apps and scripts that prefer HTTP | For individual accounts, the Client Portal Gateway (a Java program you log in to at https://localhost:5000); advisors, brokers and third-party developers use OAuth |
| FIX | FIX messages, set up with IBKR's FIX team | Professional traders, organizations and institutions | A FIX connection arranged with IBKR |
TWS vs IB Gateway for a Trading Bot
Both programs work the same way for the TWS API: IBKR says that, from an API application's point of view, TWS and IB Gateway are identical. IB Gateway is the lighter choice for a bot, while TWS adds the full trading screen for watching orders.
| TWS | IB Gateway | |
|---|---|---|
| Interface | Full trading platform with tools such as Risk Navigator, OptionTrader and BookTrader | Small window for login and API connection status |
| Resource use | Heavier | About 40% fewer resources than TWS |
| Default socket ports | 7496 live, 7497 paper | 4001 live, 4002 paper |
| Restart behaviour | Designed to restart daily; the Auto restart setting avoids a daily login | Same daily restart and Auto restart setting |
| Login | Username, password and 2FA in a login window; no headless mode | Same |
IBKR does not support running either program headless, without a graphical interface, so the server needs a desktop session: a Windows VPS, or Linux with a desktop. Each TWS or IB Gateway session accepts up to 32 API clients at the same time.
Enable the API: Ports, Client IDs and Trusted IPs
API access is switched on inside TWS or IB Gateway, not in IBKR's account portal. In TWS, open File > Global Configuration > API > Settings (Edit > Global Configuration in the Classic TWS view) and work through these steps:
- Log in to TWS or IB Gateway with the paper or live username the bot will use.
- Enable ActiveX and Socket Clients.
- Leave Read-Only API ticked while you test data feeds, and untick it only when the bot should send orders.
- Check the Socket Port. The defaults are 7496 for TWS live, 7497 for TWS paper, 4001 for IB Gateway live and 4002 for IB Gateway paper, and the bot must use the same number.
- Give every program that connects its own client ID; TWS uses the client ID to tell API clients apart.
- Keep "Allow connections from localhost only" ticked when the bot runs on the same machine. For a bot on another machine, untick it and add that machine's IP address under Trusted IPs (single addresses only, no subnets).
- Under API > Precautions, choose whether to bypass the order precaution pop-ups for API orders, so a warning dialog doesn't hold up the bot.
If the bot reports error 502, the socket could not open: TWS or IB Gateway is not running with the API enabled, the port doesn't match, or a firewall or antivirus program is blocking the connection. Before going live, confirm trading permissions and market data subscriptions for every product the bot trades.
Uptime
99.999% uptime. Built for 24/7 trading reliability.
Your VPS runs in Tier IV datacenters with redundant power and network, monitored 24/7 on site.
See the uptime SLAFrom $29.99/mo · Windows or Linux
Daily Restarts, Weekly Login and 2FA
TWS and IB Gateway are designed to restart once a day, and a bot has to survive that restart. In Global Configuration > Lock and Exit, choose "Never lock Trader Workstation" and "Auto restart", as IBKR recommends for API users, and set the restart time outside your trading hours.
With Auto restart on, TWS or IB Gateway can run from Sunday to Sunday without a new login. After IBKR's Saturday night server reset you must log in again with your password and 2FA. If the log shows "Soft token=0 received instead of expected permanent", that weekly login is due.
Two-factor authentication is required for every IBKR user. The API works with IB Key, Handy Key (smartphone apps), SMS and the Digital Security Card+, but not with the Security Code Card, Temporary Security Code Card or Online Code Card.
Two habits prevent surprise disconnects. Use a separate IBKR username for Client Portal, because logging in there with the bot's username stops TWS or IB Gateway from reconnecting after the next server reset. Code the bot to reconnect on its own, wait for the nextValidId callback, and check open orders before it sends anything new.
Python Libraries: ibapi and ib_async
Python bots usually use one of two libraries. ibapi is IBKR's official TWS API client, and ib_async is a community library with a simpler interface to the same TWS API that replaces ib_insync, whose GitHub repository is archived.
| Library | Maintained by | Install | Notes |
|---|---|---|---|
| ibapi | Interactive Brokers | Download the TWS API from IBKR, then run python3 -m pip install . in IBJts/source/pythonclient |
IBKR's minimum is Python 3.11; you write EWrapper callbacks yourself |
| ib_async | ib-api-reloaded (community) | pip install ib_async |
Python 3.10 or later; successor to ib_insync |
A minimal ib_async bot that connects to TWS on the paper port and places one test order looks like this:
from ib_async import IB, Stock, MarketOrder
ib = IB()
ib.connect('127.0.0.1', 7497, clientId=1) # TWS paper port; IB Gateway paper is 4002
contract = Stock('AAPL', 'SMART', 'USD')
trade = ib.placeOrder(contract, MarketOrder('BUY', 1))
while not trade.isDone():
ib.sleep(1)
print(trade.orderStatus.status)
ib.disconnect()
Run it only against a paper account. Swap 7497 for 4002 if you use IB Gateway, and replace the market order with your own order logic and size limits.
Paper Trading Before Live
Test every IBKR bot on a paper account before it trades real money. Paper sessions use port 7497 in TWS or 4002 in IB Gateway and connect to IBKR's US servers by default.
Here’s a simple checklist:
- Paper Trading Setup: Run your strategy on the paper account without risking real capital.
- Restart Test: Leave the bot running through at least one daily auto restart and confirm it reconnects by itself.
- Performance Monitoring: Keep an eye on key metrics like win rate, profit factor, and drawdown.
- System Validation: Check that orders, cancels, partial fills and status updates behave as intended.
- Risk Assessment: Analyze how your strategy holds up under different market conditions.
A paper session won't receive market data if it shares data from a live username that is logged in to Client Portal, which is one more reason to keep a separate username for the portal.
DDoS protection
Always-on DDoS protection with advanced filtering. On every plan.
Always-on mitigation filters attack traffic at the network edge. Every plan includes a dedicated IP and unmetered bandwidth for the trading environment.
See every security layerFrom $29.99/mo · Windows or Linux
Strategy Rules and Risk Controls
A bot needs written rules for entries, exits and position size, plus hard limits that stop it when something goes wrong. The API only carries out what those rules tell it to do.
Strategy Components
Creating automated trading strategies for Interactive Brokers involves focusing on a few essential elements. Your strategy should clearly outline entry and exit rules, position sizing, and risk management measures.
Here’s what to include:
- Entry Conditions: Specify the market scenarios that trigger trades.
- Exit Rules: Define when and how to close positions.
- Position Sizing: Determine how much capital to allocate per trade.
- Risk Controls: Set up stop losses, take profits, and trailing stops.
Once your strategy is outlined, test it in a simulated environment to ensure it performs as expected.
Common Trading Approaches
Interactive Brokers supports various algorithmic trading methods that can be automated using QuantVPS for both futures and stock markets. Below are a few popular strategies:
Trend Following
- Relies on technical indicators to spot and trade sustained price trends.
- Uses trailing stops to lock in profits as trends develop.
Mean Reversion
- Identifies overbought or oversold conditions.
- Capitalizes on price returning to its average levels.
- Includes clear profit targets and stop-loss levels.
Breakout Trading
- Focuses on key support and resistance levels.
- Executes trades when breakouts are confirmed by volume.
- Employs tight stop-loss orders to limit risk.
No matter which strategy you choose, it’s essential to maintain consistent position sizing and risk management. Avoid risking more than a set percentage of your account on any single trade.
For peak performance, make sure your strategy incorporates:
- Clear execution rules.
- Defined risk limits.
- Automated position management.
- Regular performance reviews.
Order flow
Built for scalpers. Heatmaps on dedicated resources.
Order-flow heatmaps and DOM ladders run on dedicated CPU, memory and NVMe, so your charts keep responding during volatility.
See the dedicated hardwareFrom $29.99/mo · Windows or Linux
Risk Management
Managing risks is critical when running trading bots. Here’s how you can stay prepared:
Technical Safeguards:
- Set up automated system health checks
- Use redundant internet connections
- Implement emergency shutdown procedures
- Conduct regular performance audits
Market Risk Controls:
- Limit position sizes
- Establish daily loss thresholds
- Cap maximum order quantities
- Set price deviation alerts
Hosting an IBKR Bot on a VPS
A VPS keeps TWS or IB Gateway and the bot running when your own computer is off, but every order still goes through IBKR's servers. Each IBKR account is assigned to a server region, such as America East (New York) or America Central (Chicago); TWS shows yours under Data, and IBKR can move it through a support ticket.
QuantVPS hosts its IBKR servers in Chicago, with a published 0 to 2ms to IBKR (checked on 10 Oct 2026). If TWS shows your account on IBKR's New York server, a New York VPS puts the bot closer to it.
Size the VPS for TWS or IB Gateway, your bot and any charts. VPS Lite has 4 CPU cores, 8GB RAM and 75GB NVMe (checked on 10 Oct 2026); heavier analysis may need more resources. Follow the trading software’s requirements rather than treating a single VPS size as an IBKR API requirement.
Track connection stability, order acknowledgement times and CPU and memory use, and frequently back up your algorithms, performance data and configurations to prevent data loss.
Running an IBKR bot through the trading day
Start the bot on an IBKR paper account and let it run through at least one daily IB Gateway restart to make sure it reconnects by itself. Set order size limits in the bot and in IBKR's own order precautions. An IBKR VPS for trading bots keeps the bot and IB Gateway on one server, 0 to 2ms from IBKR.









