How to Build an IBKR Trading Bot in Python (Complete Guide 2026)
This guide walks through building an automated trading bot for Interactive Brokers (IBKR) in Python: connecting to the IBKR API, pulling market data, generating a signal, placing orders with a stop loss and take profit, and keeping the bot running without you watching it. The code uses a simple moving average strategy so the focus stays on the parts that are specific to IBKR. It is an example to learn from, not a strategy to trade.
What you need before you start
- An IBKR account with a paper trading account. Every IBKR account comes with a paper account. Build and test there first.
- TWS or IB Gateway. The IBKR API does not connect to IBKR's servers directly. Your Python code talks to Trader Workstation (TWS) or IB Gateway running on your machine, and that program talks to IBKR. IB Gateway is lighter and is the better choice for a bot.
- API access switched on. In TWS or Gateway open the API settings, enable socket clients, and turn off "Read-Only API" so the bot is allowed to place orders.
- Market data subscriptions for what you trade. Without them the API returns delayed data or an error, even though charts in TWS may still show prices.
- Python 3.10 or newer.
The default API ports are worth memorising, because connecting to the wrong one is the most common first mistake:
- IB Gateway paper:
4002 - IB Gateway live:
4001 - TWS paper:
7497 - TWS live:
7496
Which IBKR API and Python library to use
Interactive Brokers has several APIs. For trading bots the standard choice is the TWS API, which is the socket API served by TWS and IB Gateway. In Python you can use it in two ways:
ibapi, the official client from IBKR. You subclassEWrapperandEClientand handle every callback yourself. It gives full control, but you write a lot of plumbing.ib_async, a higher level library built on the same API. It is the maintained successor toib_insync, which is no longer developed. It keeps positions, orders and tickers in sync for you and lets you write straightforward code.
This guide uses ib_async. If you have older ib_insync code, the function names are the same and most scripts work after changing the import.
pip install ib_async pandas
Step 1: Connect to IB Gateway
from ib_async import IB
ib = IB()
ib.connect("127.0.0.1", 4002, clientId=1) # IB Gateway, paper account
print("Connected:", ib.isConnected())
print("Accounts:", ib.managedAccounts())
The clientId identifies this connection. Two programs cannot use the same client ID at the same time, so give each script its own number.
Step 2: Define the contract and get historical data
IBKR identifies every instrument as a contract. Always qualify a contract before using it, so IBKR fills in the exact exchange and contract ID.
from ib_async import Stock, util
contract = Stock("SPY", "SMART", "USD")
ib.qualifyContracts(contract)
bars = ib.reqHistoricalData(
contract,
endDateTime="",
durationStr="30 D",
barSizeSetting="1 hour",
whatToShow="TRADES",
useRTH=True,
)
df = util.df(bars)
print(df.tail())
Historical data requests are rate limited. If you request too much too quickly you get a pacing violation, so fetch what you need once and then update it, instead of reloading the full history in a loop.
Step 3: Turn the data into a signal
Keep signal logic in a plain function that takes a DataFrame and returns a decision. It is easy to test, and you can reuse the same function in a backtest.
def get_signal(df, fast=20, slow=50):
closes = df["close"]
fast_ma = closes.rolling(fast).mean()
slow_ma = closes.rolling(slow).mean()
# use the last two completed bars to detect a cross
if fast_ma.iloc[-2] <= slow_ma.iloc[-2] and fast_ma.iloc[-1] > slow_ma.iloc[-1]:
return "BUY"
if fast_ma.iloc[-2] >= slow_ma.iloc[-2] and fast_ma.iloc[-1] < slow_ma.iloc[-1]:
return "SELL"
return None
Step 4: Size the position and place a bracket order
Never send an entry without a stop. A bracket order sends the entry, the take profit and the stop loss together. When one exit fills, IBKR cancels the other.
Position size should come from how much you are willing to lose on the trade, not from a fixed share count:
import math
def position_size(equity, risk_pct, entry, stop):
risk_per_share = abs(entry - stop)
if risk_per_share == 0:
return 0
return math.floor(equity * risk_pct / risk_per_share)
def net_liquidation():
for row in ib.accountSummary():
if row.tag == "NetLiquidation":
return float(row.value)
return 0.0
def enter_long(contract, entry, stop, target, risk_pct=0.005):
qty = position_size(net_liquidation(), risk_pct, entry, stop)
if qty < 1:
return None
bracket = ib.bracketOrder("BUY", qty, limitPrice=entry,
takeProfitPrice=target, stopLossPrice=stop)
trades = [ib.placeOrder(contract, order) for order in bracket]
return trades
Round prices to the instrument's tick size before sending them. An order with an invalid price increment is rejected.
Step 5: Check positions and track fills
Before every entry, ask IBKR what you actually hold. Do not rely on a variable in your script, because it is wrong after a restart or a manual trade.
def current_position(contract):
for pos in ib.positions():
if pos.contract.conId == contract.conId:
return pos.position
return 0
def on_fill(trade, fill):
print("Filled", fill.execution.side, fill.execution.shares,
"at", fill.execution.price)
# attach to a trade returned by placeOrder
# trade.fillEvent += on_fill
Orders can fill partially. Read the filled quantity from the trade's order status, and treat an order as done only when its status is Filled or Cancelled.
Step 6: The main loop
def run():
while True:
bars = ib.reqHistoricalData(contract, endDateTime="", durationStr="30 D",
barSizeSetting="1 hour", whatToShow="TRADES",
useRTH=True)
df = util.df(bars)
signal = get_signal(df)
if signal == "BUY" and current_position(contract) == 0:
price = df["close"].iloc[-1]
enter_long(contract, entry=round(price, 2),
stop=round(price * 0.99, 2),
target=round(price * 1.02, 2))
ib.sleep(60 * 60) # wait for the next hourly bar
run()
Use ib.sleep(), not time.sleep(). It keeps the connection's event loop running while your code waits, so order and position updates keep arriving.
Step 7: Keep the bot running
A script that works for an afternoon is the easy part. Most IBKR bots fail on the things below, which have nothing to do with the strategy.
- Disconnects. The connection to TWS or Gateway will drop sometimes. Check the connection before each pass of the loop, reconnect with a delay, and re-request any data subscriptions after reconnecting.
- The daily restart. TWS and IB Gateway restart or log out once a day. Set the auto restart time in the settings to a quiet period outside your trading hours, and make sure the bot survives it.
- Logins. Gateway needs to be logged in again after a full logout. Many people use a tool such as IBC to start Gateway and log in automatically on a server.
- State after a restart. On startup, read open orders and positions from IBKR and continue from there. Never assume you start flat.
- Logging and alerts. Log every signal, order and fill to a file, and send yourself a Telegram or email message on errors. You want to find out about a problem from an alert, not from your account balance.
- A hard risk limit. Add a daily loss limit that stops new entries when it is hit, and a kill switch that cancels orders and closes positions.
import time
def ensure_connected():
while not ib.isConnected():
try:
ib.connect("127.0.0.1", 4002, clientId=1)
except Exception as e:
print("Reconnect failed:", e)
time.sleep(10)
ib.disconnectedEvent += lambda: print("Disconnected from Gateway")
# call ensure_connected() at the top of every pass of the main loop
For 24/7 trading, run Gateway and the bot on a VPS so they do not depend on your computer or your home internet connection.
Common IBKR API errors and what they mean
- Error 502, couldn't connect. TWS or Gateway is not running, the port is wrong, or the API is not enabled in settings.
- Error 326, client ID already in use. Another script is connected with the same
clientId. - Error 162, historical data pacing violation. Too many historical data requests in a short time. Slow down and cache data.
- Error 354, market data not subscribed. Your account has no live data subscription for that instrument.
- Error 201, order rejected. The message contains the reason, for example a margin shortfall, a missing trading permission or an invalid price.
- Errors 1100 and 1102. Connectivity between IBKR and Gateway was lost and then restored. Your bot should wait and continue, not crash.
Messages such as 2104 and 2106 look like errors but are only status notices that the data farms are connected.
Going from paper to live
- Run the bot on the paper account for at least a couple of weeks and compare every trade with what the strategy should have done.
- Test the failure cases on purpose: close Gateway, cut the internet connection, restart the script while a position is open.
- Switch to the live port with the smallest position size you can trade.
- Increase size only after live fills match what you saw on paper. Paper fills are optimistic, especially for limit orders and illiquid instruments.
Frequently asked questions
Is the IBKR API free?
Yes. There is no charge for API access. You pay the usual commissions and any market data subscriptions.
Do I need to keep TWS open?
TWS or IB Gateway has to be running and logged in for the bot to work. On a VPS, IB Gateway is the usual choice.
Can the bot trade options and futures?
Yes. Use the Option or Future contract classes in place of Stock. Your account needs the trading permissions and market data for them.
Should I use ib_insync or ib_async?
Use ib_async for new projects. It continues the same library under a new name and receives updates.
Want it built for you?
If you would rather have this done properly than learn every edge case yourself, we build these systems for clients. See IBKR trading bot development for full bots, or IBKR API development if you need an integration or a fix for existing code. Related guides: IBKR backtesting with Python and TradingView alerts to IBKR with webhooks.
This article is for education. It is not financial advice, and no trading system is guaranteed to be profitable.