Options and equities trading platform integrating Backtrader framework with Alpaca API for seamless backtesting, paper trading, and live execution.
- Strategy Framework: Single codebase for backtest/paper/live modes
- Options Data Pipeline: Real-time options chains with Greeks from Alpaca API
- Risk Management: Position limits, stop-loss, drawdown protection
- Performance Monitoring: Real-time P&L tracking with CSV export and visualization
- Environment Detection: Automatic broker switching based on trading mode
- Python 3.13+
- Alpaca brokerage account (paper or live)
- API keys configured in
.envfile
# Clone and install
git clone <repository-url>
cd backtrader-bots
make install
# Configure environment
cp .env.example .env
# Edit .env with your Alpaca API credentialsCreate .env file with your Alpaca credentials:
# Alpaca API Configuration
ALPACA_API_KEY=your_api_key_here
ALPACA_SECRET_KEY=your_secret_key_here
ALPACA_BASE_URL=https://paper-api.alpaca.markets # Paper trading
# ALPACA_BASE_URL=https://api.alpaca.markets # Live trading
# Trading Configuration
TRADING_ENVIRONMENT=development
LOG_LEVEL=INFO
MAX_POSITION_SIZE=1000.0
MAX_DAILY_LOSS=100.0Test strategies against historical data:
# Basic backtest with default parameters
make backtest
# Custom symbol and timeframe
make backtest SYMBOL=TSLA DAYS=90
# Tune DivergenceStrategy parameters from the CLI
# Stop-loss / Take-profit
make backtest STOP_LOSS_PCT=0.03 TAKE_PROFIT_PCT=0.06
# TSI lengths (fast/slow)
make backtest TSI_FAST=13 TSI_SLOW=7
# EMA period
make backtest EMA_PERIOD=50
# Entry parent limit offset (as fraction of price)
make backtest ENTRY_LIMIT_OFFSET_PCT=0.0005
# Combine multiple overrides
make backtest SYMBOL=NQ DAYS=60 TSI_FAST=13 TSI_SLOW=7 EMA_PERIOD=50 ENTRY_LIMIT_OFFSET_PCT=0.0005 STOP_LOSS_PCT=0.03 TAKE_PROFIT_PCT=0.06Backtest Output:
- Performance summary logged to terminal
- Timestamped folder under
backtest_results/run_YYYYMMDD_HHMMSS/containing:report.md– Markdown summaryresults.json– Raw metricschart.png– Price, indicators, and trades chart (if generated)
Execute strategies with simulated money:
# Start paper trading (runs continuously)
make paper SYMBOL=AAPL
# Paper trading with custom symbol
make paper SYMBOL=QQQPaper Trading Features:
- Real-time market data
- Simulated order execution
- Risk management enforcement
- Performance tracking
- Stop with Ctrl+C
# Live trading (10-second confirmation delay)
make live SYMBOL=AAPLLive Trading Requirements:
- Valid live trading API keys
- Sufficient account balance
- Risk parameters configured
- Market hours operation
Extend the UnifiedStrategy base class:
from src.backtrader_alpaca.strategies.base_strategy import UnifiedStrategy
class MyStrategy(UnifiedStrategy):
params = (
('symbol', 'AAPL'),
('position_size', 100),
('stop_loss_pct', 0.05),
)
def init_strategy(self):
"""Initialize indicators and state."""
self.sma = self.data.close.sma(period=20)
def generate_signals(self):
"""Generate buy/sell signals."""
if self.data.close[0] > self.sma[0]:
return {'action': 'buy', 'size': self.params.position_size}
elif self.data.close[0] < self.sma[0]:
return {'action': 'sell', 'size': self.params.position_size}
return {'action': 'hold'}Configure via strategy params:
symbol: Trading symbol (e.g., 'AAPL', 'SPY')position_size: Default position sizemax_position_value: Maximum position value in USDstop_loss_pct: Stop loss percentage (0-1)take_profit_pct: Take profit percentagetsi_fast/tsi_slow: TSI fast/slow lengthsema_period: EMA periodentry_limit_offset_pct: Parent limit offset from current price (fraction)
These can be overridden from the CLI via the Makefile variables shown above.
Built-in risk controls:
- Position Limits: Maximum position size and value
- Drawdown Protection: Portfolio-level loss limits
- Stop Loss/Take Profit: Automatic order management
- Real-time Monitoring: Risk metrics and alerts
# Run all tests
make test
# Test with coverage
make coverage
# Quick framework test
make quick-test# Lint code
make lint
# Format code
make format
# Clean build artifacts
make cleansrc/backtrader_alpaca/
├── clients/ # API clients (Alpaca, options)
├── config/ # Settings and configuration
├── data/ # Data storage and management
├── execution/ # Brokers and execution engines
├── models/ # Data models (Pydantic)
├── monitoring/ # Performance tracking
├── risk/ # Risk management
├── strategies/ # Trading strategies
└── utils/ # Utilities and logging
Real-time tracking includes:
- Portfolio value and P&L
- Sharpe ratio calculation
- Maximum drawdown
- Win/loss ratios
- Risk-adjusted returns
Results exported to:
logs/trading.log- Structured loggingdata/trades.csv- Trade historydata/positions.csv- Position trackingdata/performance.csv- Performance metrics
Matplotlib charts generated:
- Equity curve
- Drawdown analysis
- Trade distribution
- Risk metrics over time
API Authentication Errors:
- Verify API keys in
.envfile - Check Alpaca account status
- Ensure correct base URL (paper vs live)
Import Errors:
- Run
make installto install dependencies - Verify Python 3.13+ installation
- Check virtual environment activation
Strategy Execution Issues:
- Review
logs/trading.logfor errors - Verify market hours for live trading
- Check risk parameter configuration
- Review logs in
logs/trading.log - Check test coverage with
make coverage - Validate configuration with
make quick-test
Built on proven components:
- Backtrader: Strategy framework and backtesting engine
- Alpaca API: Commission-free brokerage with options support
- Pydantic: Data validation and settings management
- Structlog: Structured logging and monitoring
[Add your license information here]