Backtester Engine
The BacktesterEngine is the heart of Algo Trading Stack.
It simulates a broker, processes historical bars one at a time, applies orders, enforces risk rules, and produces equity curves and statistics.
This page explains how it works, how it integrates with other components, and how to configure it.
1. Role in the System
The BacktesterEngine:
- Acts as a broker simulation for backtests
- Drives the bar loop (OPEN → INTRABAR → CLOSE)
- Validates orders against margin and equity
- Applies slippage, commissions, and fees
- Tracks realized/unrealized PnL and portfolio equity
- Emits signals so the TradingEnvironment, Bots, and UI can update in sync
It implements the APIInterface so bots and UIs can work the same way in both backtest and live modes.
2. Simulation Phases
Each bar goes through three phases:
-
OPEN Phase
- Bot receives a snapshot with only the OPEN price visible
- High/Low/Close hidden to prevent lookahead bias
- Bot may place new orders
-
INTRABAR Phase
- Protective orders (stop-loss, take-profit) checked against the bar’s H/L
- Gap-aware logic ensures correct trigger price if stop/TP crossed at OPEN
- Tie-breaking policies supported (
worst_case
,best_case
,sl_first
,tp_first
)
-
CLOSE Phase
- Positions marked-to-market
- Maintenance margin checked and enforced
- Forced liquidation occurs if equity < maintenance requirement
- Indicators recomputed for the bar
3. Margin & Risk Enforcement
- Initial margin required to open a position
- Maintenance margin required to keep it open
- Engine computes worst-case intrabar equity:
- Longs → equity valued at bar LOW
- Shorts → equity valued at bar HIGH
- If equity falls below total maintenance margin → positions liquidated at bar CLOSE
This ensures backtests reflect realistic margin call behavior.
4. Accounting & Costs
The engine models realistic fills:
- Tick size/value: fills rounded to exchange tick grid
- Slippage: added per order (tick-based or % based)
- Commission per contract: deducted from cash
- Per-trade fee: flat overhead cost
PnL Tracking
- Realized PnL: credited when a position is closed (includes costs)
- Unrealized PnL: tracked for open positions based on mark price
- Equity history: total portfolio equity recorded per bar
5. Statistics & Reporting
The BacktesterEngine records statistics during the run:
- Per-asset realized/unrealized PnL
- Equity curve (portfolio + per-asset)
- Maximum drawdown (per asset & portfolio)
- Campaign tracking: groups trades from flat → open → flat
- Win/loss counts, expectancy, average win/loss, profit factor
- Commission/fee totals
These stats are available through:
- UI dialogs (
StatisticsDialog
) - Methods:
get_stats_snapshot()
,get_equity_series()
,get_max_drawdown()
6. Configuration
The engine loads parameters from YAML config files (see Config Files).
Example
initial_cash: 100000
commission_per_contract: 2.5
fee_per_trade: 1.0
slippage_ticks: 1
assets:
- symbol: CL=F
type: futures
file: yahoo_finance/CL_1m.csv
contract_size: 1000
tick_size: 0.01
tick_value: 10.0
initial_margin: 5000
maintenance_margin: 4000
7. Key Methods
start_backtest(interval_ms)
— begin stepping through barspause_backtest()
/resume_backtest()
— control executionrewind_backtest(steps)
/fast_forward_backtest(steps)
— navigate history deterministicallyreset_backtest()
— reset state to the beginningplace_order(order_dict)
— validate, fill, and log an orderclose_all_positions()
— force liquidation at current bar
8. Entry Points
To run with the BacktesterEngine:
- GUI mode
PYTHONPATH=. python3 run_backtest.py
- Headless mode
PYTHONPATH=. python3 run_backtest_headless.py
9. How It Fits with the System
The BacktesterEngine is not standalone — it works in concert with:
- TradingEnvironment — computes indicators and proxies engine calls to bots
- Bots — decide entries/exits via
decide_side
andexit_strategy.update_stop
- Exits — enforce stop-loss/take-profit logic consistently across bots
- UI — listens to signals and displays charts, equity, and stats
10. Summary
The BacktesterEngine provides:
- A realistic, phase-aware broker simulation
- Accurate handling of ticks, margins, commissions, and slippage
- Standardized interface so the same bots and exits run in sim and live modes
- Comprehensive statistics for evaluation and research
It is the core runtime that powers both backtesting and live-data experiments in Algo Trading Stack.