Skip to content

Clean REST API for Interactive Brokers trading automation. Place orders, track positions, monitor executions - built with FastAPI for high-performance algorithmic trading systems.

License

Notifications You must be signed in to change notification settings

IdoPeer14/IBKR_API

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

25 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸš€ IBKR Trading API

A production-ready REST API wrapper for Interactive Brokers built with FastAPI and ib_insync. Provides a clean, simple interface for algorithmic trading, portfolio management, and order execution.

Python FastAPI License Status


✨ Key Features

Trading & Order Management

  • βœ… Limit Orders - Buy/sell at specific prices
  • βœ… Bracket Orders - Protected trades with automatic stop-loss and take-profit
  • βœ… Order Tracking - Monitor pending orders in real-time
  • βœ… Order Cancellation - Cancel unfilled orders programmatically
  • βœ… Custom References - Tag orders for easy tracking

Portfolio & Account

  • βœ… Account Summary - Real-time balance and cash availability
  • βœ… Position Tracking - Monitor all open positions with P&L
  • βœ… Execution History - Track filled orders from multiple sources

Technical Excellence

  • πŸ”’ Thread-Safe - Sequential command queue prevents race conditions
  • πŸ”„ Auto-Reconnect - Manages IB Gateway connections automatically
  • πŸ“ Type Safety - Pydantic models for request validation
  • πŸš€ Async/Await - Built on FastAPI for high performance
  • πŸ“š Auto Documentation - Interactive API docs at /docs
  • πŸ§ͺ Test Suite - Comprehensive testing included

🎯 Use Cases

This API is perfect for:

  • Algorithmic Trading Systems - Execute trades programmatically
  • Portfolio Management Tools - Monitor and rebalance portfolios
  • Trading Bots - Automate trading strategies
  • Risk Management - Implement stop-loss and take-profit automatically
  • Research & Backtesting - Connect live data to analysis tools

πŸš€ Quick Start

Prerequisites

  • Python 3.8 or higher
  • Interactive Brokers account (Paper Trading recommended for testing)
  • IB Gateway or TWS installed

1. Clone the Repository

git clone https://github.com/IdoPeer14/ibkr-trading-api.git
cd ibkr-trading-api

2. Install Dependencies

# Create virtual environment
python3 -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

# Install requirements
pip install -r requirements.txt

3. Configure IB Gateway

See IB_GATEWAY.md for detailed setup instructions.

Quick setup:

  1. Launch IB Gateway or TWS
  2. Go to Configure β†’ Settings β†’ API β†’ Settings
  3. Enable: βœ… Enable ActiveX and Socket Clients
  4. Set Port: 4002 (Paper Trading)
  5. Add Trusted IP: 127.0.0.1

4. Start the Server

# Easy start with script
./start.sh

# Or manually
uvicorn main:app --host 127.0.0.1 --port 8000 --reload

Server runs at: http://localhost:8000

5. Test the API

# Quick health check
curl http://localhost:8000/

# Get account info
curl http://localhost:8000/account

# Interactive docs
# Open browser: http://localhost:8000/docs

πŸ“‘ API Endpoints

Account & Portfolio

GET /account - Account Summary

curl http://localhost:8000/account

Response:

{
  "balance": 201879.04,
  "cash": 200000.0
}

GET /positions - Open Positions

curl http://localhost:8000/positions

Response:

{
  "positions": [
    {
      "symbol": "AAPL",
      "qty": 10,
      "avg_cost": 230.50,
      "market_value": 2305.00
    }
  ]
}

Order Management

POST /order/limit - Place Limit Order

curl -X POST http://localhost:8000/order/limit \
  -H "Content-Type: application/json" \
  -d '{
    "symbol": "AAPL",
    "action": "BUY",
    "quantity": 10,
    "limit_price": 230.00,
    "order_ref": "my_trade_001"
  }'

Response:

{
  "status": "βœ… Limit order sent",
  "permId": 1788680597
}

POST /order/bracket - Place Bracket Order

Protected order with automatic stop-loss and take-profit:

curl -X POST http://localhost:8000/order/bracket \
  -H "Content-Type: application/json" \
  -d '{
    "symbol": "AAPL",
    "action": "BUY",
    "quantity": 10,
    "entry_price": 230.00,
    "stop_loss": 225.00,
    "take_profit": 240.00,
    "order_ref": "protected_trade_001"
  }'

Response:

{
  "status": "βœ… Bracket order sent",
  "permIds": [1788680598, 1788680599, 1788680600]
}

GET /orders - Get Pending Orders

curl http://localhost:8000/orders

POST /order/cancel - Cancel Order

