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.
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 |
git clone https://github.com/Jackmeson1/ib_strategy_project.git
cd ib_strategy_project
pip install -r requirements.txt
cp config/env.example .env
# 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)
# Test with paper account (recommended)
python main.py --dry-run
# Production mode with all safety features
python main.py --production-mode
- β 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
- π 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
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
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
# Add to crontab for 9:30 AM EST execution
30 9 * * 1-5 cd /path/to/project && python main.py --production-mode
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
- Issue: System attempted 2.5x leverage causing TWS margin warnings
- Solution: Implemented SafeLeverageManager with max 1.866x based on available funds
- Issue: SPY showing -1,820 shares in supposedly long-only strategy
- Solution: LongOnlyPositionValidator prevents overselling scenarios
- Issue: CAD/USD conversions failing with reversed FX rates
- Solution: Proper currency handling with fallback mechanisms
- Manage $100B+ market with automated rebalancing
- Institutional-grade risk controls and compliance
- Multi-client portfolio management capabilities
- $6T+ global family office market
- Multi-currency portfolio support (CAD/USD/EUR)
- Advanced tax optimization and loss harvesting
- Real-time execution with sub-second rebalancing
- Multiple broker integration capabilities
- Sophisticated risk management protocols
π¦ 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
{
"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
}
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
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
Comprehensive guides available in docs/:
- π§ Interactive Brokers Setup Guide
- π Portfolio Rebalancing Strategies
- π οΈ IB API Best Practices
- π Financial Optimization Roadmap
- π§ͺ Comprehensive Testing Summary
We welcome contributions from the algorithmic trading community!
How to Contribute:
- Fork the repository
- Create a feature branch
- Add comprehensive tests
- 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
- 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.
MIT License - see LICENSE for details.
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