An enterprise-grade automated trading system with modern web dashboard
Implementing the options wheel strategy with advanced position management, automatic rolling, and intelligent risk controls
# 1. Clone and enter directory
git clone https://github.com/yourusername/wheelforge.git && cd wheelforge
# 2. Install with one command
pip install uv && uv venv && uv pip install -e . && uv pip install -r requirements_web.txt
# 3. Launch the dashboard
python web_app.py
# 4. Open http://localhost:5000 - The setup wizard will guide you through everything!That's it! The web interface will walk you through:
- ๐ Entering your Alpaca API keys
- โ๏ธ Configuring your strategy settings
- ๐ Selecting symbols to trade
- โ Starting your first wheel strategy
WheelForge is a production-ready automated trading platform that executes the options wheel strategy using the Alpaca Trading API. Built with reliability and profitability in mind, it features enterprise-grade error handling, intelligent position management, and sophisticated risk controls that go beyond basic wheel implementations.
The classic wheel strategy involves:
- Selling cash-secured puts to collect premium
- Taking assignment of shares if ITM at expiration
- Selling covered calls on assigned shares
- Repeating the cycle when shares are called away
WheelForge takes this further with:
- Multi-layer positioning for averaging down opportunities
- Premium-adjusted cost basis tracking for optimal strike selection
- Automatic option rolling to manage positions before expiration
- Per-symbol configuration for tailored risk management
- Enterprise reliability with retry logic, circuit breakers, and thread safety
- โ Intelligent Option Selection - Advanced scoring algorithm balancing return vs assignment risk
- โ Multi-Layer Wheels - Run multiple wheel cycles per symbol for dollar-cost averaging
- โ Cost Basis Optimization - Tracks premiums to adjust cost basis for better exits
- โ Automatic Rolling - Roll positions before expiration with configurable strategies
- โ Limit Order System - Smart order management with automatic repricing for better fills
- โ Database Tracking - SQLite database for all trades, premiums, and performance metrics
- โ Per-Symbol Configuration - Customize contracts and settings for each ticker
- โ Modern Web Dashboard - Real-time monitoring with dark/light mode and live config editing
- ๐ Thread-Safe Operations - Prevents race conditions with proper locking
- ๐ Automatic Retry Logic - Exponential backoff with circuit breaker pattern
- ๐พ Database Resilience - WAL mode, connection pooling, transaction management
- ๐ Comprehensive Monitoring - Detailed logging and performance tracking
โ ๏ธ API Validation - Validates all broker responses for completeness- ๐ WebSocket Updates - Real-time position and order tracking via dashboard
git clone https://github.com/yourusername/wheelforge.git
cd wheelforge
uv venv
source .venv/bin/activate # Or `.venv\Scripts\activate` on Windows
uv pip install -e .
# For web dashboard (optional but recommended)
uv pip install -r requirements_web.txtCreate .env for API credentials:
ALPACA_API_KEY=your_key
ALPACA_SECRET_KEY=your_secret
IS_PAPER=true # Start with paper tradingConfigure strategy using one of these methods:
# Start the dashboard
python web_app.py
# Or use: start_dashboard.bat (Windows) / ./start_dashboard.sh (Mac/Linux)
# Open http://localhost:5000 in your browser
# Navigate to Config tab to edit all settingspython scripts/config_manager.pyEdit config/strategy_config.json manually
First run (clean slate):
run-strategy --fresh-startRegular operation:
run-strategyWith full logging:
run-strategy --strat-log --log-level DEBUG --log-to-fileRun continuously during market hours:
run-strategy-limitTest with one cycle:
run-strategy-limit --onceCustom settings:
run-strategy-limit --update-interval 30 --cycle-interval 600Open the web dashboard for real-time monitoring:
# Start dashboard
python web_app.py
# Open browser to http://localhost:5000{
"balance_settings": {
"allocation_percentage": 0.5, // Use 50% of account
"max_wheel_layers": 2 // Layers per symbol
}
}{
"option_filters": {
"delta_min": 0.15,
"delta_max": 0.30,
"expiration_min_days": 0,
"expiration_max_days": 21,
"open_interest_min": 100
}
}{
"rolling_settings": {
"enabled": true,
"days_before_expiry": 1,
"min_premium_to_roll": 0.05,
"roll_delta_target": 0.25
}
}{
"symbols": {
"AAPL": {
"enabled": true,
"contracts": 1,
"rolling": {
"enabled": true,
"strategy": "forward" // forward, down, or both
}
}
}
}Implements the scoring algorithm:
score = (1 - |ฮ|) ร (250 / (DTE + 5)) ร (bid_price / strike_price)
Balancing annualized return with assignment probability.
Tracks wheel states:
short_putโ Assignment โlong_shareslong_sharesโ Covered call โshort_callshort_callโ Assignment/Expiry โ Repeat
- Premium tracking and analysis
- Cost basis adjustments
- Position history
- Performance metrics
- Thread-safe trade execution
- Choice of market or limit orders
- Automatic retry with backoff
- Circuit breaker protection
- Transaction logging
- Tracks pending limit orders
- Automatic price adjustments
- Progressive repricing logic
- Order lifecycle management
Access comprehensive real-time monitoring at http://localhost:5000
- ๐ Overview Tab: Key metrics, active wheels, performance charts
- ๐ผ Positions Tab: Live options and stock positions with P&L tracking
- ๐ Analytics Tab: Advanced charts, symbol performance, monthly income
- โ๏ธ Config Tab: Edit all strategy settings without restarting
- ๐ Dark/Light Mode: Toggle between themes for comfortable viewing
- ๐ Real-Time Updates: WebSocket connection for instant data refresh
- ๐ฑ Responsive Design: Works on desktop, tablet, and mobile
- ๐พ Live Config Editing: Change settings and save directly from browser
- ๐ Interactive Charts: Performance tracking with ApexCharts
- ๐ Notifications: Real-time alerts for trades and events
- ๐ Export Data: Download positions and performance data
# Overall performance summary
python scripts/db_viewer.py --summary
# Cost basis with premium adjustments
python scripts/db_viewer.py --cost-basis
# Symbol-specific analysis
python scripts/db_viewer.py --symbol AAPL --all
# Premium collection history
python scripts/db_viewer.py --premiums --days 60- Runtime logs: Console/file output for monitoring
- Strategy JSON logs: Detailed trade analysis in
strategy_logging/ - Web Dashboard logs: Real-time event streaming via WebSocket
Best for scheduled execution at specific times:
# Run at market open, midday, and before close
0 10 * * 1-5 /path/to/run-strategy >> /logs/morning.log 2>&1
0 13 * * 1-5 /path/to/run-strategy >> /logs/midday.log 2>&1
30 15 * * 1-5 /path/to/run-strategy >> /logs/closing.log 2>&1Create scheduled tasks to run run-strategy.exe at desired intervals.
Best for continuous operation during market hours:
# Run as a service or in screen/tmux
screen -S wheelforge
run-strategy-limit
# Detach with Ctrl+A, D# Run in background
Start-Process run-strategy-limit -WindowStyle Hidden- Market Orders: Simple, immediate execution, good for scheduled runs
- Limit Orders: Better prices, requires continuous monitoring, saves on spreads
Comprehensive test suite included:
# Run all tests
python tests/test_error_handling.py
python tests/test_database.py
python tests/test_strategy_logic.py
python tests/test_risk_management.pyWheelForge automatically adjusts your cost basis based on collected premiums:
- Buy shares at $100 (from put assignment)
- Sell covered call for $2 โ Adjusted basis: $98
- System targets strikes โฅ $98 for improved exit probability
Run multiple wheel cycles simultaneously:
- Layer 1: Initial put โ shares โ covered call
- Layer 2: New put while holding Layer 1 shares
- Enables averaging down in volatile markets
Three rolling approaches available:
- Forward Roll: Same/higher strike, later expiration
- Down Roll: Lower strike for better assignment odds
- Adaptive: Best option based on scoring algorithm
Avoid paying the full bid-ask spread with intelligent order management:
- Initial Pricing: Orders start at bid-ask midpoint for optimal fills
- Automatic Repricing: Unfilled orders reprice every 20 seconds (configurable)
- Progressive Strategy: Each reprice becomes slightly more aggressive
- Order Expiration: Auto-cancels after 60 seconds if unfilled
- Market Hours Operation: Runs continuously during trading hours
- โ Paper trade for 2-4 weeks minimum
- โ Start with conservative settings (30% allocation, 0.20+ delta)
- โ Monitor closely for first week of live trading
- โ Review all risk settings in configuration
- โ Understand options risks and mechanics
- Automatic position size limits
- Per-symbol contract controls
- Maximum wheel layer restrictions
- Minimum liquidity requirements
- Comprehensive error recovery
run-strategy [options]
--fresh-start # Liquidate all positions first
--strat-log # Enable JSON strategy logging
--log-level LEVEL # DEBUG, INFO, WARNING, ERROR
--log-to-file # Save logs to filerun-strategy-limit [options]
--update-interval SECS # Order repricing interval (default: 20)
--cycle-interval SECS # Strategy cycle interval (default: 60)
--max-order-age MINS # Max order age before cancel (default: 1)
--once # Run one cycle then exit
--strat-log # Enable JSON strategy logging
--log-level LEVEL # DEBUG, INFO, WARNING, ERROR
--log-to-file # Save logs to fileUse the interactive configuration manager:
python scripts/config_manager.pyBuilt on Alpaca Trading API
WheelForge includes comprehensive performance tracking:
- Total premiums collected
- Win/loss ratios
- Cost basis adjustments
- Position history
- Tax reporting data
All stored in local SQLite database for analysis and reporting.
Monitor system health with built-in diagnostics:
- API connection status
- Circuit breaker states
- Retry attempt counts
- Thread pool utilization
- Database lock statistics
Real-time portfolio metrics, active wheels, performance tracking, and pending orders
Edit strategy settings, manage symbols, adjust filters and parameters without restarting
Advanced charts showing P&L breakdown, symbol performance, monthly income, and strategy statistics
Live options and stock positions with real-time P&L tracking and position details
# Double-click start_dashboard.bat
# Or run:
python web_app.py# Make script executable (first time only)
chmod +x start_dashboard.sh
./start_dashboard.sh
# Or run:
python web_app.py- Portfolio Metrics: Total value, daily P&L, premium income, win rate
- Active Wheels Grid: Visual representation of all active positions
- Pending Orders: Live tracking with age progress bars
- Performance Chart: Interactive chart with period selection (1W, 1M, 3M, YTD, ALL)
- Options Table: All option positions with real-time P&L
- Stocks Table: Share positions with state tracking
- Export Function: Download positions data as CSV
- P&L Breakdown: Donut chart showing income sources
- Symbol Performance: Bar chart comparing symbol profitability
- Monthly Income: Track premium collection trends
- Strategy Statistics: Key metrics like average premium, put/call ratio, assignment rate
- Balance Management: Adjust allocation percentage with slider
- Option Filters: Set delta, DTE, yield ranges
- Rolling Settings: Configure automatic rolling parameters
- Symbol Management: Add/remove/toggle symbols with contracts
- Start/Stop Strategy: Use the control button in the top navigation
- Toggle Theme: Click sun/moon icon for dark/light mode
- View Market Status: Green dot = market open, red = closed
- Real-Time Updates: Data refreshes automatically via WebSocket
- Save Configuration: Changes in Config tab save to
strategy_config.json
- โ Web dashboard for real-time monitoring (COMPLETED!)
- Advanced Greeks analysis
- Volatility-based position sizing
- Multi-account support
- Backtesting framework
- Mobile app companion
- โ Modern Dashboard: Full-featured web interface with dark/light mode
- โ Live Config Editor: Change settings without restarting
- โ WebSocket Updates: Real-time position and order tracking
- โ Interactive Charts: ApexCharts for advanced visualizations
- โ Responsive Design: Works on all device sizes
- Technical indicators integration
- Alternative scoring algorithms
- Risk management enhancements
- Performance optimizations
- Dashboard theme customization
Options trading involves substantial risk and is not suitable for all investors. Please read Characteristics and Risks of Standardized Options before trading.
This software is provided as-is for educational purposes. Past performance does not guarantee future results. Always understand the risks before trading with real capital.
This project is a fork of the Alpaca options-wheel implementation, significantly enhanced with:
- Production-ready error handling and recovery
- Advanced position management with multi-layer wheels
- Automatic option rolling capabilities
- Premium-adjusted cost basis tracking
- Enterprise-grade reliability features
The original codebase and this fork are provided for educational purposes. Please ensure you understand all risks before using this software for live trading.
Contributions are welcome! Please feel free to submit pull requests, report bugs, or suggest new features through the GitHub issues page.
- Original implementation by Alpaca Markets
- Enhanced and maintained by the WheelForge community
WheelForge - Forging profitable wheels in the options market ๐โ๏ธ
Built with precision. Runs with confidence. Trades with intelligence.