Built-in Sample Strategies
Relevant source files
The following files were used as context for generating this wiki page:
The built-in sample strategies in the Backtrader project provide a diverse set of algorithmic trading templates ranging from simple trend-following systems to complex multi-indicator confirmation patterns. These strategies are designed to be modular, leveraging the core bt.Strategy class and shared utility mixins like TradeThrottling to ensure reproducibility and explainability in backtesting. Sources: strategies/moving_average_crossover.py, strategies/gaussian_triple_confirmation.py, PLAN.md
Strategy Architecture and Common Components
Most strategies in the repository follow a standardized structure for data ingestion, indicator initialization, and trade execution. They typically interact with a PostgreSQL database via get_db_data and utilize standardized performance analyzers. Sources: strategies/utils.py, strategies/moving_average_crossover.py:382-388
Standardized Execution Flow
Each strategy follows a specific lifecycle within the cerebro engine:
- Initialization (
__init__): Indicators like Moving Averages, RSI, or custom Gaussian Filters are declared. - Notification (
notify_order/notify_trade): Tracks order status (Submitted, Accepted, Completed) and records P&L. - Core Logic (
next): Evaluates market conditions for every bar and issuesbuy()orsell()orders. - Completion (
stop): Logs final portfolio values and performance metrics.
Sources: backtrader/strategy.py:279-300, strategies/risk_adverse.py:228-245
Base Component Relationship
The following diagram illustrates how sample strategies inherit from the core framework and utilize shared logic.
Trend-Following Strategies
Moving Average Crossover
This strategy identifies trends using two moving averages (short-term and long-term). A "Golden Cross" (short MA crossing above long MA) triggers a buy, while a "Death Cross" (short MA crossing below long MA) triggers a sell. Sources: strategies/moving_average_crossover.py:26-34
| Parameter | Type | Default | Description |
|---|---|---|---|
short_period | int | 50 | Period for the fast moving average. |
long_period | int | 200 | Period for the slow moving average. |
ma_type | string | SMA | Supports SMA, EMA, WMA, and SMMA. |
confirmation | int | 1 | Consecutive bars required to confirm a cross. |
Sources: strategies/moving_average_crossover.py:209-218
Mean Reversion Strategies
Bollinger Bands Mean Reversal (RSI Filtered)
Designed for sideways or range-bound markets, this strategy enters long positions when the price closes below the lower Bollinger Band while the RSI is oversold (< 30). It exits when the price touches the upper band or becomes overbought. Sources: strategies/bb_mean_reversal_rsi.py:26-32
Pattern Recognition Strategies
Cup and Handle
A sophisticated pattern recognition strategy that utilizes a state machine to track the formation of a U-shaped "cup" followed by a consolidation "handle." Sources: strategies/cup_and_handle.py:26-30
Validation Stages:
- Cup Stage: Tracks minimum depth (e.g., 15%) and validates a U-shape ratio to avoid V-shaped pullbacks. Sources: strategies/cup_and_handle.py:126-155
- Handle Stage: Ensures the handle forms in the upper 50% of the cup and tracks volume decline. Sources: strategies/cup_and_handle.py:218-230
- Breakout Stage: Executes a buy when price breaks above the handle high with a volume surge (e.g., 150% of average). Sources: strategies/cup_and_handle.py:348-355
Advanced Confirmation Strategies
Gaussian Triple Confirmation
This strategy uses an Ehlers Gaussian Filter to create a price channel. It requires three conditions for entry:
- Gaussian Trend: The filter line must be ascending (
filt > filt[-1]). - Band Breakout: Price must be above the upper Gaussian band.
- Momentum Extremes: Stochastic RSI must be at extreme readings (> 80 or < 20).
Sources: strategies/gaussian_triple_confirmation.py:29-37
Risk Adverse Strategy
Focuses on stability and controlled momentum by filtering for low volatility and price consolidation. Sources: strategies/risk_adverse.py:27-32
- Volatility Filter: Calculates average percentage change over 20 periods.
- High-Low Differential: Ratio of (Highest High - Lowest Low) to Average Price must be below a threshold (default 0.3).
- Volume Threshold: Minimum market interest required for entry (default 100,000 units).
Sources: [strategies/risk_adverse.py:165-175], strategies/risk_adverse.py:203-210
Risk Management and Throttling
All sample strategies implement standardized risk management logic, including position sizing based on portfolio equity and stop-loss mechanisms.
| Feature | Implementation | Description |
|---|---|---|
TradeThrottling | can_trade_now() | Prevents overtrading by enforcing a minimum duration (days/hours) between trades. |
Trailing Stop | trail_percent | Locks in profits by adjusting the stop price as the market moves favorably. |
Position Sizing | risk_percent | Calculates the number of shares based on the distance to stop-loss to risk exactly X% of equity. |
Sources: strategies/moving_average_crossover.py:290-305, strategies/vol_contraction.py:265-285, PLAN.md
Position Sizing Calculation
The strategies use the following logic to determine trade size:
Size = (Portfolio Value * Risk %) / (Entry Price - Stop Price)
This is then capped by a max_position parameter to prevent over-leveraging. Sources: strategies/moving_average_crossover.py:272-288, strategies/cup_and_handle.py:176-185
Conclusion
The built-in sample strategies serve as both functional trading tools and architectural references. By combining modular indicators with standardized risk management and trade throttling, they demonstrate the "Agentic" philosophy of the framework—where strategies are composable, explainable, and data-driven. Sources: PLAN.md:83-88