Table of Contents
1. Prerequisites
Before you begin connecting slmaj to Interactive Brokers, make sure you have the following in place. Missing any of these will cause the setup to fail, and the error messages from the IBKR API are not always descriptive enough to point you in the right direction.
An Interactive Brokers account. You need either a funded live trading account or a paper trading account. If you do not yet have an account, you can sign up for an IBKR paper trading account at no cost. Paper trading accounts are fully functional simulations of the live environment and are ideal for testing slmaj before committing real capital. If you already have a live IBKR account, a paper trading account is automatically available through your Account Management portal.
Trader Workstation (TWS) or IB Gateway installed. These are the two desktop applications that Interactive Brokers provides for API connectivity. You must have at least one installed and running for slmaj to communicate with the brokerage. Download the latest stable version from the IBKR TWS download page. We recommend the Latest channel rather than the Stable channel, as it includes the most recent API fixes.
Python 3.9 or higher. slmaj requires Python 3.9+ to run. Verify your Python version by opening a terminal and running:
python3 --version
If you see a version lower than 3.9, upgrade Python before proceeding. On macOS, we recommend installing Python through Homebrew. On Windows, download the latest version from python.org and ensure it is added to your system PATH during installation.
A stable internet connection. The IBKR API uses a persistent TCP socket connection between your machine and TWS or IB Gateway. Intermittent connectivity will cause disconnections that interrupt data feeds and order execution. If you plan to run slmaj on a remote server or VPS, make sure the server has reliable uptime and low latency to IBKR data centers.
Firewall and network permissions. The API communicates over localhost (127.0.0.1) by default, so no inbound firewall rules are typically needed. However, if you are running slmaj on a different machine than TWS, you will need to configure trusted IP addresses and ensure the relevant ports are open between the two machines.
2. TWS vs IB Gateway — Which to Use
Interactive Brokers provides two applications for API connectivity: Trader Workstation (TWS) and IB Gateway. Both allow slmaj to place orders, receive market data, and manage positions. The difference lies in their resource footprint and user interface.
Trader Workstation (TWS) is the full-featured trading platform. It provides a graphical interface where you can see your account balances, open positions, pending orders, and real-time market data. When slmaj places a trade, you can visually confirm it in the TWS order panel. This makes TWS the better choice for initial setup and debugging, because you can immediately verify that API commands are working as expected. The downside is that TWS consumes significantly more memory and CPU than IB Gateway, typically using 1–2 GB of RAM.
IB Gateway is a lightweight, headless alternative. It presents only a minimal login window and a status panel. There is no charting, no order book, and no position viewer. This makes it ideal for dedicated trading servers where you want to minimize resource usage. IB Gateway typically uses 200–400 MB of RAM. It is also more stable for long-running sessions because there is no GUI to consume event-loop resources.
Our recommendation: start with TWS while you are setting up and testing slmaj. Once you have confirmed that everything is working correctly and you are comfortable reading the slmaj logs and dashboard for trade confirmation, switch to IB Gateway for production use. Both applications use the same API protocol, so no code changes are needed when switching between them.
| Feature | TWS | IB Gateway |
|---|---|---|
| Graphical Interface | Full trading GUI | Minimal login window |
| Memory Usage | 1–2 GB | 200–400 MB |
| Visual Order Confirmation | Yes | No |
| Best For | Development and testing | Production servers |
| API Port (Live) | 7496 | 7496 |
| API Port (Paper) | 7497 | 7497 |
| Auto-Restart Support | Limited | Better (with IBC) |
| Stability (Long Sessions) | Good | Excellent |
If you decide to use IB Gateway in production, consider pairing it with IBC (IB Controller), an open-source tool that handles automatic login, daily restarts, and TWS/Gateway version updates. This eliminates the need to manually log in each day after the automatic session timeout.
3. Enabling API Access in TWS
By default, TWS does not accept API connections. You must explicitly enable the API through the Global Configuration settings. This is a one-time configuration that persists across TWS restarts.
Follow these steps exactly:
- Launch TWS and log in with your IBKR credentials (either live or paper trading).
- From the top menu, navigate to Edit > Global Configuration (on macOS: TWS > Global Configuration).
- In the left sidebar, expand API and click Settings.
- Check the box labeled Enable ActiveX and Socket Clients. This is the primary toggle that allows external programs like slmaj to connect.
- Set the Socket port field. Use
7496for live trading or7497for paper trading. If you are logged into a paper trading account, the port will default to 7497. - Under Trusted IPs, add
127.0.0.1if it is not already listed. This allows connections from your local machine without additional confirmation dialogs. - Uncheck the Read-Only API option. slmaj needs write access to place and modify orders. If this box is checked, the bot will be able to read account data and market data but will not be able to execute trades.
- Optionally, check Allow connections from localhost only for an additional layer of security if you are running slmaj on the same machine as TWS.
- Click Apply and then OK to save your settings.
After applying these settings, TWS is ready to accept incoming API connections. You do not need to restart TWS; the settings take effect immediately. To verify, look for the API status indicator in the top-right corner of TWS. It should show a green or neutral status, not a red warning icon.
Here is a summary of the configuration values:
# TWS API Configuration Summary
Enable ActiveX and Socket Clients: ON
Socket Port: 7497 # Use 7496 for live trading
Trusted IPs: 127.0.0.1
Read-Only API: OFF
Allow connections from localhost only: ON # Recommended for local setups
Master API client ID: (leave at default)
Important: If you see a popup dialog in TWS asking you to confirm an incoming API connection, it means the connecting IP is not in your Trusted IPs list. Either add the IP to the trusted list or click Accept. For automated operation, all connecting IPs should be pre-configured as trusted to avoid blocking the connection flow.
4. Port Configuration
The port number is how slmaj knows which TWS or IB Gateway instance to connect to, and it also determines whether you are trading with real money or in a simulated environment. Getting this wrong can have serious consequences, so take a moment to understand the port system.
Interactive Brokers uses two default ports:
- Port 7496 — Live trading. Orders placed through this port execute on real markets with real money. This is the production environment.
- Port 7497 — Paper trading. Orders are simulated against real-time market data but no actual money changes hands. This is the testing environment.
In the slmaj configuration file, you specify which port to connect to:
# config.py
IBKR_HOST = "127.0.0.1"
IBKR_PORT = 7497 # Paper trading (change to 7496 for live)
CLIENT_ID = 1
We strongly recommend starting with port 7497 (paper trading). Run slmaj in paper mode for at least several days to verify that strategies, risk parameters, and order execution behave as expected before switching to live trading. Switching between paper and live is a single-line configuration change.
To verify which port your running TWS instance is listening on, check the API settings as described in the previous section, or look at the TWS title bar, which typically shows whether you are logged into a live or paper account.
Common port conflicts and how to resolve them:
If slmaj reports a "Connection refused" error, the port may be in use by another application. You can check what is listening on a given port with these commands:
# macOS / Linux
lsof -i :7497
# Windows
netstat -ano | findstr :7497
If another application is occupying the port, you have two options: stop the conflicting application, or change the TWS API port to a non-conflicting number (for example, 7498) and update the slmaj configuration to match. Both TWS and slmaj must agree on the port number.
If you need to run multiple instances of slmaj simultaneously (for example, one connected to paper and one to live), each instance must use a different client ID, and they can share the same port if connecting to the same TWS instance. Alternatively, you can run separate TWS instances on different ports for complete isolation.
5. Setting Up a Paper Trading Account
Paper trading is a simulated trading environment provided by Interactive Brokers that mirrors real market conditions without risking actual capital. Every slmaj user should start with paper trading, regardless of experience level. It allows you to validate your configuration, test strategy parameters, and build confidence in the system before deploying real money.
Creating a paper trading account:
- Log in to your IBKR Account Management portal.
- Navigate to Settings > Paper Trading Account (under the Account section).
- If you do not already have a paper account, click Create. IBKR will generate a paper trading username, which is typically your live username with a "DU" prefix (for example, if your live username is
trader123, your paper username might beDUtrader123). - Set a password for the paper account. This password is separate from your live account password.
- Wait a few minutes for the account to be provisioned. Paper accounts are funded with a default simulated balance (usually $1,000,000 USD).
Logging in to paper trading:
When launching TWS, use your paper trading credentials (the DU-prefixed username and its password). TWS will display "Paper Trading Account" in the title bar to confirm you are in simulation mode. You can also select the "Paper Trading" option on the TWS login screen.
How paper trading simulates real conditions:
Paper trading uses real-time market data and simulates order execution based on the current order book. Market orders fill at the current ask (for buys) or bid (for sells). Limit orders fill when the market price crosses your limit. The simulation engine attempts to replicate realistic fill behavior, including partial fills on larger orders.
Limitations to be aware of:
- Fill quality: Paper trading fills may be more generous than live fills. In live markets, your order interacts with real liquidity and may experience slippage, partial fills, or rejections that paper trading does not replicate.
- Market impact: Paper orders do not affect the market. In live trading, large orders can move the price against you.
- Data delays: Some paper trading accounts receive delayed market data (15–20 minutes) unless you have subscribed to real-time data through IBKR. Check your market data subscriptions in Account Management.
- Options pricing: Paper trading may use theoretical option prices that differ from live market quotes, especially for illiquid contracts.
- Order types: While most order types work in paper trading, some advanced conditional orders may behave differently than in live trading.
Despite these limitations, paper trading is an essential step. It validates that slmaj can connect, receive data, generate signals, and execute orders. Any configuration errors will surface here rather than in a live environment where real money is at stake.
6. Connecting slmaj to IBKR
With TWS running and API access enabled, you can now connect slmaj to your Interactive Brokers account. This section covers the configuration file setup, running the connection test, and verifying a successful connection.
Step 1: Configure the connection settings.
Open the slmaj configuration file and set the IBKR connection parameters:
# config.py - IBKR Connection Settings
IBKR_HOST = "127.0.0.1" # Localhost (TWS on same machine)
IBKR_PORT = 7497 # Paper trading port
CLIENT_ID = 1 # Unique client identifier
# Account settings
ACCOUNT_ID = "DU1234567" # Your paper trading account ID
TRADING_MODE = "paper" # "paper" or "live"
The CLIENT_ID is a numeric identifier that distinguishes your slmaj connection from other API clients. If you only run one instance of slmaj, the default value of 1 is fine. If you run multiple bots or tools that connect to the same TWS instance, each must use a unique client ID (for example, 1, 2, 3).
Step 2: Run the connection test.
slmaj includes a built-in connection test that verifies API connectivity without placing any orders:
# Activate the environment and run the test
source trading_env/bin/activate
python test_connection.py
Step 3: Verify the output.
A successful connection test produces output similar to this:
$ python test_connection.py
[2026-02-27 10:15:32] Connecting to IBKR at 127.0.0.1:7497...
[2026-02-27 10:15:33] Connected. Server version: 163
[2026-02-27 10:15:33] Account ID: DU1234567
[2026-02-27 10:15:34] Account balance: $1,000,000.00
[2026-02-27 10:15:34] Market data: OK
[2026-02-27 10:15:34] Connection test PASSED
If the test fails, refer to the Troubleshooting section below. The most common issues are TWS not running, the API port not matching, or the API not being enabled.
Step 4: Understand the authentication flow.
slmaj does not handle IBKR login credentials directly. Authentication is managed entirely by TWS or IB Gateway. You log in to TWS with your username and password, and slmaj connects to the already-authenticated session over a local socket. This means TWS must be running and logged in before slmaj can connect. If TWS logs out (due to session timeout or manual logoff), slmaj will lose its connection and attempt to reconnect automatically.
For uninterrupted operation, configure TWS to stay logged in as long as possible. In Global Configuration > Lock and Exit, set the auto-logoff time to its maximum value. For IB Gateway, use IBC to handle automatic re-authentication after daily server resets (which occur around 23:45 EST).
7. Your First Paper Trade
With a successful connection test, you are ready to run slmaj in paper trading mode. This section walks you through the first hour of operation and explains what to look for to confirm that everything is working correctly.
Starting the bot:
source trading_env/bin/activate
python live_trading_bot.py
On launch, slmaj performs several initialization steps: it connects to TWS, requests account data, subscribes to market data feeds for configured symbols, and begins its signal generation cycle. You will see log output similar to:
[2026-02-27 10:30:00] Starting slmaj trading bot...
[2026-02-27 10:30:01] Connected to IBKR (paper trading)
[2026-02-27 10:30:02] Account balance: $1,000,000.00
[2026-02-27 10:30:03] Subscribing to market data: AAPL, GOOGL, MSFT, TSLA...
[2026-02-27 10:30:05] Market data received for 8/8 symbols
[2026-02-27 10:30:05] Signal generation cycle started
[2026-02-27 10:30:10] External data fetched: 12 indicators loaded
[2026-02-27 10:31:00] Signal: AAPL - BUY (confidence: 0.72)
[2026-02-27 10:31:01] Order placed: BUY 10 AAPL @ MKT
What to expect in the first hour:
During the initial period, slmaj collects enough data to begin generating trading signals. Depending on the configured strategy and market conditions, you may see your first trade within minutes or it may take longer. The bot logs every decision: when it considers a trade, when it decides to act or wait, and the reasoning behind each signal. If no trades occur in the first hour, that does not indicate a problem. It means the market conditions did not meet the strategy's entry criteria.
Reading the logs:
All activity is logged to both the terminal and a log file in the /logs/ directory. Log entries are timestamped and categorized by severity (INFO, WARNING, ERROR). Pay attention to WARNING and ERROR entries during initial testing. Common warnings include market data delays and order rejections for instruments you lack permissions for.
# View the latest log file
tail -f logs/trading_bot_2026-02-27.log
Verifying trades in TWS:
If you are running TWS (not IB Gateway), you can visually confirm trades. Open the Portfolio panel to see current positions and the Orders panel to see pending and filled orders. Every trade slmaj executes will appear in these panels in real time. Cross-reference the TWS order log with the slmaj output to verify they match.
Checking risk controls:
slmaj enforces multiple layers of risk controls on every trade. In the logs, you will see entries confirming that position sizes, daily loss limits, and account-level risk thresholds are being respected. For more details on how these controls work, see the Risk Controls documentation.
8. Troubleshooting
This section covers the most common issues encountered when connecting slmaj to Interactive Brokers, along with their solutions.
"Connection refused" error
This means slmaj cannot reach TWS or IB Gateway on the specified host and port. Possible causes:
- TWS or IB Gateway is not running. Launch the application and log in before starting slmaj.
- The port number in your slmaj config does not match the TWS API port. Verify both values match (7496 for live, 7497 for paper).
- A firewall is blocking the connection. This is rare for localhost connections but can occur with aggressive security software. Temporarily disable your firewall to test, then add an exception for the port.
- TWS crashed or logged out. Check the TWS window for error dialogs or login prompts.
# Quick diagnostic: check if TWS is listening
lsof -i :7497 # macOS/Linux
netstat -ano | findstr :7497 # Windows
"Not connected" error
This indicates that the API is not enabled in TWS. Go to Edit > Global Configuration > API > Settings and ensure that Enable ActiveX and Socket Clients is checked. Apply the settings and try connecting again. No TWS restart is required.
"Client ID already in use" error
Each API connection to TWS must use a unique client ID. This error means another application or another instance of slmaj is already connected with the same client ID. Solutions:
- Close the other API client or slmaj instance.
- Change the
CLIENT_IDin your config to a different number (for example, 2 or 3). - If the previous instance crashed without disconnecting cleanly, wait 30 seconds for TWS to release the stale connection, then try again.
Market data permissions error
IBKR requires separate market data subscriptions for different asset classes and exchanges. If slmaj reports "No market data permissions" for a symbol, you need to subscribe to the relevant data feed in your IBKR Account Management portal under Settings > Market Data Subscriptions. Paper trading accounts typically include free delayed data, but real-time data requires a paid subscription.
TWS auto-logoff
TWS automatically logs out once per day (usually around 23:45 EST on weekdays) for server maintenance. When this happens, slmaj loses its connection and cannot reconnect until TWS is logged in again. For unattended operation, use IBC (IB Controller) to handle automatic re-login. Configure the auto-logoff time in TWS under Global Configuration > Lock and Exit to maximize your session duration.
"Order rejected" errors
Order rejections can occur for several reasons: insufficient buying power, the market is closed, the instrument is not tradable in your account type, or risk management limits were exceeded. Check the specific rejection message in the slmaj logs for details. Common fixes include verifying that you are trading during market hours (9:30 AM–4:00 PM EST for US equities) and ensuring your account has sufficient margin for the trade.
If you encounter an issue not covered here, check the slmaj logs in the /logs/ directory for detailed error messages. The IBKR API error codes are documented in the official IBKR API reference.
Frequently Asked Questions
Can I run slmaj on a different machine than TWS?
Yes. Set the IBKR_HOST in your slmaj config to the IP address of the machine running TWS (instead of 127.0.0.1). You must also add the slmaj machine's IP address to the Trusted IPs list in TWS API settings, and ensure the API port is accessible through any firewalls between the two machines. This setup is common when running slmaj on a cloud server while TWS runs on a local desktop.
Do I need to keep TWS open the entire time slmaj is running?
Yes. TWS (or IB Gateway) must be running and logged in for slmaj to maintain its API connection. If TWS closes or logs out, slmaj will lose connectivity and will not be able to place or manage trades. For long-running deployments, use IB Gateway with IBC for automatic session management and daily re-authentication.
Is it safe to switch from paper trading to live trading?
The switch itself is a simple configuration change: update IBKR_PORT from 7497 to 7496 and log TWS into your live account. However, you should only make this switch after thoroughly testing in paper mode and reviewing the risk controls documentation. Paper trading results do not guarantee live trading results due to differences in fill quality, slippage, and market impact.
How many simultaneous API connections does IBKR allow?
IBKR allows up to 32 simultaneous API connections to a single TWS or IB Gateway instance. Each connection must use a unique client ID. In practice, most users need only one or two connections. If you are running multiple strategies, you can either use separate client IDs on the same TWS instance or run separate TWS instances with different accounts.