How to Build an IBKR Trading Bot in Python (Complete Guide)
Interactive Brokers (IBKR) is one of the most powerful platforms for algorithmic trading. In this guide, we will walk you through building a fully automated IBKR trading bot using Python and the ib_insync library.
## What You Need
Before you start, you need the following:
- Interactive Brokers account (paper or live)
- TWS (Trader Workstation) or IB Gateway installed
- Python 3.8 or higher
- ib_insync library installed via pip
## Step 1 — Install ib_insync
Open your terminal and run:
pip install ib_insync
This is the most popular Python wrapper for the IBKR TWS API. It simplifies connecting and placing orders significantly.
## Step 2 — Connect to TWS
from ib_insync import IB, Stock, MarketOrder
ib = IB()
ib.connect('127.0.0.1', 7497, clientId=1)
Make sure TWS is open and API connections are enabled in settings.
## Step 3 — Define Your Instrument
contract = Stock('AAPL', 'SMART', 'USD')
ib.qualifyContracts(contract)
## Step 4 — Place an Order
order = MarketOrder('BUY', 10)
trade = ib.placeOrder(contract, order)
ib.sleep(1)
print(trade.orderStatus.status)
## Step 5 — Add Your Strategy Logic
A simple moving average crossover strategy:
import pandas as pd
bars = ib.reqHistoricalData(contract, endDateTime='', durationStr='30 D',
barSizeSetting='1 hour', whatToShow='MIDPOINT', useRTH=True)
df = pd.DataFrame(bars)
df['sma20'] = df['close'].rolling(20).mean()
df['sma50'] = df['close'].rolling(50).mean()
if df['sma20'].iloc[-1] > df['sma50'].iloc[-1]:
print('Bullish signal — Buy')
else:
print('Bearish signal — Sell')
## Common IBKR Bot Features
A production-ready IBKR bot typically includes:
- Live and paper trading mode switch
- Risk management with stop loss and take profit
- Position sizing based on account equity
- Real-time alerts via Telegram
- Backtesting against historical data
## Hire an IBKR Bot Developer
Building a reliable IBKR trading bot takes experience. Team NAK has delivered 300+ custom IBKR bots for clients worldwide. We build bots for stocks, futures, options, and forex using Python and ib_insync.
Contact us at theteamnak.com to get a free quote for your IBKR bot project.