Skip to content

Production-ready portfolio rebalancing tool for Interactive Brokers with batch execution, atomic margin checks, and comprehensive safety features

License

Notifications You must be signed in to change notification settings

Jackmeson1/ib_strategy_project

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

69 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸš€ Interactive Brokers Portfolio Rebalancer | Production-Ready Algorithmic Trading

Python 3.10+ License: MIT IB API Production Ready Testing

The most advanced open-source portfolio rebalancing tool for Interactive Brokers - Built for professional traders, RIAs, and sophisticated investors managing multi-million dollar portfolios.

🎯 Production Validated: Successfully tested with real TWS paper account executing 1,000+ shares across comprehensive test scenarios with institutional-grade safety controls.

🌟 Why Choose This Tool?

Feature Our Tool Other Solutions
Multi-Currency Support βœ… CAD/USD with proper FX handling ❌ USD only
Leverage Safety βœ… Institutional-grade risk controls ❌ Basic or none
Native Batch Orders βœ… True IB-native bulk execution ❌ Sequential only
Short Position Protection βœ… Long-only strategy validation ❌ Risk of unintended shorts
Real-time Validation βœ… Before/after execution verification ❌ Fire-and-forget
Emergency Procedures βœ… Automatic liquidation at 3x leverage ❌ Manual intervention

πŸš€ Quick Start - Get Trading in 5 Minutes

1. Install & Setup

git clone https://github.com/Jackmeson1/ib_strategy_project.git
cd ib_strategy_project
pip install -r requirements.txt
cp config/env.example .env

2. Configure Your Account

# Edit .env with your Interactive Brokers details
IB_GATEWAY_PORT=7497        # 7497 for paper, 7496 for live trading
IB_CLIENT_ID=123           # Your unique client ID  
IB_ACCOUNT_ID=DU1234567    # Your IB account number
BASE_CURRENCY=CAD          # Account base currency (CAD/USD/EUR)
TARGET_LEVERAGE=1.4        # Desired portfolio leverage (1.0-1.8x safe)

3. Start Trading

# Test with paper account (recommended)
python main.py --dry-run

# Production mode with all safety features
python main.py --production-mode

πŸ›‘οΈ Production-Ready Features

Institutional-Grade Safety Controls

  • βœ… Safe Leverage Management: Automatically calculates max safe leverage based on available funds
  • βœ… Long-Only Protection: Prevents unintended short positions in long-only strategies
  • βœ… Progressive Changes: Limits leverage adjustments to 0.3x steps preventing market impact
  • βœ… Emergency Liquidation: Auto-liquidation triggers at 3x leverage threshold
  • βœ… Real-time Validation: Before/after execution verification with automatic rollback

Advanced Execution Engine

  • πŸš€ Native Batch Orders: True IB-native bulk submission (not thread pools)
  • ⚑ Smart Order Routing: Market orders <$10K, Limit orders >$10K
  • πŸ”„ Hanging Protection: 5-layer timeout system prevents stuck orders
  • πŸ“Š Multi-Currency: Full CAD/USD support with proper FX rate handling
  • 🎯 Atomic Validation: All-or-nothing execution with margin pre-checks

πŸ“ˆ Portfolio Configuration

Create your target allocation in examples/portfolio.csv:

symbol,weight,sector
SPY,0.40,US_Index
QQQ,0.20,Technology  
TLT,0.15,Bonds
GLD,0.15,Commodities
MSFT,0.10,Technology

Pre-built Strategies Available:

  • πŸ“Š 60/40 Classic: SPY/TLT balanced allocation
  • πŸš€ Growth Focus: QQQ/Individual stocks
  • πŸ›‘οΈ Conservative: Lower leverage, broader diversification
  • 🌍 Multi-Currency: CAD base with USD securities

πŸ”§ Advanced Usage

Professional Trading Modes

Conservative Mode (Recommended for beginners)

python main.py --leverage 1.2 --margin-cushion 0.3 --max-orders 5

Aggressive Mode (For experienced traders)

python main.py --leverage 1.6 --fast-execution --parallel-orders 10

Multi-Account Management

python main.py --accounts "DU1234567:CAD,DU7654321:USD" --allocation-mode proportional

Automated Daily Rebalancing

# Add to crontab for 9:30 AM EST execution
30 9 * * 1-5 cd /path/to/project && python main.py --production-mode

πŸ“Š Comprehensive Testing

This tool has undergone extensive validation with 10 comprehensive test suites:

Test Suite Status Coverage
Standard Execution βœ… Passed Real order placement and monitoring
Smart Execution βœ… Passed Hanging protection and retry logic
Native Batch βœ… Passed Bulk order processing
Margin Safety βœ… Passed Leverage limits and funding validation
Emergency Liquidation βœ… Passed Risk management scenarios
Portfolio Rebalancing βœ… Passed Weight allocation accuracy
Currency Handling βœ… Passed CAD/USD multi-currency support
Error Recovery βœ… Passed Edge case handling
Concurrent Orders βœ… Passed Parallel execution testing
Performance βœ… Passed Timing and efficiency metrics

Real Trading Environment Tested:

  • πŸ“‹ Account: TWS Paper Account with $2M+ CAD portfolio
  • πŸ’± Multi-Currency: CAD base currency with USD securities
  • πŸ“ˆ Live Orders: 1,000+ shares executed across multiple assets
  • πŸ“Š Market Data: Real-time pricing during market hours
  • πŸ›‘οΈ Margin Validation: IB margin system integration

