FastMM documentation
FastMM C++ API 0.14.0
Public headers, tier 1 and tier 2
Loading...
Searching...
No Matches
metrics.hpp
Go to the documentation of this file.
1#pragma once
2// Metrics (8.4) computed from the result rows: equity bars (1 s by default) and fills, and the
3// orders' OrderStats. Every input is an exact integer (raw 1e-8 fixed point); the doubles here are
4// reporting-only and never feed back into the simulation.
6#include "fastmm/core/latency.hpp"
8
9#include <cstdint>
10#include <vector>
11
12namespace fastmm::bt {
13
14struct FillRows;
15struct EquityRows;
16struct OrderRows;
17
18// How the net PnL of the run splits into the parts a market maker can act on:
19// net == spread_capture + mid_drift - fees_paid + rebates_received + residual
20// `mid_drift` is the move of the mid from each fill to the end of the run, valued at the signed
21// quantity of the fill: adverse selection plus the mark-to-market of whatever is still open.
22// `residual` is whatever the average-cost ledger books differently (fixed-point rounding, a
23// contract multiplier, an instrument whose book never had two sides). A large residual means the
24// decomposition does not describe this run; it is printed, not hidden.
25//
26// A fill whose venue mid is unknown at the moment of the fill (the sweep that filled it emptied
27// that side of the book) has no spread capture to attribute, so its whole
28// signed_qty * (final mid - price) goes to mid_drift instead. `capture_fills` and
29// `capture_notional` cover the rest, and are what spread_capture_bps divides by.
30struct PnlDecomposition {
31 double spread_capture = 0.0; // sum of signed_qty * (mid at fill - fill price)
32 double spread_capture_bps = 0.0;
33 double mid_drift = 0.0; // sum of signed_qty * (final mid - mid at fill)
34 double fees_paid = 0.0; // sum of the positive fees, >= 0
35 double rebates_received = 0.0; // sum of the negative fees with the sign flipped, >= 0
36 double net = 0.0; // spread_capture + mid_drift - fees_paid + rebates_received
37 double residual = 0.0; // reported net PnL - net
38 double notional = 0.0; // traded notional of every fill
39 double capture_notional = 0.0; // traded notional of the fills that had a mid at the fill
40 std::uint64_t capture_fills = 0;
41 std::uint64_t fills = 0;
42};
44// Diagnostics of how the fills were obtained, next to the markouts.
45struct FillQuality {
46 // Notional-weighted (mid at fill - price) for buys, (price - mid at fill) for sells, over the
47 // fills that had a venue mid. This is the realised spread: what markouts start from.
48 double realized_spread_bps = 0.0;
49 double realized_spread_quote = 0.0;
50 // Shares of the maker fills, by where the order was against the venue book at the fill.
51 double at_touch_share = 0.0; // at the venue's best price on our side
52 double inside_touch_share = 0.0; // at a better price than the touch (it improved it)
53 double behind_touch_share = 0.0; // at a worse price than the touch
54 // At or beyond the opposite touch: the market had moved through the resting order.
55 double through_touch_share = 0.0;
56 // Venue arrival of a new order to its first fill. Only orders that filled are counted.
57 std::uint64_t time_to_fill_p50_ns = 0;
58 std::uint64_t time_to_fill_p90_ns = 0;
59 std::uint64_t time_to_fill_p99_ns = 0;
60 // Share of new orders that got at least one fill (fill_ratio counts fills per order instead).
61 double fill_rate_per_quote = 0.0;
62 std::uint64_t quotes_placed = 0;
63 std::uint64_t quotes_filled = 0;
64 // Displayed quantity still ahead of the order when it filled; the L2Queue fill model only.
66 double queue_ahead_mean = 0.0; // base units
67 double queue_ahead_p50 = 0.0;
68 double queue_ahead_p90 = 0.0;
69};
71struct Metrics {
72 // PnL in quote currency at the last bar: net == realized + unrealized - fees.
73 double net_pnl = 0.0;
74 double realized_pnl = 0.0;
75 double unrealized_pnl = 0.0;
76 double fees = 0.0;
77 double final_position = 0.0; // base units, summed over instruments
78 double sharpe_bar = 0.0; // mean / sample stdev of per-bar equity changes
79 // sharpe_bar * sqrt(bars per 365-day year); NaN for runs more than one bar shorter than
80 // kMinAnnualizedDurationS, where the scaling turns noise into four-digit values.
81 double sharpe_annualized = 0.0;
82 double max_drawdown = 0.0; // largest fall of equity from its peak, quote currency, >= 0
83 // max_drawdown / initial_capital; NaN when initial_capital <= 0.
84 double max_drawdown_pct = 0.0;
85 std::uint64_t fills = 0;
86 std::uint64_t maker_fills = 0;
87 std::uint64_t taker_fills = 0;
88 std::uint64_t orders = 0; // new orders sent
89 std::uint64_t cancels = 0;
90 std::uint64_t replaces = 0;
91 std::uint64_t rejects = 0;
92 double fill_ratio = 0.0; // fills / new orders
93 double spread_captured_bps = 0.0; // mean of (mid - px) / mid for buys, (px - mid) / mid sells
94 double volume_base = 0.0;
95 double volume_quote = 0.0;
96 double inventory_mean = 0.0; // over bars
97 double inventory_abs_mean = 0.0; // over bars
98 double inventory_max = 0.0; // max |position| at any fill or bar
99 double quote_uptime = 0.0; // fraction of bars with both a bid and an ask resting
100 std::uint64_t bars = 0;
101 double duration_s = 0.0;
102 // Virtual tick-to-order: engine receipt of the triggering event (T0, virtual clock) to the
103 // order's arrival at the simulated venue. Deterministic; includes the order latency model.
104 std::uint64_t virtual_tick_to_order_p50_ns = 0;
105 std::uint64_t virtual_tick_to_order_p99_ns = 0;
106 // Measured wall clock per engine step that consumed market data (0 when not measured).
107 std::uint64_t wall_tick_to_order_p50_ns = 0;
108 std::uint64_t wall_tick_to_order_p99_ns = 0;
109 // Where the net PnL came from, and how good the fills were. See markout.hpp.
112 std::vector<MarkoutHorizon> markouts; // one entry per configured horizon, in order
114 // The markout of one horizon, or nullptr when it was not measured.
115 [[nodiscard]] const MarkoutHorizon* markout(std::int64_t horizon_ns) const noexcept;
116};
118// Shortest run whose Sharpe ratio is annualised: one day.
119inline constexpr double kMinAnnualizedDurationS = 86400.0;
120
122 Duration bar = seconds(1);
123 double initial_capital = 0.0; // quote currency; only used for max_drawdown_pct
124 std::uint64_t rejects = 0;
125 std::uint64_t wall_p50_ns = 0;
126 std::uint64_t wall_p99_ns = 0;
127 // Venue mid of each instrument at the end of the run (raw price, indexed by instrument id).
128 // The decomposition marks the leftover inventory and the mid drift against it; without it
129 // only instrument 0's last equity-bar mid is available.
130 std::vector<std::int64_t> final_mid;
131 // Set when the venue could report a queue position (FillModel::L2Queue).
133 // Time of the last event of the run: a fill whose horizon falls after it could not be marked
134 // because the data ended, which is a different thing from a one-sided book.
135 std::int64_t end_ts = 0;
136};
138// The order half of the metrics, kept as a run goes: the counts of new orders, cancels and
139// replaces, the virtual tick-to-order latency, and each new order's first fill for the fill
140// quality's quotes filled and time to fill (a replace chain's fills count for the new order that
141// began it, at the earliest of them). It holds only the chains that can still fill, so a run need
142// not keep its order rows (BacktestConfig::keep_orders).
143class OrderStats {
144 public:
145 // An order message sent: kind is kOrderKindNew, Cancel or Replace, `orig` the order a replace
146 // replaces, `venue_ts` its arrival at the venue (0: lost), `trigger_ts` the T0 of the event
147 // that caused it (0: unknown).
148 void on_order(std::uint8_t kind,
149 std::uint64_t id,
150 std::uint64_t orig,
151 std::int64_t venue_ts,
152 std::int64_t trigger_ts);
153 void on_fill(std::uint64_t id, std::int64_t ts);
154 // The order can no longer fill (rejected, cancelled, replaced, expired or filled).
155 void on_end(std::uint64_t id);
156 // The rows' orders, then their fills.
157 [[nodiscard]] static OrderStats of(const OrderRows& orders, const FillRows& fills);
158
159 private:
160 friend Metrics compute_metrics(const EquityRows&,
161 const FillRows&,
163 const MetricsInputs&);
164 struct Chain {
165 std::int64_t venue_ts = 0; // of the new order that began it; 0: none, or it was lost
166 std::int64_t first_fill = -1; // the earliest fill of any of its orders
167 std::uint32_t open = 0; // its orders that can still fill; 0: a free slot
168 };
169 // Open order id -> its chain's slot in chains_, open addressing with linear probing (a run sends
170 // hundreds of thousands of orders, a few of them open at a time); id 0 marks an empty entry.
171 struct Entry {
172 std::uint64_t id = 0;
173 std::uint32_t chain = 0;
174 };
175 [[nodiscard]] Entry* find(std::uint64_t id) noexcept;
176 void insert(std::uint64_t id, std::uint32_t chain);
177 void erase(Entry* e) noexcept;
178 [[nodiscard]] std::uint32_t new_chain(std::int64_t venue_ts);
179 void close(std::uint32_t chain);
180 std::vector<Entry> table_; // a power of two, at most half full
181 std::size_t entries_ = 0;
182 std::vector<Chain> chains_;
183 std::vector<std::uint32_t> free_; // chain slots to reuse
184 LogLinearHistogram virt_;
185 std::vector<std::int64_t> time_to_fill_;
186 std::uint64_t orders_ = 0;
187 std::uint64_t cancels_ = 0;
188 std::uint64_t replaces_ = 0;
189 std::uint64_t quotes_filled_ = 0;
190};
191
192[[nodiscard]] Metrics compute_metrics(const EquityRows& equity,
193 const FillRows& fills,
194 OrderStats& orders,
195 const MetricsInputs& in);
196[[nodiscard]] Metrics compute_metrics(const EquityRows& equity,
197 const FillRows& fills,
198 const OrderRows& orders,
199 const MetricsInputs& in);
200
201} // namespace fastmm::bt
The order half of the metrics, kept as a run goes: the counts of new orders, cancels and replaces,...
Definition metrics.hpp:145
void on_order(std::uint8_t kind, std::uint64_t id, std::uint64_t orig, std::int64_t venue_ts, std::int64_t trigger_ts)
An order message sent: kind is kOrderKindNew, Cancel or Replace, orig the order a replace replaces,...
void on_fill(std::uint64_t id, std::int64_t ts)
friend Metrics compute_metrics(const EquityRows &, const FillRows &, OrderStats &, const MetricsInputs &)
static OrderStats of(const OrderRows &orders, const FillRows &fills)
The rows' orders, then their fills.
void on_end(std::uint64_t id)
The order can no longer fill (rejected, cancelled, replaced, expired or filled).
Post-fill markouts: the metric that separates spread captured from adverse selection.
Definition backtest_config.hpp:44
Metrics compute_metrics(const EquityRows &equity, const FillRows &fills, OrderStats &orders, const MetricsInputs &in)
constexpr double kMinAnnualizedDurationS
Shortest run whose Sharpe ratio is annualised: one day.
Definition metrics.hpp:121
constexpr Duration seconds(std::int64_t v) noexcept
Definition time.hpp:41
Definition time.hpp:22
Definition result.hpp:54
Diagnostics of how the fills were obtained, next to the markouts.
Definition metrics.hpp:47
double queue_ahead_mean
base units
Definition metrics.hpp:68
std::uint64_t quotes_placed
Definition metrics.hpp:64
std::uint64_t time_to_fill_p50_ns
Venue arrival of a new order to its first fill. Only orders that filled are counted.
Definition metrics.hpp:59
double queue_ahead_p90
Definition metrics.hpp:70
double inside_touch_share
at a better price than the touch (it improved it)
Definition metrics.hpp:54
std::uint64_t quotes_filled
Definition metrics.hpp:65
double realized_spread_bps
Notional-weighted (mid at fill - price) for buys, (price - mid at fill) for sells,...
Definition metrics.hpp:50
std::uint64_t time_to_fill_p90_ns
Definition metrics.hpp:60
std::uint64_t time_to_fill_p99_ns
Definition metrics.hpp:61
double realized_spread_quote
Definition metrics.hpp:51
double at_touch_share
Shares of the maker fills, by where the order was against the venue book at the fill.
Definition metrics.hpp:53
bool queue_position_known
Displayed quantity still ahead of the order when it filled; the L2Queue fill model only.
Definition metrics.hpp:67
double behind_touch_share
at a worse price than the touch
Definition metrics.hpp:55
double through_touch_share
At or beyond the opposite touch: the market had moved through the resting order.
Definition metrics.hpp:57
double fill_rate_per_quote
Share of new orders that got at least one fill (fill_ratio counts fills per order instead).
Definition metrics.hpp:63
double queue_ahead_p50
Definition metrics.hpp:69
Definition result.hpp:20
Buckets of one horizon, all over the same measured fills.
Definition markout.hpp:58
Definition metrics.hpp:123
Duration bar
Definition metrics.hpp:124
std::int64_t end_ts
Time of the last event of the run: a fill whose horizon falls after it could not be marked because th...
Definition metrics.hpp:137
double initial_capital
quote currency; only used for max_drawdown_pct
Definition metrics.hpp:125
bool queue_position_known
Set when the venue could report a queue position (FillModel::L2Queue).
Definition metrics.hpp:134
std::uint64_t wall_p50_ns
Definition metrics.hpp:127
std::uint64_t wall_p99_ns
Definition metrics.hpp:128
std::vector< std::int64_t > final_mid
Venue mid of each instrument at the end of the run (raw price, indexed by instrument id).
Definition metrics.hpp:132
std::uint64_t rejects
Definition metrics.hpp:126
Definition metrics.hpp:73
double fill_ratio
fills / new orders
Definition metrics.hpp:94
double final_position
base units, summed over instruments
Definition metrics.hpp:79
std::uint64_t replaces
Definition metrics.hpp:92
std::uint64_t rejects
Definition metrics.hpp:93
double fees
Definition metrics.hpp:78
double net_pnl
PnL in quote currency at the last bar: net == realized + unrealized - fees.
Definition metrics.hpp:75
std::vector< MarkoutHorizon > markouts
one entry per configured horizon, in order
Definition metrics.hpp:114
double inventory_max
max |position| at any fill or bar
Definition metrics.hpp:100
std::uint64_t maker_fills
Definition metrics.hpp:88
std::uint64_t virtual_tick_to_order_p99_ns
Definition metrics.hpp:107
double spread_captured_bps
mean of (mid - px) / mid for buys, (px - mid) / mid sells
Definition metrics.hpp:95
PnlDecomposition decomposition
Where the net PnL came from, and how good the fills were. See markout.hpp.
Definition metrics.hpp:112
double sharpe_annualized
sharpe_bar * sqrt(bars per 365-day year); NaN for runs more than one bar shorter than kMinAnnualizedD...
Definition metrics.hpp:83
FillQuality fill_quality
Definition metrics.hpp:113
std::uint64_t taker_fills
Definition metrics.hpp:89
std::uint64_t bars
Definition metrics.hpp:102
double volume_quote
Definition metrics.hpp:97
double duration_s
Definition metrics.hpp:103
std::uint64_t cancels
Definition metrics.hpp:91
double volume_base
Definition metrics.hpp:96
std::uint64_t wall_tick_to_order_p99_ns
Definition metrics.hpp:110
double unrealized_pnl
Definition metrics.hpp:77
const MarkoutHorizon * markout(std::int64_t horizon_ns) const noexcept
The markout of one horizon, or nullptr when it was not measured.
double realized_pnl
Definition metrics.hpp:76
double quote_uptime
fraction of bars with both a bid and an ask resting
Definition metrics.hpp:101
std::uint64_t virtual_tick_to_order_p50_ns
Virtual tick-to-order: engine receipt of the triggering event (T0, virtual clock) to the order's arri...
Definition metrics.hpp:106
double inventory_mean
over bars
Definition metrics.hpp:98
std::uint64_t orders
new orders sent
Definition metrics.hpp:90
std::uint64_t fills
Definition metrics.hpp:87
double sharpe_bar
mean / sample stdev of per-bar equity changes
Definition metrics.hpp:80
double max_drawdown
largest fall of equity from its peak, quote currency, >= 0
Definition metrics.hpp:84
double max_drawdown_pct
max_drawdown / initial_capital; NaN when initial_capital <= 0.
Definition metrics.hpp:86
std::uint64_t wall_tick_to_order_p50_ns
Measured wall clock per engine step that consumed market data (0 when not measured).
Definition metrics.hpp:109
double inventory_abs_mean
over bars
Definition metrics.hpp:99
Definition result.hpp:74
How the net PnL of the run splits into the parts a market maker can act on: net == spread_capture + m...
Definition metrics.hpp:32
double notional
traded notional of every fill
Definition metrics.hpp:40
double spread_capture
sum of signed_qty * (mid at fill - fill price)
Definition metrics.hpp:33
std::uint64_t fills
Definition metrics.hpp:43
double capture_notional
traded notional of the fills that had a mid at the fill
Definition metrics.hpp:41
double residual
reported net PnL - net
Definition metrics.hpp:39
double spread_capture_bps
Definition metrics.hpp:34
double fees_paid
sum of the positive fees, >= 0
Definition metrics.hpp:36
std::uint64_t capture_fills
Definition metrics.hpp:42
double rebates_received
sum of the negative fees with the sign flipped, >= 0
Definition metrics.hpp:37
double net
spread_capture + mid_drift - fees_paid + rebates_received
Definition metrics.hpp:38
double mid_drift
sum of signed_qty * (final mid - mid at fill)
Definition metrics.hpp:35
Time primitives.