Skip to content

IdoPeer14/IBKR_API

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

 
 
 

Contributors