curl -X POST http://localhost:8000/order/cancel \
  -H "Content-Type: application/json" \
  -d '{"perm_id": 1788680597}'

Execution Tracking

GET /executions - Get Execution History

# All executions
curl http://localhost:8000/executions

# Filtered by symbol
curl "http://localhost:8000/executions?symbol=AAPL"

πŸ’» Client Examples

Python Client

import requests

class IBKRClient:
    def __init__(self, base_url="http://localhost:8000"):
        self.base_url = base_url
    
    def get_account(self):
        response = requests.get(f"{self.base_url}/account")
        return response.json()
    
    def buy_limit(self, symbol, quantity, price, order_ref=None):
        data = {
            "symbol": symbol,
            "action": "BUY",
            "quantity": quantity,
            "limit_price": price,
            "order_ref": order_ref
        }
        response = requests.post(f"{self.base_url}/order/limit", json=data)
        return response.json()
    
    def bracket_order(self, symbol, action, quantity, entry, stop, profit):
        data = {
            "symbol": symbol,
            "action": action,
            "quantity": quantity,
            "entry_price": entry,
            "stop_loss": stop,
            "take_profit": profit
        }
        response = requests.post(f"{self.base_url}/order/bracket", json=data)
        return response.json()

# Usage
client = IBKRClient()
account = client.get_account()
print(f"Balance: ${account['balance']:,.2f}")

# Place protected order
order = client.bracket_order(
    symbol="AAPL",
    action="BUY",
    quantity=10,
    entry=230.00,
    stop=225.00,
    profit=240.00
)
print(f"Order placed: {order['permIds']}")

JavaScript / Node.js Client

const axios = require('axios');

class IBKRClient {
    constructor(baseURL = 'http://localhost:8000') {
        this.client = axios.create({ baseURL });
    }
    
    async getAccount() {
        const { data } = await this.client.get('/account');
        return data;
    }
    
    async buyLimit(symbol, quantity, price, orderRef = null) {
        const { data } = await this.client.post('/order/limit', {
            symbol,
            action: 'BUY',
            quantity,
            limit_price: price,
            order_ref: orderRef
        });
        return data;
    }
    
    async bracketOrder(symbol, action, quantity, entry, stop, profit) {
        const { data } = await this.client.post('/order/bracket', {
            symbol, action, quantity,
            entry_price: entry,
            stop_loss: stop,
            take_profit: profit
        });
        return data;
    }
}

// Usage
const ibkr = new IBKRClient();

(async () => {
    const account = await ibkr.getAccount();
    console.log(`Balance: $${account.balance}`);
    
    const order = await ibkr.bracketOrder('AAPL', 'BUY', 10, 230, 225, 240);
    console.log(`Order placed: ${order.permIds}`);
})();

πŸ—οΈ Architecture

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   Client App    β”‚  (Python, JS, etc.)
β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”˜
         β”‚ HTTP REST
         β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   FastAPI Server (Port 8000)    β”‚
β”‚   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”‚
β”‚   β”‚  Routes                  β”‚  β”‚
β”‚   β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β”‚
β”‚            β”‚                     β”‚
β”‚   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”‚
β”‚   β”‚  Command Queue           β”‚  β”‚  ← Thread-safe
β”‚   β”‚  (Sequential Execution)  β”‚  β”‚
β”‚   β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β”‚
β”‚            β”‚                     β”‚
β”‚   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”‚
β”‚   β”‚  IBKR Modules            β”‚  β”‚
β”‚   β”‚  - Positions             β”‚  β”‚
β”‚   β”‚  - Orders                β”‚  β”‚
β”‚   β”‚  - Executions            β”‚  β”‚
β”‚   β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β”‚
β”‚            β”‚                     β”‚
β”‚   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”‚
β”‚   β”‚  IB Client Manager       β”‚  β”‚
β”‚   β”‚  - Auto connect          β”‚  β”‚
β”‚   β”‚  - Error handling        β”‚  β”‚
β”‚   β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
             β”‚ ib_insync
             β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   IB Gateway / TWS (Port 4002)  β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
             β”‚ TWS API
             β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   Interactive Brokers Platform  β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Key Design Decisions

  1. Command Queue - Ensures thread-safe sequential execution
  2. Transient Connections - Opens/closes IB connection per request
  3. Pydantic Models - Type-safe request validation
  4. Async/Await - Non-blocking FastAPI operations
  5. Modular Structure - Separated concerns for maintainability

πŸ§ͺ Testing

Run Test Suite

# Interactive test menu
python test_api.py

# Run all tests (safe mode)
python test_api.py --all

