backtrader
Event-driven backtesting with bar-by-bar execution, complex order types, multiple analyzers, and custom indicators
By agiprolabs · 394 installs
npx skills add agiprolabs/claude-trading-skills --skill backtrader
Source repository · Upstream listing
Backtrader
Backtrader is a Python event driven backtesting framework that processes data bar by bar, simulating realistic execution with a built in broker, order management, and position tracking. Unlike vectorized frameworks (vectorbt, pandas), backtrader walks through history one bar at a time, firing callbacks that let you implement complex order logic that depends on previous fills, partial executions, and conditional brackets.
Event Driven vs Vectorized
Aspect Backtrader (event driven) vectorbt (vectorized)
Execution model Bar by bar callbacks Whole array operations
Speed Slower (Python loop) Fast (NumPy/Numba)
Order types Market, limit, stop, stop limit, bracket, OCO Market only (native)
Realism Built in broker with commission, slippage, margin Manual slippage modeling
Multi timeframe Native resampledata Manual alignment
Best for Complex strategies, bracket orders, portfolio Fast parameter sweeps, simple signals
Use backtrader when you need:
Bracket orders (entry + stop loss + take profit as a unit)
Stop limit or trailing stop orders
Order dependent logic (scale in after first fill, cancel if not filled in N bars)
Multi timeframe strategies (daily signals, hourly execution)
Realistic commission and slippage modeling
Use vectorbt when you need:
Fast parameter optimization over thousands of combinations
Simple long/short signals without complex order management
Quick prototyping and statistical analysis of results
Core Concepts
Backtrader has five core objects that interact through an event loop:
1. Cerebro (the engine)
The central orchestrator. You add strategies, data feeds, analyzers, and sizers to Cerebro, then call run() .
2. Strategy (your logic)
A Strategy subclass contains all trading logic. Key methods:
init () — Define indicators. Runs once before backtesting starts.
next() — Called on every bar. Place orders here.
notify order(order) — Called when order status changes (submitted, accepted, completed, canceled, margin, expired).
notify trade(trade) — Called when a trade opens or closes. Access P&L here.
3. Data Feed
Backtrader data feeds provide OHLCV lines. The most common approach is loading from a pandas DataFrame:
For CSV files:
4. Broker
The built in broker simulates order execution with configurable cash, commission, and slippage.
5. Analyzers
Analyzers compute performance metrics after the backtest completes.
Order Types
Backtrader supports complex order types critical for realistic crypto backtesting.
Market Order
Limit Order
Stop Order
Triggers a market order when price reaches the stop level:
Stop Limit Order
Triggers a limit order when price reaches the stop level:
Bracket Order
Entry + stop loss + take profit as an atomic unit. If the stop fills, the take profit is canceled (and vice versa).
See references/strategy patterns.md for bracket order patterns with ATR based stops.
Position Sizing (Sizers)
Sizers determine how many units to buy/sell per order.
Custom sizer:
Crypto Considerations
24/7 Markets
Crypto trades around the clock. When using daily bars, there are no weekends to skip. Set the session times or use sessionstart / sessionend if analyzing specific windows.
High Fees
DEX swaps on Solana typically cost 0.25 0.30% per trade. Set commission accordingly:
Fractional Sizing
Crypto allows fractional units. Backtrader supports this natively no special config needed.
Slippage
For realistic simulation, enable cheat on open and add slippage:
Volatile Data
Crypto OHLCV data often has extreme wicks. Use ATR based stops rather than fixed percentage stops to adapt to volatility.
Multi Timeframe
Backtrader can resample data to multiple timeframes within a single strategy:
Access in strategy:
Custom Indicators
Plotting
Backtrader includes matplotlib based plotting:
For headless environments, save to file:
Integration with Other Skills
pandas ta : Compute indicators externally, add as data feed columns. See references/api guide.md for adding extra lines.
trading visualization : Export trade log from notify trade and plot with the visualization skill.
position sizing : Use the position sizing skill for Kelly or volatility targeting sizers.
risk management : Apply portfolio level guardrails from the risk management skill as strategy filters.
slippage modeling : Use slippage estimates from the slippage modeling skill to configure set slippage perc .
Files
References
references/api guide.md — Cerebro, Strategy, Broker, Analyzer, Data Feed API reference
references/strategy patterns.md — Reusable strategy patterns: crossover, mean reversion, multi timeframe, custom indicators
Scripts
scripts/backtest strategy.py — Complete EMA crossover backtest with analyzers and synthetic data
scripts/bracket orders.py — Bracket order demonstration with RSI entry and ATR based stops
Quick Start