algotradelib 0.0.0.9000
C++ header-only library for algorithmic trading
Loading...
Searching...
No Matches
engine.hpp
Go to the documentation of this file.
1#pragma once
2
3#include "./clock.hpp"
4#include "./fill.hpp"
5#include "./ledger.hpp"
6
7#include "../runner/order_updates.hpp"
8#include "../runner/runner.hpp"
9
10#include <algotradelib/core>
11
12#include <algorithm>
13#include <charconv>
14#include <chrono>
15#include <cstddef>
16#include <cstdint>
17#include <iterator>
18#include <optional>
19#include <stdexcept>
20#include <string>
21#include <type_traits>
22#include <unordered_map>
23#include <utility>
24#include <vector>
25
26namespace algotradelib {
27namespace backtest {
28
37
43template <typename BrokerTag>
50 std::uint64_t accepted_on_{0};
61 std::optional<std::chrono::system_clock::time_point> decided_at_;
75 bool released_{false};
81 std::optional<Decimal64> decision_price_;
86 std::optional<std::chrono::system_clock::time_point> decision_price_at_;
91 std::optional<Date> session_;
92};
93
102template <typename BrokerTag>
104 struct Slot;
105 // Each instrument's outstanding orders by serial, oldest first.
106 using ByInstrument = std::unordered_map<InstrumentId, std::vector<std::uint64_t>, id_detail::InstrumentIdHash>;
107
108public:
110 QueueingExecutor() = default;
111
116 QueueingExecutor(const QueueingExecutor& other) = default;
117
127 QueueingExecutor(QueueingExecutor&& other) noexcept(std::is_nothrow_move_constructible<ByInstrument>::value)
128 : by_instrument_(std::move(other.by_instrument_)),
129 slots_(std::move(other.slots_)),
130 live_(other.live_),
131 last_ref_(std::move(other.last_ref_)),
132 issued_(other.issued_),
133 bar_(other.bar_),
134 changes_(other.changes_ + 1),
135 deciding_at_(other.deciding_at_),
136 decision_is_exact_(other.decision_is_exact_) {
137 other.forget_queue();
138 }
139
146 if (this != &other) {
147 slots_ = std::move(other.slots_);
148 live_ = other.live_;
149 by_instrument_ = std::move(other.by_instrument_);
150 last_ref_ = std::move(other.last_ref_);
151 issued_ = other.issued_;
152 bar_ = other.bar_;
153 // The queue changed, whatever its count was: a replay comparing the count must see it move.
154 changes_ = (changes_ > other.changes_ ? changes_ : other.changes_) + 1;
155 deciding_at_ = other.deciding_at_;
156 decision_is_exact_ = other.decision_is_exact_;
157 other.forget_queue();
158 }
159 return *this;
160 }
161
169 if (this != &other) {
170 QueueingExecutor copy(other);
171 *this = std::move(copy);
172 }
173 return *this;
174 }
175
177 static constexpr bool reaches_a_broker = false;
190 if (!can_model(order)) {
192 }
193 // Room in the instrument's list first, so that once the order is stored nothing below can fail.
194 auto& serials = by_instrument_[order.instrument_];
195 if (serials.size() == serials.capacity()) {
196 serials.reserve(std::max<std::size_t>(4, 2 * serials.capacity()));
197 }
198 Slot slot;
199 slot.entry_.order_ = order;
200 slot.serial_ = issued_ + 1;
201 slot.entry_.ref_.primary_ = std::to_string(slot.serial_);
202 slot.entry_.accepted_on_ = bar_;
203 slot.entry_.decided_at_ = deciding_at_;
204 slot.entry_.decision_is_exact_ = decision_is_exact_;
205 auto last = slot.entry_.ref_;
206 slots_.push_back(std::move(slot));
207 serials.push_back(slots_.back().serial_);
208 ++issued_;
209 ++live_;
210 last_ref_ = std::move(last);
211 ++changes_;
213 }
214
226 static bool can_model(const strategy::PlannedOrder& order) noexcept {
227 if (order.session_ != OrderSession::REGULAR) {
228 return false;
229 }
230 switch (order.type_) {
232 // A stop the model can release: both prices, and a day order (the only stop KIS and Kiwoom offer).
233 return order.trigger_price_.has_value() && order.price_.has_value() && order.time_in_force_ == TimeInForce::DAY;
234 case OrderType::LIMIT:
236 // A trigger on a limit or market order would be ignored; refuse it.
237 return models_time_in_force(order.time_in_force_) && !order.trigger_price_;
238 case OrderType::UNKNOWN:
244 return false;
245 }
246 return false;
247 }
248
259 static constexpr bool models_time_in_force(TimeInForce condition) noexcept {
260 switch (condition) {
261 case TimeInForce::UNKNOWN:
262 case TimeInForce::DAY:
265 return true;
266 }
267 return false;
268 }
269
279
284 std::optional<OrderRef<BrokerTag>> last_ref() const {
285 return last_ref_;
286 }
287
293 class Queue {
294 public:
297 public:
299 using iterator_category = std::forward_iterator_tag;
303 using difference_type = std::ptrdiff_t;
308
310 const_iterator() = default;
315 reference operator*() const noexcept {
316 return at_->entry_;
317 }
318
322 pointer operator->() const noexcept {
323 return &at_->entry_;
324 }
325
330 ++at_;
331 skip();
332 return *this;
333 }
334
339 auto was = *this;
340 ++*this;
341 return was;
342 }
343
349 friend bool operator==(const const_iterator& lhs, const const_iterator& rhs) noexcept {
350 return lhs.at_ == rhs.at_;
351 }
352
358 friend bool operator!=(const const_iterator& lhs, const const_iterator& rhs) noexcept {
359 return lhs.at_ != rhs.at_;
360 }
361
362 private:
363 friend class Queue;
364 const_iterator(const Slot* at, const Slot* end) noexcept : at_(at), end_(end) {
365 skip();
366 }
367 void skip() noexcept {
368 while (at_ != end_ && !at_->live_) {
369 ++at_;
370 }
371 }
372 const Slot* at_{nullptr};
373 const Slot* end_{nullptr};
374 };
375
380 const_iterator begin() const noexcept {
381 return const_iterator(first_, last_);
382 }
383
387 const_iterator end() const noexcept {
388 return const_iterator(last_, last_);
389 }
390
394 std::size_t size() const noexcept {
395 return size_;
396 }
397
401 bool empty() const noexcept {
402 return size_ == 0;
403 }
404
408 const QueuedOrder<BrokerTag>& front() const noexcept {
409 return *begin();
410 }
411
412 private:
413 friend class QueueingExecutor;
414 Queue(const Slot* first, const Slot* last, std::size_t size) noexcept : first_(first), last_(last), size_(size) {}
415 const Slot* first_;
416 const Slot* last_;
417 std::size_t size_;
418 };
419
424 Queue queued() const noexcept {
425 return Queue(slots_.data(), slots_.data() + slots_.size(), live_);
426 }
427
436 template <typename Each>
437 void for_each_queued_in(const InstrumentId& instrument, Each&& each) const {
438 const auto found = by_instrument_.find(instrument);
439 if (found == by_instrument_.end()) {
440 return;
441 }
442 for (const auto serial : found->second) {
443 each(slots_[*slot_of(serial)].entry_);
444 }
445 }
446
453 const auto at = live_slot_of(ref);
454 return at ? &slots_[*at].entry_ : nullptr;
455 }
456
462 void assign_session(const OrderRef<BrokerTag>& ref, Date session) {
463 if (const auto at = live_slot_of(ref)) {
464 slots_[*at].entry_.session_ = session;
465 }
466 }
467
473 bool withdraw(const OrderRef<BrokerTag>& ref) {
474 const auto at = live_slot_of(ref);
475 if (!at) {
476 return false;
477 }
478 // **Marked removed where it is, not erased.** Erasing moved every later order (each with three strings)
479 // one place down, for every fill; the storage is compacted instead once removed orders outnumber the
480 // rest, which keeps placement order and costs each removal a constant on average. Finding the order in
481 // its instrument's list is linear in that instrument's outstanding orders, usually one.
482 auto& slot = slots_[*at];
483 slot.live_ = false;
484 --live_;
485 auto& serials = by_instrument_.find(slot.entry_.order_.instrument_)->second;
486 serials.erase(std::find(serials.begin(), serials.end(), slot.serial_));
487 ++changes_;
488 if (slots_.size() - live_ > live_) {
489 compact();
490 }
491 return true;
492 }
493
499 bool release(const OrderRef<BrokerTag>& ref) {
500 const auto at = live_slot_of(ref);
501 if (!at) {
502 return false;
503 }
504 slots_[*at].entry_.released_ = true;
505 return true;
506 }
507
511 void open_bar() noexcept {
512 ++bar_;
513 }
514
519 std::uint64_t bar() const noexcept {
520 return bar_;
521 }
522
530 std::uint64_t changes() const noexcept {
531 return changes_;
532 }
533
539 template <typename PriceOf>
540 void stamp_decision_prices(PriceOf&& price_of) {
541 for (auto slot = slots_.rbegin(); slot != slots_.rend() && !slot->priced_; ++slot) {
542 slot->priced_ = true;
543 auto [price, at] = price_of(slot->entry_.order_.instrument_);
544 slot->entry_.decision_price_ = std::move(price);
545 slot->entry_.decision_price_at_ = at;
546 }
547 }
548
554 void deciding_at(std::chrono::system_clock::time_point at, bool exact = true) {
555 deciding_at_ = at;
556 decision_is_exact_ = exact;
557 }
558
559private:
560 // One accepted order and its serial (the number its reference states), in placement order; `live_` turns
561 // false when it fills or is withdrawn, until `compact` drops it.
562 struct Slot {
564 std::uint64_t serial_{0};
565 bool live_{true};
566 // Whether `stamp_decision_prices` has seen it.
567 bool priced_{false};
568 };
569
570 // Where the order with `serial` is in `slots_`. Serials rise in placement order, which compaction keeps.
571 std::optional<std::size_t> slot_of(std::uint64_t serial) const noexcept {
572 const auto found =
573 std::lower_bound(slots_.begin(), slots_.end(), serial, [](const Slot& slot, std::uint64_t wanted) {
574 return slot.serial_ < wanted;
575 });
576 if (found == slots_.end() || found->serial_ != serial) {
577 return std::nullopt;
578 }
579 return static_cast<std::size_t>(found - slots_.begin());
580 }
581
582 // Where the outstanding order `ref` names is, by the serial its primary part states: a reference this
583 // executor did not issue, or one already filled or withdrawn, is found nowhere, as by a scan comparing whole
584 // references.
585 std::optional<std::size_t> live_slot_of(const OrderRef<BrokerTag>& ref) const noexcept {
586 const auto& text = ref.primary_;
587 std::uint64_t serial = 0;
588 const auto parsed = std::from_chars(text.data(), text.data() + text.size(), serial);
589 if (parsed.ec != std::errc{} || parsed.ptr != text.data() + text.size()) {
590 return std::nullopt;
591 }
592 const auto at = slot_of(serial);
593 if (!at || !slots_[*at].live_ || !(slots_[*at].entry_.ref_ == ref)) {
594 return std::nullopt;
595 }
596 return at;
597 }
598
599 // Leaves a moved-from executor with nothing queued, its count of changes moved on.
600 void forget_queue() noexcept {
601 slots_.clear();
602 by_instrument_.clear();
603 live_ = 0;
604 last_ref_.reset();
605 ++changes_;
606 }
607
608 // Drops the removed orders, keeping the rest in placement order. Moves orders; allocates nothing.
609 void compact() noexcept {
610 slots_.erase(
611 std::remove_if(
612 slots_.begin(), slots_.end(),
613 [](const Slot& slot) {
614 return !slot.live_;
615 }
616 ),
617 slots_.end()
618 );
619 }
620
621 // First, so that a move whose map throws has moved nothing else.
622 ByInstrument by_instrument_;
623 std::vector<Slot> slots_;
624 std::size_t live_{0};
625 std::optional<OrderRef<BrokerTag>> last_ref_;
626 std::uint64_t issued_{0};
627 std::uint64_t bar_{0};
628 std::uint64_t changes_{0};
629 std::optional<std::chrono::system_clock::time_point> deciding_at_;
630 bool decision_is_exact_{true};
631};
632
657
661 std::chrono::system_clock::time_point at_{};
673};
674
681 std::vector<EquityPoint> equity_;
683 std::vector<Execution> executions_;
688 std::vector<strategy::Rejection> rejected_;
690 std::vector<strategy::GuardRejection> refused_;
692 std::size_t gaps_{0};
694 std::size_t bars_{0};
696 std::size_t unfilled_{0};
707 std::optional<BrokerError> halted_;
709 std::size_t aborted_{0};
711 std::size_t quotes_{0};
713 std::size_t records_{0};
731 std::size_t unvalued_bars_{0};
733 std::optional<std::chrono::system_clock::time_point> first_unvalued_;
735 std::size_t stop_releases_{0};
737 std::size_t stop_fills_intrabar_{0};
739 std::size_t limit_fills_bounded_{0};
743 std::size_t market_fills_by_rule_{0};
754 std::size_t overdrawn_bars_{0};
756 std::optional<std::chrono::system_clock::time_point> first_overdrawn_;
758 std::optional<Money> lowest_cash_;
760 std::optional<std::chrono::system_clock::time_point> lowest_cash_at_;
762 std::size_t expired_day_orders_{0};
764 std::size_t history_bars_{0};
765};
766
819
842template <typename Strategy, typename CapsType = strategy::NoCaps>
844public:
851
858 Backtester(Strategy strategy = {}, ReplayConfig config = {}, NextBarFillModel fills = NextBarFillModel{})
859 : config_(std::move(config)),
860 fills_(std::move(fills)),
861 ledger_(config_.cash_, config_.currency_, ExecutionHistory::NONE),
862 clock_(config_.session_),
863 runner_(std::move(strategy), config_.limits_, config_.series_capacity_) {
864 for (const auto& reference : config_.instruments_) {
865 runner_.context().set_instrument(reference);
866 }
867 runner_.context().set_calendar(config_.calendar_);
868 runner_.context().set_session(config_.session_);
869 // Its queue rows are the run's open orders, installed before every pass.
870 runner::runner_detail::ReplayAccess::rows_listed(runner_);
871 // So a report can compare an execution's currency with the curve's.
872 result_.currency_ = config_.currency_;
873 result_.market_price_rule_ = fills_.market_price_rule();
874 }
875
880 const Strategy& strategy() const noexcept {
881 return runner_.strategy();
882 }
883
891 const ReplayLedger& ledger() const noexcept {
892 return ledger_;
893 }
894
899 const NextBarFillModel& fills() const noexcept {
900 return fills_;
901 }
902
907 const ReplayResult& result() const noexcept {
908 return result_;
909 }
910
916 std::optional<Money> run_cash() const {
917 return runner_.run_cash();
918 }
919
925 std::optional<Decimal64> run_holding(const InstrumentId& instrument) const {
926 return runner_.run_holding(instrument);
927 }
928
960 void feed(const strategy::BarEvent& event, std::optional<bool> trading_day = true) {
961 // **A halted replay consumes nothing further.** `feed` keeps returning `void` so no caller has to
962 // change, and a caller that ignores `ReplayResult` sees a run that ends early rather than one
963 // that carries on costing nothing: no bar counted, no fill, no mark, no equity point, and no
964 // callback into the strategy. That is API compatibility, which is not the same as invisibility,
965 // and it is why the halt is stated on the result and first in the report.
966 if (result_.halted_) {
967 pending_.clear();
968 return;
969 }
970 const bool history = is_history(event.period_end_);
971 if constexpr (Runner::takes_records) {
972 // A bar that ended before a record already fed would be decided on with that record in view: data from
973 // after the bar. Refused before anything changes, rather than replayed with a look-ahead.
974 if (latest_record_at_ && event.period_end_ < *latest_record_at_) {
975 throw std::invalid_argument(
976 "a bar that ended before a record already fed: feed records and bars in time order, a record before "
977 "the bars of its instant"
978 );
979 }
980 }
981 // **One lookup of the instrument per bar**: its slot says where its lot, its last price and its series are,
982 // and whether it already has a bar in the period being collected.
983 auto& slot = slot_for(event.instrument_);
984 if constexpr (Runner::takes_bar_slices) {
985 // **Checked before anything is counted, settled, marked or cached**, so a refused bar leaves the
986 // replay as it was. The pending period is delivered here, before this bar's settlement, exactly
987 // where `on_bar` would have run for that period's last bar.
988 check_slice_order(event, slot);
989 if (!pending_.empty() && pending_.period_end() < event.period_end_) {
990 deliver_pending();
991 if (result_.halted_) {
992 return;
993 }
994 }
995 }
996 // Before anything this bar changes, so an order `on_start` places is queued ahead of the first
997 // `open_bar`: eligible on this bar, undated, decided before anything was seen.
998 start_strategy();
999 if (history) {
1000 ++result_.history_bars_;
1001 set_price(slot, event);
1002 if constexpr (Runner::takes_bar_slices) {
1003 collect_for_slice(event, slot);
1004 } else {
1005 install_portfolio();
1006 runner_.feed_warmup(event);
1007 }
1008 previous_ = std::make_pair(event.interval_, event.period_end_);
1009 return;
1010 }
1011 history_over_ = true;
1012 ++result_.bars_;
1013 if (previous_ && !ReplayClock::contiguous(previous_->first, previous_->second, event)) {
1014 // A gap is counted rather than interpolated across: nothing happened in it that a strategy
1015 // should be told about, and inventing a bar would be inventing data.
1016 ++result_.gaps_;
1017 }
1018
1019 // Opened before anything fills against this bar, so that an order placed during it carries a
1020 // later stamp than the ones already resting and cannot fill against the bar it was decided on.
1021 runner_.executor().open_bar();
1022 // And dated, for the half of that rule a counter cannot express -- see `QueuedOrder::decided_at_`.
1023 // A bar's decisions are all made at its period end, whichever handler makes them: `on_fill`
1024 // during settlement, `on_phase`, `on_bar`, and a handler answering an order update afterwards.
1025 //
1026 // **Whether that instant is exact depends on the stamp**, and getting this wrong deferred real
1027 // fills by a month. A close-stamped bar's period end is its own timestamp, stated by the broker.
1028 // An open-stamped one is `bar_period_end`'s arithmetic, which is exact for an intraday bar (late
1029 // only for a session's last bar cut short by the close) and deliberately **nominal** for a day, a
1030 // week, a month and a year -- and every shipped adapter stamps every daily and longer bar `OPEN`.
1031 // February's nominal end is five days into March, so an order decided on February's bar looked as
1032 // though it had been decided inside March's period and was deferred to April.
1033 runner_.executor().deciding_at(event.period_end_, period_end_is_exact(event));
1034
1035 // A period's point is recorded once its last bar is in, which is when a bar of another period arrives:
1036 // before that bar fills anything, so the point is the equity the period ended with. Any other period end,
1037 // later or (bars of mixed intervals) earlier, ends the run, so no period is lost.
1038 if (period_point_ && *period_point_ != event.period_end_) {
1039 record_point(*period_point_);
1040 }
1041 settle_queued_against(event, slot);
1042 // **The halt stops this bar too, not merely the next one.** Returning only from settlement left
1043 // `feed` to mark the book, record an equity point, advance the clock and call `on_phase` and
1044 // `on_bar` on the very bar whose fill could not be costed -- so the strategy decided once more
1045 // on a portfolio missing that trade, and could queue orders that then survived in the executor
1046 // because every later `feed` is a no-op and `finish` returns early. Nothing runs after the
1047 // refusal.
1048 if (result_.halted_) {
1049 return;
1050 }
1051 // **A mark that will not fit halts the replay**, like a fill it cannot cost or record. The lot
1052 // stays at its previous price, while `Runner::feed` is about to hand the strategy this bar's
1053 // close as the last price -- so `on_bar` would decide, and `Runner::settle` would size and check
1054 // an order, against a position valued one bar ago beside a price from this one. An order placed
1055 // from that view fills on a later bar and changes every figure after it. This used to skip only
1056 // the equity point and carry on, which reported nothing and let that order through.
1057 if (slot.lot_ && !ledger_.mark_lot(*slot.lot_, event.bar_.close_)) {
1058 BrokerError error;
1060 error.reached_broker_ = false;
1061 error.broker_code_ = "mark_not_representable";
1062 error.message_ = "a position in " + event.instrument_.symbol_ +
1063 " could not be valued at the "
1064 "bar's close without leaving an exact decimal, so the replay stopped rather than let a "
1065 "strategy decide on a position one bar behind its price";
1066 result_.halted_ = std::move(error);
1067 abort_queue();
1068 return;
1069 }
1070 count_bar(event);
1071
1072 // **The price moves with the portfolio, not after it.** `Runner::settle` values a market order
1073 // at `context_.last_price`, so a view whose positions are marked to this bar while the price is
1074 // still the previous bar's is not a fresher picture -- it is an incoherent one, and it is worse
1075 // than a uniformly stale picture because it looks current. After a close moves from 10 to 100, a
1076 // market buy from `on_phase` would be checked against buying power and exposure at 10 while the
1077 // positions beside it say 100, which can admit an order those limits exist to refuse.
1078 set_price(slot, event);
1079
1080 if (clock_.advance(event, trading_day)) {
1081 runner_.context().set_phase(clock_.phase());
1082 // **The clock moves with the price and the portfolio, for the same reason.**
1083 // `Runner::feed(MarketPhase)` does not advance the context's time -- only `feed(BarEvent)`
1084 // does, and that runs later -- so `on_phase` would decide with this bar's marks and close
1085 // beside the *previous* bar's instant. `RiskGuard` records a send at `GuardInputs::now_` and
1086 // counts sends within `rate_window_` of it, so across a gap longer than that window a phase
1087 // order is filed under the old instant and the bar order that follows does not see it: two
1088 // orders through a one-order window at what the replay calls the same moment.
1089 runner_.context().set_now(event.period_end_);
1090 // **Installed before the phase change is acted on, not after.** A strategy placing an order
1091 // from `on_phase` used to decide on a portfolio predating this bar's fills and this bar's
1092 // mark, while the engine already held a fresher answer and had simply not installed it yet.
1093 install_portfolio();
1094 drain_reports(runner_.feed(clock_.phase()));
1095 } else {
1096 runner_.context().set_phase(clock_.phase());
1097 }
1098
1099 if constexpr (Runner::takes_bar_slices) {
1100 collect_for_slice(event, slot);
1101 } else {
1102 install_portfolio();
1103 drain_reports(runner_.feed(event));
1104 }
1105 // **After the dispatch, not before it**, so an order this bar's `on_bar` or `on_phase` placed is
1106 // reported. Before it would report only what settlement had already changed.
1107 publish_order_updates();
1108 previous_ = std::make_pair(event.interval_, event.period_end_);
1109 }
1110
1117 if (history_over_ || result_.halted_) {
1118 return;
1119 }
1120 if constexpr (Runner::takes_bar_slices) {
1121 if (!pending_.empty() && is_history(pending_.period_end())) {
1122 deliver_pending();
1123 }
1124 }
1125 history_over_ = true;
1126 }
1127
1149 void feed(const strategy::QuoteEvent& event, std::optional<bool> trading_day = true) {
1150 // The same rule `feed(const BarEvent&)` opens with: a halted replay consumes nothing further,
1151 // because a strategy told about anything after the halt decides on a run that has stopped being
1152 // able to cost what it asks for.
1153 if (result_.halted_) {
1154 pending_.clear();
1155 return;
1156 }
1157 if (config_.trade_from_ && event.quote_.received_at_ < *config_.trade_from_) {
1158 throw std::invalid_argument("a quote before trade_from_: a replay feeds no quote as history");
1159 }
1160 if constexpr (Runner::takes_bar_slices) {
1161 // A quote at or after the pending period comes after it: the period is delivered while its own
1162 // price, clock and phase are still installed, before this quote changes any of them.
1163 const auto at = event.quote_.received_at_;
1164 if (!pending_.empty() && at < pending_.period_end()) {
1165 throw std::invalid_argument(
1166 "a quote earlier than bars already fed: with on_bars, feed quotes and bars in time order"
1167 );
1168 }
1169 if (pending_.empty() && delivered_through_ && at < *delivered_through_) {
1170 throw std::invalid_argument(
1171 "a quote earlier than a period already delivered: with on_bars, feed quotes and bars in time order"
1172 );
1173 }
1174 if (!pending_.empty()) {
1175 deliver_pending();
1176 if (result_.halted_) {
1177 return;
1178 }
1179 }
1180 }
1181 history_over_ = true;
1182 ++result_.quotes_;
1183 // The runner prices the instrument at this quote before any handler runs on it.
1184 slot_for(event.quote_.instrument_).priced_at_ = event.quote_.received_at_;
1185 // Dated before anything can place an order, so a decision made here is not credited a price from
1186 // earlier in the bar it will fill against. See `QueuedOrder::decided_at_`.
1187 runner_.executor().deciding_at(event.quote_.received_at_);
1188 // After the dating, unlike the bar path: an order `on_start` places here carries the quote's
1189 // instant, so a bar whose period began before it cannot fill it.
1190 start_strategy();
1191
1192 // **The phase is re-derived at the quote's own instant, before the handler runs.** Without this
1193 // a quote at 10:30 was shown the phase as it stood at the previous close, and the default
1194 // `RiskLimits::permitted_phases_` refuses an opening order in every phase but `OPEN` -- so a
1195 // strategy that lives correctly refused in a replay. `PollingLoop` installs the phase before
1196 // each due poll, this is the same rule, and a change is announced first for the reason
1197 // `feed(const BarEvent&)` announces it first: a handler placing an order from `on_phase` must
1198 // decide against the phase this instant established, not the one before it.
1199 const bool phase_changed = clock_.advance_to(event.quote_.received_at_, trading_day);
1200 runner_.context().set_phase(clock_.phase());
1201 if (phase_changed) {
1202 // **The price and the clock move first, then the change is announced.** `Runner::feed` sets
1203 // both from the quote, but it runs *after* this, so announcing first left `on_phase` deciding
1204 // on the previous bar's close and stamping its send at the previous instant -- a market order
1205 // sized and guarded at the wrong value. This is the order
1206 // `feed(const BarEvent&)` already uses: mark, price, clock, announce, dispatch.
1207 runner_.context().set_last_price(event.quote_.instrument_, event.quote_.last_price_);
1208 runner_.context().set_now(event.quote_.received_at_);
1209 install_portfolio();
1210 drain_reports(runner_.feed(clock_.phase()));
1211 }
1212
1213 // Installed before the dispatch for the reason every other dispatch site here installs: a
1214 // handler reads `ctx.portfolio()`, and the engine holds a fresher answer than the last one it
1215 // pushed -- an order placed by the *previous* quote has had no settlement pass behind it.
1216 install_portfolio();
1217 drain_reports(runner_.feed(event));
1218 // **After the dispatch, exactly as the bar path does.** An earlier version left
1219 // it out, arguing that live a quote poll publishes no order update -- which is true of that one
1220 // call and false of the loop it sits in: an order placed from `on_quote` can be listed by a later
1221 // working-order poll and announced. Publishing here is the closer parity, and it also
1222 // announces an order that would otherwise fill and be gone before any later observation point.
1223 publish_order_updates();
1224 }
1225
1250 template <typename T>
1251 void feed(const strategy::DataEvent<T>& event, std::optional<bool> trading_day = true) {
1252 static_assert(
1253 strategy::strategy_detail::declares_on_data<Strategy>,
1254 "a record fed to a strategy that declares no on_data would vanish: declare on_data, or feed no records"
1255 );
1256 static_assert(std::is_same_v<T, typename Runner::DataRecord>, "a record must be of the strategy's data_type");
1257 if (result_.halted_) {
1258 pending_.clear();
1259 return;
1260 }
1261 const auto at = event.known_at_;
1262 const bool history = is_history(at);
1263 // Records come in time order, with each other and with the bars: one earlier than either was fed out of
1264 // order, and is refused before anything changes.
1265 if (latest_record_at_ && at < *latest_record_at_) {
1266 throw std::invalid_argument("a record earlier than a record already fed: feed records in time order");
1267 }
1268 if (previous_ && at < previous_->second) {
1269 throw std::invalid_argument(
1270 "a record earlier than a bar already fed: feed records and bars in time order, a record before the bars "
1271 "of its instant"
1272 );
1273 }
1274 if constexpr (Runner::takes_bar_slices) {
1275 if (!pending_.empty() && at < pending_.period_end()) {
1276 throw std::invalid_argument(
1277 "a record earlier than bars already fed: with on_bars, feed records and bars in time order"
1278 );
1279 }
1280 if (pending_.empty() && delivered_through_ && at < *delivered_through_) {
1281 throw std::invalid_argument(
1282 "a record earlier than a period already delivered: with on_bars, feed records and bars in time order"
1283 );
1284 }
1285 // Only a period that ended before the record: one ending at its instant is delivered after it, so that
1286 // period's slice sees what was known by its end.
1287 if (!pending_.empty() && pending_.period_end() < at) {
1288 deliver_pending();
1289 if (result_.halted_) {
1290 return;
1291 }
1292 }
1293 }
1294 ++result_.records_;
1295 latest_record_at_ = at;
1296 if (history) {
1297 // Undated, so an order `on_start` places here rests through history as one placed at a history bar does.
1298 start_strategy();
1299 install_portfolio();
1300 runner_.feed_warmup(event);
1301 return;
1302 }
1303 history_over_ = true;
1304 runner_.executor().deciding_at(at);
1305 start_strategy();
1306 const bool phase_changed = clock_.advance_to(at, trading_day);
1307 runner_.context().set_phase(clock_.phase());
1308 if (phase_changed) {
1309 runner_.context().set_now(at);
1310 install_portfolio();
1311 drain_reports(runner_.feed(clock_.phase()));
1312 }
1313 install_portfolio();
1314 drain_reports(runner_.feed(event));
1315 publish_order_updates();
1316 }
1317
1327 void finish() {
1328 if (result_.halted_) {
1329 // **The strategy is not stopped normally, and that is deliberate.** `Runner::stop` calls
1330 // `on_stop`, which may place or flatten -- and an order placed into a replay that has already
1331 // stopped being able to cost one would either fill uncosted or be silently dropped. Neither is
1332 // a shutdown a reader could interpret, so nothing runs: the queue was cleared at the halt and
1333 // `aborted_` says how much was in it. The report states that the strategy never saw a stop.
1334 pending_.clear();
1335 return;
1336 }
1337 // A replay given no event still starts the strategy before stopping it.
1338 start_strategy();
1339 if constexpr (Runner::takes_bar_slices) {
1340 // The last period has no later bar to deliver it: it goes before `on_stop` and before `unfilled_`
1341 // is counted, so both see what it placed.
1342 if (!pending_.empty()) {
1343 deliver_pending();
1344 if (result_.halted_) {
1345 return;
1346 }
1347 }
1348 }
1349 // The last period's point: nothing has filled since its last bar.
1350 if (period_point_) {
1351 record_point(*period_point_);
1352 }
1353 install_portfolio();
1354 drain_reports(runner_.stop());
1355 // The only boundary that can observe what `on_stop` placed or withdrew. Before `unfilled_` is
1356 // counted, so the count describes the queue the run actually ended with.
1357 publish_order_updates();
1358 result_.unfilled_ = runner_.executor().queued().size();
1359 }
1360
1361private:
1370 struct InstrumentSlot {
1372 struct ByInterval {
1374 BarInterval interval_{BarInterval::ONE_DAY};
1376 std::optional<std::chrono::system_clock::time_point> pending_;
1377#if defined(ATL_HAS_EIGEN)
1379 analytics::SeriesBuffer* series_{nullptr};
1381 std::optional<std::chrono::system_clock::time_point>* bar_time_{nullptr};
1382#endif
1383 };
1384
1385 std::optional<std::size_t> lot_;
1387 Decimal64* price_{nullptr};
1389 std::optional<std::chrono::system_clock::time_point> priced_at_;
1391 std::vector<ByInterval> intervals_;
1392
1398 ByInterval& interval(BarInterval interval) {
1399 for (auto& entry : intervals_) {
1400 if (entry.interval_ == interval) {
1401 return entry;
1402 }
1403 }
1404 ByInterval added;
1405 added.interval_ = interval;
1406 intervals_.push_back(added);
1407 return intervals_.back();
1408 }
1409 };
1410
1411 // Caches a bar for `on_bars` and holds it with the rest of its period; it is priced already, so not again.
1412 void collect_for_slice(const strategy::BarEvent& event, InstrumentSlot& slot) {
1413 auto& by_interval = slot.interval(event.interval_);
1414#if defined(ATL_HAS_EIGEN)
1415 using Access = runner::context_detail::PortfolioAccess;
1416 forget_pointers_if_replaced();
1417 if constexpr (Runner::records_bar_history) {
1418 if (by_interval.series_ == nullptr) {
1419 by_interval.series_ = &Access::series_for(runner_.context(), event);
1420 }
1421 by_interval.series_->push(event.bar_);
1422 } else {
1423 if (by_interval.bar_time_ == nullptr) {
1424 by_interval.bar_time_ = &Access::bar_time_for(runner_.context(), event);
1425 }
1426 Access::advance_bar_time(*by_interval.bar_time_, event);
1427 }
1428#endif
1429 runner_.context().set_now(event.period_end_);
1430 pending_.add_checked(event);
1431 by_interval.pending_ = event.period_end_;
1432 }
1433
1434 // Whether an event at `at` is history (`ReplayConfig::trade_from_`); refuses one once history has ended.
1435 bool is_history(std::chrono::system_clock::time_point at) const {
1436 if (!config_.trade_from_ || !(at < *config_.trade_from_)) {
1437 return false;
1438 }
1439 if (history_over_) {
1440 throw std::invalid_argument("an event before trade_from_ after history ended: feed history first");
1441 }
1442 return true;
1443 }
1444
1445 // Refuses a bar a strategy declaring `on_bars` cannot be shown consistently: one for a period already
1446 // delivered (it would start a second slice for that period, and could meet an order decided on the
1447 // first), one earlier than the pending period, or a second bar of one instrument and interval in a
1448 // period. Throws before anything changes.
1449 void check_slice_order(const strategy::BarEvent& event, InstrumentSlot& slot) {
1450 if (delivered_through_ && !(*delivered_through_ < event.period_end_)) {
1451 throw std::invalid_argument(
1452 "a bar for a period already delivered to on_bars: feed every bar of a period before anything "
1453 "later (a bar of the next period, a quote at or after it, or finish)"
1454 );
1455 }
1456 if (pending_.empty()) {
1457 return;
1458 }
1459 if (event.period_end_ < pending_.period_end()) {
1460 throw std::invalid_argument(
1461 "a bar earlier than bars already fed: with on_bars, feed bars in period-end order across "
1462 "instruments"
1463 );
1464 }
1465 if (event.period_end_ == pending_.period_end() && slot.interval(event.interval_).pending_ == event.period_end_) {
1466 throw std::invalid_argument(
1467 "a second bar of one instrument and interval for the same period end: on_bars receives one bar "
1468 "per instrument"
1469 );
1470 }
1471 }
1472
1473 // Delivers the pending period to `on_bars`, one slice per interval in the order each was first fed.
1474 //
1475 // Each slice is decided at the period end, exact if any of its bars states its end and nominal only
1476 // if all of them derive it (see `period_end_is_exact`): a nominal bar fed last must not weaken an
1477 // exact one. The portfolio is installed before each slice, because an `on_order_update` published
1478 // after the last bar, or an earlier slice, may have changed the queue.
1479 void deliver_pending() {
1480 const auto end = pending_.period_end();
1481 auto slices = pending_.take();
1482 delivered_through_ = end;
1483 const bool history = config_.trade_from_ && end < *config_.trade_from_;
1484 for (const auto& slice : slices) {
1485 if (result_.halted_) {
1486 return;
1487 }
1488 if (history) {
1489 install_portfolio();
1490 runner_.feed_warmup(slice);
1491 continue;
1492 }
1493 bool exact = false;
1494 for (const auto& bar : slice.bars_) {
1495 exact = exact || period_end_is_exact(bar);
1496 }
1497 runner_.executor().deciding_at(end, exact);
1498 install_portfolio();
1499 drain_reports(runner_.feed(slice));
1500 publish_order_updates();
1501 }
1502 }
1503
1504 // Clears every order still queued after a halt, counting them.
1505 //
1506 // They are withdrawn rather than left outstanding so that nothing downstream reads a terminal
1507 // replay as one with live working orders, and counted in `aborted_` rather than `unfilled_`
1508 // because "the data ran out with this resting" and "the replay stopped while this was resting"
1509 // are different facts about a run.
1510 void abort_queue() {
1511 // A period still being collected is never delivered after a halt.
1512 pending_.clear();
1513 std::vector<OrderRef<Tag>> remaining;
1514 remaining.reserve(runner_.executor().queued().size());
1515 for (const auto& entry : runner_.executor().queued()) {
1516 remaining.push_back(entry.ref_);
1517 }
1518 for (const auto& ref : remaining) {
1519 runner_.executor().withdraw(ref);
1520 }
1521 result_.aborted_ = remaining.size();
1522 }
1523
1524 // Returns whether `event`'s period end is enforced as the decision instant (`true`), or treated as a
1525 // nominal upper bound whose fills are allowed and counted as unchecked (`false`).
1526 //
1527 // A close-stamped bar carries its period end as its timestamp, so the broker stated it. An
1528 // open-stamped bar's end is derived by adding the interval's nominal length, which is right for an
1529 // intraday interval save a session's last bar when the session is not a whole number of them: KRX's
1530 // 15:00 hourly bar is given 16:00 for its 15:30 close. That end is late, not exact, and it is still
1531 // enforced strictly, because a late bound only defers a fill (to the next session's bars) and never
1532 // credits a price from before the decision; treating it as nominal would let such fills through
1533 // unchecked. For every calendar interval the end is an approximation -- 24 hours is not a trading day, 31 days
1534 // is not a month, and 366 is not a year. The approximation always runs **long**, which is what
1535 // makes it usable: an upper bound on the decision instant still proves causality whenever a bar's
1536 // start is at or after it.
1537 static bool period_end_is_exact(const strategy::BarEvent& event) noexcept {
1538 return event.stamp_ == BarStamp::CLOSE || bar_interval_length(event.interval_).has_value();
1539 }
1540
1541 // Returns when `event`'s period began, where that is answerable **from the event itself**.
1542 //
1543 // Three cases, in the order they are decided; the order matters:
1544 //
1545 // 1. **An open-stamped bar states it.** `BarStamp::OPEN` means `bar_.timestamp_` *is* the first
1546 // instant of the period, for every interval. Nothing has to be derived.
1547 // 2. **An intraday interval has a fixed length**, so a close-stamped one began that long before it
1548 // ended. A session's last bar cut short by the close began later than that (KRX's hourly bar ending
1549 // 15:30 began at 15:00, not 14:30): the derived start is early, which refuses fills the check could
1550 // have allowed and never allows one it should refuse.
1551 // 3. **A close-stamped daily bar** began at the session open on its own local date, which is the
1552 // date its period end falls on and where its open price comes from. **That assumes the stamp
1553 // falls on the session's own date**, which is true of a bar stamped at the close and false of
1554 // one stamped at the following local midnight; such a series gets a start a day late.
1555 //
1556 // **Everything else is unanswerable and says so.** A close-stamped weekly bar ends on Friday and
1557 // began on Monday; taking the session open on the *period end's* date would have called Friday
1558 // 09:00 its start, which is four days too late -- so a Tuesday quote would have passed the check
1559 // and filled at Monday's open, a price from two days before the decision. An earlier version of
1560 // this function did exactly that and called it conservative; it was the opposite. The same was
1561 // true of an open-stamped daily bar, whose period end is 24 hours after its start.
1562 //
1563 // What an empty answer means to the caller is in `may_fill`: not "no constraint", and not a bound
1564 // to be inferred from somewhere else either, but "this check cannot run -- allow the fill and
1565 // record that it was not checked".
1566 std::optional<std::chrono::system_clock::time_point> period_start_of(const strategy::BarEvent& event) const {
1567 return strategy::bar_period_start(event, clock_.session());
1568 }
1569
1570 // Calls `on_start` once, before the replay's first event, with the opening portfolio installed, and
1571 // publishes what it placed. What it sees: no last price, the context's clock not yet set, phase
1572 // `UNKNOWN` (so the default risk limits refuse an order that opens exposure).
1573 void start_strategy() {
1574 if (runner_.started()) {
1575 return;
1576 }
1577 install_portfolio();
1578 drain_reports(runner_.start());
1579 publish_order_updates();
1580 }
1581
1582 // Returns whether `entry` may fill against `event`, and records where the question *could this be
1583 // credited a price from before it was decided* could not be answered at all.
1584 //
1585 // Three answers:
1586 //
1587 // 1. **An undated order is eligible.** That is an order `on_start` placed before a replay's first
1588 // bar (decided before anything was seen, so no bar's open can be from after the decision), and
1589 // every order placed by a caller driving `QueueingExecutor` directly. This rule exists to defer
1590 // fills rather than to invent them. Every other dispatch that can place is dated first.
1591 // 2. **Where `period_start_of` answers, the comparison is made**: the bar's period must have begun
1592 // **at or after** the decision. A period that began before it contains the decision, and its
1593 // open price -- which is what `NextBarFillModel` credits a market order with -- is from before
1594 // the strategy decided anything. This is every bar shape this library produces: intraday,
1595 // open-stamped, and close-stamped daily. A derived start can be early (a close-stamped intraday
1596 // bar cut short by the close), which defers a fill and never credits an earlier price.
1597 // 3. **Where either side of that comparison is a calendar boundary this engine cannot establish,
1598 // it makes no inference at all.** Two ways in, and the second was found last: the bar's start is
1599 // underivable (a close-stamped weekly, monthly or yearly bar), or the decision instant is only
1600 // an upper bound (an open-stamped bar of any calendar interval, which is what every shipped
1601 // adapter produces) and the bar's start falls before it. Either way the fill is allowed, on the
1602 // bar-counter rule that governed every fill before this check existed, and **counted** in
1603 // `ReplayResult::unchecked_fill_causality_` so the report can say the check did not happen.
1604 //
1605 // **Three successive versions of this function tried to infer that period instead, and all three
1606 // were wrong.** The previous bar of the instrument: wrong, because two intervals of one
1607 // instrument overlap. The previous bar of the same instrument *and* interval: wrong, because
1608 // nothing in `feed`'s contract requires one stamp convention or anchor for a series, so two
1609 // same-interval weekly bars can overlap too. Each inference rested on an invariant that is usually
1610 // true and is not guaranteed -- and the repository's own rule covers exactly this: *a conservative
1611 // refusal beats a narrow test you cannot justify.* There is no refusal available here either,
1612 // because deferring an unprovable fill would stop a close-stamped weekly replay filling **anything**
1613 // -- every order in one is decided at a boundary this engine equally cannot place. That is a
1614 // statement about the shape rather than about every interval in it: a sound lower bound of *period
1615 // end minus seven days* does exist for a week and would let a full-week series fill on time, but it
1616 // defers a week after every holiday-shortened one, and the 31-day and 366-day bounds defer nearly
1617 // every monthly and yearly order. So the honest third answer is to check nothing, claim nothing,
1618 // and report the gap.
1619 bool may_fill(const QueuedOrder<Tag>& entry, const strategy::BarEvent& event) {
1620 if (!entry.decided_at_) {
1621 return true;
1622 }
1623 if (const auto start = period_start_of(event)) {
1624 if (!(*start < *entry.decided_at_)) {
1625 // Proven: the period began at or after the decision. A *nominal* decision instant is an
1626 // upper bound on the true one, so this proves it for those too.
1627 return true;
1628 }
1629 if (entry.decision_is_exact_) {
1630 return false;
1631 }
1632 // The start is known and the decision is only bounded, so this is the unprovable case again
1633 // from the other side: the order may have been decided before this period after all. Allowed
1634 // and counted, on the same terms as an underivable start.
1635 ++result_.unchecked_fill_causality_;
1636 return true;
1637 }
1638 ++result_.unchecked_fill_causality_;
1639 return true;
1640 }
1641
1642 // Fills orders resting from an earlier bar against `event`, and tells a strategy that declares `on_fill`.
1643 //
1644 // **Walked by reference rather than by iterator or index.** Applying a fill calls `on_fill` when the
1645 // strategy declares it, which may place or withdraw orders, so any position into the queue is invalid the moment the strategy
1646 // is told anything. The eligible references are collected first and each is looked up again when
1647 // its turn comes; one the callback withdrew is simply no longer there.
1648 //
1649 // The queue is never emptied, so an order this loop has not reached yet is outstanding, visible in
1650 // every portfolio installed along the way, and addressable by a cancellation from any callback.
1651 void settle_queued_against(const strategy::BarEvent& event, InstrumentSlot& slot) {
1652 // With nothing queued nothing can expire, fill or be assigned a session; only the publication at the end
1653 // has work left (it releases deferred targets).
1654 if (runner_.executor().queued().empty()) {
1655 publish_order_updates();
1656 return;
1657 }
1658 const auto bar_date = clock_.session().local_date(event.bar_.timestamp_);
1659 // A session the replay had no closing bar for -- a missing last minute -- still ended: an order
1660 // of an earlier date is withdrawn before this bar can fill it.
1661 expire_day_orders(event, bar_date, false);
1662 std::vector<OrderRef<Tag>> eligible;
1663 std::vector<OrderRef<Tag>> first_session;
1664 // Only this instrument's orders, oldest first: a different instrument's order waits for that
1665 // instrument's next bar, which is what makes an interleaved multi-instrument replay behave. An order
1666 // accepted during this bar waits for the next one, which is the no-lookahead rule.
1667 runner_.executor().for_each_queued_in(event.instrument_, [&](const QueuedOrder<Tag>& entry) {
1668 if (entry.accepted_on_ >= runner_.executor().bar()) {
1669 return;
1670 }
1671 // **And, where the event says enough to check it, it cannot fill against a bar whose period
1672 // had already begun when it was decided.** The counter above is enough while only bars place
1673 // orders and no two periods overlap; a quote arrives inside a period without opening one, so
1674 // without this an order decided at 10:30 fills at that day's 09:00 open -- a price from before
1675 // the decision. Where the event does *not* say enough, `may_fill` allows the fill and records
1676 // that nothing was checked. See it for all three answers.
1677 if (!may_fill(entry, event)) {
1678 return;
1679 }
1680 eligible.push_back(entry.ref_);
1681 // **Which session a DAY order lives in**, fixed at the first bar it is eligible against: that
1682 // bar's session is the one the order trades in. A decision the bar cannot fill without looking
1683 // ahead -- a quote at 10:00 against the day's bar, or the day's close -- trades in the next
1684 // session, as a market order decided there fills at the next open: one session, shifted, never
1685 // the several a resting order had before. Recorded here, beside the one `may_fill` call, so
1686 // `unchecked_fill_causality_` still counts each order once per bar.
1687 if (!entry.session_ && time_in_force_expires_at_close(entry.order_.time_in_force_)) {
1688 first_session.push_back(entry.ref_);
1689 }
1690 });
1691 for (const auto& ref : first_session) {
1692 runner_.executor().assign_session(ref, bar_date);
1693 }
1694
1695 for (const auto& ref : eligible) {
1696 const auto* entry = runner_.executor().find(ref);
1697 if (entry == nullptr) {
1698 // Withdrawn by a callback earlier in this loop. Nothing to fill.
1699 continue;
1700 }
1701 const auto order = entry->order_;
1702 const auto& rule = rule_for(order.instrument_);
1703 // An `OPEN`-stamped bar states its start, so a fill at its open has a known day; the period
1704 // end's day is nominal there -- a day late for a daily bar, days into the next month for a
1705 // monthly one. See `NextBarFillModel::decide`'s `open_date`.
1706 const auto open_date = event.stamp_ == BarStamp::OPEN ?
1707 std::optional<Date>(clock_.session().local_date(event.bar_.timestamp_)) :
1708 std::nullopt;
1709 auto decision = fills_.decide(
1710 order, event, rule, clock_.session().local_date(event.period_end_), open_date, entry->released_,
1711 entry->decision_price_, entry->decision_price_at_, entry->decided_at_
1712 );
1713 if (decision.released_) {
1714 // Recorded before anything below can withdraw the order, and whether or not it filled: a stop
1715 // that released and still rests is a limit from the next bar on.
1716 runner_.executor().release(ref);
1717 ++result_.stop_releases_;
1718 }
1719 if (decision.costing_error_) {
1720 // **Checked before the generic no-execution branch**, because that branch would leave a
1721 // resting day limit queued to be retried on the next bar, and a refusal is not a bar that
1722 // failed to reach a price. The order goes whatever its type, exactly once.
1723 runner_.executor().withdraw(ref);
1724 result_.halted_ = std::move(*decision.costing_error_);
1725 // **The halt governs the engine, not just this order.** Returning here stops the other
1726 // orders eligible on this same bar from filling behind a cost the model could not compute,
1727 // and `feed` stops consuming bars from its next call onward.
1728 abort_queue();
1729 return;
1730 }
1731 if (!decision.execution_) {
1732 if (!decision.still_working_) {
1733 // A market order the bar could not price, or a limit whose arithmetic did not fit. It does
1734 // not rest and it did not trade, so it stops being outstanding.
1735 runner_.executor().withdraw(ref);
1736 }
1737 continue;
1738 }
1739 // Removed before the ledger moves and before anything is shown a portfolio, so no view ever
1740 // carries a filled order as still working.
1741 runner_.executor().withdraw(ref);
1742 // Stamped from the same reference data the ledger is given, so the two can never disagree
1743 // about what currency one fill was in.
1744 decision.execution_->currency_ = currency_for(order.instrument_);
1745 // From the loop's own reference, not `entry`: the withdrawal above can move another order into its slot.
1746 decision.execution_->fill_.order_id_ = ref.primary_;
1747 if (!ledger_.apply(*decision.execution_, currency_for(order.instrument_))) {
1748 // **A modelled fill the ledger cannot record halts the replay**, for the same reason a cost
1749 // it cannot compute does. `apply` is atomic, so nothing is half-written -- but the fill
1750 // happened in the model and did not happen in the books, and continuing would carry on from
1751 // a portfolio missing a trade the strategy was never told about. This used to `continue`,
1752 // which recreated at the ledger boundary exactly the silently-missing-trade path the
1753 // costing refusal above exists to remove.
1754 BrokerError error;
1755 error.category_ = ErrorCategory::INVALID_ARGUMENT;
1756 error.reached_broker_ = false;
1757 error.broker_code_ = "execution_not_representable";
1758 error.message_ =
1759 "an execution's cash arithmetic does not fit an exact decimal, so the "
1760 "ledger could not record a fill the model produced";
1761 result_.halted_ = std::move(error);
1762 abort_queue();
1763 return;
1764 }
1765 // **Where the lot is, learnt as soon as it exists.** A fill can only open a lot in this bar's own
1766 // instrument, and it is recorded here, before anything below (recording, `on_fill`) can throw, so a
1767 // handler's exception caught by the caller cannot leave a held lot that is never marked again.
1768 if (!slot.lot_) {
1769 slot.lot_ = ledger_.lot_of(order.instrument_);
1770 }
1771 note_overdraft(*decision.execution_);
1772 if (decision.intrabar_release_fill_) {
1773 ++result_.stop_fills_intrabar_;
1774 }
1775 if (decision.bounded_) {
1776 ++result_.limit_fills_bounded_;
1777 }
1778 if (decision.priced_by_rule_) {
1779 ++result_.market_fills_by_rule_;
1780 }
1781 // Moved, not copied: the result is the only record of a replay's executions. Nothing below adds to
1782 // `result_.executions_` before `on_fill` returns, so the reference stays valid.
1783 result_.executions_.push_back(std::move(*decision.execution_));
1784 // **A budgeted run books what the replay filled**, at the replay's own costs, before `on_fill` can place
1785 // against it; one it cannot book halts the replay, as a fill the ledger cannot record does.
1786 if (runner::runner_detail::ReplayAccess::has_run(runner_) && !book_run(result_.executions_.back())) {
1787 BrokerError error;
1788 error.category_ = ErrorCategory::INVALID_ARGUMENT;
1789 error.reached_broker_ = false;
1790 error.broker_code_ = "execution_not_representable";
1791 error.message_ = "the run budget's ledger could not book an execution the model produced";
1792 result_.halted_ = std::move(error);
1793 abort_queue();
1794 return;
1795 }
1796 if constexpr (strategy::strategy_detail::declares_on_fill<Strategy>) {
1797 const auto& recorded = result_.executions_.back();
1798 // **No handler, nothing to show.** For a strategy without `on_fill` the install would be overwritten
1799 // unread (every later dispatch, and `settle_deferred`, installs first) and the pass would settle an
1800 // empty instruction list. Skipped at compile time: per fill, the install alone costs a row per queued
1801 // order and a copy of every position.
1802 install_portfolio();
1803 drain_reports(runner_.feed(recorded.fill_));
1804 }
1805 }
1806 expire_day_orders(event, bar_date, true);
1807 // Closes the settlement batch: every withdrawal this bar made is now done, and so is anything
1808 // an `on_fill` handler placed or cancelled in response to one.
1809 publish_order_updates();
1810 }
1811
1812 // Books an execution in the runner's run: its amount, and its commission, institution fee and tax as fee.
1813 bool book_run(const Execution& execution) {
1814 const auto& fill = execution.fill_;
1815 const auto amount = decimal_multiply(fill.quantity_, fill.price_);
1816 auto fee = decimal_add(execution.commission_, execution.tax_);
1817 if (fee && execution.institution_fee_) {
1818 fee = decimal_add(*fee, *execution.institution_fee_);
1819 }
1820 if (!amount || !fee) {
1821 return false;
1822 }
1823 return runner::runner_detail::ReplayAccess::book(
1824 runner_, fill.instrument_, fill.side_, fill.quantity_, Money{*amount, execution.currency_}, *fee
1825 );
1826 }
1827
1828 // Keeps the lowest cash an execution left in the replay's currency, when it is below zero.
1829 void note_overdraft(const Execution& execution) {
1830 if (!(execution.currency_ == result_.currency_)) {
1831 return;
1832 }
1833 const auto cash = ledger_.cash_in(execution.currency_);
1834 if (!cash || !decimal_less(*cash, Decimal64::parse("0"))) {
1835 return;
1836 }
1837 if (!result_.lowest_cash_ || decimal_less(*cash, result_.lowest_cash_->amount_)) {
1838 result_.lowest_cash_ = Money{*cash, execution.currency_};
1839 result_.lowest_cash_at_ = execution.fill_.at_;
1840 }
1841 }
1842
1843 // Withdraws every DAY order of `event`'s instrument whose session has ended: before the bar's
1844 // fills (`after_fills` false), those of an earlier date; after them, also those of the bar's own
1845 // date when the bar ends the session.
1846 //
1847 // A KRX DAY order expires at the close. Kept queued, a replay's DAY limit or stop was
1848 // good-till-cancelled on daily bars -- a limit below the market waited for weeks, and a stop placed
1849 // at an entry still rested months later -- where live it was gone that evening. A bar ends a
1850 // session when its interval is a day or longer, or when it is an intraday bar ending at or after the
1851 // session's close; a bar of a later date ends it in any case. Withdrawn inside the settlement batch,
1852 // before order updates are published and before the strategy is shown the bar, so nothing reads an
1853 // expired order as working. Counted in `ReplayResult::expired_day_orders_`.
1854 void expire_day_orders(const strategy::BarEvent& event, const Date& bar_date, bool after_fills) {
1855 // No fixed duration is what a day or longer has (`interval_duration`); an intraday interval has one.
1856 const bool daily_or_longer = !interval_duration(event.interval_);
1857 const auto closes =
1858 clock_.session().opens_at(event.bar_.timestamp_) - clock_.session().open_ + clock_.session().close_;
1859 const bool ends_session = after_fills && (daily_or_longer || !(event.period_end_ < closes));
1860 std::vector<OrderRef<Tag>> expired;
1861 runner_.executor().for_each_queued_in(event.instrument_, [&](const QueuedOrder<Tag>& entry) {
1862 if (!entry.session_ || !time_in_force_expires_at_close(entry.order_.time_in_force_)) {
1863 return;
1864 }
1865 if (*entry.session_ < bar_date || (*entry.session_ == bar_date && ends_session)) {
1866 expired.push_back(entry.ref_);
1867 }
1868 });
1869 for (const auto& ref : expired) {
1870 runner_.executor().withdraw(ref);
1871 ++result_.expired_day_orders_;
1872 }
1873 }
1874
1875 // Counts this bar's overdrawn and unvalued state, and records its point or keeps its period's for later.
1876 void count_bar(const strategy::BarEvent& event) {
1877 if (const auto cash = ledger_.cash_in(config_.currency_); cash && cash->coefficient() < 0) {
1878 ++result_.overdrawn_bars_;
1879 if (!result_.first_overdrawn_) {
1880 result_.first_overdrawn_ = event.period_end_;
1881 }
1882 }
1883 const auto equity = ledger_.equity();
1884#if defined(ATL_REPLAY_CHECK_EQUITY)
1885 ATL_REPLAY_CHECK_EQUITY(equity, ledger_.equity_in(config_.currency_));
1886#endif
1887 if (!equity) {
1888 // Every lot was marked, and the total of cash and lots still does not fit an exact decimal.
1889 // No point is recorded -- a point at an approximate total would be a figure nobody computed
1890 // -- and the omission is counted, because a gap in the curve has other causes too.
1891 ++result_.unvalued_bars_;
1892 if (!result_.first_unvalued_) {
1893 result_.first_unvalued_ = event.period_end_;
1894 }
1895 equity_gap_ = true;
1896 }
1897 switch (config_.equity_curve_) {
1898 case EquityCurve::PER_BAR:
1899 if (equity) {
1900 record_point(event.period_end_, *equity);
1901 }
1902 break;
1903 case EquityCurve::PER_PERIOD:
1904 period_point_ = event.period_end_;
1905 break;
1906 case EquityCurve::NONE:
1907 break;
1908 }
1909 }
1910
1911 // Records the point of the period ending `at`, at the equity now: the period's last bar is the last one marked.
1912 void record_point(std::chrono::system_clock::time_point at) {
1913 period_point_.reset();
1914 if (const auto equity = ledger_.equity()) {
1915 record_point(at, *equity);
1916 } else {
1917 equity_gap_ = true;
1918 }
1919 }
1920
1921 // Records a point, and the return since the previous point.
1922 void record_point(std::chrono::system_clock::time_point at, const Decimal64& equity) {
1923 EquityPoint point;
1924 point.at_ = at;
1925 point.equity_ = equity;
1926 point.period_return_ = math::missing();
1927 // **No return across an omitted point.** The one below would measure two or more periods and be
1928 // handed to the Sharpe ratio and the annualization as one period's return, so the first point
1929 // after a gap carries none -- as the first point of the run does.
1930 const bool after_gap = equity_gap_;
1931 equity_gap_ = false;
1932 if (!result_.equity_.empty() && !after_gap) {
1933 const auto& previous = result_.equity_.back().equity_;
1934 // Only from positive equity. From a negative total the ratio's sign is reversed: a further loss
1935 // reads as a gain, and a run that lost more than its capital reported a positive Sharpe ratio.
1936 if (previous.coefficient() > 0) {
1937 const auto moved = decimal_subtract(equity, previous);
1938 if (moved) {
1939 const auto ratio = decimal_divide(*moved, previous, 8);
1940 if (ratio) {
1941 point.period_return_ = analytics_to_scalar(*ratio);
1942 }
1943 }
1944 }
1945 }
1946 result_.equity_.push_back(point);
1947 }
1948
1949 // Converts an exact ratio to the scalar the metrics compute in.
1950 //
1951 // The one crossing of the decimal boundary in this engine, and it goes outward: a return is an input
1952 // to `sharpe` and the rest, which are defined on `Scalar`. Nothing converts back, because no figure
1953 // a report produces is ever sent to a broker. The same conversion as `analytics::to_scalar` (one
1954 // division by an exact power of ten, so the nearest double within its bounds), written out because
1955 // this header does not include the analytics layer; keep the two alike.
1956 static math::Scalar analytics_to_scalar(const Decimal64& value) {
1957 math::Scalar divisor{1};
1958 for (std::uint8_t at = 0; at < value.scale(); ++at) {
1959 divisor *= math::Scalar{10};
1960 }
1961 return static_cast<math::Scalar>(value.coefficient()) / divisor;
1962 }
1963
1964 // Returns the grid for `instrument`, unknown when no reference data was supplied.
1965 // Returns the currency `instrument` trades in, from the reference data the replay was given.
1966 //
1967 // **Every fill used to be booked in `config_.currency_`**, which is documented as the currency the
1968 // *starting cash* is in. A replay of a dollar-quoted instrument therefore banked dollars as won at
1969 // a rate of one -- an implicit currency conversion, which this library never makes silently.
1970 //
1971 // The fallback is defensive rather than a policy: `reconcile` refuses an instrument with no
1972 // reference data before a `PlannedOrder` exists (`strategy/reconcile.hpp`), so nothing can reach
1973 // the fill model unregistered. It is written the conservative way round anyway -- an unregistered
1974 // instrument books in the currency the ledger was opened in, which is the behaviour every existing
1975 // replay already had.
1976 // Installs the portfolio a strategy and its guards decide on.
1977 //
1978 // The single place the replay answers "what does this account look like", so that every callback
1979 // boundary is answered the same way.
1980 //
1981 // **It has to be a complete answer, because it overwrites one.**
1982 // `Runner::persist_reservation` writes an accepted order into the context portfolio and relies on
1983 // a wholesale replacement carrying what the reservation was standing in for
1984 // (`Runner::persist_reservation`'s comment). Live that replacement is a broker's listing. Here it is this
1985 // function, and a partial answer is therefore not a smaller improvement -- it is a *loss*, because
1986 // the reservation it erased was carrying the part it left out.
1987 //
1988 // The reservation carried two things, so this carries both: the outstanding orders themselves,
1989 // and the money an outstanding buy has committed.
1990 // Reports every queued order whose state has changed since the last observation.
1991 //
1992 // ## Where this is called from, and why not simply beside `install_portfolio`
1993 //
1994 // At the three points where a *batch* of changes to the queue has finished: the end of
1995 // settlement, the end of `feed`, and the end of `finish`. The queue changes in exactly three
1996 // ways -- `place` and `cancel` from a strategy dispatch, and `withdraw` from settlement -- and
1997 // each of those three boundaries closes one batch of them.
1998 //
1999 // The obvious alternative, publishing from `install_portfolio`, is wrong and quietly so: the
2000 // last install of a bar runs *before* `feed(BarEvent)` dispatches `on_bar`, so an order placed
2001 // there enters the queue after it, and the next bar's settlement withdraws the order before that
2002 // bar's first install. An order placed on one bar and filled on the next -- which is every market
2003 // order -- would be present at no install at all and would be reported nowhere.
2004 //
2005 // ## The portfolio is installed before each dispatch, not once for the batch
2006 //
2007 // A handler told about an order has to be able to find it. With every optional limit disabled
2008 // `Runner::persist_reservation` writes no working row, so nothing else would put the order in
2009 // the view, and a strategy would be told about an order it could neither see nor withdraw.
2010 // Installing once for the batch is not enough either, because a handler answering the first
2011 // update may place or cancel, which invalidates the picture the second one reads.
2012 //
2013 // ## What a handler's own order does
2014 //
2015 // It enters the queue behind this observation and is reported at the *next* boundary, never
2016 // within this one, so a strategy cannot drive itself round a loop here. An order placed by
2017 // `on_order_update` during `finish` has no later boundary and is not reported at all.
2018 void publish_order_updates() {
2019 if (result_.halted_) {
2020 // Nothing runs after a refusal, for the reason `feed` documents: a handler called here would
2021 // decide on a replay that has stopped being able to cost what it asks for.
2022 return;
2023 }
2024 if constexpr (!strategy::strategy_detail::declares_on_order_update<Strategy>) {
2025 // **No handler, no updates.** An update would reach no code: dispatching it is a no-op and the
2026 // settlement after it has no instruction to settle. The rows, the comparison and the installs
2027 // around it are skipped; the release of deferred targets is not, because it answers the passes
2028 // before this point, not the updates.
2029 settle_deferred();
2030 return;
2031 } else {
2032 publish_to_handler();
2033 }
2034 }
2035
2036 // The part of `publish_order_updates` a strategy declaring `on_order_update` needs.
2037 void publish_to_handler() {
2038 // Nothing queued and nothing tracked: no order can have changed.
2039 if (runner_.executor().queued().empty() && updates_.tracked_orders() == 0) {
2040 settle_deferred();
2041 return;
2042 }
2043 std::vector<WorkingOrder<Tag>> rows;
2044 rows.reserve(runner_.executor().queued().size());
2045 for (const auto& entry : runner_.executor().queued()) {
2046 rows.push_back(working_row(entry));
2047 }
2048 for (const auto& update : updates_.changed(rows)) {
2049 // **Re-checked against the queue immediately before it is dispatched, not only when the batch
2050 // was observed.** A handler answering the first update of a batch can cancel a *different*
2051 // order in the same batch, and the event captured for that order is then a statement about an
2052 // order that no longer exists -- the portfolio installed below would correctly omit it while
2053 // the event announced it, which is exactly the contradiction the install exists to prevent.
2054 //
2055 // Checked on the state as well as the reference, because a handler can also replace an order
2056 // with another carrying the same one.
2057 const auto* still_queued = find_queued(update);
2058 if (still_queued == nullptr) {
2059 continue;
2060 }
2061 install_portfolio();
2062 drain_reports(runner_.feed(update));
2063 if (result_.halted_) {
2064 return;
2065 }
2066 }
2067 // **Once, after the whole batch.** Every pass that can withdraw a stop -- the bar's, the phase's,
2068 // the fills' and these updates' -- ends here, so the strategy has answered every update before a
2069 // fallback is released; releasing after each pass let a later update's instruction arrive after
2070 // the fallback had already been queued. The live path waits for a whole listing the same way.
2071 settle_deferred();
2072 }
2073
2074 // Returns the queued order `update` describes, if it is still outstanding in that same state.
2075 //
2076 // Matched on the reference and then on the observable state, so an order withdrawn or amended
2077 // since the batch was observed is not announced as it stood.
2078 const QueuedOrder<Tag>* find_queued(const OrderSnapshot& update) const {
2079 for (const auto& entry : runner_.executor().queued()) {
2080 if (entry.ref_.primary_ != update.order_id_) {
2081 continue;
2082 }
2083 const auto row = working_row(entry);
2084 if (runner::order_update_detail::same_observable_state(row.order_, update)) {
2085 return &entry;
2086 }
2087 }
2088 return nullptr;
2089 }
2090
2091 // Drops every slot's pointers into the context if it was replaced since they were taken. Called right before
2092 // they are used, since any handler (`on_bars`, `on_phase`, `on_fill`, ...) can move another context into it.
2093 void forget_pointers_if_replaced() noexcept {
2094 const auto revision = runner::context_detail::PortfolioAccess::replacements(runner_.context());
2095 if (revision == slots_context_) {
2096 return;
2097 }
2098 for (auto& entry : slots_) {
2099 entry.second.price_ = nullptr;
2100#if defined(ATL_HAS_EIGEN)
2101 for (auto& by_interval : entry.second.intervals_) {
2102 by_interval.series_ = nullptr;
2103 by_interval.bar_time_ = nullptr;
2104 }
2105#endif
2106 }
2107 slots_context_ = revision;
2108 }
2109
2110 InstrumentSlot& slot_for(const InstrumentId& instrument) {
2111 auto found = slots_.find(instrument);
2112 if (found == slots_.end()) {
2113 found = slots_.emplace(instrument, InstrumentSlot{}).first;
2114 }
2115 return found->second;
2116 }
2117
2118 // Sets the bar's close as its instrument's last price, through the slot once the context's entry is known.
2119 void set_price(InstrumentSlot& slot, const strategy::BarEvent& event) {
2120 forget_pointers_if_replaced();
2121 slot.priced_at_ = event.period_end_;
2122 if (slot.price_ != nullptr) {
2123 *slot.price_ = event.bar_.close_;
2124 } else {
2125 slot.price_ =
2126 &runner::context_detail::PortfolioAccess::set_price(runner_.context(), event.instrument_, event.bar_.close_);
2127 }
2128 }
2129
2130 void install_portfolio() {
2131 // The value a weight is sized against: the ledger's equity in the replay's currency at the
2132 // latest marks, which is what the equity curve records. Cleared when that total does not fit,
2133 // so a weight is refused on such a bar rather than sized against the previous one.
2134 if (const auto equity = ledger_.equity()) {
2135 runner_.set_portfolio_value(Money{*equity, config_.currency_});
2136 } else {
2137 runner_.clear_portfolio_value();
2138 }
2139 using Access = runner::context_detail::PortfolioAccess;
2140 auto& context = runner_.context();
2141 const auto& queued = runner_.executor().queued();
2142 // **Built whole once, then kept up to date in place**, so a callback costs what changed rather than a
2143 // copy of every position. Afterwards the portfolio is what a fresh snapshot with a row per queued order
2144 // would be. Built whole on the first install and after anything replaced the portfolio outright
2145 // (`Context::set_portfolio`); otherwise the ledger rewrites the lots it changed and the cash, and the
2146 // working rows are brought up to date when the queue gained or lost an order or a runner edited them in
2147 // place (`Runner::persist_reservation`), and rebuilt when reference data (a row's currency) changed. What was
2148 // seen is acknowledged only once everything is in, so the next install finishes what one that threw left
2149 // undone.
2150 if (!installed_ || Access::replacements(context) != replacements_seen_) {
2151 auto portfolio = ledger_.snapshot<Tag>(clock_.now());
2152 portfolio.working_.reserve(queued.size());
2153 for (const auto& entry : queued) {
2154 portfolio.working_.push_back(working_row(entry));
2155 commit_open_buy(portfolio, entry);
2156 }
2157 context.set_portfolio(std::move(portfolio));
2158 ledger_.clear_changed();
2159 } else {
2160 // A runner's reservation follows an order the queue accepted, so today the queue's count moves with it;
2161 // the runner's own count is checked too, so a reservation written without a new order is not kept.
2162 const bool rows_stale = runner_.executor().changes() != queue_seen_ ||
2163 Access::runner_edits(context) != edits_seen_ || Access::reference_changes(context) != references_seen_;
2164 auto& portfolio = Access::for_replay_sync(context);
2165 ledger_.update(portfolio, clock_.now());
2166 if (rows_stale && Access::reference_changes(context) != references_seen_) {
2167 portfolio.working_.clear();
2168 for (const auto& entry : queued) {
2169 portfolio.working_.push_back(working_row(entry));
2170 }
2171 } else if (rows_stale) {
2172 refresh_rows(portfolio.working_, queued);
2173 }
2174 // `update` set the buying power back to the cash, so every open buy is taken out again; a market
2175 // buy is valued at the last price, which moves.
2176 if (config_.limits_.enforce_buying_power_) {
2177 for (const auto& entry : queued) {
2178 commit_open_buy(portfolio, entry);
2179 }
2180 }
2181 }
2182 installed_ = true;
2183 replacements_seen_ = Access::replacements(context);
2184 edits_seen_ = Access::runner_edits(context);
2185 references_seen_ = Access::reference_changes(context);
2186 queue_seen_ = runner_.executor().changes();
2187#if defined(ATL_REPLAY_CHECK_PORTFOLIO)
2188 // A test build's check (the tests define the macro as their comparison): the portfolio as kept against
2189 // the one the replay used to build from scratch, and the running equity against the full sum.
2190 {
2191 auto fresh = ledger_.snapshot<Tag>(clock_.now());
2192 for (const auto& entry : queued) {
2193 fresh.working_.push_back(working_row(entry));
2194 commit_open_buy(fresh, entry);
2195 }
2196 ATL_REPLAY_CHECK_PORTFOLIO(context.portfolio(), fresh, ledger_.equity(), ledger_.equity_in(config_.currency_));
2197 }
2198#endif
2199 }
2200
2201 // Brings the working rows up to date with the queue, in place, at the cost of what changed.
2202 //
2203 // The queue keeps its order and takes a new order only at its end; the rows this replay built lead the list in
2204 // that order, and a runner's reservations (`reserved_`) follow them. So a row whose order is still queued is
2205 // kept, the others and the reservations are dropped, and rows are built only for the orders queued since. An
2206 // install that threw partway left a prefix of this, which the next one completes the same way.
2207 template <typename Queue>
2208 void refresh_rows(std::vector<WorkingOrder<Tag>>& rows, const Queue& queued) const {
2209 std::size_t built = 0;
2210 while (built < rows.size() && !rows[built].reserved_) {
2211 ++built;
2212 }
2213 std::size_t kept = 0;
2214 std::size_t next = 0;
2215 auto entry = queued.begin();
2216 for (; entry != queued.end(); ++entry) {
2217 while (next < built && !(rows[next].ref_ == entry->ref_)) {
2218 ++next;
2219 }
2220 if (next == built) {
2221 break; // this order has no row, so neither has any later one
2222 }
2223 if (kept != next) {
2224 rows[kept] = std::move(rows[next]);
2225 }
2226 ++kept;
2227 ++next;
2228 }
2229 rows.erase(rows.begin() + static_cast<std::ptrdiff_t>(kept), rows.end());
2230 for (; entry != queued.end(); ++entry) {
2231 rows.push_back(working_row(*entry));
2232 }
2233 }
2234
2235 // Returns the working-order row for an outstanding replay order.
2236 //
2237 // `reserved_` stays false, unlike a runner's own reservation. The flag distinguishes this
2238 // library's arithmetic from what a broker reported, and in a replay the engine *is* the broker:
2239 // this row is the listing. The one consequence worth stating is that
2240 // `strategy::SellableConventionProbe`, which reads unreserved rows as evidence about a broker's
2241 // convention, will read these -- and a replay's sellable figure is a model that never moves, so
2242 // the probe reports what the simulator does rather than what a broker does.
2243 WorkingOrder<Tag> working_row(const QueuedOrder<Tag>& entry) const {
2245 row.ref_ = entry.ref_;
2246 // **The replay is this order's broker, so it is the thing that issued the number.** A row left
2247 // with an empty `order_id_` is an order a reader cannot name, which a live row never is; the
2248 // reference's primary part is the only identifier a replay has, and it is already monotone and
2249 // stable for as long as the order is outstanding. Nothing in the library matched a replay
2250 // working row on this field while it was empty, so filling it changes no existing decision.
2251 row.order_.order_id_ = entry.ref_.primary_;
2252 row.order_.instrument_ = entry.order_.instrument_;
2253 row.order_.side_ = entry.order_.side_;
2254 row.order_.type_ = entry.order_.type_;
2255 row.order_.time_in_force_ = entry.order_.time_in_force_;
2256 row.order_.session_ = entry.order_.session_;
2257 row.order_.venue_ = entry.order_.venue_;
2258 row.order_.price_ = entry.order_.price_;
2259 // A stop's trigger, as a live listing reports it -- released or not, since neither broker's
2260 // listing says which.
2261 row.order_.trigger_price_ = entry.order_.trigger_price_;
2262 row.order_.quantity_ = entry.order_.quantity_;
2263 row.order_.currency_ = currency_for(entry.order_.instrument_);
2264 // Open, and nothing filled: a replay fills an order whole or not at all, so a row that exists
2265 // has traded nothing.
2266 row.order_.status_ = OrderStatus::PENDING;
2267 row.order_.execution_.filled_quantity_ = Decimal64::parse("0");
2268 row.amendable_quantity_ = entry.order_.quantity_;
2269 return row;
2270 }
2271
2272 // Takes what an outstanding buy has committed out of the buying power the replay models.
2273 //
2274 // **Rows alone do not fix `enforce_buying_power_`**, which reads the scalar and not the orders.
2275 // `ReplayLedger::snapshot` builds buying power from ledger cash, and that cash has not paid for
2276 // anything still resting -- so with a hundred of cash, a resting buy costing a hundred, and a
2277 // second buy costing a hundred in another instrument, the second passes and both can still fill.
2278 //
2279 // Valued at the order's own price, else the last close, which is the same estimate the guard
2280 // checked the order against — and it is an **estimate**, not a bound. A limit buy cannot fill
2281 // above its limit, so for those the commitment is at least the eventual spend before costs. A
2282 // market order has no stated price at all: it fills where the next bar opens, and slippage and
2283 // commission are both outside this figure, so the real spend can exceed what was committed. An
2284 // order that can be valued by neither route is left uncommitted rather than guessed at.
2285 //
2286 // **Scoped to the limit, exactly as `Runner::reserve` is.**
2287 // `buying_power_in()` is a public figure a strategy is free to size its next order from, so
2288 // lowering it for a caller who never enabled the check would change how their strategy sizes --
2289 // a behaviour change well past enforcing a ceiling, and the reason the runner passes `spends`
2290 // rather than always debiting. It also keeps `ReportCaveats::buying_power_is_ledger_cash` true
2291 // for every replay that does not ask for the check.
2292 void commit_open_buy(strategy::Portfolio<Tag>& portfolio, const QueuedOrder<Tag>& entry) const {
2293 if (!config_.limits_.enforce_buying_power_ || entry.order_.side_ != OrderSide::BUY) {
2294 return;
2295 }
2296 const auto price =
2297 entry.order_.price_ ? entry.order_.price_ : runner_.context().last_price(entry.order_.instrument_);
2298 if (!price) {
2299 return;
2300 }
2301 const auto spent = decimal_multiply(entry.order_.quantity_, *price);
2302 if (!spent) {
2303 return;
2304 }
2305 const auto currency = currency_for(entry.order_.instrument_);
2306 for (auto& reading : portfolio.buying_power_) {
2307 if (!(reading.cash_.currency_ == currency)) {
2308 continue;
2309 }
2310 if (const auto left = decimal_subtract(reading.cash_.amount_, *spent)) {
2311 reading.cash_.amount_ = *left;
2312 }
2313 return;
2314 }
2315 }
2316
2317 // Both read the reference data in place; use the result at once (`Context::find_instrument`).
2318 const Currency& currency_for(const InstrumentId& instrument) const {
2319 const auto* reference = runner_.context().find_instrument(instrument);
2320 return reference != nullptr ? reference->currency_ : config_.currency_;
2321 }
2322
2323 const PriceRule& rule_for(const InstrumentId& instrument) const {
2324 const auto* reference = runner_.context().find_instrument(instrument);
2325 return reference != nullptr ? reference->price_rule_ : unknown_rule_;
2326 }
2327
2328 // Collects what a runner pass reported, so a replay ends with the whole picture.
2329 template <typename Report>
2330 void drain_reports(const Report& report) {
2331 // Every pass that can place ends here, so each new order is stamped with its instrument's price as it was
2332 // decided; only a market-price rule reads it.
2333 if (fills_.has_market_price_rule()) {
2334 runner_.executor().stamp_decision_prices([this](const InstrumentId& id) {
2335 return std::make_pair(runner_.context().last_price(id), slot_for(id).priced_at_);
2336 });
2337 }
2338 collect(report);
2339 }
2340
2341 // Adds a pass's refusals to the result.
2342 template <typename Report>
2343 void collect(const Report& report) {
2344 for (const auto& rejection : report.rejected_) {
2345 result_.rejected_.push_back(rejection);
2346 }
2347 for (const auto& refusal : report.refused_) {
2348 result_.refused_.push_back(refusal);
2349 }
2350 }
2351
2352 // Settles a target the runner deferred behind a stop, once this replay has withdrawn the stop and
2353 // the strategy has answered every update of the batch. Called only from `publish_order_updates`.
2354 //
2355 // **A replay's withdrawal is synchronous**: `QueueingExecutor::cancel` removes the stop from the
2356 // queue before the pass that asked for it returns. Waiting for the next bar's portfolio to show that
2357 // would place the flatten a bar late and fill it two bars late -- a delay the live path, whose
2358 // cancellation can be confirmed between bars, does not have. So after every pass the replay shows
2359 // the runner its book as it now stands and lets it release from that one snapshot: this ledger is the
2360 // broker, so the stop's absence and the holding after it are known together. See
2361 // `Runner::retry_deferred_on_one_snapshot`. An order placed here waits for the next bar like any
2362 // other, which is the lookahead rule.
2363 void settle_deferred() {
2364 if (runner_.deferred_targets().empty()) {
2365 return;
2366 }
2367 install_portfolio();
2368 collect(runner_.retry_deferred_on_one_snapshot());
2369 }
2370
2371 ReplayConfig config_;
2372 NextBarFillModel fills_;
2373 ReplayLedger ledger_;
2374 ReplayClock clock_;
2375 Runner runner_;
2376 // Turns this replay's own working listing into `on_order_update` events; unused for a strategy without one.
2378 ReplayResult result_;
2379 // Whether a bar since the last equity point went unvalued, so the next point carries no return.
2380 bool equity_gap_{false};
2381 // Each instrument's slot (`InstrumentSlot`), and the context's replacement count its pointers belong to.
2382 std::unordered_map<InstrumentId, InstrumentSlot, id_detail::InstrumentIdHash> slots_;
2383 std::uint64_t slots_context_{0};
2384 // Under `EquityCurve::PER_PERIOD`, the period end of the last bar marked, whose point is recorded when a bar of
2385 // a different period end arrives or the replay finishes.
2386 std::optional<std::chrono::system_clock::time_point> period_point_;
2387 // The rule for an instrument without reference data, kept so `rule_for` can return it by reference.
2388 PriceRule unknown_rule_{PriceRule::unknown("no reference data supplied to the replay")};
2389 // What `install_portfolio` last saw: whether it installed at all, the context's counts of replacements,
2390 // runner edits and reference-data changes, and the queue's count of changes.
2391 bool installed_{false};
2392 std::uint64_t replacements_seen_{0};
2393 std::uint64_t edits_seen_{0};
2394 std::uint64_t references_seen_{0};
2395 std::uint64_t queue_seen_{0};
2396 // The interval and period end of the previous bar, which is all `ReplayClock::contiguous` reads of it.
2397 std::optional<std::pair<BarInterval, std::chrono::system_clock::time_point>> previous_;
2398 // For a strategy declaring `on_bars`: the bars of the period not yet delivered, and the period end of
2399 // the last one delivered. A later bar may not join a delivered period, so nothing is decided twice.
2400 strategy::slice_detail::Bucket pending_;
2401 std::optional<std::chrono::system_clock::time_point> delivered_through_;
2402 // When the last record fed became known; a bar that ended before it is refused.
2403 std::optional<std::chrono::system_clock::time_point> latest_record_at_;
2404 // Whether history ended (`finish_history`, or a traded event), after which an event before `trade_from_` is refused.
2405 bool history_over_{false};
2406};
2407
2408} // namespace backtest
2409} // namespace algotradelib
Bar-interval arithmetic and the replay clock.
A three-letter currency code, such as KRW or USD (ISO 4217 style).
Definition types.hpp:374
An exact signed decimal: an int64 coefficient times 10^-scale.
Definition types.hpp:443
static Decimal64 parse(std::string_view input)
Parses a decimal string exactly (no binary floating point).
Definition types.hpp:468
The most recent observations of a few fields, for a strategy fed one bar at a time.
std::optional< Money > run_cash() const
Returns the run's cash, with RiskLimits::run_budget_ set (runner::Runner::run_cash).
Definition engine.hpp:916
std::optional< Decimal64 > run_holding(const InstrumentId &instrument) const
Returns the run's own shares of an instrument, with RiskLimits::run_budget_ set.
Definition engine.hpp:925
const ReplayLedger & ledger() const noexcept
Returns the ledger: positions, cash and realized profit.
Definition engine.hpp:891
void feed(const strategy::DataEvent< T > &event, std::optional< bool > trading_day=true)
Replays one record: moves the clock to when it became known, re-derives the phase (calling on_phase o...
Definition engine.hpp:1251
Backtester(Strategy strategy={}, ReplayConfig config={}, NextBarFillModel fills=NextBarFillModel{})
Constructs a replay.
Definition engine.hpp:858
const ReplayResult & result() const noexcept
Returns what the replay has produced so far.
Definition engine.hpp:907
void feed(const strategy::QuoteEvent &event, std::optional< bool > trading_day=true)
Replays one quote: moves the price and the clock to it, re-derives the phase (calling on_phase on a c...
Definition engine.hpp:1149
const NextBarFillModel & fills() const noexcept
Returns the fill model, for summarize.
Definition engine.hpp:899
void feed(const strategy::BarEvent &event, std::optional< bool > trading_day=true)
Replays one bar.
Definition engine.hpp:960
QueueingExecutor< Tag > Executor
The executor type.
Definition engine.hpp:848
runner::Runner< Strategy, CapsType, Tag, Executor > Runner
The runner::Runner the replay drives, the same type a live session uses.
Definition engine.hpp:850
void finish()
Ends the replay: calls on_stop (with the current portfolio, including orders from the last bar),...
Definition engine.hpp:1327
void finish_history()
Ends history now (ReplayConfig::trade_from_): delivers a pending history period to on_bars,...
Definition engine.hpp:1116
const Strategy & strategy() const noexcept
Returns the strategy, to read the state it kept.
Definition engine.hpp:880
BacktestTag Tag
The order-reference tag.
Definition engine.hpp:846
The fill model: market orders at the next bar's open, limit orders when the next bar's range reaches ...
Definition fill.hpp:142
const std::string & market_price_rule() const noexcept
Returns the market-price rule's name.
Definition fill.hpp:292
Walks the outstanding orders, oldest first.
Definition engine.hpp:296
const_iterator & operator++() noexcept
Moves to the next outstanding order.
Definition engine.hpp:329
friend bool operator!=(const const_iterator &lhs, const const_iterator &rhs) noexcept
Compares two positions in one queue.
Definition engine.hpp:358
std::ptrdiff_t difference_type
The distance between two positions.
Definition engine.hpp:303
pointer operator->() const noexcept
Points at the order here.
Definition engine.hpp:322
const QueuedOrder< BrokerTag > * pointer
A pointer to an order.
Definition engine.hpp:305
reference operator*() const noexcept
Returns the order here.
Definition engine.hpp:315
std::forward_iterator_tag iterator_category
A forward iterator.
Definition engine.hpp:299
friend bool operator==(const const_iterator &lhs, const const_iterator &rhs) noexcept
Compares two positions in one queue.
Definition engine.hpp:349
const_iterator operator++(int) noexcept
Moves to the next outstanding order.
Definition engine.hpp:338
const_iterator()=default
An iterator past the end of an empty queue.
QueuedOrder< BrokerTag > value_type
An outstanding order.
Definition engine.hpp:301
const QueuedOrder< BrokerTag > & reference
A reference to an order.
Definition engine.hpp:307
Every outstanding order, oldest first: a view over the queue, valid until the queue changes.
Definition engine.hpp:293
bool empty() const noexcept
Returns whether no order is outstanding.
Definition engine.hpp:401
const_iterator begin() const noexcept
Returns the oldest outstanding order's position.
Definition engine.hpp:380
std::size_t size() const noexcept
Returns how many orders are outstanding.
Definition engine.hpp:394
const QueuedOrder< BrokerTag > & front() const noexcept
Returns the oldest outstanding order; the queue must not be empty.
Definition engine.hpp:408
const_iterator end() const noexcept
Returns the position past the newest.
Definition engine.hpp:387
The replay's executor: accepts orders and holds them until they fill or are withdrawn.
Definition engine.hpp:103
void deciding_at(std::chrono::system_clock::time_point at, bool exact=true)
Sets the decision instant stamped on orders accepted from now on.
Definition engine.hpp:554
std::uint64_t changes() const noexcept
Returns how many times the queue gained or lost an order (place, cancel, withdraw).
Definition engine.hpp:530
static constexpr bool models_time_in_force(TimeInForce condition) noexcept
Definition engine.hpp:259
QueueingExecutor(const QueueingExecutor &other)=default
Copies an executor and its queue.
std::optional< OrderRef< BrokerTag > > last_ref() const
Returns the reference issued to the most recently accepted order.
Definition engine.hpp:284
void stamp_decision_prices(PriceOf &&price_of)
Stamps the orders accepted since the last call with their instrument's price now, and when it was obs...
Definition engine.hpp:540
std::uint64_t bar() const noexcept
Returns the bar being replayed.
Definition engine.hpp:519
Queue queued() const noexcept
Returns every outstanding order, oldest first.
Definition engine.hpp:424
runner::SendOutcome cancel(const WorkingOrder< BrokerTag > &working)
Withdraws the order a working row names, matched by reference.
Definition engine.hpp:276
QueueingExecutor & operator=(QueueingExecutor &&other) noexcept
Replaces this executor with a move of another, which is left with nothing queued.
Definition engine.hpp:145
void for_each_queued_in(const InstrumentId &instrument, Each &&each) const
Calls each with every outstanding order in one instrument, oldest first.
Definition engine.hpp:437
bool release(const OrderRef< BrokerTag > &ref)
Marks a queued stop-limit order as released.
Definition engine.hpp:499
void assign_session(const OrderRef< BrokerTag > &ref, Date session)
Records the session date of a queued order; see QueuedOrder::session_.
Definition engine.hpp:462
QueueingExecutor(QueueingExecutor &&other) noexcept(std::is_nothrow_move_constructible< ByInstrument >::value)
Moves an executor; the source is left with nothing queued.
Definition engine.hpp:127
static bool can_model(const strategy::PlannedOrder &order) noexcept
Definition engine.hpp:226
const QueuedOrder< BrokerTag > * find(const OrderRef< BrokerTag > &ref) const
Finds an outstanding order.
Definition engine.hpp:452
runner::SendOutcome place(const strategy::PlannedOrder &order)
Accepts and queues an order, issuing it a reference.
Definition engine.hpp:189
bool withdraw(const OrderRef< Tag > &ref)
Definition engine.hpp:473
void open_bar() noexcept
Starts the next bar; orders accepted from now on cannot fill against it.
Definition engine.hpp:511
QueueingExecutor & operator=(const QueueingExecutor &other)
Replaces this executor with a copy of another, entirely or not at all.
Definition engine.hpp:168
QueueingExecutor()=default
An executor with nothing queued.
static bool contiguous(const strategy::BarEvent &previous, const strategy::BarEvent &event)
Tests whether a bar follows the previous one with no gap.
Definition clock.hpp:148
Positions, cash and realized profit, updated by each execution of a replay.
Definition ledger.hpp:79
void set_session(SessionWindow session)
Sets the session window (for runners).
Definition context.hpp:513
void set_calendar(TradingCalendar calendar)
Replaces the trading calendar (for runners and sources, not strategies).
Definition context.hpp:526
Turns successive working-order listings into order updates: the rows that changed since the previous ...
Runs one strategy: feeds it events, reconciles what it asks for, checks the risk limits,...
Definition runner.hpp:305
const Context & context() const noexcept
Returns the context.
Definition runner.hpp:600
The backtest fill model: whether a queued order trades against the next bar, and at what price and co...
The replay ledger: positions, cash and realized profit a backtest keeps, in exact decimals.
Replays a strategy over stored bars: fill and cost models, the replay ledger, and the report.
Definition bootstrap.hpp:16
EquityCurve
Which points a replay records on its equity curve (ReplayResult::equity_); see ReplayConfig::equity_c...
Definition engine.hpp:637
@ PER_PERIOD
One point per period end, after the last bar of that period: one a day for daily bars,...
Definition engine.hpp:648
@ PER_BAR
One point per bar fed. A replay of many instruments records one per instrument per period,...
Definition engine.hpp:653
@ NONE
No points, for a run that does not read the curve; summarize then reports no ratio.
Definition engine.hpp:655
ExecutionHistory
Whether a ReplayLedger keeps the executions it applies.
Definition ledger.hpp:63
std::optional< std::chrono::seconds > interval_duration(BarInterval interval)
Returns the fixed duration of an interval (bar_interval_length).
Definition clock.hpp:30
double Scalar
The floating-point type the analytics and math layers compute in (double).
Definition scalar.hpp:18
Scalar missing()
Returns the value that stands for "no observation" (a quiet NaN).
Definition scalar.hpp:28
SendOutcome
What became of one instruction (a placement or a cancellation) an executor was asked to send.
Definition execution.hpp:30
@ REJECTED
The broker refused the instruction (for a placement, the order does not exist); nothing needs reconci...
Definition execution.hpp:34
@ ACCEPTED
The broker accepted the instruction (for a placement, the order exists).
Definition execution.hpp:32
@ REFUSED_LOCALLY
The binding refused the instruction before sending it (such as an idempotency key at a broker without...
Definition execution.hpp:63
void fill(S &strategy, Ctx &context, const Fill &event)
Calls strategy.on_fill(context, event) if the strategy declares on_fill; otherwise does nothing.
Definition concept.hpp:352
What a strategy sees and emits: events, intents, the portfolio, reconciliation and risk limits.
Definition concept.hpp:16
std::optional< std::chrono::system_clock::time_point > bar_period_start(const BarEvent &event, const SessionWindow &session)
Returns when a bar's period began, where the bar says so.
Definition event.hpp:401
The library: broker-neutral types (core), and the modules below.
@ CLOSE
The timestamp is the instant the period ended.
@ OPEN
The timestamp is the first instant of the period.
constexpr std::optional< std::chrono::seconds > bar_interval_length(BarInterval interval) noexcept
Returns an interval's fixed length, for an intraday interval.
std::optional< Decimal64 > decimal_add(const Decimal64 &lhs, const Decimal64 &rhs)
Adds two decimals exactly.
Definition types.hpp:760
@ INVALID_ARGUMENT
The request was invalid, refused by the client before sending or by the broker.
Definition types.hpp:974
@ LIMIT
지정가: fills at the stated price or better.
Definition types.hpp:2001
@ BEST_LIMIT
최유리지정가: priced at the best quote on the opposite side.
Definition types.hpp:2007
@ PRIMARY_LIMIT
최우선지정가: priced at the best quote on the order's own side.
Definition types.hpp:2009
@ CONDITIONAL_LIMIT
조건부지정가: a limit that becomes a market order at the close.
Definition types.hpp:2005
@ MID_PRICE
중간가: priced at the midpoint of the spread.
Definition types.hpp:2011
@ STOP_LIMIT
스톱지정가: a limit released when a trigger price is reached.
Definition types.hpp:2013
@ CLOSING_PRICE
시간외종가: priced at a session's closing price.
Definition types.hpp:2015
@ MARKET
시장가: fills at whatever the book offers.
Definition types.hpp:2003
@ REGULAR
The continuous regular session.
Definition types.hpp:2133
std::optional< Decimal64 > decimal_subtract(const Decimal64 &lhs, const Decimal64 &rhs)
Subtracts two decimals exactly.
Definition types.hpp:783
std::optional< Decimal64 > decimal_divide(const Decimal64 &lhs, const Decimal64 &rhs, std::uint8_t scale)
Divides two decimals, truncating toward zero at a given scale.
Definition types.hpp:860
constexpr bool time_in_force_expires_at_close(TimeInForce condition) noexcept
Tests whether an order with this condition expires at the session's close, so its filled quantity is ...
Definition types.hpp:2113
bool decimal_less(const Decimal64 &lhs, const Decimal64 &rhs)
Compares two decimals numerically, whatever their scales.
Definition types.hpp:926
std::optional< Decimal64 > decimal_multiply(const Decimal64 &lhs, const Decimal64 &rhs)
Multiplies two decimals exactly; the scales add.
Definition types.hpp:826
BarInterval
The period one bar covers.
TimeInForce
How long an order stays valid and what happens to an unfilled remainder.
Definition types.hpp:2088
@ FILL_OR_KILL
Fills entirely and immediately, or not at all.
Definition types.hpp:2095
@ DAY
Rests until the session ends; an unfilled remainder is cancelled then.
Definition types.hpp:2091
@ IMMEDIATE_OR_CANCEL
Fills what it can immediately and cancels the remainder.
Definition types.hpp:2093
Decimal64 close_
The last trade price.
std::chrono::system_clock::time_point timestamp_
The instant marking the period; BarSeries::stamp_ says which edge.
The error a broker or transport operation returns.
Definition types.hpp:1003
std::string message_
A human-readable description, for logs; do not parse it.
Definition types.hpp:1033
ErrorCategory category_
The kind of failure; the field to branch on.
Definition types.hpp:1005
std::string broker_code_
The broker's own error code, verbatim (for example KIS's EGW00201).
Definition types.hpp:1022
bool reached_broker_
Whether a request was sent before this error.
Definition types.hpp:1014
A calendar date with no time of day or time zone.
Definition types.hpp:1412
Identifies an instrument: its country, venue and symbol.
Definition types.hpp:85
An exact amount of money in one currency.
Definition types.hpp:1168
A broker's reference to one order, used to amend or cancel it.
Definition types.hpp:2402
The state of one order, as a broker listing reported it.
Definition types.hpp:2299
The price grid (tick sizes) an instrument's order prices must sit on.
static PriceRule unknown(std::string reason)
Returns a rule that knows no grid and refuses to round.
Decimal64 last_price_
The last traded price, as the broker reported it.
Definition types.hpp:1147
std::chrono::system_clock::time_point received_at_
When this process received the quote, on this machine's clock.
Definition types.hpp:1153
InstrumentId instrument_
The instrument.
Definition types.hpp:1145
The trading days a broker reported for one market, ascending by date.
Definition calendar.hpp:72
An order still open to modification or cancellation.
Definition types.hpp:2582
OrderRef< Broker > ref_
The reference to amend or cancel the order with.
Definition types.hpp:2586
The broker tag of a replay's order references (they reach no broker).
Definition ledger.hpp:31
What is kept per interval of the instrument.
Definition engine.hpp:1372
std::optional< std::chrono::system_clock::time_point > pending_
The period end of its bar in the period being collected, if it has one there.
Definition engine.hpp:1376
One point on a replay's equity curve: per period end, or per bar (EquityCurve).
Definition engine.hpp:659
Decimal64 equity_
Cash plus positions marked at the latest closes, in the replay's currency.
Definition engine.hpp:663
math::Scalar period_return_
The return since the previous point; missing() on the first point, after an unvalued bar,...
Definition engine.hpp:672
std::chrono::system_clock::time_point at_
The period end of the bar it was recorded after.
Definition engine.hpp:661
One execution a backtest produced, and what it cost.
Definition ledger.hpp:37
One order a replay accepted and has not yet filled or withdrawn.
Definition engine.hpp:44
std::optional< std::chrono::system_clock::time_point > decided_at_
When the strategy decided the order, if known.
Definition engine.hpp:61
std::optional< Date > session_
The market-local date of the session a DAY order lives in, once known (the date of the first bar it c...
Definition engine.hpp:91
bool released_
Whether a stop-limit order has been released, so it now rests as its limit.
Definition engine.hpp:75
bool decision_is_exact_
Whether decided_at_ is enforced strictly, or only a nominal upper bound (the period end of an open-st...
Definition engine.hpp:69
strategy::PlannedOrder order_
The order as reconciliation planned it.
Definition engine.hpp:46
std::uint64_t accepted_on_
The bar it was accepted during; it cannot fill against that bar.
Definition engine.hpp:50
std::optional< std::chrono::system_clock::time_point > decision_price_at_
When decision_price_ was observed: the period end of the bar, or the time of the quote,...
Definition engine.hpp:86
OrderRef< BrokerTag > ref_
The reference the replay issued for it.
Definition engine.hpp:48
std::optional< Decimal64 > decision_price_
The order's instrument's last price when the strategy decided it, for a market-price rule (NextBarFil...
Definition engine.hpp:81
A replay's settings, besides the strategy and the bars.
Definition engine.hpp:768
EquityCurve equity_curve_
Which points the equity curve records: one per period end (the default), one per bar,...
Definition engine.hpp:795
std::optional< std::chrono::system_clock::time_point > trade_from_
Where trading starts: an event earlier than it is history; empty, none is.
Definition engine.hpp:817
strategy::RiskLimits limits_
The risk limits, applied as they are live.
Definition engine.hpp:776
Decimal64 cash_
The starting cash, in currency_.
Definition engine.hpp:770
TradingCalendar calendar_
The calendar ctx.calendar() returns, for a strategy asking about dates it has no bar for (such as whe...
Definition engine.hpp:803
Currency currency_
The accounting currency; the equity curve is in this currency only.
Definition engine.hpp:772
std::vector< Instrument > instruments_
Reference data for every instrument replayed; orders on an instrument without it are refused.
Definition engine.hpp:774
std::size_t series_capacity_
How many trailing bars the context caches per series, for indicators; must be positive....
Definition engine.hpp:789
strategy::SessionWindow session_
The session window phases are derived from and DAY orders expire at; one for the whole replay.
Definition engine.hpp:784
Everything a replay produced; summarize turns it into a Report.
Definition engine.hpp:676
std::size_t unvalued_bars_
Bars whose equity total did not fit an exact decimal, so they have no curve point.
Definition engine.hpp:731
std::size_t stop_releases_
Stop-limit orders a bar released; see ReportCaveats::stop_releases_.
Definition engine.hpp:735
std::size_t bars_
The bars replayed; bars fed as history (ReplayConfig::trade_from_) are in history_bars_.
Definition engine.hpp:694
std::size_t limit_fills_bounded_
Limit-type fills moved to stay in range; see ReportCaveats::limit_fills_bounded_.
Definition engine.hpp:739
std::size_t unchecked_fill_causality_
How many fill decisions could not be checked for causality; see ReportCaveats::unchecked_fill_causali...
Definition engine.hpp:723
std::optional< std::chrono::system_clock::time_point > first_unvalued_
The period end of the first unvalued bar, if any.
Definition engine.hpp:733
std::vector< strategy::GuardRejection > refused_
Instructions a risk guard refused.
Definition engine.hpp:690
std::vector< strategy::Rejection > rejected_
Instructions not placed: reconciliation could not build them, or the replay cannot model them (BINDIN...
Definition engine.hpp:688
std::size_t records_
The records fed to on_data.
Definition engine.hpp:713
std::vector< Execution > executions_
Every execution, in order.
Definition engine.hpp:683
std::size_t gaps_
Bars that did not follow their predecessor; gaps are not interpolated.
Definition engine.hpp:692
std::size_t expired_day_orders_
DAY orders withdrawn unfilled when their session ended, as a broker does at the close.
Definition engine.hpp:762
std::size_t unfilled_
Orders still queued when finish ran.
Definition engine.hpp:696
std::optional< BrokerError > halted_
Why the replay stopped early, if it did.
Definition engine.hpp:707
std::size_t stop_fills_intrabar_
Fills of stops released inside a bar; see ReportCaveats::stop_fills_intrabar_.
Definition engine.hpp:737
std::string market_price_rule_
The fill model's market-price rule, or empty; see ReportCaveats::market_price_rule_.
Definition engine.hpp:741
std::size_t market_fills_by_rule_
Fills priced by the fill model's market-price rule; see ReportCaveats::market_fills_by_rule_.
Definition engine.hpp:743
std::size_t quotes_
The quotes fed; see ReportCaveats::quotes_ for what quote-driven orders mean in a replay.
Definition engine.hpp:711
Currency currency_
The currency of the equity curve (the replay's accounting currency).
Definition engine.hpp:698
std::size_t history_bars_
The bars fed as history, before ReplayConfig::trade_from_.
Definition engine.hpp:764
std::optional< std::chrono::system_clock::time_point > first_overdrawn_
The first bar end at which cash was below zero, if any.
Definition engine.hpp:756
std::size_t aborted_
Orders still working when the replay halted, cleared from the queue (unlike unfilled_).
Definition engine.hpp:709
std::optional< Money > lowest_cash_
The lowest cash any execution left in currency_, if below zero (checked at every fill).
Definition engine.hpp:758
std::optional< std::chrono::system_clock::time_point > lowest_cash_at_
When lowest_cash_ was reached (that execution's Fill::at_).
Definition engine.hpp:760
std::vector< EquityPoint > equity_
The equity curve, in order: one point per period end, or per bar, or none (ReplayConfig::equity_curve...
Definition engine.hpp:681
std::size_t overdrawn_bars_
Bars that closed with cash below zero in currency_ (counted per bar fed, so two instruments count bot...
Definition engine.hpp:754
One bar, delivered to on_bar.
Definition event.hpp:313
std::chrono::system_clock::time_point period_end_
When the bar's period ended: the earliest moment the bar could be known.
Definition event.hpp:329
InstrumentId instrument_
The instrument the bar is for.
Definition event.hpp:315
BarInterval interval_
The period length the bar covers.
Definition event.hpp:317
A record of data from outside the broker, delivered to on_data.
Definition event.hpp:856
One order the runner is to place.
InstrumentId instrument_
The instrument to trade.
What the account holds and which orders are still working, as a strategy sees it.
Definition portfolio.hpp:82
std::vector< BuyingPower > buying_power_
What may be spent, per currency.
A quote the runner has just read, delivered to on_quote.
Definition event.hpp:841
QuoteSnapshot quote_
The quote, as the broker reported it.
Definition event.hpp:843
The limits the operator sets for RiskGuard.
Definition risk.hpp:412
The intraday session of a market, as the operator states it.
Definition event.hpp:122
static SessionWindow krx()
Returns the KRX regular session, 09:00-15:30 KST.
Definition event.hpp:136