Run Live Demo

# Comprehensive demonstration
python live_demo.py

The demo will:

  • βœ… Check account status
  • βœ… Place test orders (low prices, won't fill)
  • βœ… Monitor order status
  • βœ… Cancel orders
  • βœ… Show execution history

πŸ“ Project Structure

ibkr-trading-api/
β”œβ”€β”€ main.py                 # FastAPI application entry point
β”œβ”€β”€ requirements.txt        # Python dependencies
β”œβ”€β”€ start.sh               # Quick start script
β”œβ”€β”€ api/
β”‚   └── routes.py          # API route definitions
β”œβ”€β”€ ibkr_api/
β”‚   β”œβ”€β”€ client.py          # IB connection management
β”‚   β”œβ”€β”€ command_queue.py   # Thread-safe command execution
β”‚   β”œβ”€β”€ positions.py       # Position tracking
β”‚   β”œβ”€β”€ orders.py          # Order management
β”‚   β”œβ”€β”€ executions.py      # Execution tracking
β”‚   └── utils.py           # Helper functions
β”œβ”€β”€ test_api.py            # Test suite
β”œβ”€β”€ live_demo.py           # Live demonstration
β”œβ”€β”€ README.md              # This file
└── IB_GATEWAY.md          # IB Gateway setup guide

βš™οΈ Configuration

Environment Variables

Create a .env file (optional):

IB_HOST=127.0.0.1
IB_PORT=4002          # 4002 for Paper, 4001 for Live
IB_CLIENT_ID=100

API_HOST=127.0.0.1
API_PORT=8000

IB Gateway Ports

Environment Port Risk Level
Paper Trading 4002 βœ… Safe for testing
Live Trading 4001 ⚠️ Use with caution

⚠️ ALWAYS test with Paper Trading (port 4002) first!


🎯 Best Practices

1. Use Order References

# βœ… Good - Track your orders
order_ref = f"strategy_1_{timestamp}"
client.buy_limit("AAPL", 10, 230.00, order_ref=order_ref)

# ❌ Bad - No tracking
client.buy_limit("AAPL", 10, 230.00)

2. Save Executions to Database

# βœ… Good - Persistent storage
executions = client.get_executions()
for exec in executions:
    database.save(exec)  # Your database

# ❌ Bad - Rely on API (resets on restart)
executions = client.get_executions()

3. Check Account Before Trading

# βœ… Good - Verify funds
account = client.get_account()
if account['cash'] >= required_cash:
    client.buy_limit("AAPL", 10, 230.00)
else:
    print("Insufficient funds!")

4. Use Bracket Orders for Protection

# βœ… Good - Protected trade
client.bracket_order(
    symbol="AAPL",
    action="BUY",
    quantity=10,
    entry=230.00,
    stop=225.00,   # -2.2% risk
    profit=240.00  # +4.3% reward
)

# ❌ Bad - No protection
client.buy_limit("AAPL", 10, 230.00)

πŸ› Troubleshooting

Cannot connect to IB Gateway

Solution:

  1. Verify IB Gateway/TWS is running
  2. Check API is enabled (Port 4002)
  3. Add 127.0.0.1 to trusted IPs
  4. Test connection: telnet 127.0.0.1 4002

Orders not filling

Common Causes:

  • Price too far from market
  • After-hours trading (9:30 AM - 4:00 PM ET only)
  • Insufficient funds
  • Stock halted/delisted

Executions not showing

Explanation:

  • Execution history resets when IB Gateway restarts
  • Solution: Save executions to your own database

For more troubleshooting, see README.md in the original files.


πŸ“š Documentation


🀝 Contributing

Contributions are welcome! Please:

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/amazing-feature
  3. Test thoroughly with Paper Trading
  4. Commit: git commit -m 'Add amazing feature'
  5. Push: git push origin feature/amazing-feature
  6. Open a Pull Request

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.


⚠️ Disclaimer

IMPORTANT: This software is for educational and research purposes only.

  • ❌ Not financial advice
  • ❌ No guarantees of profit
  • ❌ Trading involves risk of loss
  • ❌ Past performance β‰  future results

Use at your own risk. The authors are not responsible for any financial losses.

Always:

  • βœ… Test thoroughly with Paper Trading
  • βœ… Understand the risks
  • βœ… Never invest more than you can afford to lose
  • βœ… Consult with financial professionals

πŸ™ Acknowledgments


Built with ❀️ for algorithmic traders

About

Clean REST API for Interactive Brokers trading automation. Place orders, track positions, monitor executions - built with FastAPI for high-performance algorithmic trading systems.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published