FastMM documentation
FastMM C++ API 0.14.0
Public headers, tier 1 and tier 2
Loading...
Searching...
No Matches
capacity_price.hpp
Go to the documentation of this file.
1#pragma once
2// The capacity price ([capacity]): every action that uses an order slot is a purchase.
3//
4// A new order, and a move of a resting one, takes a slot of its account's order window and of the
5// day's orders. It is sent when what it is worth is at least what the slots cost at that moment:
6//
7// send iff value >= price(account) = L * h(z_window) + L * (h(z_weight) - 1) + day prices
8//
9// value what the strategy says the order brings in (the level's or NewOrderRequest's
10// value), in the quote currency; else the [capacity] value default: "off" (worth
11// any price) or "learned" (notional * yield * margin_bps, the yield being the
12// filled notional per placed notional of the instrument, side and size class)
13// a move buys the gain: the value at the new price less the resting order's (keep). A
14// move away from the touch cancels for free; its new order is bought as a new one
15// L what an order of the venue's minimum notional is worth at the session's yield
16// h(z) the online-knapsack threshold on the share z of the window used (Zhou,
17// Chakrabarty and Lukose 2008): 1 below z0 = 1 / (1 + ln R), (R e)^z / e above, R at a
18// full window; R = [risk] max_order_notional / the minimum notional
19// z_window the account's orders in the current window less the first fills in it (a venue
20// that credits fills), over orders_10s
21// z_weight the pool's requests in the current minute over weight_1m (0: not priced)
22// day prices the account's (orders_1d) and the strategy's (orders_per_day): the value at which
23// the demand of the rest of the UTC day fits what is left of the budget, shared out
24// by the demand of each hour of the day
25//
26// Cancels are never priced. A level whose order is not worth its price is priced out: its
27// target stays in its slot, and the engine applies it again when the window rolls over or a fill
28// gives a slot back. Every input is the engine's own: its sends, its fills, the configuration and
29// the clock, so a replay prices every order as the session did.
30//
31// Hot path: z is a counter, h a table of 101 entries, the price a few multiply-adds. The yield
32// estimates decay and the day prices are fitted once a minute (tick()). No allocation.
33#include "fastmm/core/enums.hpp"
35#include "fastmm/core/order.hpp"
37#include "fastmm/core/transport.hpp"
38
39#include <algorithm>
40#include <array>
41#include <cmath>
42#include <cstddef>
43#include <cstdint>
44#include <limits>
45#include <string_view>
46
47namespace fastmm {
48
49enum class CapacityMode : std::uint8_t {
50 Off = 0, // nothing is priced
51 Observe = 1, // prices are computed, counted and recorded; nothing is refused
52 New = 2, // new orders are refused below their price; moves are observed
53 Enforce = 3, // new orders and moves are refused below their price
54};
55[[nodiscard]] constexpr std::string_view to_string(CapacityMode m) noexcept {
56 switch (m) {
58 return "off";
60 return "observe";
62 return "new";
64 return "enforce";
65 }
66 return "off";
67}
68
69// The value of a quote level whose strategy states none.
70enum class CapacityValue : std::uint8_t {
71 Off = 0, // worth any price: the level is sent as without [capacity]
72 Learned = 1, // notional * yield(instrument, side, size class) * margin_bps
73};
74
75struct CapacityConfig {
78 // Each account's order window: its length and the orders it admits (Binance Spot: 10 s, 100).
79 // 0 orders: the window is not priced.
80 std::int64_t window_ms = 10'000;
81 std::int64_t orders_10s = 0;
82 // The venue gives a slot back on an order's first fill (Binance's unfilled order count).
83 bool fill_credit = false;
84 // Each account's orders per UTC day (Binance Spot: 200,000); 0: no day price per account.
85 std::int64_t orders_1d = 0;
86 // The strategy's own orders per UTC day over every account; 0: no budget.
87 std::int64_t orders_per_day = 0;
88 // Request weight per minute shared by the accounts of a pool (one IP); 0: not priced. A new
89 // order, a replace and a cancel each count 1.
90 std::int64_t weight_1m = 0;
91 // value = "learned": what a filled unit of notional earns, bps (rebate plus edge).
92 double margin_bps = 1.0;
93 // A move of this many bps or more is worth a whole new order when the strategy states no keep
94 // value: the resting order keeps value * (1 - move / full_move_bps).
95 double full_move_bps = 10.0;
96 // The threshold's range in notional, filled by the engine: the smallest minimum notional of the
97 // instruments and [risk] max_order_notional (quote currency).
98 double min_notional = 0.0;
99 double max_notional = 0.0;
100 // The accounts priced, bit per VenueId ([capacity] venues: those venues and their pools'
101 // members); the others are neither priced nor counted.
102 std::uint32_t accounts = ~0U;
103 [[nodiscard]] bool on() const noexcept { return mode != CapacityMode::Off; }
106// What an action costs on one account now (ctx.capacity).
107struct CapacityQuote {
108 double price = 0.0; // the whole price: what an action's value must reach
109 double floor = 0.0; // L, the value of a minimum-notional order
110 double window = 0.0; // the account window's part (L * h(z))
111 double weight = 0.0; // the pool's request weight part
112 double day = 0.0; // the account's and the strategy's day prices
113 double window_share = 0.0; // z of the account's window
114 std::int64_t window_used = 0;
115 std::int64_t window_orders = 0; // orders_10s (0: the window is not priced)
116 bool on = false;
119// A minute of one account (CapacityRecord): what was priced and refused.
120struct CapacityMinute {
121 std::uint32_t decided = 0; // actions priced
122 std::uint32_t sent = 0; // new orders and replaces sent
123 std::uint32_t priced_out_new = 0;
124 std::uint32_t priced_out_move = 0;
125 std::uint32_t observed_new = 0; // would have been priced out (observe, or moves under "new")
126 std::uint32_t observed_move = 0;
127 std::uint32_t peak_used = 0; // the most orders in one window
128 double price_min = 0.0;
129 double price_max = 0.0;
130 double price_sum = 0.0;
131 void clear() noexcept { *this = CapacityMinute{}; }
134// h(z): the knapsack threshold as a multiple of L, precomputed.
135class CapacityThreshold {
136 public:
137 static constexpr int kSteps = 100;
138 void configure(double ratio) noexcept {
139 ratio_ = std::max(ratio, 1.0);
140 const double ln = std::log(ratio_);
141 z0_ = 1.0 / (1.0 + ln);
142 for (int k = 0; k <= kSteps; ++k) {
143 const double z = static_cast<double>(k) / kSteps;
144 table_[static_cast<std::size_t>(k)] =
145 z < z0_ ? 1.0 : std::max(1.0, std::exp((z * (ln + 1.0)) - 1.0));
146 }
147 }
148 // The multiple of L at window share z (clamped to [0, 1]).
149 [[nodiscard]] double at(double z) const noexcept {
150 const double c = z <= 0.0 ? 0.0 : (z >= 1.0 ? 1.0 : z);
151 return table_[static_cast<std::size_t>(c * kSteps)];
152 }
153 [[nodiscard]] double z0() const noexcept { return z0_; }
154 [[nodiscard]] double ratio() const noexcept { return ratio_; }
156 private:
157 std::array<double, kSteps + 1> table_{};
158 double ratio_ = 1.0;
159 double z0_ = 1.0;
160};
161
162// The day price of one budget: the value at which the rest of the day's demand fits what is
163// left. Demand is every action priced, by value as a multiple of L in quarter octaves.
164class CapacityDayPrice {
165 public:
166 static constexpr int kBuckets = 64;
167 static constexpr int kZero = 16; // bucket of value L: [L, L * 2^(1/4))
168 // The lower edge of bucket b as a multiple of L.
169 [[nodiscard]] static double edge(int b) noexcept {
170 return std::exp2(static_cast<double>(b - kZero) * 0.25);
172 // The bucket of a value v given as a multiple of L (v / L); infinite: the top bucket.
173 [[nodiscard]] static int bucket(double rel) noexcept {
174 if (!(rel > 0.0)) return 0;
175 if (rel >= kTopEdge) return kBuckets - 1;
176 int e = 0;
177 const double m = std::frexp(rel, &e); // rel = m * 2^e, m in [0.5, 1)
178 // quarter octave within [0.5, 1): thresholds 2^(-1), 2^(-3/4), 2^(-1/2), 2^(-1/4)
179 int q = 0;
180 if (m >= 0.5946035575013605) q = 1;
181 if (m >= 0.7071067811865476) q = 2;
182 if (m >= 0.8408964152537145) q = 3;
183 const int b = ((e - 1) * 4) + q + kZero;
184 return std::clamp(b, 0, kBuckets - 1);
185 }
186
187 void note(double rel) noexcept { cur_[static_cast<std::size_t>(bucket(rel))] += 1.0; }
188 void note_sent() noexcept { ++used_; }
189 [[nodiscard]] double price() const noexcept { return lambda_; }
190 [[nodiscard]] std::int64_t used() const noexcept { return used_; }
192 // Once a minute: fold the minute's demand in, roll the day, and fit the price. `budget` <= 0:
193 // no price. `kind` 0 for a weekday, 1 for a weekend (their hours differ).
194 void tick(std::int64_t now_ns, std::int64_t budget, double floor, int kind) noexcept {
195 constexpr std::int64_t kDayNs = 86'400'000'000'000;
196 constexpr std::int64_t kHourNs = 3'600'000'000'000;
197 double minute = 0.0;
198 for (std::size_t b = 0; b < kBuckets; ++b) {
199 hist_[b] = (hist_[b] * kKeep) + cur_[b];
200 minute += cur_[b];
201 cur_[b] = 0.0;
202 }
203 const std::int64_t day = now_ns / kDayNs;
204 if (day != day_) {
205 day_ = day;
206 used_ = 0;
207 }
208 const int h = static_cast<int>((now_ns % kDayNs) / kHourNs);
209 if (h != hour_ || kind != kind_) {
210 if (hour_ >= 0) {
211 double& d = dem_[static_cast<std::size_t>(kind_)][static_cast<std::size_t>(hour_)];
212 bool& s = seen_[static_cast<std::size_t>(kind_)][static_cast<std::size_t>(hour_)];
213 d = s ? (0.8 * d) + (0.2 * hour_count_) : hour_count_;
214 s = true;
215 }
216 hour_ = h;
217 kind_ = kind;
218 hour_count_ = 0.0;
219 }
220 hour_count_ += minute;
221 lambda_ = 0.0;
222 if (budget <= 0) return;
223 // The demand of an hour: its profile, else the recent rate (decisions per hour).
224 double recent = 0.0;
225 for (const double x : hist_) recent += x;
226 const double recent_per_hour = recent * (1.0 - kKeep) * 60.0;
227 const auto dw = [&](int k) {
228 const auto ki = static_cast<std::size_t>(kind);
229 const auto kk = static_cast<std::size_t>(k);
230 return seen_[ki][kk] ? std::max(dem_[ki][kk], 1.0) : std::max(recent_per_hour, 1.0);
231 };
232 const double hour_left =
233 1.0 - (static_cast<double>(now_ns % kHourNs) / static_cast<double>(kHourNs));
234 double rest = dw(h) * hour_left;
235 for (int k = h + 1; k < 24; ++k) rest += dw(k);
236 const double remaining = static_cast<double>(std::max<std::int64_t>(budget - used_, 0));
237 if (remaining >= rest || recent <= 0.0) return;
238 // The fraction of the demand that fits; the most valuable part of the recent demand gets it.
239 const double keep = remaining / rest * recent;
240 double cum = 0.0;
241 for (int b = kBuckets - 1; b >= 0; --b) {
242 cum += hist_[static_cast<std::size_t>(b)];
243 if (cum > keep) {
244 lambda_ = floor * edge(std::min(b + 1, kBuckets - 1));
245 return;
246 }
247 }
248 }
249
250 private:
251 static constexpr double kKeep = 0.9; // a minute's weight in the demand: ten minutes' memory
252 static constexpr double kTopEdge = 4096.0; // 2^((kBuckets - 1 - kZero) / 4) rounded up
253 std::array<double, kBuckets> cur_{};
254 std::array<double, kBuckets> hist_{};
255 double dem_[2][24] = {};
256 bool seen_[2][24] = {};
257 double hour_count_ = 0.0;
258 int hour_ = -1;
259 int kind_ = 0;
260 std::int64_t day_ = -1;
261 std::int64_t used_ = 0;
262 double lambda_ = 0.0;
263};
264
265// The prices, the windows and the learned yields of one engine.
266class CapacityPrice {
267 public:
268 static constexpr int kClasses = 6; // by notional over the minimum: <2, <6, <12, <22, <60, more
269 static constexpr double kPriorYield = 0.02; // filled per placed notional before any is learned
270 static constexpr double kShrinkOrders = 20.0; // a cell's estimate leans on its class's for this
271 static constexpr std::int64_t kTickNs = 60'000'000'000;
272 static constexpr std::int64_t kWeightWindowNs = 60'000'000'000;
273 static constexpr double kYieldHalfLifeS = 6.0 * 3600.0;
275 void configure(const CapacityConfig& cfg) noexcept {
276 cfg_ = cfg;
277 if (!(cfg_.min_notional > 0.0))
278 cfg_.min_notional = cfg_.max_notional > 0.0 ? cfg_.max_notional / 100.0 : 1.0;
279 if (!(cfg_.max_notional > cfg_.min_notional)) cfg_.max_notional = cfg_.min_notional * 100.0;
280 window_ns_ = std::max<std::int64_t>(cfg_.window_ms, 1) * 1'000'000;
281 threshold_.configure(cfg_.max_notional / cfg_.min_notional);
282 update_floor();
283 }
284 [[nodiscard]] const CapacityConfig& config() const noexcept { return cfg_; }
285 [[nodiscard]] bool on() const noexcept { return cfg_.on(); }
286 [[nodiscard]] CapacityMode mode() const noexcept { return cfg_.mode; }
287 [[nodiscard]] const CapacityThreshold& threshold() const noexcept { return threshold_; }
288 [[nodiscard]] double floor() const noexcept { return floor_; }
289 // Whether orders on `account` are priced ([capacity] venues).
290 [[nodiscard]] bool prices(VenueId account) const noexcept {
291 return account.value < 32 && ((cfg_.accounts >> account.value) & 1U) != 0;
293
294 // Whether a refusal below the price is enforced for a new order or for a move.
295 [[nodiscard]] bool enforces(bool move) const noexcept {
296 return cfg_.mode == CapacityMode::Enforce || (cfg_.mode == CapacityMode::New && !move);
298
299 // ---- inputs: the engine's own sends and fills -------------------------------------------------
300
301 // A new order or a replace went to `account` (of the pool whose primary is `primary`).
302 void on_send(VenueId account,
303 VenueId primary,
304 InstrumentId id,
305 Side side,
306 double notional,
307 std::int64_t now_ns) noexcept {
308 if (!prices(account)) return;
309 if (account.value < kMaxVenues) {
310 Window& w = window(account, now_ns);
311 ++w.sent;
312 AccountState& a = acct_[account.value];
313 a.minute.peak_used = std::max(a.minute.peak_used, static_cast<std::uint32_t>(w.used()));
314 ++a.minute.sent;
315 a.day.note_sent();
316 }
317 all_.note_sent();
318 on_request(primary, now_ns);
319 if (id.value < kMaxInstruments && notional > 0.0) {
320 Yield& c = cell(id, side, notional);
321 c.placed += notional;
322 c.n += 1.0;
323 Yield& k = class_[static_cast<std::size_t>(class_of(notional))];
324 k.placed += notional;
325 k.n += 1.0;
326 total_.placed += notional;
327 total_.n += 1.0;
328 }
329 }
330 // A cancel (or any other request) of the pool: weight only.
331 void on_request(VenueId primary, std::int64_t now_ns) noexcept {
332 if (cfg_.weight_1m <= 0 || primary.value >= kMaxVenues) return;
333 Window& w = weight_[primary.value];
334 const std::int64_t wid = now_ns / kWeightWindowNs;
335 if (w.id != wid) w = Window{wid, 0, 0};
336 ++w.sent;
337 }
338 // A fill of an order placed with `order_notional`; `first`: the order's first fill.
339 void on_fill(VenueId account,
341 Side side,
342 double order_notional,
343 double fill_notional,
344 bool first,
345 std::int64_t now_ns) noexcept {
346 if (!prices(account)) return;
347 if (first && cfg_.fill_credit && account.value < kMaxVenues) {
348 Window& w = window(account, now_ns);
349 if (w.credit < w.sent) {
350 ++w.credit;
351 credited_ = true;
352 }
353 }
354 if (id.value < kMaxInstruments && order_notional > 0.0 && fill_notional > 0.0) {
355 cell(id, side, order_notional).filled += fill_notional;
356 class_[static_cast<std::size_t>(class_of(order_notional))].filled += fill_notional;
357 total_.filled += fill_notional;
358 }
359 }
360
361 // ---- the price ----------------------------------------------------------------------------
362
363 [[nodiscard]] CapacityQuote quote(VenueId account,
364 VenueId primary,
365 std::int64_t now_ns) const noexcept {
367 q.on = on() && prices(account);
368 q.floor = floor_;
369 q.window_orders = cfg_.orders_10s;
370 if (!q.on) return q;
371 q.window = floor_;
372 if (cfg_.orders_10s > 0 && account.value < kMaxVenues) {
373 const Window& w = acct_[account.value].window;
374 q.window_used = w.id == now_ns / window_ns_ ? w.used() : 0;
375 q.window_share = static_cast<double>(q.window_used) / static_cast<double>(cfg_.orders_10s);
376 q.window = floor_ * threshold_.at(q.window_share);
377 }
378 if (cfg_.weight_1m > 0 && primary.value < kMaxVenues) {
379 const Window& w = weight_[primary.value];
380 const std::int64_t used = w.id == now_ns / kWeightWindowNs ? w.used() : 0;
381 q.weight =
382 floor_ *
383 (threshold_.at(static_cast<double>(used) / static_cast<double>(cfg_.weight_1m)) - 1.0);
384 }
385 q.day = all_.price() + (account.value < kMaxVenues ? acct_[account.value].day.price() : 0.0);
386 q.price = q.window + q.weight + q.day;
387 return q;
388 }
389 [[nodiscard]] double price(VenueId account, VenueId primary, std::int64_t now_ns) const noexcept {
390 return quote(account, primary, now_ns).price;
391 }
392
393 // The learned value of a quote of `notional` on (id, side), quote currency.
394 [[nodiscard]] double learned_value(InstrumentId id, Side side, double notional) const noexcept {
395 if (!(notional > 0.0) || id.value >= kMaxInstruments) return 0.0;
396 const int c = class_of(notional);
397 const double global = shrink(total_, kPriorYield);
398 const double cls = shrink(class_[static_cast<std::size_t>(c)], global);
399 const double y =
400 shrink(cells_[id.value][static_cast<std::size_t>(side)][static_cast<std::size_t>(c)], cls);
401 return notional * y * cfg_.margin_bps * 1e-4;
402 }
403
404 // An action of `value` (a move: its gain) was priced at `price` on `account`; returns whether it
405 // passes. Records it in the account's minute and in the day's demand. A refusal of instrument
406 // `id`'s side that was already refused in the same window is the same demand asked again (a
407 // strategy requoting a priced-out level): refused, and recorded once.
408 bool decide(VenueId account,
409 double value,
410 double price,
411 bool move,
412 bool enforced,
414 Side side = Side::Buy,
415 std::int64_t now_ns = 0) noexcept {
416 if (value != value) value = std::numeric_limits<double>::infinity(); // unpriced
417 const bool pass = !(value < price);
418 if (!pass && enforced && id.value < kMaxInstruments) {
419 std::int64_t& last = refused_[id.value][static_cast<std::size_t>(side)];
420 const std::int64_t w = (now_ns / window_ns_) + 1;
421 if (last == w) return false;
422 last = w;
423 }
424 const double rel = floor_ > 0.0 ? value / floor_ : std::numeric_limits<double>::infinity();
425 all_.note(rel);
426 if (account.value >= kMaxVenues) return pass;
427 AccountState& a = acct_[account.value];
428 a.day.note(rel);
429 CapacityMinute& m = a.minute;
430 if (m.decided == 0) {
431 m.price_min = price;
432 m.price_max = price;
433 } else {
434 m.price_min = std::min(m.price_min, price);
435 m.price_max = std::max(m.price_max, price);
436 }
437 ++m.decided;
438 m.price_sum += price;
439 if (!pass) {
440 if (enforced) {
441 ++(move ? m.priced_out_move : m.priced_out_new);
442 ++(move ? totals_.priced_out_move : totals_.priced_out_new);
443 } else {
444 ++(move ? m.observed_move : m.observed_new);
445 ++(move ? totals_.observed_move : totals_.observed_new);
446 }
447 }
448 ++totals_.decided;
449 return pass;
450 }
451 [[nodiscard]] const CapacityMinute& totals() const noexcept { return totals_; }
452
453 // ---- the clock ----------------------------------------------------------------------------
454
455 // A priced-out level is applied again once a window has rolled over or a fill gave a slot back.
456 [[nodiscard]] bool recheck_due(std::int64_t now_ns) const noexcept {
457 return credited_ || now_ns >= recheck_ns_;
459 void rechecked(std::int64_t now_ns) noexcept {
460 credited_ = false;
461 recheck_ns_ = ((now_ns / window_ns_) + 1) * window_ns_;
463 [[nodiscard]] bool tick_due(std::int64_t now_ns) const noexcept { return now_ns >= tick_ns_; }
464 // Once a minute: decay the yields, refit the floor and the day prices, and hand each account's
465 // minute to `emit(VenueId, const CapacityMinute&)` before clearing it.
466 template <class Emit>
467 void tick(std::int64_t now_ns, Emit&& emit) noexcept {
468 const bool first = tick_ns_ == 0;
469 tick_ns_ = ((now_ns / kTickNs) + 1) * kTickNs;
470 if (first) {
471 last_decay_ns_ = now_ns;
472 return;
473 }
474 const double dt = static_cast<double>(now_ns - last_decay_ns_) * 1e-9;
475 last_decay_ns_ = now_ns;
476 if (dt > 0.0) {
477 const double k = std::exp2(-dt / kYieldHalfLifeS);
478 decay(total_, k);
479 for (Yield& y : class_) decay(y, k);
480 for (auto& inst : cells_)
481 for (auto& side : inst)
482 for (Yield& y : side) decay(y, k);
483 }
484 update_floor();
485 const int kind = weekend(now_ns) ? 1 : 0;
486 all_.tick(now_ns, cfg_.orders_per_day, floor_, kind);
487 for (std::size_t v = 0; v < kMaxVenues; ++v) {
488 AccountState& a = acct_[v];
489 a.day.tick(now_ns, cfg_.orders_1d, floor_, kind);
490 if (a.minute.decided != 0 || a.minute.sent != 0) {
491 emit(VenueId{static_cast<std::uint8_t>(v)}, a.minute);
492 a.minute.clear();
493 }
494 }
496 [[nodiscard]] double day_price(VenueId account) const noexcept {
497 return all_.price() + (account.value < kMaxVenues ? acct_[account.value].day.price() : 0.0);
498 }
499
500 private:
501 struct Window {
502 std::int64_t id = -1;
503 std::int64_t sent = 0;
504 std::int64_t credit = 0;
505 [[nodiscard]] std::int64_t used() const noexcept {
506 return std::max<std::int64_t>(sent - credit, 0);
507 }
508 };
509 struct Yield {
510 double placed = 0.0;
511 double filled = 0.0;
512 double n = 0.0;
513 };
514 struct AccountState {
515 Window window;
516 CapacityDayPrice day;
517 CapacityMinute minute;
518 };
519
520 Window& window(VenueId account, std::int64_t now_ns) noexcept {
521 Window& w = acct_[account.value].window;
522 const std::int64_t wid = now_ns / window_ns_;
523 if (w.id != wid) w = Window{wid, 0, 0};
524 return w;
525 }
526 [[nodiscard]] int class_of(double notional) const noexcept {
527 const double r = notional / cfg_.min_notional;
528 if (r < 2.0) return 0;
529 if (r < 6.0) return 1;
530 if (r < 12.0) return 2;
531 if (r < 22.0) return 3;
532 if (r < 60.0) return 4;
533 return 5;
534 }
535 Yield& cell(InstrumentId id, Side side, double notional) noexcept {
536 return cells_[id.value][static_cast<std::size_t>(side)]
537 [static_cast<std::size_t>(class_of(notional))];
538 }
539 // A yield estimate leaning on `prior` with the weight of kShrinkOrders orders of its own size.
540 [[nodiscard]] static double shrink(const Yield& y, double prior) noexcept {
541 if (!(y.n > 0.0) || !(y.placed > 0.0)) return prior;
542 const double w = kShrinkOrders * (y.placed / y.n);
543 return (y.filled + (prior * w)) / (y.placed + w);
544 }
545 static void decay(Yield& y, double k) noexcept {
546 y.placed *= k;
547 y.filled *= k;
548 y.n *= k;
549 }
550 void update_floor() noexcept {
551 floor_ = cfg_.min_notional * shrink(total_, kPriorYield) * cfg_.margin_bps * 1e-4;
552 }
553 [[nodiscard]] static bool weekend(std::int64_t ns) noexcept {
554 const auto wd = (ns / 86'400'000'000'000 + 4) % 7; // 1970-01-01 was a Thursday
555 return wd == 0 || wd == 6;
556 }
557
558 CapacityConfig cfg_{};
559 CapacityThreshold threshold_{};
560 std::int64_t window_ns_ = 10'000'000'000;
561 double floor_ = 0.0;
562 std::array<AccountState, kMaxVenues> acct_{};
563 std::array<Window, kMaxVenues> weight_{}; // by pool primary
564 CapacityDayPrice all_{};
565 Yield cells_[kMaxInstruments][2][kClasses] = {};
566 std::array<Yield, kClasses> class_{};
567 Yield total_{};
568 CapacityMinute totals_{};
569 std::int64_t refused_[kMaxInstruments][2] = {}; // 1 + the window of the last refusal
570 std::int64_t recheck_ns_ = 0;
571 bool credited_ = false;
572 std::int64_t tick_ns_ = 0;
573 std::int64_t last_decay_ns_ = 0;
574};
575
576} // namespace fastmm
static constexpr int kZero
bucket of value L: [L, L * 2^(1/4))
Definition capacity_price.hpp:169
void note(double rel) noexcept
Definition capacity_price.hpp:189
void tick(std::int64_t now_ns, std::int64_t budget, double floor, int kind) noexcept
Once a minute: fold the minute's demand in, roll the day, and fit the price.
Definition capacity_price.hpp:196
static int bucket(double rel) noexcept
The bucket of a value v given as a multiple of L (v / L); infinite: the top bucket.
Definition capacity_price.hpp:175
double price() const noexcept
Definition capacity_price.hpp:191
void note_sent() noexcept
Definition capacity_price.hpp:190
static double edge(int b) noexcept
The lower edge of bucket b as a multiple of L.
Definition capacity_price.hpp:171
std::int64_t used() const noexcept
Definition capacity_price.hpp:192
static constexpr int kBuckets
Definition capacity_price.hpp:168
double floor() const noexcept
Definition capacity_price.hpp:290
double learned_value(InstrumentId id, Side side, double notional) const noexcept
The learned value of a quote of notional on (id, side), quote currency.
Definition capacity_price.hpp:394
static constexpr double kShrinkOrders
a cell's estimate leans on its class's for this
Definition capacity_price.hpp:272
double price(VenueId account, VenueId primary, std::int64_t now_ns) const noexcept
Definition capacity_price.hpp:389
static constexpr int kClasses
by notional over the minimum: <2, <6, <12, <22, <60, more
Definition capacity_price.hpp:270
bool decide(VenueId account, double value, double price, bool move, bool enforced, InstrumentId id=InstrumentId{}, Side side=Side::Buy, std::int64_t now_ns=0) noexcept
An action of value (a move: its gain) was priced at price on account; returns whether it passes.
Definition capacity_price.hpp:408
void tick(std::int64_t now_ns, Emit &&emit) noexcept
Once a minute: decay the yields, refit the floor and the day prices, and hand each account's minute t...
Definition capacity_price.hpp:466
static constexpr double kPriorYield
filled per placed notional before any is learned
Definition capacity_price.hpp:271
static constexpr std::int64_t kTickNs
Definition capacity_price.hpp:273
bool recheck_due(std::int64_t now_ns) const noexcept
A priced-out level is applied again once a window has rolled over or a fill gave a slot back.
Definition capacity_price.hpp:455
static constexpr std::int64_t kWeightWindowNs
Definition capacity_price.hpp:274
static constexpr double kYieldHalfLifeS
Definition capacity_price.hpp:275
void on_fill(VenueId account, InstrumentId id, Side side, double order_notional, double fill_notional, bool first, std::int64_t now_ns) noexcept
A fill of an order placed with order_notional; first: the order's first fill.
Definition capacity_price.hpp:340
CapacityMode mode() const noexcept
Definition capacity_price.hpp:288
bool on() const noexcept
Definition capacity_price.hpp:287
void rechecked(std::int64_t now_ns) noexcept
Definition capacity_price.hpp:458
bool tick_due(std::int64_t now_ns) const noexcept
Definition capacity_price.hpp:462
bool prices(VenueId account) const noexcept
Whether orders on account are priced ([capacity] venues).
Definition capacity_price.hpp:292
double day_price(VenueId account) const noexcept
Definition capacity_price.hpp:495
void on_request(VenueId primary, std::int64_t now_ns) noexcept
A cancel (or any other request) of the pool: weight only.
Definition capacity_price.hpp:332
void on_send(VenueId account, VenueId primary, InstrumentId id, Side side, double notional, std::int64_t now_ns) noexcept
A new order or a replace went to account (of the pool whose primary is primary).
Definition capacity_price.hpp:303
const CapacityMinute & totals() const noexcept
Definition capacity_price.hpp:451
const CapacityThreshold & threshold() const noexcept
Definition capacity_price.hpp:289
CapacityQuote quote(VenueId account, VenueId primary, std::int64_t now_ns) const noexcept
Definition capacity_price.hpp:363
void configure(const CapacityConfig &cfg) noexcept
Definition capacity_price.hpp:277
const CapacityConfig & config() const noexcept
Definition capacity_price.hpp:286
bool enforces(bool move) const noexcept
Whether a refusal below the price is enforced for a new order or for a move.
Definition capacity_price.hpp:297
h(z): the knapsack threshold as a multiple of L, precomputed.
Definition capacity_price.hpp:137
double at(double z) const noexcept
The multiple of L at window share z (clamped to [0, 1]).
Definition capacity_price.hpp:151
double z0() const noexcept
Definition capacity_price.hpp:155
void configure(double ratio) noexcept
Definition capacity_price.hpp:140
static constexpr int kSteps
Definition capacity_price.hpp:139
double ratio() const noexcept
Definition capacity_price.hpp:156
All engine enumerations.
Instrument: the single definition of a tradable contract (5.3 / 5.15).
Definition strategy.hpp:23
@ Window
an open [[windows]] window with action = "pull" covers the instrument
@ Off
none was asked for in this session
constexpr Fixed< T > max(Fixed< T > a, Fixed< T > b) noexcept
Definition fixed_point.hpp:418
Side
Definition enums.hpp:12
CapacityMode
Definition capacity_price.hpp:51
@ New
new orders are refused below their price; moves are observed
@ Observe
prices are computed, counted and recorded; nothing is refused
@ Enforce
new orders and moves are refused below their price
@ Off
nothing is priced
StrongId< struct InstrumentTag, std::uint32_t > InstrumentId
Dense index into the engine's instrument table.
Definition strong_id.hpp:38
constexpr std::size_t kMaxInstruments
Definition instrument.hpp:26
constexpr std::string_view to_string(ParamType t) noexcept
Definition params.hpp:63
CapacityValue
The value of a quote level whose strategy states none.
Definition capacity_price.hpp:72
@ Learned
notional * yield(instrument, side, size class) * margin_bps
@ Off
worth any price: the level is sent as without [capacity]
StrongId< struct VenueTag, std::uint8_t > VenueId
Definition strong_id.hpp:39
Order: the OMS's 128-byte record for one order across its lifetime.
Strongly typed identifiers.
Definition capacity_price.hpp:77
double min_notional
The threshold's range in notional, filled by the engine: the smallest minimum notional of the instrum...
Definition capacity_price.hpp:100
std::int64_t orders_1d
Each account's orders per UTC day (Binance Spot: 200,000); 0: no day price per account.
Definition capacity_price.hpp:87
CapacityValue value
Definition capacity_price.hpp:79
bool on() const noexcept
Definition capacity_price.hpp:105
std::int64_t orders_per_day
The strategy's own orders per UTC day over every account; 0: no budget.
Definition capacity_price.hpp:89
double max_notional
Definition capacity_price.hpp:101
bool fill_credit
The venue gives a slot back on an order's first fill (Binance's unfilled order count).
Definition capacity_price.hpp:85
double margin_bps
value = "learned": what a filled unit of notional earns, bps (rebate plus edge).
Definition capacity_price.hpp:94
std::int64_t window_ms
Each account's order window: its length and the orders it admits (Binance Spot: 10 s,...
Definition capacity_price.hpp:82
std::int64_t orders_10s
Definition capacity_price.hpp:83
std::uint32_t accounts
The accounts priced, bit per VenueId ([capacity] venues: those venues and their pools' members); the ...
Definition capacity_price.hpp:104
CapacityMode mode
Definition capacity_price.hpp:78
double full_move_bps
A move of this many bps or more is worth a whole new order when the strategy states no keep value: th...
Definition capacity_price.hpp:97
std::int64_t weight_1m
Request weight per minute shared by the accounts of a pool (one IP); 0: not priced.
Definition capacity_price.hpp:92
A minute of one account (CapacityRecord): what was priced and refused.
Definition capacity_price.hpp:122
std::uint32_t sent
new orders and replaces sent
Definition capacity_price.hpp:124
double price_sum
Definition capacity_price.hpp:132
std::uint32_t peak_used
the most orders in one window
Definition capacity_price.hpp:129
std::uint32_t decided
actions priced
Definition capacity_price.hpp:123
std::uint32_t observed_new
would have been priced out (observe, or moves under "new")
Definition capacity_price.hpp:127
std::uint32_t priced_out_move
Definition capacity_price.hpp:126
void clear() noexcept
Definition capacity_price.hpp:133
std::uint32_t priced_out_new
Definition capacity_price.hpp:125
double price_min
Definition capacity_price.hpp:130
double price_max
Definition capacity_price.hpp:131
std::uint32_t observed_move
Definition capacity_price.hpp:128
What an action costs on one account now (ctx.capacity).
Definition capacity_price.hpp:109
double price
the whole price: what an action's value must reach
Definition capacity_price.hpp:110
double window
the account window's part (L * h(z))
Definition capacity_price.hpp:112
double floor
L, the value of a minimum-notional order.
Definition capacity_price.hpp:111
double window_share
z of the account's window
Definition capacity_price.hpp:115
std::int64_t window_used
Definition capacity_price.hpp:116
double day
the account's and the strategy's day prices
Definition capacity_price.hpp:114
double weight
the pool's request weight part
Definition capacity_price.hpp:113
bool on
Definition capacity_price.hpp:118
std::int64_t window_orders
orders_10s (0: the window is not priced)
Definition capacity_price.hpp:117
Rep value
Definition strong_id.hpp:26