The Complete IBKR + Python Setup Guide
Everything you need to connect Python to Interactive Brokers and build a reliable foundation for analytics, research, reporting, and automation.
Why This Guide Exists
Most Interactive Brokers tutorials focus on isolated tasks, and that usually creates confusion instead of a reliable workflow.
One article shows how to connect. Another shows data download. Another explains positions. Another discusses orders. People then spend days trying to understand how those pieces fit together.
This guide takes a different approach: instead of one isolated snippet, it explains the full foundation required to build durable Python workflows around Interactive Brokers.
How People Will Reach It Through Search
This article is intentionally tagged and indexed as the flagship post, so members can discover it quickly from the header search box.
- Search terms: IBKR setup
- Search terms: Interactive Brokers Python
- Search terms: ib_insync connection
- Search terms: historical data IBKR
What You Will Build
By the end of this guide, you will understand the architecture and setup sequence needed before analytics, research, reporting, or automation.
- How Interactive Brokers exposes data to Python
- The difference between TWS and IB Gateway
- How to configure API access correctly
- How to connect Python safely
- How to retrieve account information
- How to retrieve positions
- How to request historical data
- How to structure a maintainable project
Understanding The Architecture
Most beginners imagine Python connecting directly to market infrastructure. That is not how IBKR integration works.
Python communicates with TWS or IB Gateway, and those applications act as the bridge to Interactive Brokers and market/account data.
Python
↓
TWS or IB Gateway
↓
Interactive Brokers
↓
Market Data / Account DataTWS vs IB Gateway
Before writing code, choose how Python will connect to Interactive Brokers.
- Trader Workstation (TWS): full platform with charts, order management, and portfolio views; easier for beginners but heavier on resources.
- IB Gateway: lightweight API-focused runtime; better for automation and long-running servers, but with less visual interface.
- Learning phase: TWS is usually easier.
- Automation phase: IB Gateway is usually the better choice.
Install Python
Install the latest stable Python release and verify your installation from the terminal.
python --version
python3 --versionCreate a Virtual Environment
Never install project dependencies globally. Create an isolated environment per project.
python -m venv venv
# macOS/Linux
source venv/bin/activate
# Windows
venv\Scripts\activateInstall Required Packages
Install the core packages used throughout this guide.
- ib_insync: cleaner interface to the Interactive Brokers API
- pandas: tabular data processing, analysis, reporting, and exports
pip install ib_insync pandasEnable API Access
Before Python can connect, API access must be enabled in TWS or IB Gateway. Interface labels can change over time, so verify directly in your installation.
- API enabled
- Trusted IP settings
- Read-only mode if desired
- Connection port
First Connection Test
Create test_connection.py and run a minimal connect/disconnect script to validate the foundation.
from ib_insync import IB
ib = IB()
try:
ib.connect("127.0.0.1", 7497, clientId=1)
print("Connected:", ib.isConnected())
finally:
ib.disconnect()Understanding Client IDs
Every API connection uses a client ID. Treat it as a session identifier and keep IDs distinct per application.
- Portfolio dashboard -> clientId=1
- Reporting tool -> clientId=2
- Research tool -> clientId=3
Retrieve Account Summary
Account summary gives account-level values such as net liquidation value, balances, buying power, and margin fields.
from ib_insync import IB
ib = IB()
ib.connect("127.0.0.1", 7497, clientId=1)
for item in ib.accountSummary():
print(item.tag, item.value)
ib.disconnect()Retrieve Portfolio Positions
Positions are usually the first operational dataset teams need after connectivity is stable.
from ib_insync import IB
ib = IB()
ib.connect("127.0.0.1", 7497, clientId=1)
for position in ib.positions():
print(
position.contract.symbol,
position.position,
position.avgCost
)
ib.disconnect()Convert Positions To Pandas
Once positions are in pandas, you can export, analyze, visualize, and report using the broader Python ecosystem.
from ib_insync import IB
import pandas as pd
ib = IB()
ib.connect("127.0.0.1", 7497, clientId=1)
rows = []
for item in ib.positions():
rows.append({
"symbol": item.contract.symbol,
"position": item.position,
"avgCost": item.avgCost
})
df = pd.DataFrame(rows)
print(df)
ib.disconnect()Request Historical Data
Historical data is a common use case, but availability depends on subscriptions, permissions, exchange rules, and IBKR limits.
from ib_insync import *
ib = IB()
ib.connect("127.0.0.1", 7497, clientId=1)
contract = Stock("AAPL", "SMART", "USD")
bars = ib.reqHistoricalData(
contract,
endDateTime="",
durationStr="1 Y",
barSizeSetting="1 day",
whatToShow="TRADES",
useRTH=True
)
print(len(bars))
ib.disconnect()Recommended Project Structure
Avoid keeping everything in one script. A modular layout makes maintenance, testing, and deployment easier.
project/
├── data/
├── reports/
├── notebooks/
├── scripts/
├── src/
│ ├── ibkr/
│ ├── analytics/
│ └── reporting/
├── tests/
├── requirements.txt
└── README.mdCommon Errors
- Connection refused: TWS/Gateway not running, API disabled, wrong port.
- Client ID already in use: another app already connected; try a different clientId.
- Empty positions: no holdings, wrong account context, or connectivity issue.
- Historical data empty: subscription/contract/request constraints or exchange restrictions.
Best Practices
- Use virtual environments for every project.
- Separate research notebooks from production services.
- Log connection state, reconnects, and API errors.
- Keep configuration in env/config files instead of hard-coding.
- Use paper trading first before any order-related code.
Where To Go Next
After stable connectivity, most teams move through this sequence.
- Account summary
- Portfolio positions
- Historical data collection
- Data storage
- Analytics
- Reporting
- Dashboards
- Automation
Disclaimer
This guide is provided for educational and technical reference purposes only.
Nothing on this website constitutes financial advice, investment advice, trading advice, tax advice, or legal advice.
Interactive Brokers, IBKR, Trader Workstation, and IB Gateway are trademarks or registered trademarks of their respective owners.
Always test code in a safe environment before using it with real accounts or live trading systems.