A single-instrument event-driven backtester in modern C++20. Strategies submit market orders, the engine fills them at the next bar's open with commission and slippage, and the result is a full equity curve plus return, drawdown, Sharpe, turnover and trade statistics.
No third-party dependencies.
- Event-driven loop: orders submitted on bar
tbecome eligible on bart+1, so strategies cannot look ahead. - Order types: market, limit, stop and stop-limit, with DAY and GTC time-in-force and an explicit order state machine.
- Commission and slippage in basis points; limit fills never trade worse than the limit price.
- Partial fills: per-bar volume participation is shared across orders and unfilled quantity stays pending across bars.
- Slippage models: fixed bps, half-spread and square-root volume impact.
- Long and short positions with average-cost accounting and realized PnL.
- Order queries:
find_order,open_ordersandcancel_order. - Target positions:
order_target(x)accounts for pending orders and does not stack duplicate fills. - Metrics: total and annualized return, annualized volatility, Sharpe ratio, maximum drawdown, turnover, win rate, commission paid.
- Single-symbol CSV loader (
timestamp,open,high,low,close,volume) with validation. - Multi-symbol panels: union-aligned
BarBatchdata, missing-bar counts, a batch strategy API and a long-format CSV loader. - Multi-asset portfolio: per-symbol positions, average cost, realized PnL, shared cash, target quantities and portfolio equity.
- Walk-forward evaluation: rolling train/test windows, in-sample parameter selection, stitched out-of-sample equity and CSV export.
- Parallel parameter sweeps: independent SMA pairs on a worker group, deterministic grid ordering and serial-equivalent results.
- Corporate actions: split quantity/cost adjustment, cash dividends and a validated event CSV loader.
- Financing costs: actual/365 margin on negative cash and borrow costs on short positions, with per-run totals.
- Built-in strategies: SMA crossover (long-only or long/short) and buy-and-hold, plus momentum, mean-reversion and equal-weight rebalance examples.
- Tests, CLI, benchmark, CMake package export and multi-compiler CI.
Requirements: a C++20 compiler and CMake 3.20+. Ninja is optional.
cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release
cmake --build build
ctest --test-dir build --output-on-failureSanitizer build:
cmake -S . -B build-asan -G Ninja \
-DCMAKE_BUILD_TYPE=Debug -DCPPQUANT_SANITIZE=ON
cmake --build build-asan
ctest --test-dir build-asan --output-on-failureThreadSanitizer for the parallel sweep tests:
cmake -S . -B build-tsan -G Ninja \
-DCMAKE_BUILD_TYPE=Debug -DCPPQUANT_TSAN=ON
cmake --build build-tsan
./build-tsan/backtest_tests parallelInstall and consume:
cmake --install build --prefix /tmp/cppquantfind_package(cppquant_backtest CONFIG REQUIRED)
target_link_libraries(my_target PRIVATE cppquant::backtest)#include "cppquant/backtest.hpp"
using namespace cppquant;
class Momentum : public Strategy {
public:
void on_bar(const Bar& bar, Backtester& engine) override {
if (bar.close > previous_close_ * 1.01) {
engine.order_target(100.0); // go long 100 units
} else if (bar.close < previous_close_ * 0.99) {
engine.close_position();
}
previous_close_ = bar.close;
}
private:
double previous_close_{};
};
BacktestConfig config;
config.initial_cash = 100'000.0;
config.commission_bps = 1.0;
config.slippage_bps = 1.0;
Backtester engine(config);
Momentum strategy;
const Performance result = engine.run(bars, strategy);Orders placed in on_bar are queued and filled at the next bar's open. The
last bar can leave pending orders; they are dropped because there is no next
open. close_position() is shorthand for order_target(0).
engine.buy(100.0); // market
engine.buy_limit(100.0, 95.0); // buy limit
engine.sell_stop(100.0, 90.0); // sell stop
engine.buy_stop_limit(100.0, 105.0, 106.0); // buy stop-limit
engine.buy_limit(100.0, 95.0, TimeInForce::Day); // expires after next bar
OrderId id = engine.buy_limit(100.0, 95.0);
if (const OrderState* order = engine.find_order(id)) {
// order->status, order->filled_quantity, order->average_fill_price ...
}
engine.cancel_order(id);Fill rules use the next bar's OHLC:
| Order | Buy | Sell |
|---|---|---|
| Market | next open | next open |
| Limit | open <= limit, else low <= limit |
open >= limit, else high >= limit |
| Stop | open >= stop, else high >= stop |
open <= stop, else low <= stop |
| Stop-limit | trigger as a stop, then behave as a limit | trigger as a stop, then behave as a limit |
Limit fills use the open when it is better than the limit, otherwise the limit price. A stop-limit that is triggered only inside a bar waits for the next bar: OHLC data cannot reveal whether the limit was reached before or after the stop. A gap through the stop activates the limit immediately.
OrderStatus is one of Pending, PartiallyFilled, Filled, Cancelled or
Expired. W1 fills orders in full; partial fills arrive with the volume
participation work in W2.
BarPanel aligns per-symbol series on the union of timestamps. Each BarBatch
contains the symbols that have a bar at that timestamp; missing bars are counted
per symbol.
#include "cppquant/backtest.hpp"
const BarPanel panel = load_bar_panel_csv("data/sample_multi.csv");
class Signal : public BatchStrategy {
public:
void on_batch(const BarBatch& batch, Backtester& engine) override {
const Bar* a = batch.find("AAA");
const Bar* b = batch.find("BBB");
if (a && b) {
engine.order_target(b->close > a->close ? 10.0 : 0.0);
}
}
};
Signal strategy;
Backtester engine;
const Performance result =
engine.run_batch(panel.batches(), "AAA", strategy);Orders can target any symbol in the batch, for example
engine.buy("AAA", 10.0) or engine.order_target("BBB", 5.0). Cash is shared
across the portfolio, while position, average cost and realized PnL are tracked
per symbol. The overloads without a symbol use trade_symbol as the default.
engine.portfolio_equity() marks every position at its last known close and
falls back to average cost when a symbol has no mark yet. Target weights can be
implemented by sizing each order_target from portfolio equity and the current
price.
cppquant-backtest panel
symbols: 2, batches: 4, missing bars: 1
final equity: 100059.59
trades: 2
./build/panel_backtest data/sample_multi.csv 10./build/walk_forward_cli --csv data/sample_bars.csv \
--train 100 --test 50 --fast 5,10 --slow 20,30 \
--export walk_forward.csvFor each window, every (fast, slow) pair is trained on the training slice;
the best training total return (or Sharpe) is selected and applied only to the
following test slice. Test windows do not overlap by default, and cash
compounds across windows while positions start flat each time.
The stitched OOS curve is reported with total/annualized return, volatility,
Sharpe, drawdown and total fills. Per-window parameters and metrics are
available in WalkForwardResult and the CSV export.
See docs/WALK_FORWARD.md for the window layout, no-leak rules and CSV columns.
#include "cppquant/sweep.hpp"
const auto grid = make_sma_grid({5, 10, 20}, {30, 50, 80});
SmaSweepConfig config;
config.backtest.initial_cash = 100'000.0;
config.quantity = 100.0;
config.threads = 4; // 0 = hardware concurrency, 1 = serial
const auto results = run_sma_sweep(bars, grid, config);
// results[i].parameters, results[i].performanceResults stay in grid order regardless of worker completion order. Set
WalkForwardConfig::threads to parallelize each training sweep; cash still
compounds sequentially across windows. Both sweeps and walk-forward accept
corporate actions, scoped to each bar window. See docs/SWEEP.md.
const auto actions =
load_corporate_actions_csv("data/sample_corporate_actions.csv");
BacktestConfig config;
config.margin_rate = 0.02; // annual rate on negative cash
config.borrow_rate = 0.01; // annual rate on short market value
const Performance result = engine.run(bars, strategy, actions);
// result.total_dividends, total_margin_cost, total_borrow_costSplits adjust position quantity, average cost, marks and open orders. Cash dividends credit long positions and debit shorts. See docs/CORPORATE_ACTIONS.md for the event format, timing and day-count rules.
./build/strategy_demo --bars data/sample_bars.csv \
--strategy momentum --lookback 20
./build/strategy_demo --bars data/sample_bars.csv \
--strategy mean-reversion --lookback 20 --zscore 1.0
./build/strategy_demo --panel data/sample_multi.csv \
--strategy rebalance --rebalance-every 2See docs/EXAMPLES.md for the signal rules.
./build/backtest_cli --csv data/sample_bars.csv \
--fast 5 --slow 20 --quantity 100 --fillscppquant-backtest
data: data/sample_bars.csv
bars: 300 (2020-01-01 .. 2020-10-26)
strategy: sma fast=5 slow=20 qty=100.0000 short=no
performance
initial equity 100000.00
final equity 100936.55
total return 0.94%
annualized return 0.79%
annualized vol 0.94%
sharpe ratio 0.843
max drawdown 1.15%
turnover 1.404
trades 13
win rate 33.33%
commission paid 14.14
realized pnl 824.64
final position 100.0000
fills
date side price quantity commission
2020-01-31 B 99.8620 100.0000 1.00
2020-02-23 S 101.8384 100.0000 1.02
...
Useful flags: --strategy buyhold, --short, --cash, --commission-bps,
--slippage-bps, --rf, --periods-per-year, --fills, --help.
timestamp,open,high,low,close,volume
1577836800,100.2089,101.4595,99.5818,101.0065,598262
1577923200,100.9140,101.0806,100.4939,100.6754,1162798
timestamp is an integer (epoch seconds in the sample). A header row is
optional; blank lines and # comments are ignored. Bars must have positive
prices, high >= low, high >= open/close, low <= open/close and
non-negative volume.
./build/backtest_bench # 1,000,000 synthetic bars
./build/backtest_bench --quick # 100,000 bars, used by CIReference numbers from an Apple M-series laptop (Apple clang 21, -O3):
| Workload | Bars | Time | Throughput | Fills |
|---|---|---|---|---|
| SMA(10,30) backtest | 1,000,000 | 53 ms | 18.9 M bars/s | 38,221 |
| 35-pair sweep, 1 thread | 1,000,000 | 1.71 s | 20.4 pairs/s | — |
| 35-pair sweep, 4 threads | 1,000,000 | 0.53 s | 65.6 pairs/s | — |
The engine is arithmetic-light per bar; the number mostly measures the strategy callback and portfolio bookkeeping. Generation of the synthetic data is excluded from the timing.
- Orders are submitted from
Strategy::on_barand matched against the next bar's OHLC. - A bar can fill at most
volume * max_volume_participationacross all pending orders (default 10%). Unfilled quantity stays pending for GTC orders or expires for DAY orders. - Market and stop fills pay the configured slippage; limit and stop-limit fills never trade worse than the limit price. Market orders can therefore fill in pieces across several bars.
- Slippage models:
FixedBpsusesslippage_bps.Spreaduses half ofspread_bps.Impactusesslippage_bps + impact_bps * sqrt(fill_qty / bar.volume).
- Commission is
notional * commission_bps / 10,000, charged on every fill. - DAY orders are valid for the next bar only; unfilled quantity expires at that bar's close. GTC orders remain until filled or cancelled.
- Short selling is allowed and has no borrow cost or margin constraint; cash can go negative.
- Equity is
cash + position * close. The final position is marked at the last close, not liquidated. timestampis used for reporting only. Annualization usesperiods_per_year(default 252), not the timestamp deltas.
BacktestConfig config;
config.max_volume_participation = 0.10;
config.slippage_model = SlippageModel::Impact;
config.impact_bps = 20.0;include/cppquant/backtest.hpp public API
include/cppquant/sweep.hpp SMA grid and parallel sweep API
src/backtest.cpp engine, accounting, metrics, strategies
src/csv.cpp bar, panel and corporate-action loaders
src/panel.cpp multi-symbol alignment and batch loop
src/sweep.cpp parallel SMA parameter sweeps
src/walk_forward.cpp rolling parameter selection and OOS stitching
src/validate.hpp shared OHLC validation
examples/backtest_cli.cpp single-symbol CLI
examples/panel_backtest.cpp multi-symbol CLI
examples/walk_forward_cli.cpp walk-forward CLI
examples/strategy_demo.cpp momentum, mean-reversion and rebalance demos
At each bar the engine:
- executes orders submitted on the previous bar at the current open;
- calls
strategy.on_bar(bar, engine); - marks the portfolio at the current close and appends to the equity curve.
The position is tracked with average-cost accounting. Closing fills realize PnL against the average cost; a fill that crosses through zero closes the old position and opens the remainder at the fill price. Winning and losing closes are counted separately for the win rate.
See docs/DESIGN.md for the accounting rules, metric formulas and test strategy.
- Bar data only: no ticks, order book, queue position or latency model.
- No margin calls, buying-power constraints or per-symbol risk limits.
- No transaction taxes, withholding or dividend payable dates.
- Walk-forward and sweeps support only the built-in SMA strategy; a generic strategy factory is not implemented.
- Sweeps are CPU-only and recreate a worker group per call.
- No purged/embargoed gap between training and test windows.
- Metrics assume bars are evenly spaced and match
periods_per_year.
Natural extensions are a multi-asset risk model, a fill model with queue position and latency, and a broader corporate-action event set.
The repository uses a small header-only test harness. The 85 tests cover:
- next-open execution, commission and slippage arithmetic;
- market, limit, stop and stop-limit fills, gaps and intrabar touch rules;
- DAY expiry, GTC persistence, cancellation and order-state queries;
- volume participation, shared bar liquidity, partial fills across bars and zero-volume bars;
- multi-symbol union alignment, missing-bar counts, long-format CSV loading, batch execution and the single-symbol adapter;
- multi-asset positions, shared cash, per-symbol realized PnL, target weights, last-mark equity and per-symbol close;
- walk-forward window ordering, best-parameter selection, short final windows, compounding, reproducibility and CSV export;
- serial/parallel sweep equivalence, grid ordering, direct-backtest matching, worker resolution, worker exceptions and parallel walk-forward results;
- split equity invariance, pending-order adjustment, long/short dividends, margin and borrow accrual, batch symbol matching and action CSV validation;
- corporate-action scoping in sweeps and walk-forward test windows;
- fixed, spread and impact slippage models;
- long, short, partial close and position-flip accounting;
- target orders, closing and end-of-data pending orders;
- equity curve, total return, drawdown, volatility, Sharpe and turnover;
- SMA crossover trading and short mode;
- CSV parsing, header handling, malformed rows, invalid numbers, out-of-range values, empty symbols and empty files;
- invalid configuration, invalid orders and reset between runs;
- momentum, mean-reversion and equal-weight rebalance example runs.
./build/backtest_tests # all tests
./build/backtest_tests csv # filter by substringThe 8-week plan (2026-11-09 to 2027-01-03), milestones and acceptance criteria live in docs/ROADMAP.md. Current and historical numbers are in docs/BENCHMARKS.md; user-visible changes are tracked in CHANGELOG.md.
MIT. See LICENSE.