algotradelib 0.0.0.9000
C++ header-only library for algorithmic trading
Loading...
Searching...
No Matches
loop.hpp
1#pragma once
2
3#include "./clock.hpp"
4#include "./execution.hpp"
5#include "./stop.hpp"
6
7#include <algotradelib/core>
8#include <algotradelib/strategy>
9
10#include <algorithm>
11#include <array>
12#include <chrono>
13#include <cstddef>
14#include <functional>
15#include <optional>
16#include <string>
17#include <string_view>
18#include <type_traits>
19#include <utility>
20#include <vector>
21
22namespace algotradelib {
23namespace runner {
24
31enum class PollKind {
33 BARS,
37 HOLDINGS,
39 WORKING_ORDERS,
41 BUYING_POWER,
50 CALENDAR,
67};
68
74inline constexpr std::string_view poll_kind_name(PollKind kind) noexcept {
75 switch (kind) {
77 return "calendar";
78 case PollKind::BARS:
79 return "bars";
81 return "quotes";
83 return "holdings";
85 return "working_orders";
87 return "buying_power";
89 return "price_limits";
90 case PollKind::DATA:
91 return "data";
92 }
93 return "";
94}
95
97inline constexpr PollKind all_poll_kinds[] = {
98 // First: the phase derived from it decides whether anything else in this iteration may be sent.
100 // Second, before every poll that can feed, so this iteration's orders use this iteration's bands.
102 // The listing, then holdings, before anything that feeds. A fill between the two reads then
103 // over-counts the position (harmless) rather than under-counting it (which would buy again).
106 // After holdings, so money and positions are equally fresh.
108 // Before bars, so a bar read in the same iteration sees the records received with it.
112};
113
114static_assert(
117 [](PollKind kind) {
118 return !poll_kind_name(kind).empty();
119 }
120 ),
121 "every PollKind must appear in all_poll_kinds once: a kind left out is never polled, and the loop "
122 "would silently answer with whatever the previous poll left behind"
123);
124
126inline constexpr std::size_t poll_kind_count = std::size(all_poll_kinds);
127
144
146inline constexpr std::array<PollOutcome, 4> all_poll_outcomes{
151};
152
158inline constexpr std::string_view poll_outcome_name(PollOutcome outcome) noexcept {
159 switch (outcome) {
161 return "updated";
163 return "unchanged";
165 return "failed";
167 return "rate_limited";
168 }
169 return "";
170}
171
172static_assert(
175 [](PollOutcome outcome) {
176 return !poll_outcome_name(outcome).empty();
177 }
178 ),
179 "all_poll_outcomes must list every PollOutcome"
180);
181
193 std::optional<std::chrono::nanoseconds> bars_;
195 std::optional<std::chrono::nanoseconds> quotes_;
197 std::optional<std::chrono::nanoseconds> holdings_;
207 std::optional<std::chrono::nanoseconds> working_orders_;
215 std::optional<std::chrono::nanoseconds> buying_power_;
217 std::chrono::nanoseconds tick_{std::chrono::seconds(1)};
226 std::optional<std::chrono::nanoseconds> calendar_{std::chrono::hours(6)};
233 std::optional<std::chrono::nanoseconds> price_limits_;
238 std::optional<std::chrono::nanoseconds> data_;
244 std::optional<std::chrono::nanoseconds> interval_for(PollKind kind) const noexcept {
245 switch (kind) {
247 return calendar_;
248 case PollKind::BARS:
249 return bars_;
250 case PollKind::QUOTES:
251 return quotes_;
253 return holdings_;
255 return working_orders_;
257 return buying_power_;
259 return price_limits_;
260 case PollKind::DATA:
261 return data_;
262 }
263 return std::nullopt;
264 }
265};
266
275template <typename Source, typename = void>
276struct source_provides_working_orders : std::false_type {};
277
278template <typename Source>
279struct source_provides_working_orders<Source, std::void_t<decltype(Source::provides_working_orders)>>
280: std::bool_constant<Source::provides_working_orders> {};
281
294template <typename Source, typename = void>
295struct source_states_calendar_sessions : std::false_type {};
296
297template <typename Source>
298struct source_states_calendar_sessions<Source, std::void_t<decltype(Source::states_calendar_sessions)>>
299: std::bool_constant<Source::states_calendar_sessions> {};
300
313template <typename Source, typename = void>
314struct source_reports_buying_power : std::false_type {};
315
316template <typename Source>
317struct source_reports_buying_power<Source, std::void_t<decltype(Source::reports_buying_power)>>
318: std::bool_constant<Source::reports_buying_power> {};
319
320namespace loop_detail {
321
322// Whether a source declares `reports_buying_power` at all, which only words the loop's note.
323template <typename Source, typename = void>
324struct source_declares_buying_power : std::false_type {};
325
326template <typename Source>
327struct source_declares_buying_power<Source, std::void_t<decltype(Source::reports_buying_power)>> : std::true_type {};
328
329} // namespace loop_detail
330
341template <typename Runner, typename = void>
342struct runner_keeps_sent_orders : std::true_type {};
343
344template <typename Runner>
345struct runner_keeps_sent_orders<Runner, std::void_t<decltype(Runner::keeps_sent_orders_until_listed)>>
346: std::bool_constant<Runner::keeps_sent_orders_until_listed> {};
347
352template <typename Runner, typename = void>
353struct runner_counts_kept_drops : std::false_type {};
354
355template <typename Runner>
356struct runner_counts_kept_drops<Runner, std::void_t<decltype(std::declval<const Runner&>().kept_intents_dropped())>>
357: std::true_type {};
358
363template <typename Runner, typename = void>
364struct runner_counts_warmup : std::false_type {};
365
366template <typename Runner>
368 Runner, std::void_t<decltype(std::declval<const Runner&>().warmup_instructions_discarded())>
369> : std::true_type {};
370
385 struct StatedTotal {
389 std::size_t statements_{0};
390 };
391
393 std::vector<StatedTotal> commission_;
395 std::vector<StatedTotal> tax_;
397 std::size_t orders_stating_cost_{0};
402 std::size_t orders_stating_none_{0};
417 std::size_t unrepresentable_sums_{0};
418
424 std::optional<Decimal64> commission_in(const Currency& currency) const {
425 return figure_in(commission_, currency);
426 }
427
433 std::optional<Decimal64> tax_in(const Currency& currency) const {
434 return figure_in(tax_, currency);
435 }
436
442 std::size_t commission_statements_in(const Currency& currency) const {
443 return statements_in(commission_, currency);
444 }
445
451 std::size_t tax_statements_in(const Currency& currency) const {
452 return statements_in(tax_, currency);
453 }
454
462 bool add(std::vector<StatedTotal>& totals, const Money& amount) {
463 for (auto& held : totals) {
464 if (held.amount_.currency_ == amount.currency_) {
465 const auto sum = decimal_add(held.amount_.amount_, amount.amount_);
466 if (!sum) {
468 return false;
469 }
470 held.amount_.amount_ = *sum;
471 ++held.statements_;
472 return true;
473 }
474 }
475 totals.push_back(StatedTotal{amount, 1});
476 return true;
477 }
478
485 static std::optional<Decimal64> figure_in(const std::vector<StatedTotal>& totals, const Currency& currency) {
486 for (const auto& held : totals) {
487 if (held.amount_.currency_ == currency) {
488 return held.amount_.amount_;
489 }
490 }
491 return std::nullopt;
492 }
493
500 static std::size_t statements_in(const std::vector<StatedTotal>& totals, const Currency& currency) {
501 for (const auto& held : totals) {
502 if (held.amount_.currency_ == currency) {
503 return held.statements_;
504 }
505 }
506 return 0;
507 }
508
518 ChargedCosts since(const ChargedCosts& before) const {
519 ChargedCosts delta;
520 std::size_t refused = 0;
521 const auto difference = [&refused](const std::vector<StatedTotal>& now, const std::vector<StatedTotal>& then) {
522 std::vector<StatedTotal> out;
523 for (const auto& held : now) {
524 auto earlier = Decimal64::parse("0");
525 std::size_t before_statements = 0;
526 for (const auto& was : then) {
527 if (was.amount_.currency_ == held.amount_.currency_) {
528 earlier = was.amount_.amount_;
529 before_statements = was.statements_;
530 break;
531 }
532 }
533 // Whether anything was stated is the statement count, not the money.
534 if (held.statements_ == before_statements) {
535 continue;
536 }
537 const auto moved = decimal_subtract(held.amount_.amount_, earlier);
538 if (!moved) {
539 // Counted, not skipped: something was stated and its amount cannot be represented.
540 ++refused;
541 continue;
542 }
543 out.push_back(StatedTotal{Money{*moved, held.amount_.currency_}, held.statements_ - before_statements});
544 }
545 return out;
546 };
547 delta.commission_ = difference(commission_, before.commission_);
548 delta.tax_ = difference(tax_, before.tax_);
554 return delta;
555 }
556};
557
563template <typename Source, typename = void>
564struct source_states_charged_costs : std::false_type {};
565
566template <typename Source>
567struct source_states_charged_costs<Source, std::void_t<decltype(std::declval<const Source&>().charged_costs())>>
568: std::true_type {};
569
579template <typename Source, typename = void>
580struct source_names_buying_power_currencies : std::false_type {};
581
582template <typename Source>
584 Source, std::void_t<decltype(std::declval<const Source&>().buying_power_currencies())>
585> : std::true_type {};
586
590 std::size_t consecutive_limit_{5};
591};
592
596 std::chrono::system_clock::time_point at_{};
598 std::vector<std::pair<PollKind, PollOutcome>> polls_;
605 std::optional<strategy::HaltReason> gate_;
607 bool fed_{false};
616 bool phase_changed_{false};
617
622 bool updated() const noexcept {
623 for (const auto& entry : polls_) {
624 if (entry.second == PollOutcome::UPDATED) {
625 return true;
626 }
627 }
628 return false;
629 }
630};
631
643 std::size_t iterations_{0};
647 std::size_t attempted_[poll_kind_count] = {};
649 std::size_t failed_[poll_kind_count] = {};
651 std::size_t blocked_{0};
653 std::optional<StopIntent> stopped_by_;
655 std::optional<strategy::HaltReason> final_gate_;
670 std::size_t price_bands_withheld_{0};
676 std::size_t orders_unbuildable_{0};
680 std::size_t orders_guard_refused_{0};
693 std::size_t orders_indeterminate_{0};
701 std::size_t plans_withheld_{0};
705 std::size_t cancels_rejected_{0};
707 std::size_t cancels_refused_{0};
709 std::size_t cancels_unresolved_{0};
713 std::optional<BrokerRefusal> last_broker_refusal_;
715 std::optional<strategy::Rejection> last_unbuildable_;
717 std::size_t phase_transitions_{0};
724 bool abandoned_{false};
726 std::optional<PollKind> abandoned_kind_;
728 bool order_list_read_{false};
730 std::size_t withdrawn_{0};
732 std::size_t flattened_{0};
734 std::size_t closing_placed_{0};
736 std::size_t closing_rejected_{0};
738 std::size_t closing_refused_{0};
743 std::size_t closing_withheld_{0};
747 std::size_t closing_unavailable_{0};
749 std::size_t closing_unresolved_{0};
755 std::size_t closing_unconfirmed_{0};
761 std::chrono::nanoseconds closing_waited_{0};
774 std::optional<Obligation> owed_stop_;
775
785 std::size_t closing_contended_{0};
786
792 std::size_t closing_unsizable_{0};
793
809
828
829 std::size_t stop_handler_refused_{0};
831 std::size_t stop_handler_sent_{0};
832
834 std::vector<std::string> notes_;
835
841 std::size_t attempted(PollKind kind) const noexcept {
842 return attempted_[static_cast<int>(kind)];
843 }
844
850 std::size_t failed(PollKind kind) const noexcept {
851 return failed_[static_cast<int>(kind)];
852 }
853};
854
863template <typename Runner>
865public:
867 static constexpr bool provides_working_orders = true;
869 static constexpr bool reports_buying_power = true;
870
876 void queue(PollKind kind, PollOutcome outcome) {
877 queued_[static_cast<int>(kind)].push_back(outcome);
878 }
879
885 void set_default(PollKind kind, PollOutcome outcome) {
886 defaults_[static_cast<int>(kind)] = outcome;
887 }
888
894 order_list_ = outcome;
895 }
896
901 void set_buying_power_currencies(std::vector<Currency> currencies) {
902 currencies_ = std::move(currencies);
903 }
904
911 calendar_ = std::move(calendar);
912 defaults_[static_cast<int>(PollKind::CALENDAR)] = PollOutcome::UPDATED;
913 }
914
919 const std::vector<Currency>& buying_power_currencies() const noexcept {
920 return currencies_;
921 }
922
927 std::size_t order_list_reads() const noexcept {
928 return order_list_reads_;
929 }
930
936 std::size_t polls(PollKind kind) const noexcept {
937 return polls_[static_cast<int>(kind)];
938 }
939
946 void set_price_limits(InstrumentId instrument, PriceLimits limits) {
947 price_limits_.emplace_back(std::move(instrument), std::move(limits));
948 defaults_[static_cast<int>(PollKind::PRICE_LIMITS)] = PollOutcome::UPDATED;
949 }
950
958 PollOutcome poll(PollKind kind, Runner& runner_instance) {
959 const int at = static_cast<int>(kind);
960 ++polls_[at];
961 auto outcome = defaults_[at];
962 if (!queued_[at].empty()) {
963 outcome = queued_[at].front();
964 queued_[at].erase(queued_[at].begin());
965 }
966 // The one kind whose answer goes somewhere: the loop reads the calendar back out of the context,
967 // so a source that did not put it there would leave every phase assertion in this header testing
968 // an empty calendar.
969 if (kind == PollKind::CALENDAR && calendar_ && outcome == PollOutcome::UPDATED) {
970 runner_instance.context().set_calendar(*calendar_);
971 }
972 // The second kind whose answer goes somewhere -- onto the runner rather than into the context,
973 // which is where reconciliation reads a band from. Installed on every successful poll, as a real
974 // source does, so a test can age one by letting the loop's clock run.
975 if (kind == PollKind::PRICE_LIMITS && outcome == PollOutcome::UPDATED) {
976 for (const auto& band : price_limits_) {
977 runner_instance.set_price_limits(band.first, band.second);
978 }
979 }
980 return outcome;
981 }
982
988 ++order_list_reads_;
989 return order_list_;
990 }
991
992private:
993 // Every kind's default outcome, filled rather than listed.
994 //
995 // It used to be a list with one entry per `PollKind`, and `PollOutcome::UPDATED` is the zero value
996 // -- so adding an enumerator silently defaulted the new kind to "new data arrived" in every test
997 // that had not set it. Filling cannot be one short.
998 static std::array<PollOutcome, poll_kind_count> unchanged_defaults() {
999 std::array<PollOutcome, poll_kind_count> filled{};
1000 filled.fill(PollOutcome::UNCHANGED);
1001 return filled;
1002 }
1003
1004 std::vector<PollOutcome> queued_[poll_kind_count];
1005 std::array<PollOutcome, poll_kind_count> defaults_{unchanged_defaults()};
1006 PollOutcome order_list_{PollOutcome::UPDATED};
1007 std::vector<Currency> currencies_;
1008 std::optional<TradingCalendar> calendar_;
1009 std::vector<std::pair<InstrumentId, PriceLimits>> price_limits_;
1010 std::size_t polls_[poll_kind_count] = {};
1011 std::size_t order_list_reads_{0};
1012};
1013
1056template <typename Runner, typename Source, typename Clock = SteadyClock>
1058public:
1066 PollingLoop(Runner& runner, Source& source, PollSchedule schedule = {}, Clock clock = {})
1067 : runner_(&runner), source_(&source), schedule_(std::move(schedule)), clock_(std::move(clock)) {
1068 // The strategy reads the loop's window (`Context::session`); under stated calendar sessions the phase does not
1069 // come from it.
1070 runner_->context().set_session(session_window_);
1071 }
1072
1077 const Clock& clock() const noexcept {
1078 return clock_;
1079 }
1080
1084 Clock& clock() noexcept {
1085 return clock_;
1086 }
1087
1092 const PollSchedule& schedule() const noexcept {
1093 return schedule_;
1094 }
1095
1096private:
1097 // Every monotone instruction-outcome figure the runner holds, read at one instant.
1098 //
1099 // Twelve of them, read together rather than one call at a time, because they are differenced
1100 // against each other's snapshot: a set taken at two instants describes one interval, and twelve
1101 // separately captured values do not.
1102 struct InstructionOutcomes {
1103 std::size_t unbuildable_{0};
1104 std::size_t unconfirmed_timed_out_{0};
1105 std::size_t reconcile_withheld_{0};
1106 std::size_t guard_refused_{0};
1107 std::size_t binding_refused_{0};
1108 std::size_t broker_refused_{0};
1109 std::size_t indeterminate_{0};
1110 std::size_t cancels_rejected_{0};
1111 std::size_t cancels_refused_{0};
1112 std::size_t cancels_unresolved_{0};
1113 std::size_t cancels_indeterminate_{0};
1114 std::size_t plans_withheld_{0};
1115 std::size_t instructions_unavailable_{0};
1116 };
1117
1118 // Reads them all from the runner.
1119 InstructionOutcomes instruction_outcomes() const {
1120 InstructionOutcomes at;
1121 at.unbuildable_ = runner_->orders_unbuildable();
1122 at.unconfirmed_timed_out_ = runner_->orders_unconfirmed_timed_out();
1123 at.reconcile_withheld_ = runner_->orders_reconcile_withheld();
1124 at.guard_refused_ = runner_->orders_guard_refused();
1125 at.binding_refused_ = runner_->orders_binding_refused();
1126 at.broker_refused_ = runner_->orders_broker_refused();
1127 at.indeterminate_ = runner_->orders_indeterminate();
1128 at.cancels_rejected_ = runner_->cancels_rejected();
1129 at.cancels_refused_ = runner_->cancels_refused();
1130 at.cancels_unresolved_ = runner_->cancels_unresolved();
1131 at.cancels_indeterminate_ = runner_->cancels_indeterminate();
1132 at.plans_withheld_ = runner_->plans_withheld();
1133 at.instructions_unavailable_ = runner_->instructions_unavailable();
1134 return at;
1135 }
1136
1137 // Writes the difference between two snapshots onto `report`.
1138 static void note_instruction_outcomes(
1139 LoopReport& report, const InstructionOutcomes& before, const InstructionOutcomes& after
1140 ) {
1141 report.orders_unbuildable_ = after.unbuildable_ - before.unbuildable_;
1142 report.orders_unconfirmed_timed_out_ = after.unconfirmed_timed_out_ - before.unconfirmed_timed_out_;
1143 report.orders_reconcile_withheld_ = after.reconcile_withheld_ - before.reconcile_withheld_;
1144 report.orders_guard_refused_ = after.guard_refused_ - before.guard_refused_;
1145 report.orders_binding_refused_ = after.binding_refused_ - before.binding_refused_;
1146 report.orders_broker_refused_ = after.broker_refused_ - before.broker_refused_;
1147 report.orders_indeterminate_ = after.indeterminate_ - before.indeterminate_;
1148 report.cancels_rejected_ = after.cancels_rejected_ - before.cancels_rejected_;
1149 report.cancels_refused_ = after.cancels_refused_ - before.cancels_refused_;
1150 report.cancels_unresolved_ = after.cancels_unresolved_ - before.cancels_unresolved_;
1151 report.cancels_indeterminate_ = after.cancels_indeterminate_ - before.cancels_indeterminate_;
1152 report.plans_withheld_ = after.plans_withheld_ - before.plans_withheld_;
1153 report.instructions_unavailable_ = after.instructions_unavailable_ - before.instructions_unavailable_;
1154 }
1155
1156public:
1167 void set_maximum_portfolio_age(std::chrono::nanoseconds age) {
1168 maximum_portfolio_age_ = age;
1169 // Pushed down as the **policy**, not as a verdict. The runner re-evaluates it against whatever
1170 // snapshot is in hand when it settles, which is the only version that cannot describe a
1171 // portfolio that has since been replaced -- a source callback can feed, and settle, between this
1172 // loop's own checks.
1173 runner_->set_maximum_portfolio_age(age);
1174 }
1175
1206 void set_closing_wait(std::chrono::nanoseconds limit) {
1207 closing_wait_ = limit;
1208 }
1209
1260 void set_owed_order_limit(std::chrono::nanoseconds limit) {
1261 owed_order_limit_ = limit;
1262 }
1263
1275 allow_unbounded_portfolio_age_ = true;
1276 maximum_portfolio_age_.reset();
1277 runner_->set_maximum_portfolio_age(std::nullopt);
1278 }
1279
1285 void set_maximum_price_limits_age(std::optional<std::chrono::nanoseconds> age) {
1286 runner_->set_maximum_price_limits_age(age);
1287 }
1288
1291 runner_->allow_unbounded_price_limits_age();
1292 }
1293
1302 allow_absent_portfolio_ = true;
1303 // Pushed down for the same reason the age policy is: this loop's hold is not in force at every
1304 // point an instruction can be settled, so the runner enforces the absence rule itself and an
1305 // opt-out that stopped at the hold would not actually opt out of anything.
1306 runner_->allow_absent_portfolio();
1307 }
1308
1319 runner_->context().set_session(window);
1320 session_window_ = std::move(window);
1321 }
1322
1327 const strategy::SessionWindow& session_window() const noexcept {
1328 return session_window_;
1329 }
1330
1336 failure_policy_ = std::move(policy);
1337 }
1338
1356 std::function<std::optional<std::vector<typename Runner::DataRecord>>(std::chrono::system_clock::time_point)> poll
1357 ) {
1358 static_assert(
1360 "a data poll for a strategy that declares no on_data would read records that vanish: declare on_data"
1361 );
1362 data_poll_ = std::move(poll);
1363 }
1364
1370 control_ = std::move(channel);
1371 }
1372
1394 LoopReport run(StopSource& stop, std::size_t max_iterations = 0) {
1395 LoopReport report;
1396 // Carried in rather than left false: the field says whether the order list has been read at
1397 // least once, and the loop remembers that across runs. A second `run` on the same loop had been
1398 // reporting it as unread, which reads as a startup gate that never opened.
1399 report.order_list_read_ = order_list_read_;
1400 // **Differenced around the run, not accumulated from the passes.** An order can leave the
1401 // process from inside a source's `poll`, which calls `Runner::feed` itself and discards the
1402 // report it gets back, so a per-pass figure would only ever see what a stop did. The runner's
1403 // counter is monotonic for exactly this reason, and reading it at both ends is how
1404 // `RiskGuard::total_sent` is already used around a callback. Taken per `run` so a second run on
1405 // the same loop reports its own sends rather than the first one's as well.
1406 const auto outside_phase_before = runner_->sends_outside_permitted_phase();
1407 // Differenced for the reason above: both are monotone on the runner, which outlives this call.
1408 const auto bands_withheld_before = runner_->price_bands_withheld();
1409 const auto unclamped_rejected_before = runner_->unclamped_orders_rejected();
1410 const auto unclamped_refused_before = runner_->unclamped_orders_refused();
1411 // **The polling path's own figures, taken before any stop is honoured.** `honour` runs the stop
1412 // handler and the closing pass through the same `Runner::settle`, so a snapshot taken at the end
1413 // of `run` would count a refused flatten here *and* in `closing_refused_` -- one failure reported
1414 // twice, under a contract that says this family describes the polling path.
1415 const auto outcomes_before = instruction_outcomes();
1416 auto outcomes_after = outcomes_before;
1417 // **The record travels with the counters, and for the same reason.** Read after `honour`, a
1418 // refusal from the *closing* pass would have replaced it while the count still described a
1419 // polling one -- a report naming an order none of its figures counted.
1420 std::optional<BrokerRefusal> refusal_at_boundary;
1421 std::optional<strategy::Rejection> unbuildable_at_boundary;
1422 // Differenced around the run for the same reason, and the reason is sharper here: the source
1423 // survives `run` returning, so an absolute figure would report the previous run's charges again.
1424 const auto charged_before = [&]() {
1426 return source_->charged_costs();
1427 } else {
1428 return ChargedCosts{};
1429 }
1430 }();
1431 for (auto& due : next_due_) {
1432 due.reset();
1433 }
1434 for (auto& count : consecutive_failures_) {
1435 count = 0;
1436 }
1437 closing_.reset();
1438 warmup_discarded_at_start_ = warmup_discarded();
1440 kept_dropped_at_start_ = runner_->kept_intents_dropped();
1441 }
1442
1443 while (max_iterations == 0 || report.iterations_ < max_iterations) {
1444 const auto iteration = step(stop, report);
1445 ++report.iterations_;
1446 if (iteration.gate_) {
1447 ++report.blocked_;
1448 }
1449 report.final_gate_ = iteration.gate_;
1450 report.final_phase_ = iteration.phase_;
1451 if (iteration.phase_changed_) {
1452 ++report.phase_transitions_;
1453 }
1454 last_ = iteration;
1455
1456 if (report.abandoned_) {
1457 if (!closing_) {
1458 outcomes_after = instruction_outcomes();
1459 refusal_at_boundary = runner_->last_broker_refusal();
1460 unbuildable_at_boundary = runner_->last_unbuildable();
1461 }
1462 // As for a stop: retained work lives for one run. A run resumed after an outage of unknown
1463 // length must not place what was decided before it.
1464 runner_->clear_retained_targets();
1465 if (const auto intent = stop.intent()) {
1466 interrupt_stop(*intent, report);
1467 } else if (owed_past_limit(clock_.now())) {
1468 // Giving up took `POLL_FAILING`, which lets a withdrawal through. The hold for an order nobody
1469 // can account for (`set_owed_order_limit`) is the stronger one and stays, with no stop
1470 // requested: no read has decided yet, and a later run on this loop takes it up again.
1472 report.final_gate_ = runner_->guard().blocking_reason();
1473 }
1474 break;
1475 }
1476 if (const auto intent = stop.intent()) {
1477 if (!closing_) {
1478 // Sampled here, before the stop runs anything, for the reason stated where this began. Once,
1479 // when the stop is first seen: what a strategy asks for while the stop waits is refused by
1480 // the hold, and those refusals describe the stop, not the polling path.
1481 outcomes_after = instruction_outcomes();
1482 refusal_at_boundary = runner_->last_broker_refusal();
1483 unbuildable_at_boundary = runner_->last_unbuildable();
1484 begin_stop(report);
1485 }
1486 // A run's last permitted iteration honours the stop rather than leave it pending.
1487 const bool last_iteration = max_iterations != 0 && report.iterations_ >= max_iterations;
1488 if (!last_iteration && closing_should_wait(*intent, report)) {
1489 clock_.wait_for(closing_until_next());
1490 continue;
1491 }
1492 finish_stop(*intent, report);
1493 report.stopped_by_ = intent;
1494 break;
1495 }
1496 clock_.wait_for(until_next(iteration.at_));
1497 }
1498
1499 // Deliberately **not** released here. A run that ended because an operator asked it to, or
1500 // because a poll kept failing, must leave the runner unable to send: releasing the halt on the
1501 // way out would reopen the gate at exactly the moment the loop stopped watching it. A caller who
1502 // genuinely wants to trade again resumes the guard themselves, which is a deliberate act.
1503 //
1504 // A healthy run that simply exhausted `max_iterations` never halted anything, so there is
1505 // nothing to leave behind in that case.
1506 report.sends_outside_permitted_phase_ = runner_->sends_outside_permitted_phase() - outside_phase_before;
1507 report.price_bands_withheld_ = runner_->price_bands_withheld() - bands_withheld_before;
1508 report.unclamped_orders_rejected_ = runner_->unclamped_orders_rejected() - unclamped_rejected_before;
1509 report.unclamped_orders_refused_ = runner_->unclamped_orders_refused() - unclamped_refused_before;
1510 // Taken at the loop's exit for a run nothing stopped, and at the stop for one something did.
1511 if (!report.stopped_by_ && !report.abandoned_) {
1512 outcomes_after = instruction_outcomes();
1513 refusal_at_boundary = runner_->last_broker_refusal();
1514 unbuildable_at_boundary = runner_->last_unbuildable();
1515 }
1516 note_instruction_outcomes(report, outcomes_before, outcomes_after);
1517 // **Carried only when this run's polling saw one**, which the count already decides: any refusal
1518 // during this run overwrote whatever the runner held before it, so a non-zero count means the
1519 // record is this run's. Comparing the records instead would need an equality `BrokerRefusal` has
1520 // no reason to have.
1521 if (report.orders_broker_refused_ != 0) {
1522 report.last_broker_refusal_ = refusal_at_boundary;
1523 }
1524 // The same rule for the reconciliation's own refusals.
1525 if (report.orders_unbuildable_ != 0) {
1526 report.last_unbuildable_ = unbuildable_at_boundary;
1527 }
1528 // **Said only when a band was actually held back**, not merely because no policy was stated. A
1529 // run that registers no band and polls none has nothing to decide, and a note telling it to
1530 // state a policy would be advice about a mechanism it is not using. Once per loop, like the
1531 // portfolio's own note, because a run that ignores it does not need it every iteration.
1532 //
1533 // **Asked of the runner rather than remembered here.** This loop borrows a mutable runner and
1534 // does not own its policy: a maximum stated directly on the runner before this loop existed
1535 // would have read as "nobody stated one", and a withdrawal made directly on the runner would
1536 // have been suppressed by this loop's memory of its own wrapper being called. One policy, one
1537 // place that answers for it.
1538 if (report.price_bands_withheld_ > 0 && !runner_->price_limits_age_policy_stated() && !said_no_band_age_policy_) {
1539 said_no_band_age_policy_ = true;
1540 report.notes_.emplace_back(
1541 "no price band age policy: call set_maximum_price_limits_age or "
1542 "allow_unbounded_price_limits_age"
1543 );
1544 }
1546 report.charged_costs_ = source_->charged_costs().since(charged_before);
1547 }
1548 note_sellable_convention(report);
1549 note_unestablished_phase(report);
1550 note_on_fill_never_fires(report);
1551 note_listing_outpaces_holdings(report);
1552 note_warmup_discarded(report);
1553 note_kept_intents_dropped(report);
1554 return report;
1555 }
1556
1561 const IterationReport& last() const noexcept {
1562 return last_;
1563 }
1564
1565private:
1566 // Puts the sellable-convention probe's verdict in the report, when it reached one.
1567 //
1568 // The probe answers a question no broker's documentation is known to -- whether the sellable figure
1569 // already excludes resting sells -- and it answers it as a by-product of ordinary polling. An
1570 // operator should not have to write code to read that, so a run that learned something says so,
1571 // with the counts behind it because one observation is evidence rather than proof.
1572 //
1573 // Silent when nothing was observed, which is most runs: a note saying "undetermined" on every run
1574 // that never sold anything is noise, and noise is how a report stops being read.
1575 void note_sellable_convention(LoopReport& report) const {
1576 const auto evidence = runner_->sellable_convention().overall();
1577 if (evidence.total() == 0) {
1578 return;
1579 }
1580 report.notes_.push_back(
1581 "broker's sellable figure appears " + std::string(strategy::sellable_convention_name(evidence.verdict())) + " (" +
1582 std::to_string(evidence.net_) + " net, " + std::to_string(evidence.gross_) + " gross)"
1583 );
1584 }
1585
1586 // Returns how many instructions the runner has discarded as history, where it counts them.
1587 std::size_t warmup_discarded() const {
1588 if constexpr (runner_counts_warmup<Runner>::value) {
1589 return runner_->warmup_instructions_discarded();
1590 } else {
1591 return 0;
1592 }
1593 }
1594
1595 // Says, once per run, how many instructions were decided on bars fed as history and not sent.
1596 //
1597 // Only the newest bar of each instrument's read may send (`Runner::feed_warmup`), so a cold start's
1598 // history and a backlog after an outage are shown to the strategy and nothing decided on them goes
1599 // out. Worth a line because it is also what a bar cadence slower than the bars' interval costs: a
1600 // poll bringing five minute bars acts on the newest one only.
1601 void note_warmup_discarded(LoopReport& report) const {
1602 const auto discarded = warmup_discarded() - warmup_discarded_at_start_;
1603 if (discarded == 0) {
1604 return;
1605 }
1606 report.notes_.push_back(
1607 std::to_string(discarded) +
1608 " instruction(s) decided on bars fed as history were not sent: "
1609 "only the newest bar of each instrument's read may send (poll bars no slower than their interval)"
1610 );
1611 }
1612
1613 // Says, once per run, how many order intents kept for the phase were dropped at release.
1614 void note_kept_intents_dropped(LoopReport& report) const {
1615 if constexpr (runner_counts_kept_drops<Runner>::value) {
1616 const auto dropped = runner_->kept_intents_dropped() - kept_dropped_at_start_;
1617 if (dropped != 0) {
1618 report.notes_.push_back(
1619 std::to_string(dropped) +
1620 " order intent(s) kept for the market phase were not sent at the "
1621 "open: the instrument's holding had changed since they were decided, or a stop now rested"
1622 );
1623 }
1624 } else {
1625 static_cast<void>(report);
1626 }
1627 }
1628
1629 // Says, once per run, that the strategy's `on_fill` never fires on this runner.
1630 //
1631 // See `Runner::on_fill_never_fires`. On every run rather than only the first, because a report is
1632 // read on its own, and a note that appeared only in a run nobody kept would be no note at all.
1633 void note_on_fill_never_fires(LoopReport& report) const {
1634 if constexpr (Runner::on_fill_never_fires) {
1635 report.notes_.push_back(
1636 "strategy defines on_fill; it never fires on this runner (fills are not observed live: "
1637 "read positions from holdings, see writing-a-strategy.md)"
1638 );
1639 } else {
1640 static_cast<void>(report);
1641 }
1642 }
1643
1644 // Says, once per run, that working orders are polled more often than holdings.
1645 //
1646 // Not refused: it is a legitimate choice for a strategy that mostly watches its orders. But every
1647 // plan made between a listing and the next holdings read is withheld (`PollSchedule::working_orders_`
1648 // says why), and an operator reading a report full of `portfolio_superseded` should find the cause
1649 // stated beside it.
1650 void note_listing_outpaces_holdings(LoopReport& report) const {
1651 const auto& listing = schedule_.working_orders_;
1652 const auto& holdings = schedule_.holdings_;
1653 if (listing && holdings && *listing < *holdings) {
1654 report.notes_.push_back(
1655 "working orders are polled more often than holdings; plans made between a listing and the "
1656 "next holdings read are withheld as portfolio_superseded"
1657 );
1658 }
1659 }
1660
1661 // Runs one iteration: poll what is due, then let the runner act if the gate is open.
1662 IterationReport step(StopSource& stop, LoopReport& report) {
1663 IterationReport iteration;
1664 iteration.at_ = clock_.now();
1665
1666 // Read before polling, so an operator's stop is honoured without first spending requests on a
1667 // broker the loop is about to walk away from.
1668 check_control_file(stop, report);
1669 // A stop discards what was retained for a better account read: nothing decided before it is to be
1670 // replayed after it.
1671 if (stop.requested()) {
1672 runner_->clear_retained_targets();
1673 }
1674
1675 // **Installed before anything can send, and announced only after the polls.** The two halves are
1676 // separate on purpose and neither is optional.
1677 //
1678 // A source's `poll` calls `Runner::feed`, which settles, so an order can leave the process from
1679 // inside a poll -- the same fact the gate below is computed early for. If the phase were installed
1680 // after the polls, the first bar arriving after the close would be settled while the context still
1681 // said `OPEN`, and an opening order would pass a phase limit that exists to refuse it. Once per
1682 // session, on the close.
1683 //
1684 // Announcing the change is the opposite case: `on_phase` may place orders, and it should see this
1685 // iteration's polls rather than the previous one's -- fresh prices, a fresh portfolio, and a gate
1686 // re-evaluated against them. That is what the replay's step does (`backtest/engine.hpp`, "The price moves with the portfolio"), with
1687 // the same argument: a handler deciding on a mark from one moment beside a price from another is
1688 // not looking at a fresher picture, it is looking at an incoherent one.
1689 install_phase(iteration);
1690
1691 // **Before anything this loop calls can feed, because several of them can.** The runner measures
1692 // a snapshot's age against the later of this and its own decision instant, and its decision
1693 // instant is a bar's period end -- which on a daily bar is yesterday's close. Set here, a plan
1694 // settled from inside `read_order_list` or a poll is aged against the clock rather than against
1695 // the event that triggered it.
1696 runner_->set_observed_at(iteration.at_);
1697 // Stated here too, and for the same reason: the runner enforces the absence rule at the moment
1698 // an instruction is decided, which is the only place that is inside every callback this loop
1699 // makes. A run that opted out says so, and the runner then places as it did before.
1700 runner_->require_known_portfolio(!allow_absent_portfolio_);
1701
1702 // **Established before any poll runs, because a poll is what feeds the runner.** A source's
1703 // `poll` calls `Runner::feed` itself -- `live::SessionSource::poll_bars` does, per instrument --
1704 // and `feed` settles, so an order can leave the process from inside a poll. Computing the gate
1705 // afterwards would mean the startup gate and the staleness gate were installed one poll too
1706 // late, and on the very first iteration they would not be installed at all: a bar arriving
1707 // before the first order-list read could place an order against a position a predecessor may
1708 // have left, which is the exact hazard the startup gate exists for.
1709 // **The strategy starts before anything this loop calls can feed it**, once per runner: before the
1710 // order-list read below (a source's read may feed) and before every poll (a poll feeds `on_bar`,
1711 // warm-up included, `on_quote` and `on_order_update`). Under a gate that does not read, so what
1712 // `on_start` asks for meets the holds standing now: on a cold start the account is unread, an
1713 // order intent is withheld and a target retained until a holdings read lets it through. The clock
1714 // moves forwards to this reading, as it does for `on_phase`. The hold that stood before is put
1715 // back afterwards, so the read below runs under the same hold as it does without `on_start`.
1716 if (!runner_->started()) {
1717 const auto before = held_;
1718 hold(gate_for(stop, iteration.at_, report, /*may_read=*/false));
1719 if (runner_->context().now() < iteration.at_) {
1720 runner_->context().set_now(iteration.at_);
1721 }
1722 const auto watch = watch_phase(iteration);
1723 runner_->start();
1724 note_revised_phase("on_start handler", watch, report);
1725 hold(before);
1726 }
1727 hold(gate_for(stop, iteration.at_, report, /*may_read=*/true));
1728
1729 for (const auto kind : all_poll_kinds) {
1730 if (!is_due(kind, iteration.at_)) {
1731 continue;
1732 }
1733 // **Re-established immediately before every poll**, because a poll is a point at which an order
1734 // can leave the process and anything that ran before it may have replaced the calendar the phase
1735 // was derived from. Three things can have: a previous poll in this same loop, the calendar poll
1736 // in particular since it is polled first, and `gate_for`'s out-of-band `read_order_list` above.
1737 //
1738 // Before rather than after, which is the correction: "after every poll" closed the first two and
1739 // left the third, because the pre-loop install runs *before* `gate_for` and nothing re-derived
1740 // the phase between that call and the first poll. Placing it here makes the rule positional
1741 // instead of enumerated -- every send site is preceded by an install, and no list of which polls
1742 // can change what has to stay correct.
1743 //
1744 // The cost is a date comparison per due poll.
1745 install_phase(iteration);
1746 // **And the gate, for the same reason.** The polls before this one may have read the account: on
1747 // a cold start the hold for an account never read was installed before the polls, and without
1748 // re-evaluating it here it would still stand when the bars read after this iteration's holdings
1749 // are fed -- withholding the first decision against an account that has, by then, been read.
1750 // `may_read` is false: the order list is attempted once per iteration, above.
1751 hold(gate_for(stop, iteration.at_, report, /*may_read=*/false));
1752 const auto watch = watch_phase(iteration);
1753 // **Sampled before the poll, not after it.** A poll can send: `Runner::feed` settles, and a
1754 // working-order poll now feeds `on_order_update` as well as the bar and quote polls feeding
1755 // their handlers. An order a handler places during the working-order poll was sent *after*
1756 // the listing was fetched and cannot be in it -- so counting placements afterwards would
1757 // stamp that listing as though it covered the order, and `closing_source_verified` would
1758 // then approve a flatten against a picture missing a resting order. The count taken here is
1759 // the one that was true when the listing was read.
1760 const auto placements_before_poll = runner_->placements_at_broker();
1761 const auto outcome = kind == PollKind::DATA ? poll_data(iteration.at_) : source_->poll(kind, *runner_);
1762 if (kind == PollKind::WORKING_ORDERS) {
1763 working_asked_at_ = clock_.monotonic_now();
1764 } else if (kind == PollKind::HOLDINGS) {
1765 holdings_asked_at_ = clock_.monotonic_now();
1766 }
1767 note_revised_phase(std::string(poll_kind_name(kind)) + " poll", watch, report);
1768 // `UNCHANGED` counts, because a listing that is identical to the last one is still a listing
1769 // -- but only on a source that publishes them at all, which `note_working_orders_read`
1770 // enforces: a broker without the inquiry answers `UNCHANGED` without asking anybody.
1771 if (kind == PollKind::WORKING_ORDERS && (outcome == PollOutcome::UPDATED || outcome == PollOutcome::UNCHANGED)) {
1772 note_working_orders_read(iteration.at_, placements_before_poll);
1773 }
1774 ++report.attempted_[static_cast<int>(kind)];
1775 iteration.polls_.emplace_back(kind, outcome);
1776 schedule_next(kind, iteration.at_);
1777 note_outcome(kind, outcome, report);
1778 if (outcome == PollOutcome::UPDATED) {
1779 iteration.fed_ = true;
1780 }
1781 if (report.abandoned_) {
1782 // Recorded before returning, so the report does not claim sending was permitted while the
1783 // guard `note_outcome` just halted says otherwise.
1784 iteration.gate_ = runner_->guard().blocking_reason();
1785 return iteration;
1786 }
1787 }
1788
1789 // Observed after the polls, not before: a poll can refresh the listing without a bar arriving,
1790 // and that is precisely when an order of ours begins showing as resting. Observing first would
1791 // read every iteration's portfolio one iteration late. A repeat observation of unchanged state
1792 // concludes nothing, so a quiet iteration costs a scan and teaches the probe nothing.
1793 runner_->observe_sellable_convention();
1794
1795 // Re-evaluated after the polls so the report and the next iteration reflect what those polls
1796 // changed -- a holdings refresh should lift the staleness hold now, not one iteration later.
1797 // The order list is deliberately not attempted a second time: one attempt per iteration, and
1798 // the gate simply stands until the next one.
1799 // The last send site: the announcement below settles what `on_phase` asks for, and the final poll
1800 // may have replaced the calendar after its own pre-poll install.
1801 install_phase(iteration);
1802 hold(gate_for(stop, iteration.at_, report, /*may_read=*/false));
1803
1804 // Announced last, so the handler runs on everything this iteration established. A change is
1805 // announced once, not every iteration it persists for.
1806 if (announced_ != iteration.phase_) {
1807 // **The clock moves with the phase, and only forwards.** `Runner::feed(MarketPhase)` does not
1808 // advance `Context::now_`; only a bar or a quote does, from a broker's stamp. So a daily-bar run
1809 // would hand `on_phase` an instant hours old, and `RiskGuard` files a send at
1810 // `GuardInputs::now_` and counts sends within `rate_window_` of it -- the phase order and the
1811 // next bar's order would be filed at what the guard thinks are two unrelated moments, and two
1812 // orders would pass a one-order window. The replay's step (`backtest/engine.hpp`) documents the same hazard
1813 // for the replay.
1814 //
1815 // Forwards only: a broker stamp ahead of this machine's clock must not be walked backwards,
1816 // because a handler deciding at an instant *earlier* than the bar it has already been shown is
1817 // the same incoherence with the sign flipped. The skew is the broker's and is not this loop's
1818 // to quietly correct.
1819 //
1820 // A bar fed earlier in this same iteration set `now_` to its own period end, which on a daily bar
1821 // is yesterday's close. Its order is still counted in the rate window at this iteration's
1822 // reading, beside this one: the runner counts a send at the later of the decision instant and
1823 // the reading this loop gave it.
1824 if (runner_->context().now() < iteration.at_) {
1825 runner_->context().set_now(iteration.at_);
1826 }
1827 announced_ = iteration.phase_;
1828 iteration.phase_changed_ = true;
1829 // Watched for the same reason a poll is: `Context::set_calendar` is public, so an `on_phase`
1830 // handler can revise the calendar and submit in one call, and `settle` runs before this returns.
1831 const auto watch = watch_phase(iteration);
1832 runner_->feed(iteration.phase_);
1833 note_revised_phase("on_phase handler", watch, report);
1834 }
1835
1836 // **Last of all the iteration's decisions**, so every handler that could restate the instrument --
1837 // the bars, the quotes, the listing's updates, and `on_phase` just above -- has spoken first, and
1838 // its instruction has replaced the retained target; a retry before `on_phase` could send an entry
1839 // the phase change was about to countermand. And after every account poll and the gate they
1840 // refreshed, so what is retried is sized against this iteration's holdings, listing and budget,
1841 // under this iteration's holds -- inside the holdings poll it ran before the gate lifted and before
1842 // buying power was read.
1843 runner_->retry_retained_targets();
1844
1845 // Reported from the guard rather than from what the loop just computed, so the report names the
1846 // most fundamental hold in force whoever owns it -- an operator's halt, or a journal that
1847 // failed, outranks anything the loop decided.
1848 iteration.gate_ = runner_->guard().blocking_reason();
1849 return iteration;
1850 }
1851
1852 // What the phase and the send count were before the loop handed control to somebody else.
1853 struct PhaseWatch {
1854 std::chrono::system_clock::time_point at_{};
1856 std::size_t sends_{0};
1857 };
1858
1859 // Records the phase and the send count, for comparison after a call into user code.
1860 PhaseWatch watch_phase(const IterationReport& iteration) const {
1861 return PhaseWatch{iteration.at_, iteration.phase_, runner_->guard().total_sent()};
1862 }
1863
1864 // Counts and names a call that sent an order and left the phase changed behind it.
1865 //
1866 // **The one hazard here the loop cannot prevent and can only witness.** It re-derives the phase before
1867 // every call it makes that could send, but nothing of its runs *inside* such a call: a
1868 // source that replaces the calendar and then feeds, or an `on_phase` handler that does the same before
1869 // submitting, settles an order against the phase as it stood when the call began. So the loop looks
1870 // afterwards, which turns an invisible violation into a line in the report -- the same choice
1871 // `closing_source_unverified_` makes about a listing it could not trust.
1872 //
1873 // **Both halves are required, and each one removes a wrong answer.** The phase must have moved, or an
1874 // ordinary send would be reported. Something must have been sent, or an ordinary calendar poll would be
1875 // reported on every iteration -- which is why this no longer excludes the calendar poll by kind. That
1876 // exclusion was a false-positive workaround and it hid this case: a source obeying
1877 // the letter of the contract, writing the calendar in the calendar poll and *then* feeding.
1878 //
1879 // `total_sent()` rather than the guard's rate-window deque, because that one prunes and can fall, so
1880 // it cannot be differenced across a call.
1881 void note_revised_phase(const std::string& what, const PhaseWatch& before, LoopReport& report) {
1882 if (runner_->guard().total_sent() == before.sends_) {
1883 return;
1884 }
1885 if (phase_at(before.at_) == before.phase_) {
1886 return;
1887 }
1888 ++report.sends_under_a_revised_phase_;
1889 if (report.sends_under_a_revised_phase_ == 1) {
1890 // Once per run, not once per call: a strategy doing this on every bar would otherwise bury every
1891 // other note under thousands of copies of this one.
1892 // **Worded to exactly what was observed**, which is co-occurrence and not causation. Two cases
1893 // the stronger claim would have got wrong: a call that sent *first* and revised the calendar
1894 // afterwards, where no order used the stale answer; and a call that only cancelled, since
1895 // `Runner::send_cancel` never consults the phase at all. Both still break the writer contract and
1896 // are worth reporting, so the note states the facts and names the check rather than the verdict.
1897 report.notes_.push_back(
1898 "the " + what +
1899 " changed the market phase and sent a request in the same call; check whether "
1900 "that request used the earlier phase. Only the calendar poll may write the trading calendar, "
1901 "and it must not send"
1902 );
1903 }
1904 }
1905
1906 // Computes the phase for this iteration and installs it, so nothing can send under a stale one.
1907 //
1908 // **Called immediately before every point at which this loop hands control to the source**: once
1909 // before `gate_for`, which performs an out-of-band order-list read; once before each due poll; and
1910 // once before the phase announcement. So the invariant is exactly this, and no stronger:
1911 // **whenever the loop calls into the source, `Context::phase_` is derived from the calendar as it
1912 // stood at that call.**
1913 //
1914 // **What that deliberately does not promise**, because it cannot: a source is free to replace the
1915 // calendar and then feed the runner inside a single `poll`, and no loop code runs in between, so
1916 // that order would settle against the phase as it stood when the poll began. `PollKind::CALENDAR`
1917 // documents the contract that rules it out, `SessionSource` satisfies it -- it writes the calendar in
1918 // the calendar poll and nowhere else -- and `note_revised_phase` reports a source that
1919 // breaks it, because a violation nobody is told about is one nobody fixes. The stronger at-send-site
1920 // invariant does not hold.
1921 //
1922 // The instant is the iteration's own `at_` throughout, never re-read from the clock, so a poll that
1923 // took a second does not move the session boundary mid-iteration.
1924 void install_phase(IterationReport& iteration) {
1925 iteration.phase_ = phase_at(iteration.at_);
1926 // Recorded here rather than derived later, and it outlives a `run` for the same reason `announced_`
1927 // does: "this loop has never known the phase" is a claim about the loop, not about one call.
1928 if (iteration.phase_ != strategy::MarketPhase::UNKNOWN) {
1929 phase_ever_known_ = true;
1930 }
1931 runner_->context().set_phase(iteration.phase_);
1932 }
1933
1934 // Returns the phase at `at`, from whatever calendar has arrived and either the hours it states or the
1935 // configured window.
1936 //
1937 // A source declaring `states_calendar_sessions` gets the phase from the calendar's hours, as instants: the gap
1938 // between two consecutive stated days is `POST_CLOSE` or `CLOSED` even across unlisted dates, and an instant
1939 // the hours do not decide is `UNKNOWN`.
1940 //
1941 // Otherwise the composition `ReplayClock` already performs, with a polled calendar in place of a replay's
1942 // per-bar answer. An uncovered date is `UNKNOWN` and never "closed": `TradingCalendar` draws that
1943 // distinction because assuming closed stops a strategy on a day that is in fact open, and assuming
1944 // open lets one order into a holiday. The date is the *market's*, not this process's. `SessionWindow` owns
1945 // the offset and derives both answers from it, so the day the calendar is asked about and the day the
1946 // session boundaries are computed for cannot disagree.
1947 //
1948 // An undeclared source over a calendar with hours is `UNKNOWN`: the window would put a broker that states
1949 // its own hours on KRX's.
1950 strategy::MarketPhase phase_at(std::chrono::system_clock::time_point at) const {
1951 const auto& calendar = runner_->context().calendar();
1952 if constexpr (source_states_calendar_sessions<Source>::value) {
1953 return strategy::stated_session_phase(calendar, at);
1954 } else {
1955 if (undeclared_hours()) {
1957 }
1958 return session_window_.phase(at, calendar.is_trading_day(session_window_.local_date(at)));
1959 }
1960 }
1961
1962 // Whether the source does not declare `states_calendar_sessions` but the installed calendar states hours on an
1963 // open day: the contradiction `phase_at` refuses to resolve.
1964 bool undeclared_hours() const {
1965 if constexpr (source_states_calendar_sessions<Source>::value) {
1966 return false;
1967 } else {
1968 const auto& days = runner_->context().calendar().days_;
1969 return std::any_of(days.begin(), days.end(), [](const TradingDay& day) {
1970 return day.open_ && day.regular_.has_value();
1971 });
1972 }
1973 }
1974
1975 // The clause naming unreadable calendar rows, or nothing when there were none.
1976 //
1977 // A row whose date the broker sent unreadably is dropped, so the day it was for is uncovered and
1978 // the note above would otherwise send an operator to check a span or a broker that is fine. The
1979 // count says the broker *did* answer, and what it answered could not be read.
1980 std::string unreadable_calendar_rows() const {
1981 const auto unreadable = runner_->context().calendar().unreadable_days_;
1982 if (unreadable == 0) {
1983 return {};
1984 }
1985 return "; the broker sent " + std::to_string(unreadable) + " calendar row" + (unreadable == 1 ? "" : "s") +
1986 " whose date could not be read";
1987 }
1988
1989 // Says so when a run never established the phase, and names which reason applies.
1990 //
1991 // Silent otherwise, like `note_sellable_convention`: a line on every healthy run is how a report
1992 // stops being read. But a run that placed nothing because the phase was never known must not look
1993 // like a quiet market -- and this is **not** a hold on the guard, deliberately. A hold would also
1994 // stop cancellations, which `Runner::send_cancel` refuses on any blocking reason while never
1995 // consulting the phase at all; taking one because a reference-data poll failed would make an
1996 // unknown phase more restrictive than a closed one, and a withdrawal only ever reduces exposure.
1997 // `RiskGuard` already refuses every placement that opens or increases a position with
1998 // `PHASE_NOT_PERMITTED`, and permits one that closes a held position -- which is exactly what a
1999 // hold would wrongly stop, for the same reason it would wrongly stop a cancellation.
2000 void note_unestablished_phase(LoopReport& report) const {
2001 if (report.iterations_ == 0 || report.final_phase_ != strategy::MarketPhase::UNKNOWN) {
2002 return;
2003 }
2004 // **"Never" is a claim, so it is tracked rather than derived.** A loop can establish the phase and
2005 // then lose it -- the local date rolls past what the calendar covers, or the broker revises it --
2006 // and telling an operator it was never established would send them looking for a configuration
2007 // fault that is not there.
2008 //
2009 // This used to read `report.phase_transitions_ > 0`, which was wrong: `announced_`
2010 // outlives a `run` while the report's counter restarts at zero, so a run with nothing left to
2011 // announce reports no transitions and would claim the phase had never been known -- of a loop that
2012 // spent its first run open. The verdict was right in the case that was tested and the reasoning was
2013 // wrong, which is the worse of the two.
2014 const bool ever_known = phase_ever_known_;
2015 // "The poll never came due" is not among the reasons, because it is unreachable: `run` resets
2016 // `next_due_`, so a configured cadence makes the calendar due on the first iteration of every
2017 // run. A branch describing a state that cannot happen is worse than no branch, because a reader
2018 // who sees it believes it can.
2019 std::string reason;
2020 if (undeclared_hours()) {
2021 // First: the calendar outlives failed polls and runs, so this can hold whatever else does.
2022 reason =
2023 "the calendar states session hours but the source does not declare states_calendar_sessions; declare it, "
2024 "or forward it from the SessionSource it wraps";
2025 } else if (!schedule_.calendar_) {
2026 reason = "no calendar cadence is configured";
2027 } else if (report.failed(PollKind::CALENDAR) == report.attempted(PollKind::CALENDAR)) {
2028 reason = "every calendar poll failed";
2029 } else if (runner_->context().calendar().days_.empty()) {
2030 // What the loop can actually tell: a poll reported success and no calendar arrived. It does
2031 // **not** claim to know why, because it cannot distinguish a broker that publishes none -- where
2032 // the request is not even compiled -- from a source that fetched one and installed nothing.
2033 reason = "a calendar poll succeeded but no calendar arrived (this broker may publish none)";
2034 reason += unreadable_calendar_rows();
2035 } else if (source_states_calendar_sessions<Source>::value) {
2036 reason = "the calendar's session hours do not decide " + format_iso8601_utc(last_.at_);
2037 reason += unreadable_calendar_rows();
2038 } else {
2039 // Named, not merely called uncovered. "The calendar does not cover today" sends a reader to
2040 // check a span they cannot see; the date is the one thing that turns this note into an action.
2041 const auto date = session_window_.local_date(last_.at_);
2042 reason = "the calendar does not cover " + std::to_string(date.year_) + "-" + std::to_string(date.month_) + "-" +
2043 std::to_string(date.day_);
2044 reason += unreadable_calendar_rows();
2045 }
2046 report.notes_.push_back(
2047 std::string(
2048 ever_known ? "the market phase stopped being established (" : "the market phase was never established ("
2049 ) +
2050 reason + "); a guard permitting only known phases refused every placement opening a position" +
2051 (ever_known ? " after that" : "")
2052 );
2053 }
2054
2055 // Attempts the startup order-list read once, and returns whether it succeeded.
2056 //
2057 // The startup gate's read and a pending stop's both come here, so the two cannot drift apart.
2058 bool read_order_list_once(std::chrono::system_clock::time_point at, LoopReport& report) {
2059 // Watched like a poll, because it is the same kind of thing: a call into the source, from which a
2060 // source that revised the calendar and sent would reach the identical hazard through a different
2061 // door. The phase in force here is the one `step` installed immediately before calling this.
2062 const auto watch = PhaseWatch{at, phase_at(at), runner_->guard().total_sent()};
2063 // As in `step`, and here the startup read dispatches nothing at all -- but the count is taken
2064 // before the call for the same reason, so that the rule holds positionally rather than by an
2065 // argument about which reads can send.
2066 const auto placements_before_read = runner_->placements_at_broker();
2067 const auto outcome = source_->read_order_list(*runner_);
2068 // The working-order endpoint, where the source has one: a closing wait counts this as asking it.
2069 working_asked_at_ = clock_.monotonic_now();
2070 note_revised_phase("order-list read", watch, report);
2071 if (outcome != PollOutcome::UPDATED && outcome != PollOutcome::UNCHANGED) {
2072 return false;
2073 }
2074 order_list_read_ = true;
2075 report.order_list_read_ = true;
2076 order_list_at_ = at;
2077 // The startup read is a working-order read *on a source that has the inquiry*. On one that
2078 // does not, it reads order history for the journal and never populates `working_`, so
2079 // `note_working_orders_read` deliberately does nothing and a closing pass stays unverified.
2080 note_working_orders_read(at, placements_before_read);
2081 return true;
2082 }
2083
2084 // Returns which of the loop's *own* conditions blocks sending, reading the order list if due.
2085 //
2086 // Only conditions the loop computes, because a hold is released by whoever took it. `OPERATOR`
2087 // belongs to a person and `LOCAL_FAILURE` to the runner; a loop that took either would be a
2088 // second holder of someone else's hold -- the defect `HaltReason` exists to prevent,
2089 // reintroduced one layer up.
2090 //
2091 // **Always evaluated, even while someone else's hold stands.** Short-circuiting on a foreign hold
2092 // would leave the loop's own hold un-maintained underneath it, so the moment an operator resumed,
2093 // the guard would be wide open against a portfolio nobody had rechecked.
2094 //
2095 // Called twice per iteration -- before the polls, which is what actually protects anything, and
2096 // after them so the report is current. `may_read` is false on the second call so the order-list
2097 // read is attempted at most once per iteration.
2098 std::optional<strategy::HaltReason> gate_for(
2099 StopSource& stop, std::chrono::system_clock::time_point at, LoopReport& report, bool may_read
2100 ) {
2101 if (stop.requested()) {
2102 // **A withdraw or a flatten reads the broker's order list first, if it never has.** Each builds
2103 // its instructions from the picture, and a stop pending before the first iteration -- a process
2104 // started with `flatten` in its control file -- used to return here before the startup read, so
2105 // its closing pass was unverified and a flatten closed nothing, for any position. That also left
2106 // no way to flatten a position behind a resting stop: the in-process flatten withdraws the stop
2107 // and, rightly, sends nothing beside it, and the restart that should finish the job could not.
2108 // The read is the startup gate's own, under its conditions; a quiesce sends nothing and needs no
2109 // picture, so it does not spend the request.
2110 //
2111 // **`STOPPING` on every path, the failed read included.** `ORDER_LIST_UNREAD` lets reducing
2112 // orders through (`halt_blocks`), and nothing but the stop's own may go out once one is pending.
2113 // Held before the read as well, because the source is a template parameter and may feed.
2114 const auto intent = stop.intent();
2115 // Once a stop is waiting, on the wait's own floor: a read that failed is not asked again at
2116 // every tick. The iteration that takes the stop up reads as any other.
2117 const bool on_the_floor = !closing_ || !asked_within_floor(PollKind::WORKING_ORDERS);
2118 if (
2119 intent && stop_intent_closes(*intent) && !order_list_read_ && may_read && on_the_floor &&
2120 !runner_->guard().halted(strategy::HaltReason::LOCAL_FAILURE)
2121 ) {
2123 read_order_list_once(at, report);
2124 }
2126 }
2127 if (!order_list_read_) {
2128 // Not attempted when the caller says not to, and not attempted at all while the runner's
2129 // journal is broken: a runner that cannot record what it does must not be sent looking for
2130 // more work to fail at. Either way the gate stands, which is the safe answer.
2131 //
2132 // `STOPPING` rather than `ORDER_LIST_UNREAD` on each path here while an order nobody can account
2133 // for is past the limit (below): the stronger hold, which also refuses a withdrawal, must not be
2134 // traded for the weaker one because a read failed. And held before the read, since the source is
2135 // a template parameter and its read may feed.
2136 const bool owed = owed_past_limit(clock_.now());
2138 if (!may_read || runner_->guard().halted(strategy::HaltReason::LOCAL_FAILURE)) {
2139 return unread;
2140 }
2141 if (owed) {
2143 } else if (const auto configured = buying_power_configuration_hold(report)) {
2144 // A source that reports no buying power is held before its read, which may feed and place.
2145 hold(*configured);
2146 }
2147 if (!read_order_list_once(at, report)) {
2148 return unread;
2149 }
2150 }
2151 // **An order nobody can account for, owed too long, stops the run's placements**
2152 // (`set_owed_order_limit`), in two steps. Once the limit has passed on the clock, this gate holds
2153 // `STOPPING`; it is evaluated before every poll, so an order-list read that begins after a check
2154 // that found the limit passed, and whatever its handlers ask for, runs under the hold (what was
2155 // already under way at the limit runs on the check before it). Once a read in an iteration that
2156 // began after the limit has succeeded and left the order unaccounted for, the stop is requested:
2157 // that iteration's every check found the limit passed, so that read ran under the hold. A read
2158 // whose sweep names the order lifts the hold instead.
2159 if (auto owed = owed_too_long()) {
2160 report.notes_.push_back(owed_stop_note(*owed));
2161 report.owed_stop_ = std::move(owed);
2162 stop.request(StopIntent::QUIESCE);
2164 }
2165 if (owed_past_limit(clock_.now())) {
2167 }
2168 // Measured from the snapshot's own `as_of_` rather than from when the poll returned, because
2169 // that is when the broker says the positions were true. A poll that succeeded at noon carrying
2170 // a snapshot the broker took at 11:00 is an hour stale, and the poll's own timestamp would call
2171 // it fresh.
2172 const auto as_of = runner_->context().portfolio().as_of_;
2173 if (as_of == std::chrono::system_clock::time_point{}) {
2174 // A default-constructed `Portfolio` carries the epoch, and no broker ever reports a snapshot
2175 // taken in 1970, so the epoch means **never populated** -- which is not the same as old, and
2176 // is the more dangerous of the two: an empty portfolio is the *permissive* answer to every
2177 // question the send path asks it, so a run that has never read the account sizes an entry as
2178 // though it were flat.
2179 //
2180 // **No longer inside the age check.** It was, and hoisting it was not a one-line change:
2181 // the hold would reach cancellations, and an order that cannot be withdrawn keeps resting and
2182 // can fill. That objection is answered rather than avoided -- `strategy::halt_blocks` lets a
2183 // named withdrawal through a hold that only means this runner is uninformed, and
2184 // `Runner::plan_withhold_reason` stops the *derived* cancellation that objection overlooked.
2185 //
2186 // The opt-out reaches the age comparison below as well, not just this hold. The epoch is 1970
2187 // and therefore older than any bound an operator would state, so an absence opt-out that did
2188 // not skip the comparison would simply move the refusal to `PORTFOLIO_STALE`.
2189 if (!allow_absent_portfolio_) {
2191 }
2192 // Opted out, so the age comparison is skipped rather than fallen through to -- and the checks
2193 // after this one still run, because an absent portfolio says nothing about buying power.
2194 }
2195
2196 // **A run must state how old a snapshot may be, or state that it accepts any age.**
2197 //
2198 // This was optional, and optional meant that a run which never thought about holdings sent
2199 // orders sized against whatever the portfolio happened to contain -- including nothing at all.
2200 // Fail-open by default was the defect. The library states no default
2201 // duration of its own, because any constant it picked would be a risk policy it has no basis
2202 // for: how stale a position may be before it must not be sized against is the operator's
2203 // judgement about their own market and cadence, not this library's.
2204 // **Checked after absence, not before it.** Both can be true at once, and "you have never read
2205 // this account" is the more useful of the two to be told: the missing policy is a configuration
2206 // fact the note below states in full, while absence is a fact about the data every ceiling and
2207 // every target subtraction is about to be measured against.
2208 if (!maximum_portfolio_age_ && !allow_unbounded_portfolio_age_) {
2209 if (!said_no_age_policy_) {
2210 said_no_age_policy_ = true;
2211 report.notes_.emplace_back(
2212 "no portfolio age policy: call set_maximum_portfolio_age or allow_unbounded_portfolio_age"
2213 );
2214 }
2216 }
2217 if (
2218 maximum_portfolio_age_ && as_of != std::chrono::system_clock::time_point{} && at - as_of > *maximum_portfolio_age_
2219 ) {
2221 }
2222 // **A runner that keeps its orders until the broker accounts for them needs the listing.** A holdings
2223 // poll refreshes positions and keeps `working_`; only a working-order poll replaces it. A runner
2224 // that sends to a broker keeps each order it sent in `working_` until that listing arrives
2225 // (`Runner::persist_reservation`), so with no listing -- none published, none polled, or one
2226 // older than the policy -- an order that expired or was refused would stay "working" for ever,
2227 // a target would stop being chased, and a filled one would be cancelled again on every pass.
2228 // Held, with the missing piece named once, whatever the portfolio age policy: opting out of a
2229 // holdings age is not opting out of a listing.
2230 if constexpr (runner_keeps_sent_orders<Runner>::value) {
2231 if (const auto missing = listing_missing(at)) {
2232 if ((said_listing_ & missing->first) == 0) {
2233 said_listing_ |= missing->first;
2234 report.notes_.emplace_back(missing->second);
2235 }
2237 }
2238 }
2239 if constexpr (!source_reports_buying_power<Source>::value) {
2240 return buying_power_configuration_hold(report);
2241 }
2242 if (runner_->guard().limits().enforce_buying_power_) {
2243 // Checked only when the caller asked for the limit. A loop with no buying-power cadence and
2244 // no check configured is an ordinary loop, and must not be held for a reading nobody wants.
2245 if (const auto unread = buying_power_unread(at)) {
2246 return *unread;
2247 }
2248 }
2249 return std::nullopt;
2250 }
2251
2252 // Returns whether some budget the run needs is missing or too old to size against.
2253 //
2254 // **Every configured currency must have its own fresh reading**, not merely one of them. A source
2255 // that names its currencies is asked, because an account trading two and answering for one is a
2256 // partial answer: the per-order guard would still refuse the unread currency, but the loop would
2257 // go on reporting an open gate while a budget it was told to watch never arrived at all.
2258 //
2259 // A source that names none falls back to "any reading at all", which is the most the loop can
2260 // check without knowing what was asked for.
2261 std::optional<strategy::HaltReason> buying_power_unread(std::chrono::system_clock::time_point at) const {
2262 const auto& readings = runner_->context().portfolio().buying_power_;
2263 // Aged against the reading's own stamp, for the same reason the portfolio is: a figure that
2264 // arrived an hour ago is an hour old however recently the poll succeeded.
2265 const auto usable = [&](const BuyingPower& reading) {
2266 return !maximum_buying_power_age_ || at - reading.received_at_ <= *maximum_buying_power_age_;
2267 };
2268 if constexpr (source_names_buying_power_currencies<Source>::value) {
2269 const auto& wanted = source_->buying_power_currencies();
2270 if (!wanted.empty()) {
2271 for (const auto& currency : wanted) {
2272 bool found = false;
2273 for (const auto& reading : readings) {
2274 if (reading.cash_.currency_ == currency && usable(reading)) {
2275 found = true;
2276 break;
2277 }
2278 }
2279 if (!found) {
2281 }
2282 }
2283 return std::nullopt;
2284 }
2285 }
2286 if (readings.empty()) {
2288 }
2289 for (const auto& reading : readings) {
2290 if (!usable(reading)) {
2292 }
2293 }
2294 return std::nullopt;
2295 }
2296
2297 // The hold over a source that reports no buying power (or does not say): the run budget is then the only
2298 // figure that bounds a buy, and a reading for `enforce_buying_power_` never arrives
2299 // (`live::SessionSource::poll_buying_power`). `BUYING_POWER_UNREAD` without a budget, or with one while
2300 // `enforce_buying_power_` is on; nothing otherwise, and nothing for a source that reports it, which compiles
2301 // none of this. Installed before every call into the source and kept through a stop's closing pass.
2302 std::optional<strategy::HaltReason> buying_power_configuration_hold(LoopReport& report) {
2303 if constexpr (source_reports_buying_power<Source>::value) {
2304 (void)report;
2305 return std::nullopt;
2306 } else {
2307 constexpr bool declared = loop_detail::source_declares_buying_power<Source>::value;
2308 const auto& limits = runner_->guard().limits();
2309 if (!limits.run_budget_) {
2310 say_buying_power_once(
2311 1U, report,
2312 declared ?
2313 "the broker reports no buying power: set RiskLimits::run_budget_, the run's starting cash" :
2314 "the source does not declare reports_buying_power: declare or forward it, or set run_budget_"
2315 );
2317 }
2318 if (limits.enforce_buying_power_) {
2319 say_buying_power_once(
2320 2U, report,
2321 declared ?
2322 "the broker reports no buying power: turn enforce_buying_power_ off; run_budget_ limits buys" :
2323 "the source does not declare reports_buying_power: declare or forward it for enforce_buying_power_"
2324 );
2326 }
2327 return std::nullopt;
2328 }
2329 }
2330
2331 // Adds a configuration note once per loop; `bit` names which.
2332 void say_buying_power_once(unsigned bit, LoopReport& report, const char* note) {
2333 if ((said_buying_power_ & bit) == 0) {
2334 said_buying_power_ |= bit;
2335 report.notes_.emplace_back(note);
2336 }
2337 }
2338
2339 // Sets how old a buying-power reading may be before the gate closes on it.
2340public:
2353 void set_maximum_buying_power_age(std::chrono::nanoseconds age) {
2354 maximum_buying_power_age_ = age;
2355 }
2356
2357private:
2358 // Reads the control file, escalating `stop` when it names an intent.
2359 void check_control_file(StopSource& stop, LoopReport& report) {
2360 if (!control_.enabled()) {
2361 return;
2362 }
2363 if (const auto intent = control_.poll()) {
2364 stop.request(*intent);
2365 return;
2366 }
2367 if (!control_.unrecognized().empty()) {
2368 // Reported rather than guessed at, because picking the nearest intent would decide how much of
2369 // an operator's position to close on their behalf.
2370 report.notes_.push_back("control file names no intent: '" + control_.unrecognized() + "'");
2371 }
2372 }
2373
2374 // Counts an outcome, and abandons the run when one kind keeps failing.
2375 void note_outcome(PollKind kind, PollOutcome outcome, LoopReport& report) {
2376 const int at = static_cast<int>(kind);
2377 if (outcome == PollOutcome::FAILED) {
2378 ++report.failed_[at];
2379 ++consecutive_failures_[at];
2380 if (consecutive_failures_[at] >= failure_policy_.consecutive_limit_) {
2381 report.abandoned_ = true;
2382 report.abandoned_kind_ = kind;
2383 report.notes_.push_back(
2384 std::string("gave up after repeated failures polling ") + std::string(poll_kind_name(kind))
2385 );
2387 }
2388 return;
2389 }
2390 switch (outcome) {
2392 // Counted above.
2393 return;
2395 // The limiter working says nothing either way, so the count stands: a kind alternating
2396 // failure and refusal is still broken.
2397 return;
2400 // A poll that answered, with something new or with nothing new, ends a run of failures.
2401 consecutive_failures_[at] = 0;
2402 return;
2403 }
2404 }
2405
2406 // Enters a stop, once per run: the hold, the strategy's notice, and the end of whatever it had pending.
2407 // A stop that closes may then wait (`closing_should_wait`) before `finish_stop` builds its pass.
2408 void begin_stop(LoopReport& report) {
2409 closing_ = ClosingWait{};
2410 closing_->began_ = clock_.monotonic_now();
2411 closing_->deadline_ = closing_->began_ +
2412 std::chrono::duration_cast<std::chrono::steady_clock::duration>(
2413 closing_wait_ > std::chrono::nanoseconds::zero() ? closing_wait_ : std::chrono::nanoseconds::zero()
2414 );
2416 // Whenever the stop was requested -- before the iteration or during one of its polls -- nothing
2417 // retained before it is to be replayed after it, by this run or a resumed one. A target waiting on
2418 // a resting stop is the same kind of work.
2419 runner_->clear_retained_targets();
2420 runner_->clear_deferred_targets();
2421
2422 // **The strategy is told first, and cannot trade on the way out.** `on_stop` is dispatched here,
2423 // while the hold stands, so every instruction it asks for is refused by the guard and counted.
2424 // It must not be dispatched later: from the moment the loop queues its own closing orders, a
2425 // strategy's order would be planned against the same snapshot and settled in the same window,
2426 // going through none of the sizing the closing pass does -- a second full-size close beside the
2427 // first, or a placement during a `WITHDRAW`, which promises none.
2428 // **Not watched, and it does not need to be.** `on_stop` runs with a mutable context and can revise
2429 // the calendar like any other handler, but `hold(STOPPING)` above is already in force, so every
2430 // instruction it asks for is refused before anything is sent -- which `stop_handler_sent_` asserts as
2431 // a report field precisely so that ordering cannot be broken silently. The revision it may have made
2432 // *is* answered, one call later: the closing derive below picks it up.
2433 //
2434 // For the record, the complete list of calls this loop makes out of itself is: `source_->poll`,
2435 // `source_->read_order_list`, `source_->buying_power_currencies` (a const accessor that is handed no
2436 // runner and so can neither feed nor write a calendar), `runner_->observe_sellable_convention` (which
2437 // reads the portfolio and dispatches nothing), this one, and `settle_closing`. The two that can send
2438 // under a phase are watched.
2439 const auto parting = runner_->notify_stop();
2440 // `withheld_plans_` counts here for the same reason it counts in `Report::quiet`: an `on_stop`
2441 // handler may state a target, `STOPPING` is held by then, and a plan that would have cancelled
2442 // something is withheld whole. Left out of this total, the loop would report that a parting
2443 // instruction met no resistance while the instruction never went anywhere.
2444 report.stop_handler_refused_ = parting.refused_.size() + parting.refused_cancel_.size() + parting.rejected_.size() +
2445 parting.withheld_.size() + parting.withheld_plans_.size() + parting.unavailable_.size();
2446 report.stop_handler_sent_ = parting.would_place_.size() + parting.would_cancel_.size();
2447 }
2448
2449 // Leaves the runner unable to send when a run is abandoned with a stop pending, and says the stop's
2450 // closing pass did not run. The abandonment took `POLL_FAILING`, under which a named withdrawal still
2451 // goes; a stop asked for more than that.
2452 void interrupt_stop(StopIntent intent, LoopReport& report) {
2454 // The stop may never have been taken up (`begin_stop`): a target waiting on a resting stop order is
2455 // not to go out after it either.
2456 runner_->clear_deferred_targets();
2457 report.stopped_by_ = intent;
2458 if (closing_) {
2459 report.closing_waited_ =
2460 std::chrono::duration_cast<std::chrono::nanoseconds>(clock_.monotonic_now() - closing_->began_);
2461 }
2462 if (stop_intent_closes(intent)) {
2463 report.closing_interrupted_ = true;
2464 report.notes_.push_back(
2465 std::string("the run was abandoned for failing polls with a ") + std::string(stop_intent_name(intent)) +
2466 " pending: its closing pass did not run, nothing was withdrawn or closed by it, and the runner is"
2467 " left unable to send; read the broker's order list and holdings"
2468 );
2469 }
2470 }
2471
2472 // Carries out `intent`, which is where the three stops actually differ.
2473 void finish_stop(StopIntent intent, LoopReport& report) {
2474 report.closing_waited_ =
2475 std::chrono::duration_cast<std::chrono::nanoseconds>(clock_.monotonic_now() - closing_->began_);
2476 closing_->reads_wanted_ = false;
2477 if (!stop_intent_closes(intent)) {
2478 return;
2479 }
2480 // **Whatever a strategy queued without settling goes nowhere.** The closing instructions below are
2481 // settled with the loop's hold lifted, and anything else still on the queue would be settled with
2482 // them. Settled here, under the hold, it is refused like the rest of what a strategy asks during a stop.
2483 {
2484 const auto stale = runner_->settle_closing();
2485 report.stop_handler_refused_ += stale.refused_.size() + stale.refused_cancel_.size() + stale.rejected_.size() +
2486 stale.withheld_.size() + stale.withheld_plans_.size() + stale.unavailable_.size();
2487 report.stop_handler_sent_ += stale.would_place_.size() + stale.would_cancel_.size();
2488 }
2489 // Nothing decided under the hold is kept, so this clears nothing today. It stands so that a change
2490 // to that rule cannot let kept work out with the closing orders below.
2491 runner_->clear_retained_targets();
2492 runner_->clear_deferred_targets();
2493
2494 // **Both intents state their instructions outright rather than expressing them as a target.**
2495 //
2496 // A withdraw always had to: there is no target to reconcile against, so the working orders are
2497 // named one by one. A flatten used to state a zero `TargetPosition` and let reconciliation do
2498 // the cancelling, which was wrong twice over -- reconciliation keeps a resting order that points
2499 // the same way as the target, so the flatten could send nothing at all, and it skipped orders on
2500 // instruments with no position to target. Stating both halves here means one withdrawal per
2501 // resting order, no instruction derived from another, and no case where the two disagree.
2502 //
2503 // Recorded before anything is queued, because it is a statement about the picture the pass is
2504 // built from rather than about any instruction in it.
2505 report.closing_source_unverified_ = !closing_source_verified(clock_.now());
2506
2507 // Sized from what is working, which counts an order this runner sent and holdings do not show yet
2508 // only once that row is rebuilt: a sell that filled while holdings lag is otherwise sold again.
2509 runner_->refresh_unconfirmed();
2510 // Counted before the pass, so its own new orders are not: what a serialized runner owes that no
2511 // listing or holdings explain is exposure this pass cannot withdraw or size around.
2512 report.closing_unconfirmed_ = runner_->obligations_unexplained();
2513 const auto& portfolio = runner_->context().portfolio();
2514 if (!stop_intent_closes_positions(intent)) {
2515 for (const auto& working : portfolio.working_) {
2516 // Already withdrawn by this runner, and the broker took the request: asked again it refuses.
2517 if (runner_->withdrawal_accepted_for(working)) {
2518 continue;
2519 }
2520 runner_->context().cancel(working.ref_, "stop-withdraw");
2521 ++report.withdrawn_;
2522 }
2523 } else {
2524 // **A flatten withdraws everything, then closes only what it cannot double-sell.**
2525 //
2526 // Two ways to get this wrong, and the library has now had both. Expressing the flatten as a
2527 // zero `TargetPosition` lets reconciliation treat a resting same-side order as progress and
2528 // send nothing at all -- a limit sell that may never fill is not being out of the market.
2529 // Sending the *whole* holding instead ignores that order, and since a cancellation is a
2530 // request rather than an outcome, the resting sell can fill while its cancellation is still
2531 // pending: ten long becomes ten short. The second error is much worse than the first, because
2532 // it manufactures a position in the opposite direction rather than leaving the one that was
2533 // already there.
2534 //
2535 // So the close is sized to what cannot double up: the holding minus whatever is still working
2536 // on the same side. Every working order is withdrawn either way, so a cancellation that
2537 // completes leaves part of the position open rather than a resting order nobody is watching,
2538 // and a cancellation that fails because the order filled leaves the account flat. Neither
2539 // outcome can overshoot, and the pass says it could not prove which one happened.
2540 for (const auto& working : portfolio.working_) {
2541 if (runner_->withdrawal_accepted_for(working)) {
2542 continue;
2543 }
2544 runner_->context().cancel(working.ref_, "stop-flatten");
2545 ++report.withdrawn_;
2546 }
2547 // **One close per instrument, sized from the net of its rows.** This looped over rows, and a
2548 // broker reporting one instrument as several lots is ordinary -- so it went wrong twice at
2549 // once. Rows of +100 and -40 are a holding of +60, and it submitted SELL 100 *and* BUY 40:
2550 // outside the session the phase rule refuses both, so the operator's flatten sent nothing
2551 // although SELL 60 was permitted all along. And the deduction below subtracts what is working
2552 // on the closing side, which is a figure for the whole instrument -- subtracted once per row,
2553 // it was charged twice, so rows of +60 and +40 against a working SELL 20 sent 40 and 20 and
2554 // left 20 of the position behind. Neither is reachable once the instrument is the unit.
2555 std::vector<InstrumentId> closed;
2556 for (const auto& position : portfolio.positions_) {
2557 bool seen = false;
2558 for (const auto& already : closed) {
2559 if (already == position.instrument_) {
2560 seen = true;
2561 break;
2562 }
2563 }
2564 if (seen) {
2565 continue;
2566 }
2567 closed.push_back(position.instrument_);
2568
2569 // The net, not this row. A snapshot whose rows will not add up cannot say what flattening
2570 // would take, and guessing is the one thing a closing pass must not do.
2571 const auto net = portfolio.net_quantity_of(position.instrument_);
2572 if (!net) {
2573 // **Not `closing_contended_`.** That one means a competing order, and its note sends an
2574 // operator to the order list. What failed here is the holding's own arithmetic.
2575 ++report.closing_unsizable_;
2576 continue;
2577 }
2578 if (net->coefficient() == 0) {
2579 // Flat on the net, however many rows say so. A closed position can sit in a snapshot at
2580 // zero, and two rows can cancel; an order for none of it is one the broker would reject,
2581 // for nothing.
2582 continue;
2583 }
2584 if (report.closing_source_unverified_) {
2585 // **Nothing is placed against a listing that cannot be trusted.** The deduction below
2586 // subtracts what is *known* to be working on the closing side, and an unverified picture
2587 // is precisely one where that is not all of it: an order this runner sent after the last
2588 // listing, or a source that cannot enumerate orders at all. Sending a full-size close
2589 // beside an order nobody can see is the same double sell, reached by a different door --
2590 // and reporting it afterwards does not recall the instruction.
2591 //
2592 // The withdrawals above still went, because cancelling only ever reduces exposure. What
2593 // is left is the position, held and reported, which is the safe end of every branch here.
2594 ++report.closing_contended_;
2595 continue;
2596 }
2597 const bool held_long = decimal_less(Decimal64{}, *net);
2598 const auto magnitude = held_long ? std::optional<Decimal64>(*net) : decimal_subtract(Decimal64{}, *net);
2599 if (!magnitude) {
2600 // **A representable net can have no representable magnitude**: two rows summing to the
2601 // most negative `Decimal64` have no positive counterpart, so the size of the buy that
2602 // would close them cannot be stated. This used to `continue` in silence, which moved no
2603 // count -- so `closing_complete()` returned true over a position the pass had never
2604 // sized, which is the one thing that call promises it will not do.
2605 ++report.closing_unsizable_;
2606 continue;
2607 }
2608 const OrderSide closing_side = held_long ? OrderSide::SELL : OrderSide::BUY;
2609 const auto contending = portfolio.working_quantity(position.instrument_, closing_side);
2610 const auto sendable = decimal_subtract(*magnitude, contending);
2611 if (!sendable) {
2612 // The same silence for the same reason: a size that cannot be computed is not a size of
2613 // zero, and a pass that skipped it did not knowingly send nothing. **Unlike the two cases
2614 // above, this one can fail with both inputs representable** -- a held magnitude and a
2615 // working quantity whose scales cannot be aligned -- which is why the note names the
2616 // working orders as well as the holdings.
2617 ++report.closing_unsizable_;
2618 continue;
2619 }
2620 if (contending.coefficient() != 0) {
2621 // Sized down, and the reduction is a fact about what this pass could not establish rather
2622 // than about what the operator asked for. Counted so `closing_complete()` cannot claim a
2623 // flatten that may have left part of the position open.
2624 ++report.closing_contended_;
2625 }
2626 if (decimal_less(*sendable, Decimal64{}) || sendable->coefficient() == 0) {
2627 // Everything held is already working on the closing side. Sending anything at all here is
2628 // the over-close, so the withdrawal above is the whole of this instrument's flatten.
2629 continue;
2630 }
2631 runner_->context().submit(
2632 strategy::OrderIntent::market(position.instrument_, closing_side, strategy::SizeSpec::quantity(*sendable))
2633 .with_tag("stop-flatten")
2634 );
2635 ++report.flattened_;
2636 }
2637 }
2638
2639 // Lifted so the closing instructions can actually go out -- a withdraw that cannot send is not a
2640 // withdraw -- and closed again immediately afterwards. The window is exactly one `stop()` call
2641 // wide, and it is the only point at which a stop in progress can send anything.
2642 //
2643 // Only the loop's *own* hold lifts. An operator who halted by hand, or a runner whose journal
2644 // failed, still refuses every closing instruction -- placements through `RiskGuard::check` and
2645 // cancellations through the same holds in `Runner::send_cancel` -- and the closing counts say
2646 // so, so `closing_complete()` is false and the notes say the position is still held. A stop
2647 // arriving by signal or control file therefore cannot send anything through a halt somebody had
2648 // already set. Over a source that reports no buying power, the configuration's hold stays
2649 // (`buying_power_configuration_hold`): a closing placement is refused while a withdrawal still goes.
2650 hold(buying_power_configuration_hold(report));
2651 // **Derived once more, immediately before the only call that can send during a stop.** `on_stop` ran
2652 // a few lines above with a mutable context, so it may have revised the calendar -- and unlike a
2653 // strategy's write inside `on_phase`, this one the loop *can* answer, because `settle_closing` is a
2654 // separate call it makes itself. Without this, a handler that revised the calendar to closed
2655 // saw the flatten go out under the `OPEN` it replaced.
2656 //
2657 // At `clock_.now()` rather than the iteration's instant, because a stop is honoured after the
2658 // iteration and a closing pass should be checked against the session as it is now.
2659 const auto closing_at = clock_.now();
2660 runner_->context().set_phase(phase_at(closing_at));
2661 const auto watch = PhaseWatch{closing_at, phase_at(closing_at), runner_->guard().total_sent()};
2662 const auto closing = runner_->settle_closing();
2663 note_revised_phase("closing pass", watch, report);
2665 // What the pass itself caused to be kept (a close the phase or the broker's hours refused) is not to
2666 // go out later either: a stop makes each request once.
2667 runner_->clear_retained_targets();
2668 runner_->clear_deferred_targets();
2669
2670 report.closing_placed_ = closing.would_place_.size();
2671 // **Both halves of every bucket.** A closing instruction is a placement or a cancellation, and
2672 // each can fail in the same five ways; counting only the placement half is how a stop that sent
2673 // nothing reported itself complete.
2674 report.closing_rejected_ = closing.rejected_.size() + closing.rejected_cancel_.size();
2675 report.closing_refused_ = closing.refused_.size() + closing.refused_cancel_.size();
2676 // Whole plans too: a serialized runner withholds a closing order's plan while the instrument owes one.
2677 report.closing_withheld_ = closing.withheld_.size() + closing.withheld_plans_.size();
2678 report.closing_indeterminate_ = closing.indeterminate_.size() + closing.indeterminate_cancel_.size();
2679 report.closing_unavailable_ = closing.unavailable_.size() + closing.unavailable_cancel_.size();
2680 report.closing_unresolved_ = closing.unresolved_cancel_.size();
2681
2682 // Named individually rather than summarized, because "your flatten did not go out" is the one
2683 // note in this whole report an operator must not have to infer.
2684 if (!closing.refused_.empty() || !closing.refused_cancel_.empty()) {
2685 report.notes_.push_back(
2686 "a guard refused " + std::to_string(report.closing_refused_) +
2687 " closing instruction(s); the position is still held"
2688 );
2689 }
2690 if (!closing.rejected_.empty()) {
2691 // Deliberately does not name who decided. The bucket holds three things -- reconciliation
2692 // could not build the instruction, the broker refused it, or the binding refused to send it
2693 // -- and an operator reading a stop report needs the consequence, which is the same for all
2694 // three. The report's own entries carry which it was, on `RejectReason` for a placement and
2695 // on `by_broker_` for a cancellation.
2696 report.notes_.push_back(
2697 std::to_string(closing.rejected_.size()) + " closing instruction(s) were not placed; the position is still held"
2698 );
2699 }
2700 if (!closing.rejected_cancel_.empty()) {
2701 report.notes_.push_back(
2702 std::to_string(closing.rejected_cancel_.size()) +
2703 " closing cancellation(s) were refused; read the broker's order list for their state"
2704 );
2705 }
2706 if (report.closing_withheld_ != 0) {
2707 report.notes_.push_back(
2708 "withheld " + std::to_string(report.closing_withheld_) +
2709 " closing instruction(s) pending reconciliation, or until an earlier order is accounted for;"
2710 " read the broker's order list"
2711 );
2712 }
2713 if (report.closing_unconfirmed_ != 0) {
2714 report.notes_.push_back(
2715 std::to_string(report.closing_unconfirmed_) +
2716 " order(s) this runner sent were not yet accounted for by holdings or a listing, so the closing pass"
2717 " could not withdraw or size around them; read the broker's order list and holdings"
2718 );
2719 }
2720 if (report.closing_wait_expired_) {
2721 report.notes_.push_back(
2722 "the stop waited " +
2723 std::to_string(std::chrono::duration_cast<std::chrono::seconds>(report.closing_waited_).count()) +
2724 " s for holdings and the order list to account for this runner's orders, or for a marked"
2725 " instrument to be resolved, and that did not happen; the closing pass was built from what was in"
2726 " hand (set_closing_wait)"
2727 );
2728 }
2729 if (report.closing_indeterminate_ != 0) {
2730 report.notes_.push_back(
2731 std::to_string(report.closing_indeterminate_) +
2732 " closing instruction(s) have an unknown outcome; read the broker's order list"
2733 );
2734 }
2735 if (report.closing_unavailable_ != 0) {
2736 report.notes_.push_back(
2737 "local machinery could not send " + std::to_string(report.closing_unavailable_) +
2738 " closing instruction(s); no broker was asked and the position is still held"
2739 );
2740 }
2741 if (report.stop_handler_refused_ != 0) {
2742 report.notes_.push_back(
2743 "the strategy's on_stop asked for " + std::to_string(report.stop_handler_refused_) +
2744 " instruction(s) during the stop; none were sent, because an operator's stop is not a"
2745 " moment for a strategy to trade"
2746 );
2747 }
2748 if (report.closing_contended_ != 0) {
2749 report.notes_.push_back(
2750 report.closing_source_unverified_ ?
2751 "no closing order was sent for " + std::to_string(report.closing_contended_) +
2752 " position(s), because an order this loop cannot see could close them too; they are"
2753 " still held and the withdrawals above are all that went" :
2754 std::to_string(report.closing_contended_) +
2755 " position(s) were closed only for the part no working order was already selling or"
2756 " buying; if those withdrawals succeed, part of the position is still held"
2757 );
2758 }
2759 if (report.closing_unsizable_ != 0) {
2760 // **Names both inputs, because the three causes do not share one.** Two of them are the
2761 // holdings rows alone -- they will not add up, or the net has no representable closing
2762 // magnitude. The third subtracts what is already working on the closing side, and that
2763 // subtraction can fail with both inputs perfectly representable: a held quantity of
2764 // 1,000,000,000,000,000,000 and a working close of 0.1 cannot be aligned. An earlier note
2765 // blamed the holdings snapshot alone and would have sent an operator to check one of two
2766 // inputs. It still does not say "contended", which means a competing order reduced the close;
2767 // here nothing could be sized at all.
2768 report.notes_.push_back(
2769 "no closing order could be sized for " + std::to_string(report.closing_unsizable_) +
2770 " position(s): the holdings quantities would not add up or fit, or could not be combined"
2771 " with what is already working on the closing side; nothing was sent for them and they are"
2772 " still held"
2773 );
2774 }
2775 if (report.closing_source_unverified_) {
2776 report.notes_.push_back(
2777 std::string("the stop could not verify what was outstanding: ") + unverified_source_reason() +
2778 "; orders or positions a previous process left may remain"
2779 );
2780 }
2781 if (report.closing_unresolved_ != 0) {
2782 report.notes_.push_back(
2783 std::to_string(report.closing_unresolved_) +
2784 " closing cancellation(s) named an order the portfolio does not hold; read the broker's"
2785 " order list"
2786 );
2787 }
2788 }
2789
2790 // Takes `gate`'s hold on the guard and releases the one this loop took before it.
2791 //
2792 // There is no "did I halt it" flag any more, and that is the point: the loop names the hold it
2793 // takes and releases only that one, so an operator halting by hand into a loop's closed gate is
2794 // no longer invisible, and the loop reopening its gate no longer lifts their halt with it. The
2795 // hold is released and retaken rather than diffed, because taking a hold is idempotent.
2796 //
2797 // Only the loop's *own* conditions are held. `OPERATOR` belongs to a person and `LOCAL_FAILURE`
2798 // to the runner; both outlive any gate the loop computes, so they are reported and never taken or
2799 // released here.
2800 void hold(std::optional<strategy::HaltReason> gate) {
2801 if (gate && !owns(*gate)) {
2802 gate.reset();
2803 }
2804 if (held_ == gate) {
2805 return;
2806 }
2807 if (held_) {
2808 runner_->guard().resume(*held_);
2809 }
2810 if (gate) {
2811 runner_->guard().halt(*gate);
2812 }
2813 held_ = gate;
2814 }
2815
2816 // Says what is missing for a runner that keeps its sent orders until the broker accounts for them, as a
2817 // note bit and the note, or nothing when the listing is in hand.
2818 std::optional<std::pair<unsigned, std::string>> listing_missing(std::chrono::system_clock::time_point at) const {
2819 if constexpr (!source_provides_working_orders<Source>::value) {
2820 (void)at;
2821 return std::make_pair(
2822 1u,
2823 std::string(
2824 "this runner keeps the orders it sends until a working-order listing or holdings account for "
2825 "them, and the source publishes no listing: placing holds (declare provides_working_orders and "
2826 "poll the listing)"
2827 )
2828 );
2829 } else {
2830 if (!schedule_.working_orders_) {
2831 return std::make_pair(
2832 2u,
2833 std::string(
2834 "no working-order cadence: this runner keeps the orders it sends until a working-order "
2835 "listing or holdings account for them, so placing holds until PollSchedule::working_orders_ "
2836 "is set"
2837 )
2838 );
2839 }
2840 if (maximum_portfolio_age_ && working_orders_at_ && at - *working_orders_at_ > *maximum_portfolio_age_) {
2841 return std::make_pair(
2842 4u,
2843 std::string(
2844 "working-order listing older than the portfolio age policy: poll working orders "
2845 "(PollSchedule::working_orders_) more often than that age, by at least a tick; placing "
2846 "holds until it is read"
2847 )
2848 );
2849 }
2850 return std::nullopt;
2851 }
2852 }
2853
2854 // Returns the oldest order nobody can account for that was sent longer than the limit before `at`: one
2855 // no sweep has named, or one held for an operator (`set_owed_order_limit`). None with the limit off, or
2856 // from a runner that is not serialized.
2857 std::optional<Obligation> owed_longer_than_limit(std::chrono::system_clock::time_point at) const {
2858 std::optional<Obligation> oldest;
2859 if (owed_order_limit_ <= std::chrono::nanoseconds::zero()) {
2860 return oldest;
2861 }
2862 for (auto& owed : runner_->obligations()) {
2863 if (!obligation_is_unaccounted(owed.state_)) {
2864 continue;
2865 }
2866 if (at - owed.sent_at_ > owed_order_limit_ && (!oldest || owed.sent_at_ < oldest->sent_at_)) {
2867 oldest = std::move(owed);
2868 }
2869 }
2870 return oldest;
2871 }
2872
2873 // Whether such an order is past the limit as of `now`: placing is held from here on.
2874 bool owed_past_limit(std::chrono::system_clock::time_point now) const {
2875 return owed_longer_than_limit(now).has_value();
2876 }
2877
2878 // The order the run stops for: one still unaccounted for after the last successful order-list read,
2879 // where that read's iteration began longer after the order's send than the limit (`order_list_at_` is
2880 // the iteration's instant, which is not later than any check made in it). Measured to that read and
2881 // not to now, so that a loop reading the list less often than the limit gives a sweep its chance to
2882 // name the order first. None before the order list was read.
2883 std::optional<Obligation> owed_too_long() const {
2884 if (!order_list_read_ || !order_list_at_) {
2885 return std::nullopt;
2886 }
2887 return owed_longer_than_limit(*order_list_at_);
2888 }
2889
2890 // The note for a run the loop stopped for `owed`.
2891 static std::string owed_stop_note(const Obligation& owed) {
2892 return "stopped placing: the " + std::string(owed.side_ == OrderSide::BUY ? "buy" : "sell") + " of " +
2893 owed.quantity_.str() + " " + owed.instrument_.symbol_ + " sent " + format_iso8601_utc(owed.sent_at_) +
2894 " (journal id " + owed.journal_id_ + ") is still owed, and " +
2895 (owed.state_ == ObligationState::OPERATOR ? "is held for an operator" : "no sweep has found its order") +
2896 ". Nothing was cancelled or closed. Read the broker's order list and holdings for it, then account for "
2897 "it with Runner::release_obligations; until then every start stops here again";
2898 }
2899
2900 // Returns whether a stop that closes should let the loop read again before its pass is built.
2901 //
2902 // True while a read could still give the pass what it lacks and the wait has not reached its limit;
2903 // `STOPPING` is held throughout (`begin_stop`, `gate_for`), so the loop only reads meanwhile: what a
2904 // strategy asks for is refused. See `set_closing_wait` for what it waits for and what it does not.
2905 bool closing_should_wait(StopIntent intent, LoopReport& report) {
2906 if (!stop_intent_closes(intent) || closing_wait_ <= std::chrono::nanoseconds::zero()) {
2907 return false;
2908 }
2909 // A source that lists no working orders can never verify the pass, however long the loop reads:
2910 // waiting would only delay the same result.
2911 if constexpr (!source_provides_working_orders<Source>::value) {
2912 return false;
2913 }
2914 // Under a person's hold or the runner's own, the pass can send nothing whatever the reads show.
2915 if (
2916 runner_->guard().halted(strategy::HaltReason::OPERATOR) ||
2917 runner_->guard().halted(strategy::HaltReason::LOCAL_FAILURE)
2918 ) {
2919 return false;
2920 }
2921 const auto monotonic = clock_.monotonic_now();
2922 report.closing_waited_ = std::chrono::duration_cast<std::chrono::nanoseconds>(monotonic - closing_->began_);
2923 // As the pass does before it counts: an order holdings now show is no longer owed.
2924 runner_->refresh_unconfirmed();
2925 closing_->reads_wanted_ = closing_needs_evidence(clock_.now());
2926 if (!closing_->reads_wanted_) {
2927 return false;
2928 }
2929 if (monotonic >= closing_->deadline_) {
2930 report.closing_wait_expired_ = true;
2931 closing_->reads_wanted_ = false;
2932 return false;
2933 }
2934 return true;
2935 }
2936
2937 // Whether a further read could change what the closing pass would do: the picture it is built from is
2938 // not verified, an order of this runner awaits an account, or an instrument that is held is marked.
2939 bool closing_needs_evidence(std::chrono::system_clock::time_point at) const {
2940 if (!closing_source_verified(at) || runner_->obligations_awaiting_account() != 0) {
2941 return true;
2942 }
2943 // A mark on something held, unless only an operator can lift it. Held by the instrument's net, as the
2944 // pass sizes it; rows that cannot be netted count as held.
2945 const auto& portfolio = runner_->context().portfolio();
2946 for (const auto& position : portfolio.positions_) {
2947 const auto net = portfolio.net_quantity_of(position.instrument_);
2948 if (
2949 (!net || net->coefficient() != 0) && runner_->ledger().requires_reconcile(position.instrument_) &&
2950 !obligation_needs_operator(runner_->obligation_state(position.instrument_))
2951 ) {
2952 return true;
2953 }
2954 }
2955 return false;
2956 }
2957
2958 // Whether a closing wait may read `kind` (working orders or holdings) now: it wants the read, and that
2959 // endpoint was last asked at least `closing_reread_` ago, whoever asked -- the ordinary cadence, the
2960 // startup read, or this wait. The iteration in which the limit passes may still read, like the startup
2961 // read: the pass that follows is built from it, and nothing reads after it.
2962 bool closing_read_due(PollKind kind) const {
2963 if (!closing_ || !closing_->reads_wanted_) {
2964 return false;
2965 }
2966 return !asked_within_floor(kind);
2967 }
2968
2969 // Whether `kind`'s endpoint (working orders or holdings) was last asked less than `closing_reread_` ago.
2970 bool asked_within_floor(PollKind kind) const {
2971 const auto& asked = kind == PollKind::WORKING_ORDERS ? working_asked_at_ : holdings_asked_at_;
2972 return asked && clock_.monotonic_now() - *asked < closing_reread_;
2973 }
2974
2975 // Returns how long a waiting stop sleeps: until the next read it may make, its limit, an ordinary poll
2976 // of another kind, or the tick, whichever is first. The ordinary due times of the two closing reads are
2977 // left out: the wait reads them on its own floor, and an overdue one would otherwise spin the loop.
2978 std::chrono::nanoseconds closing_until_next() const {
2979 auto wait = schedule_.tick_;
2980 const auto wall = clock_.now();
2981 for (const auto kind : all_poll_kinds) {
2982 const auto& due = next_due_[static_cast<int>(kind)];
2983 if (!due || kind == PollKind::WORKING_ORDERS || kind == PollKind::HOLDINGS) {
2984 continue;
2985 }
2986 wait = std::min(wait, std::chrono::duration_cast<std::chrono::nanoseconds>(*due - wall));
2987 }
2988 const auto monotonic = clock_.monotonic_now();
2989 const auto until = [&](std::chrono::steady_clock::time_point when) {
2990 return std::chrono::duration_cast<std::chrono::nanoseconds>(when - monotonic);
2991 };
2992 wait = std::min(wait, until(closing_->deadline_));
2993 for (const auto* asked : {&working_asked_at_, &holdings_asked_at_}) {
2994 wait = std::min(wait, *asked ? until(**asked + closing_reread_) : std::chrono::nanoseconds::zero());
2995 }
2996 return wait > std::chrono::nanoseconds::zero() ? wait : std::chrono::nanoseconds::zero();
2997 }
2998
2999 // Returns whether the loop knows what a closing pass at `at` would have to send.
3000 //
3001 // Two sources, both required. The broker's own order list must have been read once, which is what
3002 // the startup gate exists for, and what a stop requested before the first iteration attempts itself
3003 // (a failed attempt leaves it unread). And the
3004 // holdings snapshot -- which is where a `WITHDRAW`'s working orders and a `FLATTEN`'s positions
3005 // actually come from -- must exist, be within the configured age, and be **no older than the
3006 // working-order listing**: a fill between the two reads leaves the listing before it reaches the
3007 // holdings, so a flatten would see neither the order nor the shares it bought.
3008 bool closing_source_verified(std::chrono::system_clock::time_point at) const {
3009 if (!order_list_read_) {
3010 return false;
3011 }
3012 // The working-order picture is its own source with its own freshness, and `as_of_` is not its
3013 // timestamp: `SessionSource::poll_holdings` refreshes positions and `as_of_` while *keeping* the
3014 // working orders it already had, and only a working-order poll replaces those. So a stop can
3015 // have a snapshot stamped a second ago whose resting orders were last read an hour ago.
3016 if (!working_orders_at_) {
3017 return false;
3018 }
3019 // And the decisive one, which no timestamp catches: an order this runner sent after that read
3020 // cannot be in it. A listing is out of date the moment the next placement is accepted, and an
3021 // indeterminate send counts too, because the order may exist.
3022 if (runner_->placements_at_broker() != placements_at_working_read_) {
3023 return false;
3024 }
3025 if (maximum_portfolio_age_ && at - *working_orders_at_ > *maximum_portfolio_age_) {
3026 return false;
3027 }
3028 const auto as_of = runner_->context().portfolio().as_of_;
3029 if (as_of == std::chrono::system_clock::time_point{}) {
3030 return false;
3031 }
3032 // On one clock: both stamps are the local arrival time of their replies, which
3033 // `working_orders_at_` above is not.
3034 if (runner_->context().portfolio().listing_newer_than_holdings()) {
3035 return false;
3036 }
3037 return !maximum_portfolio_age_ || at - as_of <= *maximum_portfolio_age_;
3038 }
3039
3040 // Records that the working-order picture was just refreshed, with what it could not contain.
3041 //
3042 // Does nothing when the source does not publish working orders, so a stop on such a broker stays
3043 // unverified rather than being told a history read or a no-op poll refreshed a listing it never
3044 // built.
3045 void note_working_orders_read(std::chrono::system_clock::time_point at, std::size_t placements_before_poll) {
3046 if constexpr (source_provides_working_orders<Source>::value) {
3047 working_orders_at_ = at;
3048 order_list_at_ = at;
3049 // **The caller's count, taken before the poll ran.** Reading it here instead would include
3050 // an order an `on_order_update` handler placed *during* the poll -- an order sent after the
3051 // listing was fetched, which the listing therefore cannot contain.
3052 placements_at_working_read_ = placements_before_poll;
3053 } else {
3054 (void)at;
3055 (void)placements_before_poll;
3056 }
3057 }
3058
3059 // Returns which half of the closing source is missing, for the operator's note.
3060 std::string unverified_source_reason() const {
3061 if constexpr (!source_provides_working_orders<Source>::value) {
3062 return "this source does not publish the broker's outstanding orders";
3063 }
3064 if (!order_list_read_ || !working_orders_at_) {
3065 return "the broker's order list has not been read";
3066 }
3067 if (runner_->placements_at_broker() != placements_at_working_read_) {
3068 return "an order was sent after the working orders were last read";
3069 }
3070 if (runner_->context().portfolio().as_of_ == std::chrono::system_clock::time_point{}) {
3071 return "no holdings snapshot has arrived";
3072 }
3073 if (runner_->context().portfolio().listing_newer_than_holdings()) {
3074 return "the holdings were read before the working orders, so a fill between them is in neither";
3075 }
3076 if (maximum_portfolio_age_ && clock_.now() - *working_orders_at_ > *maximum_portfolio_age_) {
3077 return "the working orders were read longer ago than the configured maximum";
3078 }
3079 return "the holdings snapshot is older than the configured maximum";
3080 }
3081
3082 // Calls the data poll and feeds each record it returns, known at `at`.
3083 PollOutcome poll_data(std::chrono::system_clock::time_point at) {
3084 if constexpr (Runner::takes_records) {
3085 auto records = data_poll_(at);
3086 if (!records) {
3087 return PollOutcome::FAILED;
3088 }
3089 if (records->empty()) {
3091 }
3092 for (auto& record : *records) {
3093 runner_->feed(strategy::DataEvent<typename Runner::DataRecord>{at, std::move(record)});
3094 }
3095 return PollOutcome::UPDATED;
3096 } else {
3097 static_cast<void>(at);
3098 return PollOutcome::FAILED;
3099 }
3100 }
3101
3102 // Returns whether `kind` is due at `at`.
3103 bool is_due(PollKind kind, std::chrono::system_clock::time_point at) const {
3104 // A waiting stop reads the two closing kinds on its own floor, whatever their cadence (a disabled
3105 // one included), and nothing reads them faster than that meanwhile. The iteration that takes the
3106 // stop up is not waiting yet: it reads as any other.
3107 if (closing_ && closing_->reads_wanted_ && (kind == PollKind::WORKING_ORDERS || kind == PollKind::HOLDINGS)) {
3108 return closing_read_due(kind);
3109 }
3110 const auto interval = schedule_.interval_for(kind);
3111 if (!interval || (kind == PollKind::DATA && !data_poll_)) {
3112 return false;
3113 }
3114 const auto& due = next_due_[static_cast<int>(kind)];
3115 return !due || at >= *due;
3116 }
3117
3118 // Records when `kind` is next due.
3119 void schedule_next(PollKind kind, std::chrono::system_clock::time_point at) {
3120 const auto interval = schedule_.interval_for(kind);
3121 if (!interval) {
3122 return;
3123 }
3124 next_due_[static_cast<int>(kind)] = at + std::chrono::duration_cast<std::chrono::system_clock::duration>(*interval);
3125 }
3126
3127 // Returns how long to wait before the next iteration.
3128 //
3129 // The soonest due poll, capped at the tick so a stop through the control file is noticed within
3130 // one tick however sparse the polling is. Never negative: a loop that has fallen behind catches up
3131 // rather than pausing once per overdue poll.
3132 std::chrono::nanoseconds until_next(std::chrono::system_clock::time_point at) const {
3133 auto wait = schedule_.tick_;
3134 for (const auto kind : all_poll_kinds) {
3135 const auto& due = next_due_[static_cast<int>(kind)];
3136 if (!due) {
3137 continue;
3138 }
3139 const auto remaining = std::chrono::duration_cast<std::chrono::nanoseconds>(*due - at);
3140 if (remaining < wait) {
3141 wait = remaining;
3142 }
3143 }
3144 return wait > std::chrono::nanoseconds::zero() ? wait : std::chrono::nanoseconds::zero();
3145 }
3146
3147 Runner* runner_;
3148 Source* source_;
3149 // The data poll, if installed; see `set_data_poll`.
3150 std::function<std::optional<std::vector<typename Runner::DataRecord>>(std::chrono::system_clock::time_point)>
3151 data_poll_;
3152 PollSchedule schedule_;
3153 Clock clock_;
3154 FileStopChannel control_;
3155 FailurePolicy failure_policy_;
3156 strategy::SessionWindow session_window_{strategy::SessionWindow::krx()};
3157 // The phase most recently announced, which is not the same as the phase in force.
3158 //
3159 // `UNKNOWN` to begin with rather than "nothing announced yet", because that is genuinely what the
3160 // loop knows before its first calendar arrives -- and it means a run that starts knowing nothing and
3161 // then learns the market is open announces that as a change, which is exactly right.
3163 // Whether this loop has ever derived a phase that was not `UNKNOWN`, across every `run`.
3164 bool phase_ever_known_{false};
3165 std::optional<std::chrono::nanoseconds> maximum_portfolio_age_;
3166 // How long a stop that closes may wait for the reads that account for this runner's orders, and how
3167 // often it repeats them.
3168 std::chrono::nanoseconds closing_wait_{std::chrono::seconds(30)};
3169 std::chrono::nanoseconds owed_order_limit_{std::chrono::minutes(10)};
3170 static constexpr std::chrono::seconds closing_reread_{5};
3171 // A stop in progress in this run: when it was entered and when its wait ends, on the monotonic reading,
3172 // and whether the wait currently wants the two closing reads.
3173 struct ClosingWait {
3174 std::chrono::steady_clock::time_point began_{};
3175 std::chrono::steady_clock::time_point deadline_{};
3176 bool reads_wanted_{false};
3177 };
3178 std::optional<ClosingWait> closing_;
3179 // When each closing read's endpoint was last asked, on the monotonic reading: by its ordinary poll, by
3180 // the startup order-list read (the working-order endpoint), or by a closing wait.
3181 std::optional<std::chrono::steady_clock::time_point> working_asked_at_;
3182 std::optional<std::chrono::steady_clock::time_point> holdings_asked_at_;
3183 // Whether the missing-band-policy note has been said; it is said once per loop.
3184 bool said_no_band_age_policy_{false};
3185 // Whether the operator stated that any snapshot age is acceptable; see the setter.
3186 bool allow_unbounded_portfolio_age_{false};
3187 // Whether the operator stated that this run may act with no snapshot at all; see the setter.
3188 bool allow_absent_portfolio_{false};
3189 // Whether the missing-age-policy note has been reported, so it is said once and not per poll.
3190 bool said_no_age_policy_{false};
3191 // Which of `listing_missing`'s notes have been given, so each is said once per loop.
3192 unsigned said_listing_{0};
3193 // Which of the no-buying-power notes have been given, so each is said once per loop.
3194 unsigned said_buying_power_{0};
3195 // The runner's discarded-history count when this run began; see `note_warmup_discarded`.
3196 std::size_t warmup_discarded_at_start_{0};
3197 // The runner's dropped-kept-intent count when this run began; see `note_kept_intents_dropped`.
3198 std::size_t kept_dropped_at_start_{0};
3199 std::optional<std::chrono::nanoseconds> maximum_buying_power_age_;
3200 std::optional<std::chrono::system_clock::time_point> next_due_[poll_kind_count];
3201 std::size_t consecutive_failures_[poll_kind_count] = {};
3202 bool order_list_read_{false};
3203 // Returns whether `reason` is a condition this loop computes, and may therefore hold.
3204 static constexpr bool owns(strategy::HaltReason reason) noexcept {
3205 switch (reason) {
3206 // A person's hold and a local failure are released by their owners, never by the loop.
3209 return false;
3216 return true;
3217 }
3218 return false;
3219 }
3220
3221 // When the working-order picture was last refreshed, or nothing while it never has been.
3222 std::optional<std::chrono::system_clock::time_point> working_orders_at_;
3223 // The instant of the iteration in which the source last read the broker's order list, of either kind:
3224 // a working-order listing, or the startup read of a source without that inquiry (which reads order
3225 // history for its journal). The sweep that can name an order runs inside that read.
3226 std::optional<std::chrono::system_clock::time_point> order_list_at_;
3227 // `Runner::placements_at_broker()` as of that read, so a later send invalidates it.
3228 std::size_t placements_at_working_read_{0};
3229
3230 // The hold this loop currently owns, and the only one it will ever release.
3231 std::optional<strategy::HaltReason> held_;
3232 IterationReport last_;
3233};
3234
3235} // namespace runner
3236} // namespace algotradelib
A three-letter currency code, such as KRW or USD (ISO 4217 style).
Definition types.hpp:374
static Decimal64 parse(std::string_view input)
Parses a decimal string exactly (no binary floating point).
Definition types.hpp:468
void set_calendar(TradingCalendar calendar)
Replaces the trading calendar (for runners and sources, not strategies).
Definition context.hpp:526
A control file an operator writes to stop a running loop with a given intent.
Definition stop.hpp:235
bool enabled() const noexcept
Tests whether a path was configured.
Definition stop.hpp:247
std::optional< StopIntent > poll()
Reads the file's first word.
Definition stop.hpp:264
const std::string & unrecognized() const noexcept
Returns the word the last poll did not recognize.
Definition stop.hpp:299
A source for tests: each poll returns a queued or default outcome, without any network.
Definition loop.hpp:864
PollOutcome poll(PollKind kind, Runner &runner_instance)
Polls: returns the next queued outcome or the default, and on UPDATED installs the calendar or bands ...
Definition loop.hpp:958
static constexpr bool provides_working_orders
true: its outcomes stand for a real working-order listing.
Definition loop.hpp:867
void queue(PollKind kind, PollOutcome outcome)
Queues the outcome of the next poll of a kind.
Definition loop.hpp:876
std::size_t polls(PollKind kind) const noexcept
Returns how many times a kind was polled.
Definition loop.hpp:936
void set_price_limits(InstrumentId instrument, PriceLimits limits)
Adds a band a successful price-limits poll installs, and makes that poll default to UPDATED.
Definition loop.hpp:946
void set_buying_power_currencies(std::vector< Currency > currencies)
Sets the buying-power currencies the source claims to ask about.
Definition loop.hpp:901
void set_order_list(PollOutcome outcome)
Sets the outcome of the order-list read (UPDATED by default).
Definition loop.hpp:893
static constexpr bool reports_buying_power
true: its caller installs whatever buying power it has; it stands for no broker.
Definition loop.hpp:869
void set_default(PollKind kind, PollOutcome outcome)
Sets the outcome of every unqueued poll of a kind (UNCHANGED by default).
Definition loop.hpp:885
PollOutcome read_order_list(Runner &)
Reads the order list: returns the configured outcome. The runner argument is ignored.
Definition loop.hpp:987
void set_calendar(TradingCalendar calendar)
Sets the calendar a successful calendar poll installs, and makes that poll default to UPDATED.
Definition loop.hpp:910
std::size_t order_list_reads() const noexcept
Returns how many times the order list was read.
Definition loop.hpp:927
const std::vector< Currency > & buying_power_currencies() const noexcept
Returns the buying-power currencies.
Definition loop.hpp:919
void set_maximum_portfolio_age(std::chrono::nanoseconds age)
Sets how old the holdings (and, for a runner that sends to a broker, the working-order listing) may b...
Definition loop.hpp:1167
void set_maximum_price_limits_age(std::optional< std::chrono::nanoseconds > age)
Sets how old a price band may be and still be applied; passed to the runner (see Runner::set_maximum_...
Definition loop.hpp:1285
void set_maximum_buying_power_age(std::chrono::nanoseconds age)
Sets how old buying-power readings may be.
Definition loop.hpp:2353
void set_failure_policy(FailurePolicy policy)
Sets how many consecutive failures of one poll kind stop the loop.
Definition loop.hpp:1335
void set_session_window(strategy::SessionWindow window)
Sets the session window the market phase is derived from (KRX by default, as in a backtest),...
Definition loop.hpp:1318
void set_control_file(FileStopChannel channel)
Sets the control file an operator writes a stop intent into.
Definition loop.hpp:1369
void set_closing_wait(std::chrono::nanoseconds limit)
Sets how long a WITHDRAW or FLATTEN may wait before its closing pass (30 seconds by default).
Definition loop.hpp:1206
const Clock & clock() const noexcept
Returns the clock.
Definition loop.hpp:1077
void set_data_poll(std::function< std::optional< std::vector< typename Runner::DataRecord > >(std::chrono::system_clock::time_point)> poll)
Installs the data poll that reads records for the strategy's on_data, called on PollSchedule::data_'s...
Definition loop.hpp:1355
void allow_unbounded_portfolio_age()
Accepts holdings of any age, instead of stating a maximum.
Definition loop.hpp:1274
void allow_unbounded_price_limits_age()
Applies price bands of any age (see Runner::allow_unbounded_price_limits_age).
Definition loop.hpp:1290
void set_owed_order_limit(std::chrono::nanoseconds limit)
Sets how long a serialized runner's order may stay owed with nobody able to account for it before the...
Definition loop.hpp:1260
LoopReport run(StopSource &stop, std::size_t max_iterations=0)
Runs until a stop is requested, a poll kind exhausts its failure budget, or max_iterations iterations...
Definition loop.hpp:1394
Clock & clock() noexcept
Returns the clock, for a test to advance.
Definition loop.hpp:1084
const IterationReport & last() const noexcept
Returns what the last iteration did.
Definition loop.hpp:1561
const PollSchedule & schedule() const noexcept
Returns the schedule.
Definition loop.hpp:1092
PollingLoop(Runner &runner, Source &source, PollSchedule schedule={}, Clock clock={})
Constructs a loop.
Definition loop.hpp:1066
void allow_absent_portfolio()
Lets the run place orders before holdings have ever been read (for a broker without a holdings inquir...
Definition loop.hpp:1301
const strategy::SessionWindow & session_window() const noexcept
Returns the session window.
Definition loop.hpp:1327
Runs one strategy: feeds it events, reconciles what it asks for, checks the risk limits,...
Definition runner.hpp:305
static constexpr bool on_fill_never_fires
true when this runner sends to a broker and the strategy defines on_fill, which then never fires (no ...
Definition runner.hpp:329
const strategy::SellableConventionProbe< Tag > & sellable_convention() const noexcept
Returns the sellable-convention probe.
Definition runner.hpp:577
std::size_t warmup_instructions_discarded() const noexcept
Returns how many instructions feed_warmup discarded.
Definition runner.hpp:1988
void set_price_limits(const InstrumentId &id, PriceLimits limits)
Records an instrument's price band for today, used to clamp order prices.
Definition runner.hpp:639
static constexpr bool takes_records
true when the strategy declares on_data, so records may be fed (feed(const DataEvent&)).
Definition runner.hpp:320
const Context & context() const noexcept
Returns the context.
Definition runner.hpp:600
A stop request the loop polls; safe to set from a signal handler.
Definition stop.hpp:163
OrderIntent with_tag(std::string tag) const
Returns a copy with a tag.
Definition intent.hpp:336
static OrderIntent market(InstrumentId instrument, OrderSide side, SizeSpec size, TimeInForce time_in_force=TimeInForce::DAY)
Makes a market order, which carries no price.
Definition intent.hpp:318
SellableEvidence overall() const
Returns the evidence summed over every instrument.
static SizeSpec quantity(Decimal64 amount)
Makes a size in shares or contracts.
Definition intent.hpp:149
Scalar missing()
Returns the value that stands for "no observation" (a quiet NaN).
Definition scalar.hpp:28
Runs a strategy: the runner, the polling loop, the order journal, and stopping.
Definition clock.hpp:7
constexpr std::string_view poll_kind_name(PollKind kind) noexcept
Returns a poll kind's lowercase name, such as "working_orders".
Definition loop.hpp:74
PollKind
What a PollingLoop polls for; each has a cadence in PollSchedule.
Definition loop.hpp:31
@ WORKING_ORDERS
Working orders, which reconciliation and cancellation need.
Definition loop.hpp:39
@ BARS
Completed bars.
Definition loop.hpp:33
@ PRICE_LIMITS
Today's price bands, which an aggressive limit price is clamped to; polled second,...
Definition loop.hpp:59
@ HOLDINGS
Holdings, which orders are sized against.
Definition loop.hpp:37
@ QUOTES
Current quotes, for strategies that act between bars.
Definition loop.hpp:35
@ CALENDAR
The trading calendar, from which the loop derives the market phase; polled first, and on by default.
Definition loop.hpp:50
@ BUYING_POWER
Buying power, polled beside holdings (not before each order).
Definition loop.hpp:41
@ DATA
Records for a strategy's on_data, from the data poll PollingLoop::set_data_poll installs; never from ...
Definition loop.hpp:66
constexpr bool stop_intent_closes_positions(StopIntent intent) noexcept
Tests whether a stop intent closes positions with market orders, after withdrawing the working orders...
Definition stop.hpp:136
constexpr bool obligation_is_unaccounted(ObligationState state) noexcept
Tests whether an order in this state counts toward the loop's owed-order time limit (PollingLoop::set...
PollOutcome
What became of one poll.
Definition loop.hpp:134
@ RATE_LIMITED
The rate limiter refused the poll; not counted as a failure.
Definition loop.hpp:142
@ UNCHANGED
The poll succeeded and there was nothing new.
Definition loop.hpp:138
@ FAILED
The poll failed; counted toward the failure budget.
Definition loop.hpp:140
@ UPDATED
New data arrived and was fed to the runner, or installed in it (a calendar, price bands).
Definition loop.hpp:136
constexpr std::string_view poll_outcome_name(PollOutcome outcome) noexcept
Returns an outcome's lowercase name, such as "rate_limited".
Definition loop.hpp:158
constexpr PollKind all_poll_kinds[]
Every poll kind, in the order an iteration polls them.
Definition loop.hpp:97
constexpr std::array< PollOutcome, 4 > all_poll_outcomes
Every PollOutcome, in declaration order.
Definition loop.hpp:146
StopIntent
What an operator asks for when stopping a running loop.
Definition stop.hpp:29
@ QUIESCE
Stop sending new orders; nothing is cancelled or closed. The default, and what a signal means.
Definition stop.hpp:34
constexpr std::size_t poll_kind_count
The number of PollKind values.
Definition loop.hpp:126
constexpr bool obligation_needs_operator(ObligationState state) noexcept
Tests whether only an operator can settle an obligation in this state, so no read of the broker's lis...
@ OPERATOR
An order only an operator may account for (Runner::release_obligations).
constexpr bool stop_intent_closes(StopIntent intent) noexcept
Tests whether a stop intent asks for a closing pass (cancellations, and for FLATTEN closing orders) a...
Definition stop.hpp:119
constexpr std::string_view stop_intent_name(StopIntent intent) noexcept
Returns a lowercase name for an intent, as written in the control file ("withdraw").
Definition stop.hpp:61
void stop(S &strategy, Ctx &context)
Calls strategy.on_stop(context) if the strategy declares on_stop; otherwise does nothing.
Definition concept.hpp:259
MarketPhase
Where the clock stands relative to the trading session.
Definition event.hpp:33
@ UNKNOWN
Nothing is known about this instant: the calendar does not cover its date, or the filled session hour...
Definition event.hpp:38
constexpr std::string_view sellable_convention_name(SellableConvention convention) noexcept
Returns a lowercase name for a convention, such as "net_of_resting", for logs.
MarketPhase stated_session_phase(const TradingCalendar &calendar, std::chrono::system_clock::time_point now)
Returns the market phase at an instant from the session hours filled in a calendar.
Definition event.hpp:238
HaltReason
Who or what is holding trading stopped.
Definition risk.hpp:30
@ BUYING_POWER_UNREAD
A buying-power limit is enforced, but there is no current reading to check it against.
Definition risk.hpp:71
@ LOCAL_FAILURE
Local machinery failed, such as the order journal not being writable; nothing is sent.
Definition risk.hpp:40
@ PORTFOLIO_ABSENT
No holdings snapshot has been read yet, so what the account holds is unknown.
Definition risk.hpp:55
@ ORDER_LIST_UNREAD
The broker's order list has not been read since this process started.
Definition risk.hpp:49
@ OPERATOR
A person stopped trading with RiskGuard::halt(); only RiskGuard::resume() clears it.
Definition risk.hpp:32
@ PORTFOLIO_STALE
The holdings snapshot is older than the configured maximum age.
Definition risk.hpp:61
@ POLL_FAILING
A poll kept failing and the loop gave up, as opposed to STOPPING on request.
Definition risk.hpp:73
@ STOPPING
A stop was requested and the run is shutting down.
Definition risk.hpp:42
The library: broker-neutral types (core), and the modules below.
constexpr bool lists_every_value(const std::array< Enum, N > &values, IsEnumerator is_enumerator) noexcept
Tests whether a list holds every value of an enum exactly once, in any order.
std::optional< Decimal64 > decimal_add(const Decimal64 &lhs, const Decimal64 &rhs)
Adds two decimals exactly.
Definition types.hpp:760
std::optional< Decimal64 > decimal_subtract(const Decimal64 &lhs, const Decimal64 &rhs)
Subtracts two decimals exactly.
Definition types.hpp:783
bool decimal_less(const Decimal64 &lhs, const Decimal64 &rhs)
Compares two decimals numerically, whatever their scales.
Definition types.hpp:926
OrderSide
The side of an order: its economic direction, buy or sell.
Definition types.hpp:1974
std::string format_iso8601_utc(std::chrono::system_clock::time_point value)
Formats an instant as an ISO 8601 timestamp in UTC, such as 2026-10-06T00:30:00Z.
Definition types.hpp:2741
Identifies an instrument: its country, venue and symbol.
Definition types.hpp:85
An exact amount of money in one currency.
Definition types.hpp:1168
Currency currency_
The currency; the library never adds amounts in different currencies.
Definition types.hpp:1172
Decimal64 amount_
The amount.
Definition types.hpp:1170
The highest and lowest price an instrument may trade at today.
The trading days a broker reported for one market, ascending by date.
Definition calendar.hpp:72
One currency's running figure and how many statements contributed to it.
Definition loop.hpp:385
std::size_t statements_
How many statements contributed.
Definition loop.hpp:389
Commission and tax the broker stated on the orders a loop happened to poll (Toss states them; KIS doe...
Definition loop.hpp:379
std::size_t unrepresentable_sums_
How many additions or subtractions did not fit a Decimal64; nonzero means the figures are short (it c...
Definition loop.hpp:417
std::size_t orders_stating_none_
How many orders were first seen stating no cost (every KIS order); never decreased,...
Definition loop.hpp:402
std::size_t tax_statements_in(const Currency &currency) const
Returns how many tax statements a currency has.
Definition loop.hpp:451
std::size_t working_list_disappearances_
How many orders left the working-order listing between two polls (filled, cancelled or expired); a di...
Definition loop.hpp:407
std::size_t conflicting_restatements_
How many times an order restated a different cost at the same filled quantity; the first figure is ke...
Definition loop.hpp:412
std::vector< StatedTotal > tax_
Tax stated, per currency, on the same terms.
Definition loop.hpp:395
bool add(std::vector< StatedTotal > &totals, const Money &amount)
Adds an amount to its currency's figure in a list of totals.
Definition loop.hpp:462
static std::size_t statements_in(const std::vector< StatedTotal > &totals, const Currency &currency)
Returns a currency's statement count from a list of totals.
Definition loop.hpp:500
std::optional< Decimal64 > tax_in(const Currency &currency) const
Returns the tax stated in a currency.
Definition loop.hpp:433
std::optional< Decimal64 > commission_in(const Currency &currency) const
Returns the commission stated in a currency.
Definition loop.hpp:424
ChargedCosts since(const ChargedCosts &before) const
Returns what was observed since an earlier copy, for one run's report.
Definition loop.hpp:518
std::size_t commission_statements_in(const Currency &currency) const
Returns how many commission statements a currency has.
Definition loop.hpp:442
static std::optional< Decimal64 > figure_in(const std::vector< StatedTotal > &totals, const Currency &currency)
Returns a currency's figure from a list of totals.
Definition loop.hpp:485
std::vector< StatedTotal > commission_
Commission stated, per currency; a currency with no statement has no entry (not zero).
Definition loop.hpp:393
std::size_t orders_stating_cost_
How many orders have stated a cost (including zero); counted once per order, never decreased.
Definition loop.hpp:397
How a PollingLoop responds to polls that keep failing.
Definition loop.hpp:588
std::size_t consecutive_limit_
Consecutive failures of one poll kind after which the loop stops (POLL_FAILING).
Definition loop.hpp:590
What one loop iteration did.
Definition loop.hpp:594
bool phase_changed_
Whether a phase change was announced to the strategy.
Definition loop.hpp:616
strategy::MarketPhase phase_
The market phase the loop computed.
Definition loop.hpp:614
bool updated() const noexcept
Tests whether any poll brought new data.
Definition loop.hpp:622
std::optional< strategy::HaltReason > gate_
The hold that blocked placements, if any.
Definition loop.hpp:605
bool fed_
Whether any poll returned UPDATED: something was fed to the runner or installed in it.
Definition loop.hpp:607
std::vector< std::pair< PollKind, PollOutcome > > polls_
What each poll returned, in order.
Definition loop.hpp:598
std::chrono::system_clock::time_point at_
When the iteration ran.
Definition loop.hpp:596
What a whole PollingLoop::run did, and why it ended.
Definition loop.hpp:641
std::size_t closing_contended_
Positions whose closing order was sized down, or not sent, because another order could close them too...
Definition loop.hpp:785
std::size_t price_bands_withheld_
Plans built while a known price band was not applied (no age policy, too old, or dated after the cloc...
Definition loop.hpp:670
std::size_t phase_transitions_
How many phase changes were announced to the strategy.
Definition loop.hpp:717
bool abandoned_
Whether the loop gave up because a poll kept failing.
Definition loop.hpp:724
std::size_t plans_withheld_
Whole plans held back (any WithheldPlanReason); see Runner::plans_withheld.
Definition loop.hpp:701
std::size_t orders_reconcile_withheld_
Orders held back for an instrument of unknown order state; see Runner::orders_reconcile_withheld.
Definition loop.hpp:678
std::size_t flattened_
Closing orders queued for a FLATTEN (asked for, not necessarily sent).
Definition loop.hpp:732
std::optional< Obligation > owed_stop_
The order for which the loop stopped placing by itself (PollingLoop::set_owed_order_limit): owed long...
Definition loop.hpp:774
std::size_t iterations_
How many iterations ran.
Definition loop.hpp:643
strategy::MarketPhase final_phase_
The phase the last iteration computed.
Definition loop.hpp:657
std::size_t orders_unconfirmed_timed_out_
Sent orders that timed out unconfirmed; see Runner::set_confirmation_timeout for what each mode then ...
Definition loop.hpp:699
bool closing_wait_expired_
Whether that wait ended at its limit, with the closing pass built from what was in hand then.
Definition loop.hpp:763
std::size_t closing_placed_
Closing orders (placements, not cancellations) accepted by the executor (for a dry run,...
Definition loop.hpp:734
std::optional< PollKind > abandoned_kind_
The poll kind that exhausted its failure budget, if one did.
Definition loop.hpp:726
std::size_t blocked_
How many iterations were blocked from placing (a named cancellation may still have gone).
Definition loop.hpp:651
std::size_t instructions_unavailable_
Instructions not sent because local machinery was unavailable; see Runner::instructions_unavailable.
Definition loop.hpp:703
std::size_t sends_outside_permitted_phase_
Orders sent in a phase RiskLimits::permitted_phases_ does not permit, because they close toward flat;...
Definition loop.hpp:722
std::size_t closing_rejected_
Closing instructions (placements and cancellations) rejected by reconciliation, the broker or the bin...
Definition loop.hpp:736
std::size_t closing_unavailable_
Closing instructions not sent because local machinery was unavailable; fix it, resume_after_local_fai...
Definition loop.hpp:747
std::size_t stop_handler_sent_
Instructions the strategy's on_stop got out during a stop; always zero.
Definition loop.hpp:831
std::size_t sends_under_a_revised_phase_
How many calls into a source or strategy both sent something and left the market phase changed.
Definition loop.hpp:665
std::size_t failed_[poll_kind_count]
How many polls of each kind failed; see failed().
Definition loop.hpp:649
bool closing_interrupted_
Whether a WITHDRAW or FLATTEN was pending when the run was abandoned for failing polls,...
Definition loop.hpp:768
std::size_t failed(PollKind kind) const noexcept
Returns how many polls of a kind failed.
Definition loop.hpp:850
std::chrono::nanoseconds closing_waited_
The time from the loop taking up a stop to its closing pass (or to the run's abandonment),...
Definition loop.hpp:761
std::size_t stop_handler_refused_
Instructions the strategy's on_stop asked for during a stop, refused as intended (the operator's orde...
Definition loop.hpp:829
std::size_t cancels_rejected_
Cancellations refused by the broker or binding; see Runner::cancels_rejected.
Definition loop.hpp:705
std::optional< strategy::Rejection > last_unbuildable_
Why reconciliation could not build the last such instruction in this run, if any.
Definition loop.hpp:715
std::size_t closing_indeterminate_
Closing instructions (cancellations included) with an unknown outcome.
Definition loop.hpp:745
std::size_t closing_withheld_
Closing instructions held back because the instrument has an order of unknown outcome,...
Definition loop.hpp:743
std::optional< strategy::HaltReason > final_gate_
The most fundamental hold in force when the run ended, whoever took it.
Definition loop.hpp:655
std::size_t closing_unresolved_
Closing cancellations naming an order the portfolio does not list; read the broker's list rather than...
Definition loop.hpp:749
std::size_t orders_guard_refused_
Orders the risk guard refused; see Runner::orders_guard_refused.
Definition loop.hpp:680
bool order_list_read_
Whether the broker's order list was read at least once.
Definition loop.hpp:728
std::size_t withdrawn_
Cancellations queued for a WITHDRAW or FLATTEN (asked for, not necessarily sent).
Definition loop.hpp:730
bool closing_source_unverified_
Whether the closing pass could not trust its picture of the account. Makes closing_complete() false.
Definition loop.hpp:808
ChargedCosts charged_costs_
Commission and tax the broker stated on the orders this run saw; a subtotal (see ChargedCosts).
Definition loop.hpp:645
std::optional< BrokerRefusal > last_broker_refusal_
The broker's code and message for the last order it refused during this run, if any.
Definition loop.hpp:713
std::size_t unclamped_orders_refused_
Orders refused before sending while carrying such a price; see Runner::unclamped_orders_refused.
Definition loop.hpp:674
std::size_t cancels_indeterminate_
Cancellations with an unknown outcome.
Definition loop.hpp:711
std::optional< StopIntent > stopped_by_
The stop intent that ended the run, if one did.
Definition loop.hpp:653
std::size_t orders_indeterminate_
Orders with an unknown outcome (SendOutcome::INDETERMINATE, including most KIS, Toss and Kiwoom refus...
Definition loop.hpp:693
std::size_t cancels_unresolved_
Cancellations naming an order the portfolio does not list.
Definition loop.hpp:709
std::size_t attempted(PollKind kind) const noexcept
Returns how many polls of a kind were attempted.
Definition loop.hpp:841
bool closing_complete() const noexcept
Tests whether every closing instruction the loop asked for was accepted, and the loop knew what to as...
Definition loop.hpp:823
std::size_t closing_refused_
Closing instructions the risk guard refused.
Definition loop.hpp:738
std::size_t cancels_refused_
Cancellations a hold refused.
Definition loop.hpp:707
std::size_t attempted_[poll_kind_count]
How many polls of each kind were attempted, indexed by PollKind; see attempted().
Definition loop.hpp:647
std::size_t orders_unbuildable_
Orders reconciliation could not build during this run's polling; see Runner::orders_unbuildable.
Definition loop.hpp:676
std::size_t closing_unconfirmed_
Orders a serialized runner still owed when the closing pass began that neither holdings nor a listing...
Definition loop.hpp:755
std::size_t unclamped_orders_rejected_
Sent orders the broker refused while carrying a price a withheld band would have clamped; see Runner:...
Definition loop.hpp:672
std::size_t closing_unsizable_
Positions whose closing order could not be sized: the holding rows do not add up, the closing quantit...
Definition loop.hpp:792
std::vector< std::string > notes_
Notes for the operator, such as an unrecognized control-file word or a missing policy.
Definition loop.hpp:834
std::size_t orders_binding_refused_
Orders the binding refused to send; see Runner::orders_binding_refused.
Definition loop.hpp:682
std::size_t orders_broker_refused_
Orders the broker refused (SendOutcome::REJECTED); see last_broker_refusal_. At KIS,...
Definition loop.hpp:688
How often a PollingLoop polls each kind; an unset interval disables that poll.
Definition loop.hpp:191
std::optional< std::chrono::nanoseconds > interval_for(PollKind kind) const noexcept
Returns the interval for a poll kind.
Definition loop.hpp:244
std::optional< std::chrono::nanoseconds > calendar_
How often to read the trading calendar; six hours by default.
Definition loop.hpp:226
std::optional< std::chrono::nanoseconds > holdings_
How often to read holdings; without it the portfolio is never refreshed.
Definition loop.hpp:197
std::chrono::nanoseconds tick_
The loop's step, which bounds how quickly a stop is noticed; not a poll.
Definition loop.hpp:217
std::optional< std::chrono::nanoseconds > data_
How often to call the data poll (PollingLoop::set_data_poll); without it, or without a data poll,...
Definition loop.hpp:238
std::optional< std::chrono::nanoseconds > price_limits_
How often to read today's price bands.
Definition loop.hpp:233
std::optional< std::chrono::nanoseconds > bars_
How often to fetch bars.
Definition loop.hpp:193
std::optional< std::chrono::nanoseconds > working_orders_
How often to read the working orders.
Definition loop.hpp:207
std::optional< std::chrono::nanoseconds > buying_power_
How often to read buying power.
Definition loop.hpp:215
std::optional< std::chrono::nanoseconds > quotes_
How often to fetch quotes.
Definition loop.hpp:195
Detects whether a runner reports kept_intents_dropped().
Definition loop.hpp:353
Detects whether a runner reports warmup_instructions_discarded().
Definition loop.hpp:364
Detects Runner::keeps_sent_orders_until_listed.
Definition loop.hpp:342
Detects whether a source provides const std::vector<Currency>& buying_power_currencies() const.
Definition loop.hpp:580
Detects whether a source declares static constexpr bool provides_working_orders = true,...
Definition loop.hpp:276
Detects whether a source declares static constexpr bool reports_buying_power = true,...
Definition loop.hpp:314
Detects whether a source declares static constexpr bool states_calendar_sessions = true,...
Definition loop.hpp:295
Detects whether a source provides const ChargedCosts& charged_costs() const, which LoopReport then re...
Definition loop.hpp:564
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