πŸ› Critical Bugs Fixed

Leverage Validation Crisis ⚠️ β†’ βœ… FIXED

  • Issue: System attempted 2.5x leverage causing TWS margin warnings
  • Solution: Implemented SafeLeverageManager with max 1.866x based on available funds

Short Position Bug ⚠️ β†’ βœ… FIXED

  • Issue: SPY showing -1,820 shares in supposedly long-only strategy
  • Solution: LongOnlyPositionValidator prevents overselling scenarios

Currency Conversion ⚠️ β†’ βœ… FIXED

  • Issue: CAD/USD conversions failing with reversed FX rates
  • Solution: Proper currency handling with fallback mechanisms

🎯 Target Market & Business Applications

Registered Investment Advisors (RIAs)

  • Manage $100B+ market with automated rebalancing
  • Institutional-grade risk controls and compliance
  • Multi-client portfolio management capabilities

Family Offices & High Net Worth

  • $6T+ global family office market
  • Multi-currency portfolio support (CAD/USD/EUR)
  • Advanced tax optimization and loss harvesting

Algorithmic Trading Firms

  • Real-time execution with sub-second rebalancing
  • Multiple broker integration capabilities
  • Sophisticated risk management protocols

πŸ“ Repository Structure

πŸ“¦ ib_strategy_project/
β”œβ”€β”€ πŸ—οΈ src/                    # Core application code
β”‚   β”œβ”€β”€ execution/             # Advanced order execution engines
β”‚   β”œβ”€β”€ portfolio/             # Portfolio management & rebalancing
β”‚   β”œβ”€β”€ strategy/              # Trading strategies & risk management
β”‚   └── utils/                 # Currency, logging, notifications
β”œβ”€β”€ πŸ§ͺ tests/                  # Comprehensive testing suite
β”‚   β”œβ”€β”€ integration/           # IB TWS/Gateway API tests
β”‚   β”œβ”€β”€ functional/            # End-to-end workflow validation
β”‚   β”œβ”€β”€ unit/                  # Component testing
β”‚   β”œβ”€β”€ data/                  # Test portfolios & configurations
β”‚   └── tools/                 # Debug & analysis utilities
β”œβ”€β”€ πŸ“š docs/                   # Documentation & guides
β”œβ”€β”€ πŸ“Š examples/               # Sample portfolio configurations
└── πŸ“ˆ portfolio_snapshots/    # Historical execution records

πŸ” Monitoring & Analytics

Real-time Portfolio Snapshots

{
  "timestamp": "2024-06-13T14:30:00",
  "portfolio_value_cad": 2075000,
  "available_funds_cad": 847264,
  "current_leverage": 1.406,
  "target_leverage": 1.4,
  "orders_executed": 8,
  "execution_time_seconds": 45.2,
  "margin_utilization": 0.546
}

Optional Telegram Alerts

TELEGRAM_BOT_TOKEN=your_bot_token
TELEGRAM_CHAT_ID=your_chat_id

Get instant notifications for:

  • βœ… Successful rebalancing completion
  • ⚠️ Margin warnings or safety triggers
  • 🚨 Emergency liquidation events
  • πŸ“Š Daily portfolio performance summaries

πŸš€ Production Deployment Checklist

Before going live with real money:

  • Test Extensively: Run comprehensive test suite with paper account
  • Verify Connections: Ensure IB Gateway/TWS connectivity
  • Review Limits: Confirm leverage and position size limits
  • Safety Checks: Validate emergency liquidation procedures
  • Start Small: Begin with reduced position sizes
  • Monitor Closely: Watch first few executions manually
  • Backup Plan: Have manual override procedures ready

πŸ“– Documentation

Comprehensive guides available in docs/:

🀝 Contributing

We welcome contributions from the algorithmic trading community!

How to Contribute:

  1. Fork the repository
  2. Create a feature branch
  3. Add comprehensive tests
  4. Submit a pull request

Areas for Contribution:

  • Additional broker integrations (TD Ameritrade, Schwab, etc.)
  • Advanced portfolio optimization algorithms
  • Tax-loss harvesting enhancements
  • Alternative asset class support

βš–οΈ Legal & Risk Disclaimers

⚠️ Important Risk Warning:

  • Trading with leverage involves substantial risk of loss
  • Past performance does not guarantee future results
  • This software is provided "as-is" without warranties
  • Always test thoroughly before live trading
  • Consider your risk tolerance and investment objectives

Compliance Note: Ensure your usage complies with applicable securities regulations in your jurisdiction.

πŸ“„ License

MIT License - see LICENSE for details.


🏷️ Keywords

Interactive Brokers, IB API, Portfolio Rebalancing, Algorithmic Trading, Python Trading Bot, Multi-Currency Trading, Leverage Management, Risk Management, Automated Trading, Financial Technology, Investment Management, Quantitative Finance


⭐ Star this repository if you find it useful for your trading operations!

πŸ”— Follow for updates on new features and trading strategies.


Built with ❀️ for the algorithmic trading community

About

Production-ready portfolio rebalancing tool for Interactive Brokers with batch execution, atomic margin checks, and comprehensive safety features

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •  

Languages