algotradelib 0.0.0.9000
C++ header-only library for algorithmic trading
Loading...
Searching...
No Matches
runner.hpp
1#pragma once
2
3#include "./context.hpp"
4#include "./dispatch.hpp"
5#include "./execution.hpp"
6#include "./journal.hpp"
7#include "./run_ledger.hpp"
8
10#include "../strategy/risk.hpp"
11#include "../strategy/sellable_convention.hpp"
12
13#include <algotradelib/core>
14
15#include <algorithm>
16#include <cstddef>
17#include <iterator>
18#include <map>
19#include <memory>
20#include <optional>
21#include <stdexcept>
22#include <string>
23#include <type_traits>
24#include <unordered_map>
25#include <unordered_set>
26#include <utility>
27#include <variant>
28#include <vector>
29
30namespace algotradelib {
31namespace runner {
32
33namespace runner_detail {
34
35// Whether an executor can ask the broker what may be sold of one instrument.
36//
37// Detected rather than required, for the same reason the strategy's handlers are: a dry runner, a
38// replay's queueing executor and a test double have no broker to ask, and none of them should have
39// to grow a method that returns nothing. An executor bound to a broker whose holdings already carry
40// the figure declares it too and answers nothing, so the runner's own condition stays one test.
41template <typename Executor, typename = void>
42struct fills_sellable : std::false_type {};
43
44template <typename Executor>
45struct fills_sellable<
46 Executor, std::void_t<decltype(std::declval<Executor&>().sellable_quantity(std::declval<const InstrumentId&>()))>
47> : std::true_type {};
48
49// Whether `Executor` states what its sellable *inquiry* answer is evidence of.
50//
51// Detected rather than required, and the default is what matters: an executor that answers a
52// sellable quantity and says nothing about its basis is treated as having established nothing, so
53// the guard refuses rather than measuring a sell against a figure nobody characterized. A consumer's
54// own executor gets that default without being told it exists, which is the point -- the alternative
55// default would silently enforce against whatever its author happened to return.
56template <typename Executor, typename = void>
57struct states_sellable_basis : std::false_type {};
58
59template <typename Executor>
60struct states_sellable_basis<Executor, std::void_t<decltype(Executor::sellable_inquiry_basis())>> : std::true_type {};
61
62// Returns what `Executor`'s inquiry answer is evidence of, or an unestablished basis.
63template <typename Executor>
64constexpr SellableBasis sellable_inquiry_basis_of() {
65 if constexpr (states_sellable_basis<Executor>::value) {
66 return Executor::sellable_inquiry_basis();
67 } else {
68 return SellableBasis{};
69 }
70}
71
72// Whether `Executor` can say which reference the broker issued for the order it just accepted.
73//
74// Detected rather than required, for the same reason as above: a dry runner and a replay's
75// queueing executor have no broker to have been answered by. A reservation written without one is
76// still worth writing -- a limit that ignored the order would be the worse failure -- but it cannot
77// be cancelled by reference until a listing supplies one.
78template <typename Executor, typename = void>
79struct reports_last_ref : std::false_type {};
80
81template <typename Executor>
82struct reports_last_ref<Executor, std::void_t<decltype(std::declval<const Executor&>().last_ref())>> : std::true_type {
83};
84
85// Whether `Executor` decides which venue an order that names none is sent to.
86//
87// Detected rather than required: only a broker binding routes, and a dry runner, an observer and a
88// replay's queueing executor send the planned venue as it stands. `live::SessionExecutor` answers
89// with its `default_route()`, and a `JournalingExecutor` forwards its inner executor's answer.
90template <typename Executor, typename = void>
91struct resolves_route : std::false_type {};
92
93template <typename Executor>
94struct resolves_route<
95 Executor, std::void_t<decltype(std::declval<const Executor&>().requested_route(Venue::UNSPECIFIED))>
96> : std::true_type {};
97
98// Whether `Executor` can say **why** the last instruction failed.
99//
100// Detected rather than required, on the same terms as the two above: a dry runner refuses nothing
101// and a replay's queueing executor has no broker to be refused by, so neither should have to grow a
102// method that answers nothing. An executor that binds a session declares
103// `const std::optional<BrokerError>& last_error() const` and its refusals then reach
104// `Runner::last_broker_refusal`, where a report can carry the broker's own code and message instead
105// of a count with nothing to chase.
106//
107// **The *shape* is detected, not the name.** An earlier version asked only whether `last_error()`
108// was a valid expression, which would have selected this branch for any executor that happened to
109// have a method of that name -- one returning `std::optional<std::string>`, say -- and then failed
110// to compile on `broker_code_`. A name is not a contract; the return type is.
111template <typename Executor, typename = void>
112struct states_last_error : std::false_type {};
113
114template <typename Executor>
115struct states_last_error<
116 Executor,
117 std::enable_if_t<
118 std::is_same_v<std::decay_t<decltype(std::declval<const Executor&>().last_error())>, std::optional<BrokerError>>
119 >
120> : std::true_type {};
121
122// Whether `Executor` journals what it sends (`JournalingExecutor`); a runner sending through one to a
123// broker is serialized unless told otherwise (`Runner::allow_overlapping_orders`).
124template <typename Executor, typename = void>
125struct journals : std::false_type {};
126
127template <typename Executor>
128struct journals<Executor, std::void_t<decltype(std::declval<const Executor&>().journal_failures())>> : std::true_type {
129};
130
131// Whether `Executor` writes what serialization needs: the holding an order was decided against, the
132// line it wrote for the order, and a line the runner builds (a discharge or a hold).
133template <typename Executor, typename = void>
134struct serializes : std::false_type {};
135
136template <typename Executor>
137struct serializes<
138 Executor,
139 std::void_t<
140 decltype(std::declval<Executor&>().place(
141 std::declval<const strategy::PlannedOrder&>(), std::optional<Decimal64>{}
142 )),
143 decltype(std::declval<const Executor&>().last_entry()),
144 decltype(std::declval<Executor&>().record(std::declval<JournalEntry&>()))
145 >
146> : std::true_type {};
147
148// Whether `Executor` can keep a run budget's records in its journal: it stamps a run's placements (`set_run`)
149// and names a ledger line (`next_run_id`), as `JournalingExecutor` does. A live budgeted runner needs it.
150template <typename Executor, typename = void>
151struct can_journal_run : std::false_type {};
152
153template <typename Executor>
154struct can_journal_run<
155 Executor,
156 std::void_t<
157 decltype(std::declval<Executor&>().set_run(std::string())), decltype(std::declval<Executor&>().next_run_id())
158 >
159> : std::true_type {};
160
161// How a replay books its executions in a budgeted runner's run (`RunLedger`); defined after `Runner`.
162struct ReplayAccess;
163
164} // namespace runner_detail
165
170template <typename BrokerTag>
177
182template <typename BrokerTag>
192
201template <typename BrokerTag>
204 std::vector<strategy::PlannedOrder> would_place_;
211 std::vector<OrderRef<BrokerTag>> would_cancel_;
218 std::vector<strategy::Rejection> rejected_;
220 std::vector<strategy::GuardRejection> refused_;
227 std::vector<WithheldOrder> withheld_;
232 std::vector<WithheldPlan<BrokerTag>> withheld_plans_;
237 std::vector<strategy::PlannedOrder> indeterminate_;
243 std::vector<RejectedCancel<BrokerTag>> rejected_cancel_;
245 std::vector<OrderRef<BrokerTag>> indeterminate_cancel_;
247 std::vector<OrderRef<BrokerTag>> unresolved_cancel_;
252 std::vector<WithheldOrder> unavailable_;
254 std::vector<OrderRef<BrokerTag>> unavailable_cancel_;
262 std::vector<RefusedCancel<BrokerTag>> refused_cancel_;
264 std::vector<std::string> log_;
265
270 bool quiet() const noexcept {
271 // Every outcome bucket belongs here; one left out would report as silence.
272 return would_place_.empty() && would_cancel_.empty() && rejected_.empty() && refused_.empty() &&
273 withheld_.empty() && withheld_plans_.empty() && indeterminate_.empty() && unresolved_cancel_.empty() &&
274 unavailable_.empty() && unavailable_cancel_.empty() && refused_cancel_.empty() && indeterminate_cancel_.empty() &&
275 rejected_cancel_.empty();
276 }
277};
278
280struct DryTag {
282 static constexpr std::string_view name = "dryrun";
283};
284
301template <
302 typename Strategy, typename CapsType = strategy::NoCaps, typename BrokerTag = DryTag,
303 typename Executor = RecordingExecutor<DryTag>
304>
305class Runner {
306public:
308 using Tag = BrokerTag;
313
314 ATL_ASSERT_STRATEGY(Strategy, Context);
315
317 using DataRecord = strategy::strategy_detail::data_record_t<Strategy>;
318
320 static constexpr bool takes_records = strategy::strategy_detail::declares_on_data<Strategy>;
321
329 static constexpr bool on_fill_never_fires =
330 runner_detail::sends_to_a_broker<Executor>::value && strategy::strategy_detail::declares_on_fill<Strategy>;
331
337 static constexpr bool takes_bar_slices = strategy::strategy_detail::declares_on_bars<Strategy>;
338
344 static constexpr bool records_bar_history = strategy::strategy_detail::reads_bar_history<Strategy>;
345
353 static constexpr bool keeps_sent_orders_until_listed =
354 runner_detail::sends_to_a_broker<Executor>::value && CapsType::has_working_orders;
355
360 static constexpr bool journals_to_a_broker =
361 runner_detail::sends_to_a_broker<Executor>::value && runner_detail::journals<Executor>::value;
362
376 explicit Runner(
377 Strategy strategy = {}, strategy::RiskLimits limits = {}, std::size_t series_capacity = 512, Executor executor = {}
378 )
379 : strategy_(std::move(strategy)),
380 guard_(std::move(limits)),
381 context_(series_capacity),
382 executor_(std::move(executor)) {
383#if defined(ATL_HAS_EIGEN)
384 if constexpr (!records_bar_history) {
385 context_detail::PortfolioAccess::stop_bar_history(context_);
386 }
387#endif
388 if (guard_.limits().run_budget_) {
389 open_run();
390 }
391 }
392
397 const Executor& executor() const noexcept {
398 return executor_;
399 }
400
404 Executor& executor() noexcept {
405 return executor_;
406 }
407
415 const IndeterminacyLedger& ledger() const noexcept {
416 return ledger_;
417 }
418
423 return ledger_;
424 }
425
434 std::optional<std::string> local_failure() const {
435 if (!guard_.halted(strategy::HaltReason::LOCAL_FAILURE)) {
436 return std::nullopt;
437 }
438 return guard_.hold_detail(strategy::HaltReason::LOCAL_FAILURE);
439 }
440
449 acknowledged_journal_failures_ = executor_journal_failures();
450 }
451
462 void set_maximum_portfolio_age(std::optional<std::chrono::nanoseconds> age) {
463 maximum_portfolio_age_ = age;
464 }
465
475 void set_observed_at(std::chrono::system_clock::time_point at) {
476 observed_at_ = at;
477 }
478
483 std::chrono::system_clock::time_point observed_at() const noexcept {
484 return observed_at_;
485 }
486
494 allow_absent_portfolio_ = true;
495 }
496
507 void require_known_portfolio(bool required) {
508 require_known_portfolio_ = required;
509 }
510
519 void halt_locally(std::string detail) {
520 note_local_failure(std::move(detail));
521 }
522
527 std::size_t placements_at_broker() const noexcept {
528 return placements_at_broker_;
529 }
530
541 std::size_t sends_outside_permitted_phase() const noexcept {
542 return sends_outside_permitted_phase_;
543 }
544
554 void probe_sellable_convention(bool enabled = true) {
555 probing_sellable_ = enabled;
556 }
557
565 // Skipped, not forgotten, while the listing is newer than the holdings: the resting quantity
566 // and the sellable figure would come from two moments, and a sell starting to rest between them
567 // reads as a figure that did not move. The baseline stays the last paired reading.
568 if (probing_sellable_ && !context_.portfolio().listing_newer_than_holdings()) {
569 sellable_probe_.observe(context_.portfolio());
570 }
571 }
572
578 return sellable_probe_;
579 }
580
585 const Strategy& strategy() const noexcept {
586 return strategy_;
587 }
588
592 Strategy& strategy() noexcept {
593 return strategy_;
594 }
595
600 const Context& context() const noexcept {
601 return context_;
602 }
603
607 Context& context() noexcept {
608 return context_;
609 }
610
615 const strategy::RiskGuard& guard() const noexcept {
616 return guard_;
617 }
618
623 return guard_;
624 }
625
639 void set_price_limits(const InstrumentId& id, PriceLimits limits) {
640 DatedBand dated;
641 dated.received_at_ = observed_at_;
642 dated.limits_ = std::move(limits);
643 price_limits_.insert_or_assign(id, std::move(dated));
644 }
645
662 void set_maximum_price_limits_age(std::optional<std::chrono::nanoseconds> age) {
663 maximum_price_limits_age_ = age;
664 // This call is now the whole policy, so it also withdraws "any age".
665 allow_unbounded_price_limits_age_ = false;
666 }
667
670 allow_unbounded_price_limits_age_ = true;
671 maximum_price_limits_age_.reset();
672 }
673
678 std::size_t price_bands_withheld() const noexcept {
679 return price_bands_withheld_;
680 }
681
686 bool price_limits_age_policy_stated() const noexcept {
687 return maximum_price_limits_age_.has_value() || allow_unbounded_price_limits_age_;
688 }
689
699 std::size_t unclamped_orders_rejected() const noexcept {
700 return unclamped_orders_rejected_;
701 }
702
708 std::size_t unclamped_orders_refused() const noexcept {
709 return unclamped_orders_refused_;
710 }
711
725 std::size_t orders_unbuildable() const noexcept {
726 return orders_unbuildable_;
727 }
728
733 std::size_t orders_reconcile_withheld() const noexcept {
734 return orders_reconcile_withheld_;
735 }
736
740 std::size_t orders_guard_refused() const noexcept {
741 return orders_guard_refused_;
742 }
743
752 std::optional<Money> run_cash() const {
753 return run_ && !run_closing_ ? std::optional<Money>(run_->cash()) : std::nullopt;
754 }
755
762 std::optional<Decimal64> run_holding(const InstrumentId& instrument) const {
763 return run_ && !run_closing_ ? std::optional<Decimal64>(run_->holding(instrument)) : std::nullopt;
764 }
765
774 std::vector<RunPlacement> run_unsettled() const {
775 return run_ ? run_->unsettled() : std::vector<RunPlacement>{};
776 }
777
791 if (!guard_.limits().run_budget_ || recovered_) {
792 throw std::logic_error("set_run_opening needs a run budget and must come before runner::recover_runner");
793 }
794 if (!opening.resume_ && !opening.transfers_.empty()) {
795 throw std::invalid_argument("a new run takes its cash from run_budget_: transfers apply to a resumed run");
796 }
797 for (std::size_t at = 0; at < opening.transfers_.size(); ++at) {
798 const auto& transfer = opening.transfers_[at];
799 if (transfer.id_.empty() || !decimal_less(Decimal64::parse("0"), transfer.amount_.amount_)) {
800 throw std::invalid_argument("a run's transfer needs an id and an amount above zero");
801 }
802 for (std::size_t other = 0; other < at; ++other) {
803 if (opening.transfers_[other].id_ == transfer.id_) {
804 throw std::invalid_argument("two of a run's transfers share the id " + transfer.id_);
805 }
806 }
807 }
808 run_opening_ = std::move(opening);
809 }
810
816 const std::optional<RunRecoverySummary>& run_recovery() const noexcept {
817 return run_recovery_;
818 }
819
831 bool run_writes_closed() const noexcept {
832 if constexpr (keeps_run_in_journal) {
833 return guard_.limits().run_budget_.has_value() && ((!run_ && !run_absent_) || run_journal_latched_);
834 } else {
835 return false;
836 }
837 }
838
845 run_journal_latched_ = run_journal_latched_ || guard_.limits().run_budget_.has_value();
846 }
847
864 [[maybe_unused]] const std::string& placement_id, [[maybe_unused]] const Decimal64& filled,
865 [[maybe_unused]] const Money& amount, [[maybe_unused]] const Decimal64& fee,
866 [[maybe_unused]] const std::string& reason
867 ) {
868 if constexpr (keeps_run_in_journal) {
869 const auto zero = Decimal64::parse("0");
870 if (
871 run_writes_closed() || !run_ || decimal_less(zero, filled) != decimal_less(zero, amount.amount_) ||
872 !run_->can_book_released(placement_id, filled, amount, fee)
873 ) {
874 return false;
875 }
876 auto record = std::make_shared<RunRecord>();
877 record->run_ = run_->id();
879 record->of_ = placement_id;
880 record->amount_ = amount;
881 record->filled_ = filled;
882 record->fee_ = fee;
883 auto line = ledger_line(std::move(record), "booked by an operator: " + reason);
884 if (!run_record(line) || !run_->book_released(placement_id, filled, amount, fee)) {
885 return false;
886 }
887 // The old run's last booking lets a new run waiting on it open.
888 open_new_run_once_closed();
889 return true;
890 } else {
891 return false;
892 }
893 }
894
898 std::size_t orders_binding_refused() const noexcept {
899 return orders_binding_refused_;
900 }
901
907 std::size_t orders_broker_refused() const noexcept {
908 return orders_broker_refused_;
909 }
910
915 std::size_t orders_indeterminate() const noexcept {
916 return orders_indeterminate_;
917 }
918
925 std::size_t plans_withheld() const noexcept {
926 return plans_withheld_;
927 }
928
947 std::vector<strategy::TargetPosition> deferred_targets() const {
948 std::vector<strategy::TargetPosition> targets;
949 targets.reserve(deferred_targets_.size());
950 for (const auto& deferred : deferred_targets_) {
951 targets.push_back(deferred.target_);
952 }
953 return targets;
954 }
955
960 std::size_t targets_deferred() const noexcept {
961 return targets_deferred_;
962 }
963
968 std::size_t deferred_dropped_after_fill() const noexcept {
969 return deferred_dropped_after_fill_;
970 }
971
977 std::optional<std::chrono::system_clock::time_point> deferred_awaiting_evidence() const {
978 std::optional<std::chrono::system_clock::time_point> earliest;
979 for (const auto& deferred : deferred_targets_) {
980 if (stop_listed(deferred.target_.instrument_)) {
981 continue;
982 }
983 if (!earliest || deferred.deferred_at_ < *earliest) {
984 earliest = deferred.deferred_at_;
985 }
986 }
987 return earliest;
988 }
989
999 Report retry_deferred(const std::vector<OrderSnapshot>& evidence) {
1000 return release_deferred(&evidence);
1001 }
1002
1024 std::size_t unconfirmed_orders() const noexcept {
1025 return unconfirmed_.size();
1026 }
1027
1034 confirm_reservations();
1035 }
1036
1056 [[maybe_unused]] const InstrumentId& instrument, [[maybe_unused]] OrderSide side,
1057 [[maybe_unused]] const std::optional<std::string>& order_id, [[maybe_unused]] const std::string& journal_id = {}
1058 ) {
1059 if constexpr (keeps_sent_orders_until_listed) {
1060 if (order_id && order_id->empty()) {
1061 return;
1062 }
1063 const auto found = serialized() ? unnamed_by_journal_id(journal_id) : newest_unnamed(instrument, side);
1064 // Serialized, a sweep only names: absence from a listing is not proof the order was never placed.
1065 if (found == unconfirmed_.end() || (serialized() && !order_id)) {
1066 return;
1067 }
1068 // The row first: it is recognized by the reference about to change, and left behind it would be
1069 // counted beside the rebuilt one.
1070 drop_reserved_row(*found);
1071 if (order_id) {
1072 // The primary part only: a broker's row is matched on it everywhere, and the listing that
1073 // carries the order supplies the rest of the reference.
1074 found->ref_.primary_ = *order_id;
1075 found->row_.ref_.primary_ = *order_id;
1076 // Named now, so a fresh start: a hand-cleared hold may have let it miss its history meanwhile.
1077 found->history_missed_ = false;
1078 if (found->unexplained_since_) {
1079 found->unexplained_since_ = freshness_instant();
1080 }
1081 } else {
1082 unconfirmed_.erase(found);
1083 }
1084 confirm_reservations();
1085 }
1086 }
1087
1129 bool serialized() const noexcept {
1130 return journals_to_a_broker && !overlapping_;
1131 }
1132
1146 if (guard_.limits().run_budget_) {
1147 throw std::logic_error("a run budget books its orders one at a time, so allow_overlapping_orders is refused");
1148 }
1149 if (placements_at_broker_ != 0 || recovered_) {
1150 throw std::logic_error("allow_overlapping_orders must be chosen before recovery and before trading");
1151 }
1152 overlapping_ = true;
1153 }
1154
1162 auto state = ObligationState::NONE;
1163 if (!serialized()) {
1164 return state;
1165 }
1166 for (const auto& entry : unconfirmed_) {
1167 if (!(entry.instrument_ == instrument)) {
1168 continue;
1169 }
1170 const auto owed = state_of(entry);
1171 if (obligation_weight(state) < obligation_weight(owed)) {
1172 state = owed;
1173 }
1174 }
1175 return state;
1176 }
1177
1183 std::vector<Obligation> obligations(const InstrumentId& instrument) const {
1184 auto owed = obligations();
1185 owed.erase(
1186 std::remove_if(
1187 owed.begin(), owed.end(),
1188 [&](const Obligation& one) {
1189 return !(one.instrument_ == instrument);
1190 }
1191 ),
1192 owed.end()
1193 );
1194 return owed;
1195 }
1196
1201 std::vector<Obligation> obligations() const {
1202 std::vector<Obligation> owed;
1203 if (!serialized()) {
1204 return owed;
1205 }
1206 for (const auto& entry : unconfirmed_) {
1207 Obligation obligation;
1208 obligation.instrument_ = entry.instrument_;
1209 obligation.journal_id_ = entry.journal_ ? entry.journal_->id_ : std::string();
1210 obligation.order_id_ = entry.ref_.primary_;
1211 obligation.side_ = entry.side_;
1212 obligation.quantity_ = entry.expected_;
1213 obligation.sent_at_ = entry.sent_at_;
1214 obligation.state_ = state_of(entry);
1215 owed.push_back(std::move(obligation));
1216 }
1217 return owed;
1218 }
1219
1237 [[maybe_unused]] const InstrumentId& instrument, [[maybe_unused]] const std::string& reason
1238 ) {
1239 bool written = true;
1240 if constexpr (can_serialize) {
1241 if (run_writes_closed()) {
1242 return false;
1243 }
1244 for (auto at = unconfirmed_.begin(); at != unconfirmed_.end();) {
1245 if (!(at->instrument_ == instrument)) {
1246 ++at;
1247 continue;
1248 }
1249 auto line = closing_line(*at, JournalOutcome::CONFIRMED, std::nullopt, "released by an operator: " + reason);
1250 if (!run_record(line)) {
1251 written = false;
1252 ++at;
1253 continue;
1254 }
1255 set_boundary(instrument, line.recorded_at_, /*strict=*/true);
1256 drop_reserved_row(*at);
1257 // Released with no booking: the run stays unsettled until `book_run_fill`, as its journal now reads.
1258 if (run_ && at->run_order_) {
1259 run_->release(run_placement_of(*at));
1260 }
1261 at = unconfirmed_.erase(at);
1262 }
1263 confirm_reservations();
1264 }
1265 return written;
1266 }
1267
1285 void restore_obligations([[maybe_unused]] const JournalReplay& replay) {
1286 recovered_ = true;
1287 if constexpr (can_serialize) {
1288 if (!serialized()) {
1289 return;
1290 }
1291 restore_from(replay);
1292 // The run opens before anything can account for a restored order, so a run's order is booked.
1293 if constexpr (keeps_run_in_journal) {
1294 if (guard_.limits().run_budget_) {
1295 open_run_from(replay);
1296 }
1297 }
1298 confirm_reservations();
1299 }
1300 }
1301
1308 std::size_t orders_awaiting_confirmation() const noexcept {
1309 return orders_awaiting_confirmation_;
1310 }
1311
1320 std::size_t obligations_unexplained() const noexcept {
1321 if (!serialized()) {
1322 return 0;
1323 }
1324 return static_cast<std::size_t>(
1325 std::count_if(unconfirmed_.begin(), unconfirmed_.end(), [](const Unconfirmed& entry) {
1326 return entry.operator_only_ || entry.residual_.coefficient() != 0 || entry.awaiting_booking_;
1327 })
1328 );
1329 }
1330
1346 void set_confirmation_timeout(std::chrono::nanoseconds timeout) {
1347 confirmation_timeout_ = timeout;
1348 }
1349
1354 std::size_t orders_unconfirmed_timed_out() const noexcept {
1355 return orders_unconfirmed_timed_out_;
1356 }
1357
1371 std::optional<std::chrono::system_clock::time_point> unconfirmed_awaiting_evidence() {
1372 // Against the portfolio as it stands: a listing just installed may carry, or no longer carry, an
1373 // order, and no pass has run since.
1374 confirm_reservations();
1375 std::optional<std::chrono::system_clock::time_point> earliest;
1376 const auto now = freshness_instant();
1377 for (const auto& entry : unconfirmed_) {
1378 if (!awaits_evidence(entry, now)) {
1379 continue;
1380 }
1381 if (!earliest || entry.sent_at_ < *earliest) {
1382 earliest = entry.sent_at_;
1383 }
1384 }
1385 return earliest;
1386 }
1387
1401 void confirm_from_history(const std::vector<OrderSnapshot>& evidence) {
1402 if (serialized()) {
1403 confirm_serialized_from_history(evidence);
1404 return;
1405 }
1406 confirm_reservations();
1407 const auto now = freshness_instant();
1408 for (auto& entry : unconfirmed_) {
1409 entry.consulted_ = awaits_evidence(entry, now);
1410 if (!entry.consulted_) {
1411 continue;
1412 }
1413 // An entry not yet named matches no row: a row whose number is missing would read as equal.
1414 if (entry.ref_.primary_.empty()) {
1415 continue;
1416 }
1417 const auto* row = history_row_for(
1418 evidence, entry.ref_.primary_, entry.instrument_, entry.side_, entry.sent_at_ - order_time_tolerance_,
1419 entry.sent_at_ + order_time_tolerance_
1420 );
1421 if (row != nullptr && (entry.session_ended_ || !strategy::order_is_open(row->status_))) {
1422 if (decimal_less(row->execution_.filled_quantity_, entry.expected_)) {
1423 entry.expected_ = row->execution_.filled_quantity_;
1424 }
1425 entry.settled_ = true;
1426 // Holdings get a full timeout from here to show it (`confirm_reservations`).
1427 entry.unexplained_since_ = now;
1428 }
1429 }
1430 // Past the timeout and the history had no answer: noted, and judged by `confirm_reservations` against
1431 // the next holdings read, as a settled order is. Marking here, on the clock, marked a fill one
1432 // holdings read early on a loop polling slower than the timeout (the listing, and so this history,
1433 // is read before holdings in each iteration).
1434 for (auto& entry : unconfirmed_) {
1435 if (entry.consulted_ && !entry.settled_ && timed_out(entry, now)) {
1436 entry.history_missed_ = true;
1437 }
1438 }
1439 // Retires what the history just settled, and withholds what the holdings in hand already condemn.
1440 confirm_reservations();
1441 }
1442
1481 // Once per iteration, so the context shows what this iteration's holdings confirmed even when no
1482 // pass runs (`unconfirmed_orders`).
1483 confirm_reservations();
1484 if (guard_.halted(strategy::HaltReason::OPERATOR) || guard_.halted(strategy::HaltReason::LOCAL_FAILURE)) {
1485 retained_targets_.erase(
1486 std::remove_if(
1487 retained_targets_.begin(), retained_targets_.end(),
1488 [](const RetainedTarget& kept) {
1489 return kept.for_phase_;
1490 }
1491 ),
1492 retained_targets_.end()
1493 );
1494 kept_intents_.clear();
1495 }
1496 // **A statement still queued is newer than anything retained.** Releasing retained work appends it to
1497 // the queue, behind what a caller driving the runner itself has queued, where it would be settled as
1498 // the latest word on its instrument. So what a queued target or order speaks about is forgotten first,
1499 // as `settle` would forget it (a `CancelIntent` names an order, not an instrument, and forgets nothing).
1500 for (const auto& queued : context_.queued()) {
1501 forget_retained(instruction_instrument(queued));
1502 }
1503 if (
1504 (retained_targets_.empty() && kept_intents_.empty()) ||
1505 context_.portfolio().as_of_ == std::chrono::system_clock::time_point{} ||
1506 context_.portfolio().listing_newer_than_holdings() || guard_.blocking_reason()
1507 ) {
1508 return Report{};
1509 }
1510 const bool phase_permits = guard_.permits_phase(context_.phase());
1511 std::vector<RetainedTarget> kept;
1512 bool released = false;
1513 const auto as_of = context_.portfolio().as_of_;
1514 // Kept because the broker could not be reached: not offered again until it has answered since.
1515 const auto awaiting_broker = [&](const auto& entry) {
1516 return entry.after_ && !(*entry.after_ < as_of);
1517 };
1518 for (auto& entry : retained_targets_) {
1519 if (
1520 (entry.for_phase_ && !phase_permits) || awaiting_broker(entry) ||
1521 (entry.until_accounted_ && owes(entry.target_.instrument_))
1522 ) {
1523 kept.push_back(std::move(entry));
1524 continue;
1525 }
1526 context_.submit(std::move(entry.target_));
1527 released = true;
1528 }
1529 retained_targets_ = std::move(kept);
1530 // Kept intents follow, in order, once the phase permits; each goes out only if the holding it was
1531 // decided against is unchanged (and, for a stop, no stop has come to rest meanwhile).
1532 if (phase_permits && !kept_intents_.empty()) {
1533 auto intents = std::move(kept_intents_);
1534 kept_intents_.clear();
1535 for (auto& entry : intents) {
1536 if (awaiting_broker(entry)) {
1537 kept_intents_.push_back(std::move(entry));
1538 continue;
1539 }
1540 const auto held = context_.portfolio().net_quantity_of(entry.intent_.instrument());
1541 const auto gap = held ? decimal_subtract(*held, entry.held_) : std::nullopt;
1542 // A weight is planned again as the position it states, against the holding at release, so
1543 // the book it was decided against does not bind it.
1544 const bool weight = strategy::size_kind_is_target(entry.intent_.size().kind());
1545 const bool same_book = weight || (gap && gap->coefficient() == 0);
1546 const bool stop_now_rests = entry.intent_.trigger() && stop_listed(entry.intent_.instrument());
1547 if (!same_book || stop_now_rests) {
1548 ++kept_intents_dropped_;
1549 continue;
1550 }
1551 context_.submit(std::move(entry.intent_));
1552 released = true;
1553 }
1554 }
1555 if (!released) {
1556 return Report{};
1557 }
1558 return settle();
1559 }
1560
1566 std::size_t intents_kept_for_phase() const noexcept {
1567 return kept_intents_.size();
1568 }
1569
1575 std::size_t kept_intents_dropped() const noexcept {
1576 return kept_intents_dropped_;
1577 }
1578
1583 std::size_t targets_retained() const noexcept {
1584 return retained_targets_.size();
1585 }
1586
1592 std::size_t targets_retained_for_phase() const noexcept {
1593 return static_cast<std::size_t>(
1594 std::count_if(retained_targets_.begin(), retained_targets_.end(), [](const RetainedTarget& kept) {
1595 return kept.for_phase_;
1596 })
1597 );
1598 }
1599
1601 void clear_retained_targets() noexcept {
1602 retained_targets_.clear();
1603 kept_intents_.clear();
1604 }
1605
1611 void clear_deferred_targets() noexcept {
1612 deferred_targets_.clear();
1613 }
1614
1625 std::size_t obligations_awaiting_account() const noexcept {
1626 if (!serialized()) {
1627 return 0;
1628 }
1629 return static_cast<std::size_t>(
1630 std::count_if(unconfirmed_.begin(), unconfirmed_.end(), [](const Unconfirmed& entry) {
1631 return !entry.operator_only_ && (!entry.listed_now_ || entry.withdrawn_);
1632 })
1633 );
1634 }
1635
1647 bool withdrawal_accepted_for(const WorkingOrder<Tag>& working) const {
1648 if constexpr (keeps_sent_orders_until_listed) {
1649 for (const auto& entry : unconfirmed_) {
1650 if (
1651 entry.withdrawn_ && !entry.ref_.primary_.empty() && working.ref_.primary_ == entry.ref_.primary_ &&
1652 working.order_.order_id_ == entry.ref_.primary_ && own_row(working.order_, entry)
1653 ) {
1654 return true;
1655 }
1656 }
1657 }
1658 return false;
1659 }
1660
1671 return release_deferred(nullptr);
1672 }
1673
1678 std::size_t instructions_unavailable() const noexcept {
1679 return instructions_unavailable_;
1680 }
1681
1686 std::size_t cancels_rejected() const noexcept {
1687 return cancels_rejected_;
1688 }
1689
1693 std::size_t cancels_refused() const noexcept {
1694 return cancels_refused_;
1695 }
1696
1700 std::size_t cancels_unresolved() const noexcept {
1701 return cancels_unresolved_;
1702 }
1703
1707 std::size_t cancels_indeterminate() const noexcept {
1708 return cancels_indeterminate_;
1709 }
1710
1719 const std::optional<BrokerRefusal>& last_broker_refusal() const noexcept {
1720 return last_broker_refusal_;
1721 }
1722
1731 const std::optional<strategy::Rejection>& last_unbuildable() const noexcept {
1732 return last_unbuildable_;
1733 }
1734
1740 tolerance_ = std::move(tolerance);
1741 }
1742
1751 tolerance_.minimum_quantity_ = std::move(quantity);
1752 }
1753
1763 portfolio_value_ = std::move(value);
1764 portfolio_value_currency_.reset();
1765 }
1766
1776 portfolio_value_ = std::move(value.amount_);
1777 portfolio_value_currency_ = std::move(value.currency_);
1778 }
1779
1781 void clear_portfolio_value() noexcept {
1782 portfolio_value_.reset();
1783 portfolio_value_currency_.reset();
1784 }
1785
1800 if (started_) {
1801 return Report{};
1802 }
1803 started_ = true;
1804 dispatch::start(strategy_, context_);
1805 // A pass only for what `on_start` asked for: a settlement with nothing to place still observes
1806 // and confirms, and moving that one step earlier would change a run whose `on_start` asks nothing.
1807 if (context_.queued().empty()) {
1808 return Report{};
1809 }
1810 return settle();
1811 }
1812
1817 bool started() const noexcept {
1818 return started_;
1819 }
1820
1830 dispatch::stop(strategy_, context_);
1831 return settle();
1832 }
1833
1841 dispatch::stop(strategy_, context_);
1842 return settle();
1843 }
1844
1853 return settle();
1854 }
1855
1869 record_bar(event);
1870 context_.set_last_price(event.instrument_, event.bar_.close_);
1871 context_.set_now(event.period_end_);
1872 confirm_reservations();
1873 dispatch::bar(strategy_, context_, event);
1874 return settle();
1875 }
1876
1895 void feed_warmup(const strategy::BarEvent& event) {
1896 record_bar(event);
1897 context_.set_last_price(event.instrument_, event.bar_.close_);
1898 context_.set_now(event.period_end_);
1899 dispatch::bar(strategy_, context_, event);
1900 warmup_instructions_discarded_ += context_.drain().size();
1901 }
1902
1914 void record(const strategy::BarEvent& event) {
1915 record_bar(event);
1916 context_.set_last_price(event.instrument_, event.bar_.close_);
1917 context_.set_now(event.period_end_);
1918 }
1919
1932 record_bar(event);
1933 }
1934
1946 confirm_reservations();
1947 dispatch::bars(strategy_, context_, slice);
1948 return settle();
1949 }
1950
1960 void feed_warmup(const strategy::BarSlice& slice) {
1961 dispatch::bars(strategy_, context_, slice);
1962 warmup_instructions_discarded_ += context_.drain().size();
1963 }
1964
1972 template <typename T>
1974 static_assert(
1975 strategy::strategy_detail::declares_on_data<Strategy>,
1976 "a record fed to a strategy that declares no on_data would vanish: declare on_data, or feed no records"
1977 );
1978 static_assert(std::is_same_v<T, DataRecord>, "a record must be of the strategy's data_type");
1979 context_.set_now(event.known_at_);
1980 dispatch::data(strategy_, context_, event);
1981 warmup_instructions_discarded_ += context_.drain().size();
1982 }
1983
1988 std::size_t warmup_instructions_discarded() const noexcept {
1989 return warmup_instructions_discarded_;
1990 }
1991
1998 context_.set_last_price(event.quote_.instrument_, event.quote_.last_price_);
1999 context_.set_now(event.quote_.received_at_);
2000 confirm_reservations();
2001 dispatch::quote(strategy_, context_, event);
2002 return settle();
2003 }
2004
2015 template <typename T>
2017 static_assert(
2018 strategy::strategy_detail::declares_on_data<Strategy>,
2019 "a record fed to a strategy that declares no on_data would vanish: declare on_data, or feed no records"
2020 );
2021 static_assert(std::is_same_v<T, DataRecord>, "a record must be of the strategy's data_type");
2022 context_.set_now(event.known_at_);
2023 confirm_reservations();
2024 dispatch::data(strategy_, context_, event);
2025 return settle();
2026 }
2027
2034 confirm_reservations();
2035 dispatch::fill(strategy_, context_, event);
2036 return settle();
2037 }
2038
2044 Report feed(const OrderSnapshot& event) {
2045 confirm_reservations();
2046 dispatch::order_update(strategy_, context_, event);
2047 return settle();
2048 }
2049
2056 context_.set_phase(phase);
2057 // A DAY order does not outlive its session, whatever its history row says afterwards: a broker may
2058 // leave an expired order's remainder on the row (KIS reads it from `rmn_qty`), so the row's filled
2059 // quantity is taken as final once the session has closed (`confirm_from_history`).
2061 for (auto& entry : unconfirmed_) {
2062 if (time_in_force_expires_at_close(entry.row_.order_.time_in_force_)) {
2063 entry.session_ended_ = true;
2064 }
2065 }
2066 }
2067 confirm_reservations();
2068 dispatch::phase(strategy_, context_, phase);
2069 return settle();
2070 }
2071
2072private:
2073 // Caches a bar in its series, or with no bar history kept, refuses it unless later than its series' last.
2074 void record_bar(const strategy::BarEvent& event) {
2075#if defined(ATL_HAS_EIGEN)
2076 if constexpr (records_bar_history) {
2077 context_.record_bar(event);
2078 } else {
2079 using Access = context_detail::PortfolioAccess;
2080 Access::advance_bar_time(Access::bar_time_for(context_, event), event);
2081 }
2082#else
2083 static_cast<void>(event);
2084#endif
2085 }
2086
2087 // Drains the queue and turns it into a report.
2088 //
2089 // **Cancellations are collected before any order is placed**, across the whole queue, rather than
2090 // per instruction. That is the sequencing `Plan` documents as the caller's obligation, and here
2091 // is the caller: a replacement placed before its predecessor is withdrawn is briefly a double
2092 // position, while cancelling first leaves the instrument unrepresented for a moment instead.
2093 //
2094 // A guard refusal drops that instruction and nothing else. One instrument breaching a position
2095 // ceiling must not silence the rest of a cross-sectional rebalance.
2096 Report settle() {
2097 // Before anything is planned, because this pass has not yet added anything of its own: the
2098 // probe must not read this runner's intentions as the broker's report. The portfolio can still
2099 // carry a reservation an *earlier* pass persisted, which is why those rows are marked and why
2100 // the probe skips them rather than relying on when it is called.
2102 // After the probe, which must read the broker's report rather than this runner's rows, and before
2103 // anything is planned: whatever replaced `working_` since the last pass, each order this runner
2104 // sent is counted again at what nothing yet explains (`unconfirmed_orders`).
2105 confirm_reservations();
2106
2107 Report report;
2108 cancel_closing_run_orders(report);
2109 // **One index of the portfolio's rows for a pass with many instructions**, so each target finds its own
2110 // rows instead of scanning all of them (`strategy::PortfolioRows`). It describes the portfolio as it is
2111 // now; `plan_for` uses it only while the context's portfolio has been neither replaced nor edited since
2112 // (an executor's cancellation can replace it), and scans otherwise. Built before the instructions are
2113 // taken, so a failed allocation leaves them queued; cleared on every way out of the pass.
2114 std::optional<strategy::PortfolioRows> rows;
2115 if (context_.queued().size() > id_detail::scan_limit) {
2116 rows.emplace(context_.portfolio());
2117 rows_replacements_ = context_detail::PortfolioAccess::replacements(context_);
2118 rows_edits_ = context_detail::PortfolioAccess::runner_edits(context_);
2119 }
2120 struct ForgetRows {
2121 const strategy::PortfolioRows*& rows_;
2122 ~ForgetRows() {
2123 rows_ = nullptr;
2124 }
2125 } forget_rows{pass_rows_};
2126 pass_rows_ = rows ? &*rows : nullptr;
2127 auto instructions = context_.drain();
2128 kept_this_pass_.clear();
2129 drop_superseded_deferred(instructions);
2130 std::vector<strategy::PlannedOrder> pending;
2131 // The instruction each pending order came from, aligned with `pending`, so a phase refusal can
2132 // keep the target that produced it (`retain_for_phase`). Points into `instructions`, which lives
2133 // for the whole pass.
2134 std::vector<const Instruction<Tag>*> origin;
2135 // Whether a later instruction of this pass speaks about `source`'s instrument (`source` is one of
2136 // `instructions`): the latest statement wins.
2137 const auto restated_later = [&instructions](const Instruction<Tag>& source) {
2138 const auto instrument = instruction_instrument(source);
2139 const auto* const end = instructions.data() + instructions.size();
2140 for (const auto* later = &source + 1; later < end; ++later) {
2141 if (instruction_instrument(*later) == instrument) {
2142 return true;
2143 }
2144 }
2145 return false;
2146 };
2147
2148 // **One withdrawal per order per pass.** A strategy that clears what is resting and then states
2149 // a target asks twice for the same order: the explicit `CancelIntent` goes out, and then
2150 // `plan_for` reconciles the target against `context_.portfolio()` -- which does not carry the
2151 // cancellation just sent -- and plans a withdrawal for the same row. Two requests, and a broker
2152 // answering the second with "already cancelled" then reads as a rejected withdrawal in the
2153 // report.
2154 //
2155 // **Only the duplicate send is suppressed; the picture planning reads is untouched.** Removing
2156 // the row from that view is the tempting fix and it is unsafe: `SendOutcome::ACCEPTED` on a
2157 // withdrawal means the broker took the *request*, and `PENDING_CANCEL` counts as open in
2158 // `strategy::order_is_open`. Sizing a replacement against an emptied book would place a fresh
2159 // order of the full target while the original may still fill -- doubling a position to save a
2160 // request. Reconciliation keeps treating a possibly-working order as working, which is the
2161 // right answer until a listing says otherwise.
2162 //
2163 // Keyed on *attempted*, not on accepted: no outcome here means the order is gone, and a
2164 // withdrawal that was refused locally will be refused the same way a second time.
2165 std::vector<OrderRef<Tag>> attempted;
2166 const auto attempt_cancel = [this, &attempted, &report](const OrderRef<Tag>& ref) {
2167 // An unaddressed reference is exempt. Two of them compare equal, so deduping would collapse
2168 // two distinct unsendable withdrawals into one report entry and hide the second.
2169 if (!ref.primary_.empty() || !ref.secondary_.empty()) {
2170 for (const auto& seen : attempted) {
2171 if (seen == ref) {
2172 return;
2173 }
2174 }
2175 attempted.push_back(ref);
2176 }
2177 send_cancel(ref, report);
2178 };
2179 // Serialized: the instruments a plan in this pass places on, so a second plan for one of them is
2180 // withheld before its withdrawals go out (`serial_hold`).
2181 std::vector<InstrumentId> claimed;
2182
2183 for (const auto& instruction : instructions) {
2184 // **A later target or order replaces a retained target**: the strategy has spoken again about this
2185 // instrument, and replaying what it said before would override it. A withheld target is retained
2186 // again below, as the latest. A `CancelIntent` names an order, not an instrument, and leaves it.
2187 forget_retained(instruction_instrument(instruction));
2188 if (const auto* cancel = std::get_if<strategy::CancelIntent<Tag>>(&instruction)) {
2189 attempt_cancel(cancel->ref_);
2190 continue;
2191 }
2192
2193 const auto planned = plan_for(instruction);
2194 // **Checked before a single cancellation goes out, and on the plan rather than on its parts.**
2195 //
2196 // `plan_for` derives both halves from `context_.portfolio()`: which rows oppose the target, and
2197 // what remains to be placed. So a plan is only as good as the snapshot under it, and the
2198 // cancellations are sent below -- before the guard has seen the placements at all. Deciding the
2199 // halves separately is how a reprice becomes a bare withdrawal.
2200 //
2201 // Only a plan that would cancel something is stopped. One that only places is left to the guard
2202 // exactly as before, so a direct `OrderIntent` keeps reporting as a refusal rather than quietly
2203 // changing bucket.
2204 const bool would_cancel = !planned.cancel_.empty();
2205 if (const auto reason = plan_withhold_reason(would_cancel)) {
2206 // **A missing account stops the whole plan; a hold on placements stops only a plan that
2207 // would also withdraw something.**
2208 //
2209 // The difference is which of the two the *guard* can be relied on to catch. A held placement
2210 // is refused by `RiskGuard` a few lines below, with the hold named on its own report entry,
2211 // and that is the better result -- so a plan with nothing to cancel is left to it. What the
2212 // guard cannot catch is data: a snapshot nobody has read is not a hold, and the loop's hold
2213 // for it is not yet installed at every point an instruction can be settled. A source's
2214 // `read_order_list` runs before `PollingLoop` installs any hold and is handed a mutable
2215 // runner, so a target settled inside that call reaches here with the guard clear. Deciding
2216 // absence and staleness here, on the snapshot itself, is what makes the rule hold at every
2217 // send site rather than at most of them.
2218 // A missing-account reason is only ever returned when it should stop this plan, so it needs
2219 // no second test here. A hold on placements stops only a plan that would also withdraw
2220 // something: a placement-only plan is left to `RiskGuard` below, which refuses it with the
2221 // hold named on its own report entry, and that is the better result.
2222 const bool data_is_missing = *reason != WithheldPlanReason::PLACEMENT_HELD;
2223 if (data_is_missing || would_cancel) {
2224 // The whole plan, before any of its parts were counted separately. **Four reasons reach
2225 // here** and this counts them together: an account never read, one older than the stated
2226 // maximum, one read before the listing it would be reconciled with, and a hold refusing
2227 // placements for a plan that also wanted to withdraw something -- the last two on a perfectly
2228 // fresh portfolio. Counted at all because the loop's own gate
2229 // does not always describe it: with `allow_absent_portfolio` the gate can be open while this
2230 // fires.
2231 ++plans_withheld_;
2232 std::string detail = withhold_detail(*reason);
2233 if (data_is_missing) {
2234 if (retain_withheld(instruction)) {
2235 detail = "retained for the next holdings read";
2236 } else if (
2238 std::holds_alternative<strategy::OrderIntent>(instruction)
2239 ) {
2240 detail = "dropped: an order intent states a size against the mis-ordered picture";
2241 }
2242 }
2243 report.withheld_plans_.push_back(
2244 WithheldPlan<Tag>{
2245 *reason,
2246 instruction_instrument(instruction),
2247 instruction_tag(instruction),
2248 planned.cancel_,
2249 planned.place_.size(),
2250 std::move(detail),
2251 }
2252 );
2253 continue;
2254 }
2255 }
2256 // **Serialized: decided on the plan, before any of its withdrawals go.** A plan whose placement will
2257 // be withheld must not withdraw first: a reprice would become a bare withdrawal, and a protective
2258 // order could be withdrawn with its replacement left waiting. A plan that only withdraws is not
2259 // held.
2260 // A target behind a resting stop places later: its plan withdraws the stop and waits
2261 // (`STOP_ORDER_RESTING`), so it is decided here too, or the stop could go with nothing to follow it.
2262 const bool defers = !planned.cancel_.empty() &&
2263 std::any_of(planned.rejected_.begin(), planned.rejected_.end(), [](const strategy::Rejection& rejection) {
2264 return rejection.reason_ == strategy::RejectReason::STOP_ORDER_RESTING;
2265 });
2266 if (serialized() && (!planned.place_.empty() || defers)) {
2267 std::optional<std::string> hold;
2268 for (const auto& order : planned.place_) {
2269 hold = serial_hold(order.instrument_, claimed);
2270 if (hold) {
2271 break;
2272 }
2273 }
2274 if (!hold && defers) {
2275 hold = serial_hold(instruction_instrument(instruction), claimed);
2276 }
2277 if (hold) {
2278 ++plans_withheld_;
2279 if (retain_withheld(instruction, /*for_phase=*/false, context_.portfolio().as_of_)) {
2280 *hold += "; retained for a later holdings read";
2281 }
2282 report.withheld_plans_.push_back(
2283 WithheldPlan<Tag>{
2285 instruction_instrument(instruction),
2286 instruction_tag(instruction),
2287 planned.cancel_,
2288 planned.place_.size(),
2289 std::move(*hold),
2290 }
2291 );
2292 continue;
2293 }
2294 for (const auto& order : planned.place_) {
2295 claimed.push_back(order.instrument_);
2296 }
2297 if (defers) {
2298 claimed.push_back(instruction_instrument(instruction));
2299 }
2300 }
2301 // **Serialized: a target that could only withdraw an order this runner still owes is kept**, and its
2302 // withdrawals go out all the same (`withdraws_owed`). Nothing is reported as withheld: nothing was.
2303 if (serialized() && planned.place_.empty() && !defers && withdraws_owed(instruction, planned.cancel_)) {
2304 retain_withheld(instruction, /*for_phase=*/false, context_.portfolio().as_of_, /*until_accounted=*/true);
2305 }
2306 for (const auto& ref : planned.cancel_) {
2307 attempt_cancel(ref);
2308 }
2309 defer_if_waiting_on_stop(instruction, planned);
2310 for (const auto& rejection : planned.rejected_) {
2311 // Reconciliation's own refusal: it could not build a valid instruction at all, which is a
2312 // different fact from a broker saying no. **Not a diagnosis**: the same bucket holds a
2313 // quantity that rounded away on the lot, which is a deliberate drop. The reason is on the
2314 // entry.
2315 ++orders_unbuildable_;
2316 last_unbuildable_ = rejection;
2317 report.rejected_.push_back(rejection);
2318 }
2319 for (const auto& order : planned.place_) {
2320 pending.push_back(order);
2321 origin.push_back(&instruction);
2322 }
2323 }
2324 // Placements below change the portfolio (`persist_reservation`), so the index ends with the planning.
2325 pass_rows_ = nullptr;
2326
2327 strategy::GuardInputs inputs;
2328 // When the order actually goes out (`send_instant`): a target kept at a ledger mark, or one
2329 // released at a holdings read, is sent between bars, and a send recorded at the bar that decided it
2330 // would already look a window old to the next bar.
2331 inputs.now_ = send_instant();
2332 inputs.phase_ = context_.phase();
2333
2334 // **Every order in this pass is checked against a view that already contains the orders this
2335 // pass has sent.** Without that, a limit is re-evaluated from the same starting point for every
2336 // order, and two orders that each fit can breach it together: with a hundred sellable and no
2337 // resting order, two sells of sixty both pass and twenty shares are sold that were not there.
2338 //
2339 // A copy per pass, mutated as orders are accepted, closes that within one `settle`.
2340 // `persist_reservation` closes the same hazard *across* passes: always for a runner that sends to
2341 // a broker listing working orders, and otherwise for the limits that read what is outstanding.
2342 // Nothing has to recognise its own order in a later listing: a working-order poll assigns
2343 // `working_` wholesale (a holdings poll keeps it), so the broker's own answer replaces the
2344 // reservation when it arrives. Between a placement and that poll, the context portfolio is
2345 // therefore the broker's last report **plus** what this runner has sent since -- which is what a
2346 // target and a limit have to size against, and why the rows are marked so that anything inferring
2347 // the broker's behaviour from the listing can tell them apart.
2348 //
2349 // **Copied only when it can differ from the context's.** Until this pass places an order or asks the
2350 // executor anything, the view is the context's portfolio as it stands, so orders are checked against the
2351 // portfolio itself. The copy is taken before the first call out to the executor that could change that:
2352 // a sellable inquiry (an executor may publish a new portfolio while answering), or a send with more
2353 // orders to check after it, taken before the send so it is followed by no more allocation than a
2354 // reservation. Each placed order is reserved in it. A pass with one order to place and no inquiry, or
2355 // none -- most passes -- copies nothing.
2356 std::optional<strategy::Portfolio<Tag>> reserved_view;
2357 const auto view = [&]() -> const strategy::Portfolio<Tag>& {
2358 return reserved_view ? *reserved_view : context_.portfolio();
2359 };
2360 const auto reserve_for_later =
2361 [&](std::size_t at, const strategy::PlannedOrder& order, const std::optional<OrderRef<Tag>>& ref) {
2362 if (!reserved_view || at + 1 == pending.size()) {
2363 return;
2364 }
2365 reserve(
2366 *reserved_view, order, inputs.reference_price_, inputs.order_currency_, ref,
2367 guard_.limits().enforce_buying_power_
2368 );
2369 };
2370 // Resolved once for the pass. The currencies and marks do not move as orders are accepted --
2371 // only quantities do, and the guard reads those from the view -- and resolving per order would
2372 // repeat a map lookup per instrument for every instrument. Built only when the ceiling is on, so
2373 // a caller who has not asked for it pays nothing.
2374 if (!pending.empty() && guard_.limits().max_gross_exposure_) {
2375 inputs.exposure_basis_ = exposure_basis_for(view(), pending);
2376 }
2377 if (run_ && !pending.empty()) {
2378 run_pass_inputs(view(), inputs);
2379 }
2380 for (std::size_t at = 0; at < pending.size(); ++at) {
2381 auto& order = pending[at];
2382 const auto& source_instruction = *origin[at];
2383 // Checked before the guards, because an unresolved instrument is a safety hold rather than a
2384 // limit breach: reporting a notional ceiling for an order that was never going to be sent
2385 // would point an operator at the wrong problem.
2386 // Checked before the ledger and before the guards, and checked *per order* rather than once
2387 // at the top. A journal that failed on the first order of a batch will fail on the second, so
2388 // a batch that carried on would produce one unexplained refusal per instrument. This is also
2389 // what makes the condition hold for a direct `feed()`, which never reaches `PollingLoop`'s
2390 // gate at all.
2391 if (guard_.halted(strategy::HaltReason::LOCAL_FAILURE)) {
2392 ++instructions_unavailable_;
2393 report.unavailable_.push_back(
2394 WithheldOrder{
2396 order,
2397 guard_.hold_detail(strategy::HaltReason::LOCAL_FAILURE),
2398 }
2399 );
2400 continue;
2401 }
2402 if (ledger_.requires_reconcile(order.instrument_)) {
2403 // The indeterminacy ledger, not a guard: this instrument has an outcome nobody knows, so
2404 // nothing further goes out for it until a listing settles the question. Counted apart from
2405 // every other origin because the operator's response is to reconcile rather than to relax a
2406 // limit or fix a price.
2407 ++orders_reconcile_withheld_;
2408 std::string detail(ledger_.detail(order.instrument_));
2409 // **Serialized: the target is kept**, as at the gate below, and planned again at a later holdings
2410 // read: withheld again while the instrument is marked, sent once a listing has settled it. Not when
2411 // a later instruction of this pass spoke about the instrument: every instruction is planned before
2412 // any order is sent, so keeping this one here would undo the later one.
2413 if (
2414 serialized() && !restated_later(source_instruction) &&
2415 retain_withheld(source_instruction, /*for_phase=*/false, context_.portfolio().as_of_)
2416 ) {
2417 detail += "; retained for a later holdings read";
2418 }
2419 report.withheld_.push_back(WithheldOrder{WithheldReason::RECONCILE_REQUIRED, order, std::move(detail)});
2420 continue;
2421 }
2422
2423 // **Serialized, again at the send**: an order placed earlier in this pass on the same instrument is
2424 // an order not yet accounted for. The baseline is taken here, once, and the same value goes to the
2425 // journal and to the order's record (`track_unconfirmed`).
2426 std::optional<Decimal64> baseline;
2427 if (serialized()) {
2428 if (auto hold = serial_hold(order.instrument_, {})) {
2429 ++orders_awaiting_confirmation_;
2430 if (retain_withheld(source_instruction, /*for_phase=*/false, context_.portfolio().as_of_)) {
2431 *hold += "; retained for a later holdings read";
2432 }
2433 report.withheld_.push_back(WithheldOrder{WithheldReason::AWAITING_CONFIRMATION, order, std::move(*hold)});
2434 continue;
2435 }
2436 baseline = context_.portfolio().net_quantity_of(order.instrument_);
2437 }
2438
2439 fill_sellable_if_needed(reserved_view, pending.size() - at, order);
2440
2441 inputs.reference_price_ = context_.last_price(order.instrument_);
2442 // The currency the order is priced in, which only the reference data knows. A buying-power
2443 // limit is per currency, and an unresolved instrument leaves it absent rather than defaulting
2444 // to one: guessing here would spend one currency's budget on another's order.
2445 const auto* reference = context_.find_instrument(order.instrument_);
2446 inputs.order_currency_ = reference ? std::optional<Currency>(reference->currency_) : std::nullopt;
2447 if (run_) {
2448 // Per order, every order: a figure left from the previous one would bound this one's sell.
2449 inputs.run_holding_ =
2450 order.side_ == OrderSide::SELL ? run_holding_for(view(), order.instrument_) : std::nullopt;
2451 }
2452 // `evaluate` rather than `check`, for one fact `check` drops: whether the phase limit admitted
2453 // this order only because it closes a position. Nothing downstream can recover that -- the
2454 // order, the portfolio and the report all look the same either way -- and it is the one thing
2455 // an operator needs to see, because it is this library sending into a session the operator's
2456 // own limits said not to trade in.
2457 auto decision = guard_.evaluate(order, view(), inputs);
2458 if (decision.rejection_) {
2459 // **Counted here and not at the send site, because there is no send.** A buy left above a
2460 // withheld ceiling is the larger notional, so every limit that multiplies quantity by price
2461 // sees a bigger number than the clamped order would have shown it. (A sell left below a
2462 // withheld floor is the smaller notional; these limits are not what stops that one.)
2463 if (order.price_would_have_been_clamped_) {
2464 ++unclamped_orders_refused_;
2465 }
2466 ++orders_guard_refused_;
2467 if (decision.rejection_->reason_ == strategy::GuardReason::PHASE_NOT_PERMITTED) {
2468 retain_for_phase(source_instruction);
2469 }
2470 report.refused_.push_back(std::move(*decision.rejection_));
2471 continue;
2472 }
2473
2474 // The copy later orders are checked against, taken before this one is sent (see above).
2475 if (!reserved_view && at + 1 < pending.size()) {
2476 reserved_view = context_.portfolio();
2477 reserved_view->working_.reserve(reserved_view->working_.size() + pending.size() - at);
2478 }
2479
2480 // **The route it is sent with, written into the order before anything records it.** A
2481 // strategy names no venue, and a binding may send one anyway (`SessionExecutor::default_route`).
2482 // Resolved here rather than only at the wire so the journal line, the row `reserve` keeps --
2483 // which `cancel_all` and every other instruction built from it restate -- and the report all
2484 // name the venue the broker was asked for, not the blank the strategy left.
2485 order.venue_ = requested_route(order.venue_);
2486 const auto outcome = place_order(order, baseline);
2487 // **Counted where the outcome is known, not where the exception was granted.** An admitted
2488 // order can still be refused by the sellable check, a buying-power limit or either ceiling and
2489 // never leave the process, so counting at the guard would report a proxy for the harm rather
2490 // than the harm. `REJECTED` counts: the request went out and the broker answered it, which is
2491 // exactly the nightly-rejection case this exception was chosen knowing about, and a witness
2492 // that stayed at zero through every one of them would be silent in the case it exists for.
2493 // `REFUSED_LOCALLY` and `UNAVAILABLE` do not: nothing was sent. This is the same division
2494 // `note_sent` already makes, for the same reason.
2495 if (decision.admitted_outside_phase_ && send_outcome_reached_broker(outcome)) {
2496 ++sends_outside_permitted_phase_;
2497 }
2498 // **Split on whether a broker was asked, which is the division `send_outcome_reached_broker`
2499 // already makes.** `REJECTED` means the exchange saw this price and refused it.
2500 // `REFUSED_LOCALLY` means the binding did -- and that is a price-dependent refusal too: a
2501 // limit price no adapter will send is a limit price the withheld band might have moved into
2502 // range. The concrete case is a sell at zero that `Price::checked` admits
2503 // because zero sits on a stated grid. Counting only the first left that invisible.
2504 // `INDETERMINATE` is excluded because it is not a refusal at all -- the request may well be
2505 // resting -- and `UNAVAILABLE` because it is local machinery being unavailable, which no price
2506 // affects.
2507 if (order.price_would_have_been_clamped_) {
2508 if (outcome == SendOutcome::REJECTED) {
2509 ++unclamped_orders_rejected_;
2510 } else if (outcome == SendOutcome::REFUSED_LOCALLY) {
2511 ++unclamped_orders_refused_;
2512 }
2513 }
2514 // After every send, not only after a refusal. A terminal journal write that fails leaves the
2515 // broker's own outcome intact -- the send happened, and saying otherwise would be a lie -- but
2516 // it still means the journal is broken, and the runner must stop.
2517 note_executor_failure(send_outcome_is_local_failure(outcome));
2518 switch (outcome) {
2520 // Counted against the rate limit only once the instruction actually went, so an order a
2521 // guard refused or the ledger withheld does not spend budget.
2522 guard_.note_sent(inputs.now_);
2523 ++placements_at_broker_;
2524 // And it is working now, as far as anything later in this pass is concerned, and its
2525 // money is spent. An `INDETERMINATE` send is counted the same way below, with no reference.
2526 spend_run_cash(order, inputs);
2527 reserve_for_later(at, order, last_ref());
2528 persist_reservation(order, inputs.reference_price_, inputs.order_currency_, last_ref());
2529 track_unconfirmed(order, last_ref(), /*indeterminate=*/false, baseline);
2530 report.would_place_.push_back(std::move(order));
2531 break;
2533 // A refusal is an answer: the order does not exist, so nothing needs reconciling. It
2534 // still consumed a request, which is what the broker will have counted.
2535 guard_.note_sent(inputs.now_);
2536 ++orders_broker_refused_;
2537 // An exit the phase limit let out of session, refused by a broker not taking orders then:
2538 // the target waits for the session instead of for its next bar, which may be a day away.
2539 if (decision.admitted_outside_phase_) {
2540 retain_for_phase(source_instruction, /*broker_answered=*/true);
2541 } else if (last_error_is(broker_rate_limited)) {
2542 // **Turned away for the broker's rate limit, which is about the moment.** Kept as an
2543 // unreachable send is, and offered again after a newer holdings read: dropped, a daily
2544 // strategy's opening order or protective stop refused once at a busy open waited a day
2545 // (in a simulated run, one `EGW00201` at 09:00 moved a buy to the next session and left a position
2546 // without its stop all day). The broker processed nothing, so a retry cannot double it.
2547 retain_for_phase(source_instruction, /*broker_answered=*/true, context_.portfolio().as_of_);
2548 }
2549 note_broker_refusal(order);
2550 report.rejected_.push_back(
2551 strategy::Rejection{strategy::RejectReason::BROKER_REFUSED, order.instrument_, order.tag_}
2552 );
2553 break;
2555 guard_.note_sent(inputs.now_);
2556 // Counted like an acceptance for the purpose below: the order may exist, and a listing
2557 // read before this moment cannot show it either way.
2558 ++placements_at_broker_;
2559 ledger_.mark(order.instrument_, "an order request has an unknown outcome");
2560 ++orders_indeterminate_;
2561 note_run_unknown(order, inputs);
2562 // **Counted as if accepted, until the sweep says what became of it.** The ledger
2563 // withholds the instrument meanwhile; but once a sweep finds the order in the broker's
2564 // listing it clears the ledger, and a market order that filled is then in no listing while
2565 // holdings may not show it yet, so a target sent it again (twice the target, in one
2566 // process). Reserved and tracked here with the holding at send as the baseline, and handed
2567 // its reference by `resolve_indeterminate_placement`. **No reference** is passed on purpose:
2568 // `last_ref()` still names the previous accepted order, and a row carrying it could be
2569 // withdrawn in that order's place.
2570 // A serialized runner records it whatever its executor reports: it owns the instrument until
2571 // accounted for.
2572 if constexpr (keeps_sent_orders_until_listed) {
2573 if (serialized() || runner_detail::reports_last_ref<Executor>::value) {
2574 reserve_for_later(at, order, std::nullopt);
2575 persist_reservation(order, inputs.reference_price_, inputs.order_currency_, std::nullopt);
2576 track_unconfirmed(order, std::nullopt, /*indeterminate=*/true, baseline);
2577 }
2578 }
2579 report.indeterminate_.push_back(std::move(order));
2580 break;
2582 // **No `note_sent`**: the binding refused it, so no request went out and the broker
2583 // counted nothing. Spending rate-limit budget here would refuse a later order that would
2584 // have been allowed, for a request nobody made. Reported as a rejection because that is
2585 // what it is from the order's point of view -- it does not exist, and nothing needs
2586 // reconciling -- and the runner keeps trading, because the next instruction may be
2587 // perfectly sendable. The reason is carried on the entry itself rather than left to
2588 // `last_error()`: a later accepted order in the same pass clears that, so a report can
2589 // outlive the only record of which refusal this was.
2590 ++orders_binding_refused_;
2591 if (decision.admitted_outside_phase_) {
2592 retain_for_phase(source_instruction);
2593 } else if (last_error_is(broker_unreachable)) {
2594 // **The broker could not be reached, so the decision is kept rather than lost.** Dropped,
2595 // a daily strategy's target or protective stop released at the open into a dropped
2596 // connection waited for its next bar, a day away (in a simulated run, a 30-minute outage at 09:00 moved a
2597 // buy to the next session and left a position without its stop all day). Kept as a phase
2598 // refusal is -- discarded by a stop, an operator's halt or a local failure, replaced by a
2599 // later statement, an intent checked against the book -- and offered again only after a
2600 // holdings read newer than this one, which is the evidence the broker answers again: a
2601 // retry every tick into a dead connection would wait out a connect timeout per instrument
2602 // per iteration, and hold up a stop behind it.
2603 retain_for_phase(source_instruction, /*broker_answered=*/false, context_.portfolio().as_of_);
2604 }
2605 report.rejected_.push_back(
2606 strategy::Rejection{strategy::RejectReason::BINDING_REFUSED, order.instrument_, order.tag_}
2607 );
2608 break;
2610 // No `note_sent`: nothing went out, so the broker counted nothing and no rate-limit
2611 // budget was spent. The ledger is not marked either -- an instruction that was never
2612 // attempted leaves no doubt about the position, and withholding the instrument would be
2613 // withholding it for the wrong reason.
2614 ++instructions_unavailable_;
2615 report.unavailable_.push_back(
2616 WithheldOrder{
2618 order,
2620 guard_.hold_detail(strategy::HaltReason::LOCAL_FAILURE) :
2621 std::string("local machinery refused to send"),
2622 }
2623 );
2624 break;
2625 }
2626 }
2627
2628 // The pass's instructions die with it; so do the pointers kept to deduplicate them.
2629 kept_this_pass_.clear();
2630 report.log_ = context_.log().take();
2631 return report;
2632 }
2633
2634 // Sends one cancellation, and marks the instrument when its outcome is unknown.
2635 //
2636 // A cancellation that fails in transit leaves the same question an order does -- the order may
2637 // now be withdrawn or may still be resting -- so it obliges the same reconciliation. A
2638 // cancellation is not gated by the ledger, because withdrawing an order is the one action that
2639 // cannot make an unresolved position worse.
2640 // Asks the broker what may be sold, but only when nothing else can answer.
2641 //
2642 // Four conditions, and every one of them is there to avoid a request:
2643 //
2644 // - the executor can ask at all -- a dry run and a replay cannot, and compile to nothing here;
2645 // - the caller enforces the limit, so nobody pays for a figure no check reads;
2646 // - the order is a sell, since the figure says nothing about buying;
2647 // - and the snapshot has not already answered, which at a `HOLDINGS` broker it always has.
2648 //
2649 // The answer is written to the context's portfolio as well as to this pass's copy, so a later
2650 // pass in the same holdings cycle reuses it rather than asking again. The next holdings poll
2651 // replaces the positions wholesale and the figure goes with them, which is the right lifetime: it
2652 // is exactly as fresh as the position it describes.
2653 void fill_sellable_if_needed(
2654 std::optional<strategy::Portfolio<Tag>>& reserved_view, std::size_t orders_left, const strategy::PlannedOrder& order
2655 ) {
2656 if constexpr (runner_detail::fills_sellable<Executor>::value) {
2657 if (!guard_.limits().enforce_sellable_quantity_ || order.side_ != OrderSide::SELL) {
2658 return;
2659 }
2660 if ((reserved_view ? *reserved_view : context_.portfolio()).sellable_quantity_of(order.instrument_)) {
2661 return;
2662 }
2663 // The view is fixed before the executor is asked: it may replace the context's portfolio meanwhile.
2664 if (!reserved_view) {
2665 reserved_view = context_.portfolio();
2666 reserved_view->working_.reserve(reserved_view->working_.size() + orders_left);
2667 }
2668 const auto answered = executor_.sellable_quantity(order.instrument_);
2669 if (!answered) {
2670 // Left absent, so the guard refuses for the reason it already has. Reporting a failure to
2671 // establish the figure as a sellable quantity of zero would be a different claim.
2672 return;
2673 }
2674 write_sellable(*reserved_view, order.instrument_, *answered);
2675 auto persisted = context_.portfolio();
2676 write_sellable(persisted, order.instrument_, *answered);
2677 context_.set_portfolio(std::move(persisted));
2678 } else {
2679 static_cast<void>(reserved_view);
2680 static_cast<void>(orders_left);
2681 static_cast<void>(order);
2682 }
2683 }
2684
2685 // Sends one order, stating the baseline to the journal in serialized mode.
2686 SendOutcome place_order(
2687 const strategy::PlannedOrder& order, [[maybe_unused]] const std::optional<Decimal64>& baseline
2688 ) {
2689 if constexpr (can_serialize) {
2690 if (serialized()) {
2691 return executor_.place(order, baseline);
2692 }
2693 }
2694 return executor_.place(order);
2695 }
2696
2697 // Returns the venue the executor sends an order asking for `asked` to; `asked` where it does not route.
2698 Venue requested_route(Venue asked) const {
2699 if constexpr (runner_detail::resolves_route<Executor>::value) {
2700 return executor_.requested_route(asked);
2701 } else {
2702 return asked;
2703 }
2704 }
2705
2706 // Returns the reference the broker issued for the order just accepted, where there is one.
2707 //
2708 // Nothing where the executor has no broker to have been answered by, which is every dry run and
2709 // every replay.
2710 std::optional<OrderRef<Tag>> last_ref() const {
2711 if constexpr (runner_detail::reports_last_ref<Executor>::value) {
2712 return executor_.last_ref();
2713 } else {
2714 return std::nullopt;
2715 }
2716 }
2717
2718 // What a run's order filled, taken from a dated history row of its own (serialized mode, a run budget).
2719 struct RunBooking {
2720 // Equals `expected_` when taken, and checked again when the order is accounted for.
2721 Decimal64 filled_;
2722 // The row's `filled_amount_`, else its average price times `filled_`, in the run's currency.
2723 Money amount_;
2724 // As the row states them, if it does.
2725 std::optional<Money> commission_;
2726 std::optional<Money> tax_;
2727 };
2728
2729 // A run order's booking as its `CONFIRMED` line writes it, and the note when its fees are above the estimate.
2730 struct RunBooked {
2731 std::shared_ptr<const RunRecord> record_;
2732 std::string note_;
2733 };
2734
2735 // An order the broker accepted, or one whose request failed in transit, that holdings have not yet
2736 // shown in full; see `unconfirmed_orders`.
2737 struct Unconfirmed {
2738 // Empty while the order's outcome is unknown; see `resolve_indeterminate_placement`.
2739 OrderRef<Tag> ref_;
2740 InstrumentId instrument_;
2741 OrderSide side_{OrderSide::BUY};
2742 // What holdings must still show: the order's quantity, or less once its history says so.
2743 Decimal64 expected_;
2744 // The instrument's net holding when it was sent.
2745 Decimal64 baseline_;
2746 // The reserved row as `reserve` wrote it; rebuilt with the residual quantity.
2747 WorkingOrder<Tag> row_;
2748 std::chrono::system_clock::time_point sent_at_{};
2749 // Whether any listing has carried it, and whether the latest one does.
2750 bool listed_{false};
2751 bool listed_now_{false};
2752 // Whether this runner's withdrawal of it was accepted.
2753 bool withdrawn_{false};
2754 // Whether a terminal history row has capped `expected_`.
2755 bool settled_{false};
2756 // Whether it is a DAY order and the session it was sent in has closed since.
2757 bool session_ended_{false};
2758 // Whether the current `confirm_from_history` looked for it.
2759 bool consulted_{false};
2760 // Whether the history, read past the timeout, had no terminal row for it.
2761 bool history_missed_{false};
2762 // The quantity nothing explains, as of the last rebuild, and since when some has been.
2763 Decimal64 residual_;
2764 std::optional<std::chrono::system_clock::time_point> unexplained_since_;
2765 // Serialized mode (`serialized`). The order's journal line, whose id names it to a sweep and to the
2766 // line that accounts for it.
2767 std::optional<JournalEntry> journal_;
2768 // Whether `ref_` came from the broker's own acceptance, so a cancellation can be built from it; a
2769 // restored order or one a sweep named carries the order id alone.
2770 bool broker_ref_{false};
2771 // Restored from the journal at startup: its history is read once even though no listing carried it.
2772 bool restored_{false};
2773 // Only an operator may account for it (`release_obligations`).
2774 bool operator_only_{false};
2775 // Whether its timeout was counted, which happens once (and, for one not yet named, marked the ledger).
2776 bool noticed_{false};
2777 // Whether its name is the broker's own: given at acceptance, or confirmed by a dated history row of
2778 // its send. A name a sweep gave from a listing may belong to another day's order.
2779 bool identified_{false};
2780 // The holdings read it was decided against; an older one says nothing about it.
2781 std::chrono::system_clock::time_point baseline_at_{};
2782 // Why it is held for an operator, while that hold's `HELD` line is not yet written.
2783 std::string unwritten_hold_;
2784 // A run budget's order (serialized mode): its fill is booked in the run's ledger when it is accounted for.
2785 bool run_order_{false};
2786 // Holdings show what it filled but no history row has booked it yet, so it is not yet accounted for.
2787 bool awaiting_booking_{false};
2788 // What it filled and for how much, from its own history row; cleared whenever `expected_` changes.
2789 std::optional<RunBooking> booking_;
2790 };
2791
2792 // ---------------------------------------------------------------------------------------------------
2793 // Serialized mode (`serialized`): one order per instrument until holdings or its own history account
2794 // for it. In file order: tracking (`track_serialized`), confirmation (`confirm_serialized`), the gate
2795 // (`serial_hold`), evidence (`examine_evidence`), the journal writes (`discharge`, `persist_hold`) and
2796 // restore (`restore_from`). Confirmation and the gate use these only when `serialized()`;
2797 // `release_obligations` uses some whenever `can_serialize`.
2798 // ---------------------------------------------------------------------------------------------------
2799
2800 // `track_unconfirmed` for a serialized runner: every order, named or not, with the baseline the send
2801 // stated and the journal line it wrote. The gate guaranteed the holdings.
2802 void track_serialized(
2803 const strategy::PlannedOrder& order, const std::optional<OrderRef<Tag>>& ref, bool indeterminate,
2804 const Decimal64& baseline
2805 ) {
2806 const auto& portfolio = context_.portfolio();
2807 Unconfirmed entry;
2808 if (ref && !indeterminate) {
2809 entry.ref_ = *ref;
2810 entry.broker_ref_ = !ref->primary_.empty();
2811 entry.identified_ = entry.broker_ref_;
2812 }
2813 entry.baseline_at_ = portfolio.as_of_;
2814 entry.instrument_ = order.instrument_;
2815 entry.side_ = order.side_;
2816 entry.expected_ = order.quantity_;
2817 entry.baseline_ = baseline;
2818 entry.row_ = portfolio.working_.back();
2819 entry.sent_at_ = freshness_instant();
2820 entry.residual_ = order.quantity_;
2821 entry.journal_ = executor_.last_entry();
2822 // A serialized runner's run is open only from its journal, and its executor stamped this order's lines.
2823 entry.run_order_ = run_.has_value();
2824 if (entry.sent_at_ != std::chrono::system_clock::time_point{}) {
2825 entry.unexplained_since_ = entry.sent_at_;
2826 }
2827 unconfirmed_.push_back(std::move(entry));
2828 }
2829
2830 // Whether a reserved row carries the reference the broker gave when it accepted the order.
2831 bool cancellable_reservation(const WorkingOrder<Tag>& working) const {
2832 if (working.ref_.primary_.empty()) {
2833 return false;
2834 }
2835 for (const auto& entry : unconfirmed_) {
2836 if (is_reserved_row_of(working, entry)) {
2837 return entry.broker_ref_;
2838 }
2839 }
2840 return true;
2841 }
2842
2843 // The serialized half of `confirm_reservations`: one order per instrument, so no group arithmetic.
2844 //
2845 // Each order is accounted for, with a `CONFIRMED` line written first, when it is named, no listing
2846 // shows it open, and either its history capped what it filled at zero, or a holdings read shows
2847 // exactly its baseline plus what it filled. Holdings past that hold it for an operator. Anything else
2848 // rebuilds its reserved row from what nothing explains yet; a timeout is counted once and releases
2849 // nothing (only an order not yet named marks the ledger).
2850 void confirm_serialized(strategy::Portfolio<Tag>& portfolio, std::chrono::system_clock::time_point now) {
2851 const auto zero = Decimal64::parse("0");
2852 const auto epoch = std::chrono::system_clock::time_point{};
2853 const auto equal = [](const Decimal64& a, const Decimal64& b) {
2854 return !decimal_less(a, b) && !decimal_less(b, a);
2855 };
2856 for (auto at = unconfirmed_.begin(); at != unconfirmed_.end();) {
2857 auto& entry = *at;
2858 persist_hold(entry);
2859 entry.awaiting_booking_ = false;
2860 // An actual read, and not one older than the read the order was decided against.
2861 const bool read = portfolio.as_of_ != epoch && !(portfolio.as_of_ < entry.baseline_at_);
2862 // What a listing still shows of it: that part cannot have reached holdings.
2863 Decimal64 listed = zero;
2864 entry.listed_now_ = false;
2865 std::optional<Decimal64> listed_filled;
2866 if (const auto* working = broker_row_for(portfolio, entry)) {
2867 entry.listed_ = true;
2868 entry.listed_now_ = true;
2869 listed =
2870 decimal_subtract(working->order_.quantity_, working->order_.execution_.filled_quantity_).value_or(zero);
2871 listed_filled = working->order_.execution_.filled_quantity_;
2872 }
2873 // A listing of its own reporting more filled than it was for, or than its history said it ended with,
2874 // contradicts what is known: held for an operator before the listing can move on and the contradiction
2875 // be forgotten. (Holding is the safe direction, so an undated row may prove it.)
2876 if (
2877 listed_filled && !entry.operator_only_ &&
2878 (decimal_less(entry.row_.order_.quantity_, *listed_filled) ||
2879 (entry.settled_ && decimal_less(entry.expected_, *listed_filled)))
2880 ) {
2881 hold_for_operator(
2882 entry,
2883 "an order this runner sent" + named(entry) + " is listed with " + listed_filled->str() +
2884 " filled, more than " +
2885 (entry.settled_ ? "its history said it ended with (" + entry.expected_.str() + ")" : "it was for")
2886 );
2887 }
2888 // The holding, and its movement in the order's direction since the baseline, from an actual read.
2889 std::optional<Decimal64> held;
2890 std::optional<Decimal64> moved;
2891 if (read) {
2892 held = portfolio.net_quantity_of(entry.instrument_);
2893 if (held) {
2894 moved = entry.side_ == OrderSide::BUY ?
2895 decimal_subtract(*held, entry.baseline_) :
2896 decimal_subtract(entry.baseline_, *held);
2897 }
2898 }
2899 const bool is_named = !entry.ref_.primary_.empty();
2900 if (!entry.operator_only_ && is_named && entry.identified_ && !entry.listed_now_) {
2901 // A run's order is accounted for only with what it cost, prepared here once: until a history row
2902 // books it, it stays owed.
2903 const bool ending = entry.expected_.coefficient() == 0 || (moved && equal(*moved, entry.expected_));
2904 const auto booked = ending && run_ && entry.run_order_ ? run_booking_of(entry) : std::nullopt;
2905 if (entry.expected_.coefficient() == 0) {
2906 if (discharge(entry, std::nullopt, "its own history row shows it ended with nothing filled", booked)) {
2907 at = unconfirmed_.erase(at);
2908 continue;
2909 }
2910 } else if (moved && equal(*moved, entry.expected_)) {
2911 if (run_ && entry.run_order_ && !booked) {
2912 entry.awaiting_booking_ = true;
2913 } else if (
2914 discharge(
2915 entry, held,
2916 "holdings show " + held->str() + ": its baseline " + entry.baseline_.str() + " and the " +
2917 entry.expected_.str() + " it filled",
2918 booked
2919 )
2920 ) {
2921 set_boundary(entry.instrument_, portfolio.as_of_, /*strict=*/false);
2922 at = unconfirmed_.erase(at);
2923 continue;
2924 }
2925 } else if (moved && decimal_less(entry.expected_, *moved)) {
2926 hold_for_operator(
2927 entry,
2928 "holdings moved " + moved->str() + " from the baseline " + entry.baseline_.str() + ", more than the " +
2929 entry.expected_.str() + " an order this runner sent" + named(entry) + " can explain"
2930 );
2931 }
2932 }
2933
2934 // What nothing explains yet: what it expects, less what holdings show of it, less what is listed.
2935 Decimal64 covered = zero;
2936 const auto fillable = decimal_subtract(entry.expected_, listed).value_or(zero);
2937 if (!entry.operator_only_ && moved && decimal_less(zero, *moved) && decimal_less(zero, fillable)) {
2938 covered = decimal_less(*moved, fillable) ? *moved : fillable;
2939 }
2940 auto residual = decimal_subtract(fillable, covered).value_or(entry.expected_);
2941 const bool explained = !decimal_less(zero, residual);
2942 // Waiting for its booking, it is not explained: its clock runs and its timeout is counted below.
2943 if (explained && !entry.awaiting_booking_) {
2944 mark_explained(entry);
2945 ++at;
2946 continue;
2947 }
2948 entry.residual_ = explained ? zero : residual;
2949 // Not from the epoch: a restored order's clock starts with the first real instant.
2950 if (!entry.unexplained_since_ && now != epoch) {
2951 entry.unexplained_since_ = now;
2952 }
2953 if (
2954 !entry.noticed_ && !entry.operator_only_ && (entry.settled_ || entry.history_missed_ || !is_named) &&
2955 (!entry.awaiting_booking_ || entry.history_missed_) && timed_out(entry, now) &&
2956 portfolio.as_of_ - *entry.unexplained_since_ > confirmation_timeout_
2957 ) {
2958 // A notice, not a release: the order still holds its instrument, and later evidence can still
2959 // account for it. A named one marks no ledger: the gate already withholds the instrument while it
2960 // is owed, and a mark would outlive the holdings that account for it. An unnamed one is accounted
2961 // for only by an operator.
2962 entry.noticed_ = true;
2963 ++orders_unconfirmed_timed_out_;
2964 if (!is_named) {
2965 ledger_.mark(
2966 entry.instrument_,
2967 "an order this runner sent" + named(entry) +
2968 " was not accounted for by holdings within the confirmation timeout; it still holds the instrument"
2969 );
2970 }
2971 }
2972 // Not shown while the ledger holds an order not yet named; see the overlapping branch.
2973 if (!is_named && ledger_.requires_reconcile(entry.instrument_)) {
2974 ++at;
2975 continue;
2976 }
2977 if (!explained) {
2978 rebuild_residual_row(portfolio, entry, residual);
2979 }
2980 ++at;
2981 }
2982 }
2983
2984 // The instant after which a holdings read may size the next order on an instrument (serialized
2985 // mode): the read that accounted for its last order (that read itself qualifies), or the instant an
2986 // operator released it or a previous process confirmed it (only a later read qualifies).
2987 struct Boundary {
2988 InstrumentId instrument_;
2989 std::chrono::system_clock::time_point at_{};
2990 bool strict_{false};
2991 };
2992
2993 // Records `instrument`'s boundary, replacing an earlier one.
2994 void set_boundary(const InstrumentId& instrument, std::chrono::system_clock::time_point at, bool strict) {
2995 for (auto& boundary : boundaries_) {
2996 if (boundary.instrument_ == instrument) {
2997 if (boundary.at_ < at || (!(at < boundary.at_) && strict)) {
2998 boundary.at_ = at;
2999 boundary.strict_ = strict;
3000 }
3001 return;
3002 }
3003 }
3004 boundaries_.push_back(Boundary{instrument, at, strict});
3005 }
3006
3007 // Why the holdings in hand cannot be the baseline of an order on `instrument`, or nothing.
3008 std::optional<std::string> baseline_missing(const InstrumentId& instrument) const {
3009 const auto& portfolio = context_.portfolio();
3010 if (portfolio.as_of_ == std::chrono::system_clock::time_point{}) {
3011 return std::string("holdings have not been read, so the order would have no baseline");
3012 }
3013 if (!portfolio.net_quantity_of(instrument)) {
3014 return std::string("the holding's rows do not add up, so the order would have no baseline");
3015 }
3016 for (const auto& boundary : boundaries_) {
3017 if (
3018 boundary.instrument_ == instrument &&
3019 (boundary.strict_ ? !(boundary.at_ < portfolio.as_of_) : portfolio.as_of_ < boundary.at_)
3020 ) {
3021 return std::string(
3022 "the holdings were read before the last order on this instrument was accounted for; waiting for a "
3023 "newer read"
3024 );
3025 }
3026 }
3027 return std::nullopt;
3028 }
3029
3030 // Why a serialized runner may not place on `instrument` now, or nothing; `claimed` lists the
3031 // instruments an earlier plan in this pass places on.
3032 std::optional<std::string> serial_hold(
3033 const InstrumentId& instrument, const std::vector<InstrumentId>& claimed
3034 ) const {
3035 if (!can_serialize) {
3036 return std::string(
3037 "this runner journals to a broker but cannot serialize its orders (it needs a broker that lists working "
3038 "orders, and an executor with last_entry and record); see allow_overlapping_orders"
3039 );
3040 }
3041 if (!recovered_) {
3042 return std::string("nothing is placed before runner::recover_runner has run");
3043 }
3044 for (const auto& entry : unconfirmed_) {
3045 if (!(entry.instrument_ == instrument)) {
3046 continue;
3047 }
3048 switch (state_of(entry)) {
3050 return "an order on this instrument" + named(entry) + " is held for an operator (release_obligations)";
3052 return std::string("an order on this instrument has an unknown outcome and no sweep has named it");
3055 break;
3056 }
3057 return "an order on this instrument" + named(entry) + " is not yet accounted for by holdings";
3058 }
3059 for (const auto& id : claimed) {
3060 if (id == instrument) {
3061 return std::string("an earlier instruction in this pass places on this instrument");
3062 }
3063 }
3064 return baseline_missing(instrument);
3065 }
3066
3067 static std::string named(const Unconfirmed& entry) {
3068 return entry.ref_.primary_.empty() ? std::string() : " (" + entry.ref_.primary_ + ")";
3069 }
3070
3071 // Whether a history row's status ends the original order, so its filled quantity is final.
3072 // `CANCEL_REJECTED` and `REPLACE_REJECTED` say a request about it failed, not that it ended.
3073 static bool ends_the_order(OrderStatus status) noexcept {
3074 switch (status) {
3075 case OrderStatus::FILLED:
3076 case OrderStatus::CANCELED:
3077 case OrderStatus::REJECTED:
3078 return true;
3079 // Not an end of this order: a replacement or a refused change leaves it, or its successor, to settle.
3080 case OrderStatus::UNKNOWN:
3081 case OrderStatus::PENDING:
3082 case OrderStatus::PENDING_CANCEL:
3083 case OrderStatus::PENDING_REPLACE:
3084 case OrderStatus::PARTIAL_FILLED:
3085 case OrderStatus::CANCEL_REJECTED:
3086 case OrderStatus::REPLACE_REJECTED:
3087 case OrderStatus::REPLACED:
3088 return false;
3089 }
3090 return false;
3091 }
3092
3093 // The rows that are `entry`'s own order: its number, instrument and side, dated within the tolerance of
3094 // its send. An undated row is nobody's in particular.
3095 bool own_row(const OrderSnapshot& row, const Unconfirmed& entry) const {
3096 return row.order_id_ == entry.ref_.primary_ && row.instrument_ == entry.instrument_ && row.side_ == entry.side_ &&
3097 row.ordered_at_ && !(*row.ordered_at_ < entry.sent_at_ - order_time_tolerance_) &&
3098 !(entry.sent_at_ + order_time_tolerance_ < *row.ordered_at_);
3099 }
3100
3101 // The history row that settles a serialized order: every row with its number, instrument and side (and,
3102 // where dated, inside its window) is dated, ended it, and filled the same, no more than it was for.
3103 // Otherwise none: an undated row may be another day's order, and `CANCEL_REJECTED` beside `CANCELED`
3104 // means the pages disagree about whether it ended.
3105 const OrderSnapshot* ended_row_for(const std::vector<OrderSnapshot>& evidence, const Unconfirmed& entry) const {
3106 const OrderSnapshot* found = nullptr;
3107 for (const auto& row : evidence) {
3108 if (row.order_id_ != entry.ref_.primary_ || !(row.instrument_ == entry.instrument_) || row.side_ != entry.side_) {
3109 continue;
3110 }
3111 if (row.ordered_at_ && !own_row(row, entry)) {
3112 continue;
3113 }
3114 if (
3115 !row.ordered_at_ || !ends_the_order(row.status_) ||
3116 decimal_less(entry.row_.order_.quantity_, row.execution_.filled_quantity_) ||
3117 (found != nullptr &&
3118 (decimal_less(found->execution_.filled_quantity_, row.execution_.filled_quantity_) ||
3119 decimal_less(row.execution_.filled_quantity_, found->execution_.filled_quantity_)))
3120 ) {
3121 return nullptr;
3122 }
3123 found = &row;
3124 }
3125 return found;
3126 }
3127
3128 // What a serialized order owes: held for an operator, unknown, or named and waiting.
3129 static ObligationState state_of(const Unconfirmed& entry) noexcept {
3130 return entry.operator_only_ ?
3132 entry.ref_.primary_.empty() ?
3135 }
3136
3137 // Takes in everything history rows say about each named order, before anything can account for it,
3138 // whether or not this read was scheduled for it:
3139 // - a row of its own confirms a name a sweep gave it;
3140 // - a row of its own reporting more filled than it was for, or, once its final quantity is known, a
3141 // different final quantity or more filled than it, holds it for an operator;
3142 // - rows that all say it ended (`ended_row_for`) cap what holdings must show, unless a listing still
3143 // shows it open.
3144 void examine_evidence(const std::vector<OrderSnapshot>& evidence) {
3145 if (run_writes_closed()) {
3146 return;
3147 }
3148 const auto now = freshness_instant();
3149 const auto differ = [](const Decimal64& a, const Decimal64& b) {
3150 return decimal_less(a, b) || decimal_less(b, a);
3151 };
3152 for (auto& entry : unconfirmed_) {
3153 if (entry.operator_only_ || entry.ref_.primary_.empty()) {
3154 continue;
3155 }
3156 std::optional<std::string> contradiction;
3157 for (const auto& row : evidence) {
3158 if (!own_row(row, entry)) {
3159 continue;
3160 }
3161 entry.identified_ = true;
3162 const auto& filled = row.execution_.filled_quantity_;
3163 if (decimal_less(entry.row_.order_.quantity_, filled)) {
3164 contradiction = "its history row reports " + filled.str() + " filled, more than the " +
3165 entry.row_.order_.quantity_.str() + " it was for";
3166 } else if (
3167 entry.settled_ &&
3168 (decimal_less(entry.expected_, filled) || (ends_the_order(row.status_) && differ(entry.expected_, filled)))
3169 ) {
3170 contradiction = "its history rows report " + filled.str() + " filled after reporting it ended with " +
3171 entry.expected_.str();
3172 }
3173 if (contradiction) {
3174 break;
3175 }
3176 }
3177 if (contradiction) {
3178 hold_for_operator(entry, "an order this runner sent" + named(entry) + ": " + *contradiction);
3179 continue;
3180 }
3181 if (!entry.settled_ && broker_row_for(context_.portfolio(), entry) == nullptr) {
3182 if (const auto* row = ended_row_for(evidence, entry)) {
3183 entry.expected_ = row->execution_.filled_quantity_;
3184 entry.settled_ = true;
3185 entry.booking_.reset();
3186 // Holdings get a full timeout from here to show it (`confirm_serialized`).
3187 entry.unexplained_since_ = now;
3188 }
3189 }
3190 // On every read, settled or not, after the cap: the booking is for the quantity it finally filled.
3191 if (run_ && entry.run_order_) {
3192 take_run_booking(evidence, entry);
3193 }
3194 }
3195 }
3196
3197 // `confirm_from_history` for a serialized runner: what the rows say is taken in before anything can
3198 // account for an order (`examine_evidence`); then, as for an overlapping runner, an order consulted past
3199 // the timeout with no answer is noted for the next holdings read.
3200 void confirm_serialized_from_history(const std::vector<OrderSnapshot>& evidence) {
3201 if (run_writes_closed()) {
3202 return;
3203 }
3204 examine_evidence(evidence);
3205 confirm_reservations();
3206 const auto now = freshness_instant();
3207 for (auto& entry : unconfirmed_) {
3208 entry.consulted_ = awaits_evidence(entry, now);
3209 if (entry.consulted_ && (!entry.settled_ || entry.awaiting_booking_) && timed_out(entry, now)) {
3210 entry.history_missed_ = true;
3211 }
3212 }
3213 confirm_reservations();
3214 }
3215
3216 // `awaits_evidence` for a serialized runner.
3217 bool awaits_evidence_serialized(const Unconfirmed& entry, std::chrono::system_clock::time_point now) const {
3218 if (run_writes_closed()) {
3219 return false;
3220 }
3221 // An unnamed order waits for a sweep or an operator, and a held one for the operator: no history row
3222 // can be matched to the first or account for the second.
3223 if (entry.operator_only_ || entry.ref_.primary_.empty()) {
3224 return false;
3225 }
3226 // A name a sweep gave needs a row of the order's own day, however much of it holdings already show.
3227 if (!entry.identified_) {
3228 return true;
3229 }
3230 // Its booking comes only from its own history row, until the history has had no answer past the timeout.
3231 if (entry.awaiting_booking_) {
3232 return !entry.history_missed_;
3233 }
3234 if (entry.residual_.coefficient() == 0 || entry.settled_ || entry.history_missed_) {
3235 return false;
3236 }
3237 if (timed_out(entry, now)) {
3238 return true;
3239 }
3240 // A restored order may have left every listing while no process was running.
3241 return !entry.listed_now_ && (entry.listed_ || entry.withdrawn_ || entry.restored_);
3242 }
3243
3244 // The line that accounts for, or holds, an order (serialized mode).
3245 static JournalEntry closing_line(
3246 const Unconfirmed& entry, JournalOutcome outcome, std::optional<Decimal64> holding, std::string detail
3247 ) {
3248 JournalEntry line = entry.journal_ ? *entry.journal_ : JournalEntry{};
3249 line.outcome_ = outcome;
3250 line.order_id_ = entry.ref_.primary_;
3251 line.baseline_ = std::move(holding);
3252 line.detail_ = std::move(detail);
3253 line.requires_operator_ = journal_outcome_requires_operator(outcome);
3254 return line;
3255 }
3256
3257 // Writes one of this runner's own lines (a closing line, a hold, a release, a run's record): refused while the
3258 // run's writes are closed, except a run's opening lines before the run is open, never after a failed write. A
3259 // failure halts and stops a budgeted run's writes.
3260 bool run_record([[maybe_unused]] JournalEntry& line, [[maybe_unused]] bool opening = false) {
3261 if constexpr (can_serialize) {
3262 if (run_journal_latched_ || (!opening && run_writes_closed())) {
3263 return false;
3264 }
3265 if (executor_.record(line)) {
3266 return true;
3267 }
3269 note_executor_failure(false);
3270 }
3271 return false;
3272 }
3273
3274 // Writes the line accounting for `entry`, with a run order's booking as confirmation prepared it; on failure
3275 // the runner stops sending and `entry` stays.
3276 bool discharge(
3277 [[maybe_unused]] const Unconfirmed& entry, [[maybe_unused]] std::optional<Decimal64> holding,
3278 [[maybe_unused]] std::string detail, [[maybe_unused]] const std::optional<RunBooked>& booked = std::nullopt
3279 ) {
3280 if constexpr (can_serialize) {
3281 // A run's order is never accounted for without its booking, which rides on this line: one append.
3282 if (run_ && entry.run_order_ && !booked) {
3283 return false;
3284 }
3285 auto line = closing_line(entry, JournalOutcome::CONFIRMED, std::move(holding), std::move(detail));
3286 if (booked) {
3287 line.run_ = booked->record_;
3288 line.detail_ += booked->note_;
3289 }
3290 if (run_record(line)) {
3291 if (booked) {
3292 run_->book_placement(
3293 run_placement_of(entry), *booked->record_->filled_, *booked->record_->amount_, *booked->record_->fee_
3294 );
3295 }
3296 return true;
3297 }
3298 }
3299 return false;
3300 }
3301
3302 // Holds `entry` for an operator. In memory at once, whatever the journal does: a contradiction is never
3303 // forgotten. Durably as soon as the `HELD` line is written; until then the runner stops sending, and every
3304 // refresh writes it again (`persist_hold`).
3305 void hold_for_operator(Unconfirmed& entry, const std::string& detail) {
3306 entry.operator_only_ = true;
3307 entry.unwritten_hold_ = detail;
3308 ledger_.mark(entry.instrument_, detail + "; an operator must account for it (release_obligations)");
3309 persist_hold(entry);
3310 }
3311
3312 // Writes the `HELD` line of a hold not yet in the journal; on failure the runner stops sending.
3313 void persist_hold([[maybe_unused]] Unconfirmed& entry) {
3314 if constexpr (can_serialize) {
3315 if (entry.unwritten_hold_.empty()) {
3316 return;
3317 }
3318 auto line = closing_line(entry, JournalOutcome::HELD, std::nullopt, entry.unwritten_hold_);
3319 if (run_record(line)) {
3320 entry.unwritten_hold_.clear();
3321 if (run_ && entry.run_order_) {
3322 run_->hold(run_placement_of(entry));
3323 }
3324 }
3325 }
3326 }
3327
3328 // The unnamed order a serialized sweep answered: the one whose journal line is `journal_id`, or none. A
3329 // guess could name another order, and a late answer to one already accounted for finds nothing.
3330 typename std::vector<Unconfirmed>::iterator unnamed_by_journal_id(const std::string& journal_id) {
3331 return std::find_if(unconfirmed_.begin(), unconfirmed_.end(), [&](const Unconfirmed& entry) {
3332 return !journal_id.empty() && entry.journal_ && entry.journal_->id_ == journal_id && entry.ref_.primary_.empty();
3333 });
3334 }
3335
3336 // Restores what a journal left unaccounted for; see `restore_obligations`.
3337 void restore_from(const JournalReplay& replay) {
3338 const auto same = [](const std::optional<Decimal64>& a, const std::optional<Decimal64>& b) {
3339 return a.has_value() == b.has_value() && (!a || (!decimal_less(*a, *b) && !decimal_less(*b, *a)));
3340 };
3341 // Every line repeats the instruction, and the run it belongs to; a `CONFIRMED` or `HELD` line carries
3342 // another holding.
3343 const auto same_instruction = [&](const JournalEntry& a, const JournalEntry& b) {
3344 return a.instrument_ == b.instrument_ && a.side_ == b.side_ && a.type_ == b.type_ &&
3345 a.time_in_force_ == b.time_in_force_ && a.session_ == b.session_ && a.venue_ == b.venue_ &&
3346 same(a.quantity_, b.quantity_) && same(a.price_, b.price_) && same(a.trigger_price_, b.trigger_price_) &&
3347 same(a.baseline_, b.baseline_) && journal_run_of(a) == journal_run_of(b);
3348 };
3349 struct Fold {
3350 JournalEntry line_;
3351 std::chrono::system_clock::time_point sent_at_{};
3352 std::string name_;
3353 // Whether the name came with the broker's acceptance rather than from a sweep.
3354 bool accepted_{false};
3355 bool done_{false};
3356 bool operator_only_{false};
3357 std::string why_;
3358 };
3359 std::vector<Fold> folds;
3360 // Each id's fold, so a long journal is read in one pass.
3361 std::unordered_map<std::string, std::size_t> fold_of;
3362 for (const auto& line : replay.entries_) {
3363 if (line.action_ != JournalAction::PLACE || line.instrument_.symbol_.empty()) {
3364 continue;
3365 }
3366 const bool closing = journal_outcome_is_closing_account(line.outcome_);
3367 const auto known = fold_of.find(line.id_);
3368 auto fold = known == fold_of.end() ? folds.end() : folds.begin() + static_cast<std::ptrdiff_t>(known->second);
3369 if (fold == folds.end()) {
3370 fold_of.emplace(line.id_, folds.size());
3371 folds.push_back(Fold{line, line.recorded_at_, {}, false, false, false, {}});
3372 fold = std::prev(folds.end());
3373 if (closing) {
3374 fold->line_.baseline_.reset();
3375 }
3376 } else {
3377 if (!closing && !same_instruction(fold->line_, line)) {
3378 fold->operator_only_ = true;
3379 fold->why_ = "its journal lines disagree about the order";
3380 }
3381 if (line.recorded_at_ < fold->sent_at_) {
3382 fold->sent_at_ = line.recorded_at_;
3383 }
3384 }
3385 if (line.requires_operator_ && !journal_outcome_requires_operator(line.outcome_)) {
3386 fold->operator_only_ = true;
3387 fold->why_ = line.detail_.empty() ? std::string("a damaged journal line") : line.detail_;
3388 }
3389 switch (line.outcome_) {
3392 if (!line.order_id_.empty()) {
3393 fold->name_ = line.order_id_;
3394 // The broker's reply named it (`ACCEPTED`), not a sweep (`RESOLVED`).
3395 fold->accepted_ = journal_outcome_answers_send(line.outcome_);
3396 }
3397 break;
3399 fold->done_ = true;
3400 set_boundary(line.instrument_, line.recorded_at_, /*strict=*/true);
3401 break;
3403 fold->done_ = true;
3404 break;
3406 fold->operator_only_ = true;
3407 fold->why_ = line.detail_;
3408 break;
3412 break;
3413 }
3414 }
3415
3416 std::vector<Unconfirmed> restored;
3417 // Why each restored order is held for an operator, aligned with `restored`.
3418 std::vector<std::string> why;
3419 for (auto& fold : folds) {
3420 if (fold.done_) {
3421 continue;
3422 }
3423 Unconfirmed entry;
3424 entry.journal_ = fold.line_;
3425 entry.ref_.primary_ = fold.name_;
3426 entry.instrument_ = fold.line_.instrument_;
3427 entry.side_ = fold.line_.side_;
3428 entry.expected_ = fold.line_.quantity_;
3429 entry.baseline_ = fold.line_.baseline_.value_or(Decimal64::parse("0"));
3430 entry.sent_at_ = fold.sent_at_;
3431 // On the shared clock (`serialized`): a holdings read older than the order's own line says nothing.
3432 entry.baseline_at_ = fold.sent_at_;
3433 entry.identified_ = fold.accepted_;
3434 entry.residual_ = fold.line_.quantity_;
3435 entry.restored_ = true;
3436 entry.operator_only_ = fold.operator_only_ || !fold.line_.baseline_;
3437 if (!fold.line_.baseline_ && fold.why_.empty()) {
3438 fold.why_ = "its journal line records no baseline (an overlapping or older runner wrote it)";
3439 }
3440 // The reserved row, rebuilt from the journal's record of the order.
3441 strategy::PlannedOrder order;
3442 order.instrument_ = fold.line_.instrument_;
3443 order.side_ = fold.line_.side_;
3444 order.type_ = fold.line_.type_;
3445 order.time_in_force_ = fold.line_.time_in_force_;
3446 order.session_ = fold.line_.session_;
3447 order.venue_ = fold.line_.venue_.value_or(Venue::UNSPECIFIED);
3448 order.quantity_ = fold.line_.quantity_;
3449 order.price_ = fold.line_.price_;
3450 order.trigger_price_ = fold.line_.trigger_price_;
3451 strategy::Portfolio<Tag> scratch;
3452 reserve(scratch, order, std::nullopt, std::nullopt, entry.ref_, /*spends=*/false);
3453 entry.row_ = scratch.working_.back();
3454 restored.push_back(std::move(entry));
3455 why.push_back(fold.why_);
3456 }
3457 for (std::size_t at = 0; at < restored.size(); ++at) {
3458 for (std::size_t other = 0; other < restored.size(); ++other) {
3459 if (other != at && restored[other].instrument_ == restored[at].instrument_) {
3460 restored[at].operator_only_ = true;
3461 if (why[at].empty()) {
3462 why[at] = "another order on its instrument is also unaccounted for";
3463 }
3464 }
3465 }
3466 }
3467 for (std::size_t at = 0; at < restored.size(); ++at) {
3468 if (restored[at].operator_only_) {
3469 ledger_.mark(
3470 restored[at].instrument_,
3471 "a previous process left an order" + named(restored[at]) + " only an operator may account for (" + why[at] +
3472 "); see release_obligations"
3473 );
3474 }
3475 unconfirmed_.push_back(std::move(restored[at]));
3476 }
3477 }
3478 // Remembers an order the broker just accepted, so a listing that lacks it cannot retire its
3479 // reservation; see `unconfirmed_orders`. Called right after `persist_reservation` wrote its row.
3480 //
3481 // `indeterminate`: an order whose request failed in transit, tracked with no reference until a sweep
3482 // names it (`resolve_indeterminate_placement`).
3483 void track_unconfirmed(
3484 [[maybe_unused]] const strategy::PlannedOrder& order, [[maybe_unused]] const std::optional<OrderRef<Tag>>& ref,
3485 [[maybe_unused]] bool indeterminate = false,
3486 [[maybe_unused]] const std::optional<Decimal64>& baseline = std::nullopt
3487 ) {
3488 if constexpr (keeps_sent_orders_until_listed) {
3489 if constexpr (can_serialize) {
3490 if (serialized() && baseline && !context_.portfolio().working_.empty()) {
3491 track_serialized(order, ref, indeterminate, *baseline);
3492 return;
3493 }
3494 }
3495 track_overlapping(order, ref, indeterminate);
3496 }
3497 }
3498
3499 // `track_unconfirmed` without serialization.
3500 //
3501 // Only an order with a broker reference and a portfolio that has been read: without a reference no
3502 // listing or history row can be matched to it, and without a read portfolio there is no baseline. Those
3503 // keep the old behaviour, where the next listing retires the row. An order of unknown outcome shows no
3504 // row while the indeterminacy ledger withholds its instrument (nothing can be placed there anyway, and a
3505 // resting order's own listed row would be counted twice) and does not time out; only holdings can cover it.
3506 void track_overlapping(
3507 const strategy::PlannedOrder& order, const std::optional<OrderRef<Tag>>& ref, bool indeterminate
3508 ) {
3509 const auto& portfolio = context_.portfolio();
3510 if (
3511 (!indeterminate && (!ref || ref->primary_.empty())) ||
3512 portfolio.as_of_ == std::chrono::system_clock::time_point{} || portfolio.working_.empty()
3513 ) {
3514 return;
3515 }
3516 const auto held = portfolio.net_quantity_of(order.instrument_);
3517 if (!held) {
3518 return;
3519 }
3520 Unconfirmed entry;
3521 if (ref) {
3522 entry.ref_ = *ref;
3523 }
3524 entry.instrument_ = order.instrument_;
3525 entry.side_ = order.side_;
3526 entry.expected_ = order.quantity_;
3527 entry.baseline_ = *held;
3528 entry.row_ = portfolio.working_.back();
3529 entry.sent_at_ = freshness_instant();
3530 entry.residual_ = order.quantity_;
3531 entry.unexplained_since_ = entry.sent_at_;
3532 unconfirmed_.push_back(std::move(entry));
3533 }
3534
3535 // Records that the broker accepted this runner's withdrawal of `ref`, if it is a sent order still counted.
3536 void note_withdrawal_accepted(const OrderRef<Tag>& ref) {
3537 for (auto& entry : unconfirmed_) {
3538 // The primary part alone, as everywhere a broker's own row is matched to the order.
3539 if (!entry.ref_.primary_.empty() && entry.ref_.primary_ == ref.primary_) {
3540 entry.withdrawn_ = true;
3541 }
3542 }
3543 }
3544
3545 // Whether some of `entry`'s quantity has been unexplained for longer than the confirmation timeout.
3546 bool timed_out(const Unconfirmed& entry, std::chrono::system_clock::time_point now) const {
3547 return entry.unexplained_since_ && now - *entry.unexplained_since_ > confirmation_timeout_;
3548 }
3549
3550 // How far a broker's order time may stand from this runner's own record of the order. Order numbers
3551 // repeat only across days, so an hour tells two orders apart and
3552 // still allows for a clock that is off.
3553 static constexpr std::chrono::hours order_time_tolerance_{1};
3554
3555 // The history row that answers for an order: a row with its number and instrument (and side, if
3556 // given) whose order time, where stated, is within `[earliest, latest]`. Null if there is none, or if
3557 // two such rows disagree on what filled or on whether the order is still open: a number reused on
3558 // another day must not answer for this order, and when the rows cannot tell which is which, neither
3559 // does. Rows that agree are one answer (a dated read can return an undated row once per day).
3560 static const OrderSnapshot* history_row_for(
3561 const std::vector<OrderSnapshot>& evidence, const std::string& order_id, const InstrumentId& instrument,
3562 std::optional<OrderSide> side, std::optional<std::chrono::system_clock::time_point> earliest,
3563 std::optional<std::chrono::system_clock::time_point> latest
3564 ) {
3565 const OrderSnapshot* found = nullptr;
3566 for (const auto& row : evidence) {
3567 if (row.order_id_ != order_id || !(row.instrument_ == instrument) || (side && row.side_ != *side)) {
3568 continue;
3569 }
3570 if (row.ordered_at_ && ((earliest && *row.ordered_at_ < *earliest) || (latest && *latest < *row.ordered_at_))) {
3571 continue;
3572 }
3573 if (found == nullptr) {
3574 found = &row;
3575 } else if (
3576 decimal_less(found->execution_.filled_quantity_, row.execution_.filled_quantity_) ||
3577 decimal_less(row.execution_.filled_quantity_, found->execution_.filled_quantity_) ||
3578 strategy::order_is_open(found->status_) != strategy::order_is_open(row.status_)
3579 ) {
3580 return nullptr;
3581 }
3582 }
3583 return found;
3584 }
3585
3586 // Whether only the broker's history can settle `entry` now; see `unconfirmed_awaiting_evidence`.
3587 bool awaits_evidence(const Unconfirmed& entry, std::chrono::system_clock::time_point now) const {
3588 return serialized() ? awaits_evidence_serialized(entry, now) : awaits_evidence_overlapping(entry, now);
3589 }
3590
3591 bool awaits_evidence_overlapping(const Unconfirmed& entry, std::chrono::system_clock::time_point now) const {
3592 // A settled entry has had its answer: what it filled is known, and only holdings remain to show it.
3593 // One the history had no answer for past the timeout waits on holdings too, without a read per poll.
3594 // One with no reference yet never times out *while the ledger holds its instrument*: a sweep will
3595 // name the order or forget it (`resolve_indeterminate_placement`). Once something else lifted the
3596 // hold -- an operator clearing an `ambiguous` sweep by hand -- it is an ordinary entry again: its
3597 // history read finds no row, and a holdings read a timeout on withholds the instrument, counted,
3598 // rather than leaving an order that may never have existed reserved for the rest of the run.
3599 if (
3600 entry.residual_.coefficient() == 0 || entry.settled_ || entry.history_missed_ || entry.operator_only_ ||
3601 (entry.ref_.primary_.empty() && ledger_.requires_reconcile(entry.instrument_))
3602 ) {
3603 return false;
3604 }
3605 if (timed_out(entry, now)) {
3606 return true;
3607 }
3608 return !entry.listed_now_ && (entry.listed_ || entry.withdrawn_ || entry.restored_);
3609 }
3610
3611 // Whether `working` is this runner's reserved row for `entry`.
3612 static bool is_reserved_row_of(const WorkingOrder<Tag>& working, const Unconfirmed& entry) {
3613 return working.reserved_ && working.ref_.primary_ == entry.ref_.primary_ &&
3614 working.order_.instrument_ == entry.instrument_ && working.order_.side_ == entry.side_;
3615 }
3616
3617 // The broker's own open row for `entry`'s order in `portfolio` (never a reservation), or none.
3618 static const WorkingOrder<Tag>* broker_row_for(const strategy::Portfolio<Tag>& portfolio, const Unconfirmed& entry) {
3619 if (entry.ref_.primary_.empty()) {
3620 return nullptr;
3621 }
3622 for (const auto& working : portfolio.working_) {
3623 if (
3624 !working.reserved_ && working.ref_.primary_ == entry.ref_.primary_ &&
3625 working.order_.instrument_ == entry.instrument_ && working.order_.side_ == entry.side_ &&
3626 strategy::order_is_open(working.order_.status_)
3627 ) {
3628 return &working;
3629 }
3630 }
3631 return nullptr;
3632 }
3633
3634 // Puts `entry`'s reserved row back into `portfolio` for the quantity nothing explains yet.
3635 static void rebuild_residual_row(
3636 strategy::Portfolio<Tag>& portfolio, const Unconfirmed& entry, const Decimal64& residual
3637 ) {
3638 auto row = entry.row_;
3639 row.order_.quantity_ = residual;
3640 row.amendable_quantity_ = residual;
3641 portfolio.working_.push_back(std::move(row));
3642 }
3643
3644 // Marks `entry` fully explained by holdings and listing; a later gap starts over, with a fresh timeout and
3645 // a fresh history read.
3646 static void mark_explained(Unconfirmed& entry) {
3647 entry.residual_ = Decimal64::parse("0");
3648 entry.unexplained_since_.reset();
3649 entry.history_missed_ = false;
3650 }
3651
3652 // The newest unnamed order on `instrument` and `side`: the sweep answers the order just sent, and an
3653 // older one still unnamed is left over from a hold cleared by hand without naming it.
3654 typename std::vector<Unconfirmed>::iterator newest_unnamed(const InstrumentId& instrument, OrderSide side) {
3655 const auto newest = std::find_if(unconfirmed_.rbegin(), unconfirmed_.rend(), [&](const Unconfirmed& entry) {
3656 return entry.ref_.primary_.empty() && entry.instrument_ == instrument && entry.side_ == side;
3657 });
3658 return newest == unconfirmed_.rend() ? unconfirmed_.end() : std::prev(newest.base());
3659 }
3660
3661 // Removes `entry`'s reserved row from the context portfolio.
3662 void drop_reserved_row(const Unconfirmed& entry) {
3663 auto portfolio = context_.portfolio();
3664 portfolio.working_.erase(
3665 std::remove_if(
3666 portfolio.working_.begin(), portfolio.working_.end(),
3667 [&](const WorkingOrder<Tag>& working) {
3668 return is_reserved_row_of(working, entry);
3669 }
3670 ),
3671 portfolio.working_.end()
3672 );
3673 context_.set_portfolio(std::move(portfolio));
3674 }
3675
3676 // Rebuilds the reserved row of every sent order still counted, and forgets those holdings confirm.
3677 //
3678 // Run before every handler and every pass, so whatever replaced `working_` since -- a listing, or a
3679 // source of the caller's own -- the strategy and the guard see each order's unexplained quantity.
3680 // `confirm_serialized` and `confirm_overlapping` say when an order counts as confirmed.
3681 void confirm_reservations() {
3682 if constexpr (keeps_sent_orders_until_listed) {
3683 open_new_run_once_closed();
3684 // Closed, nothing is accounted for and no reserved row is stripped: the run's writes have stopped.
3685 if (unconfirmed_.empty() || run_writes_closed()) {
3686 return;
3687 }
3688 const auto now = freshness_instant();
3689 auto portfolio = context_.portfolio();
3690 // Every row this list owns comes out first, and the residual goes back in below.
3691 portfolio.working_.erase(
3692 std::remove_if(
3693 portfolio.working_.begin(), portfolio.working_.end(),
3694 [&](const WorkingOrder<Tag>& working) {
3695 for (const auto& entry : unconfirmed_) {
3696 if (is_reserved_row_of(working, entry)) {
3697 return true;
3698 }
3699 }
3700 return false;
3701 }
3702 ),
3703 portfolio.working_.end()
3704 );
3705 if (serialized()) {
3706 confirm_serialized(portfolio, now);
3707 } else {
3708 confirm_overlapping(portfolio, now);
3709 }
3710 context_.set_portfolio(std::move(portfolio));
3711 }
3712 }
3713
3714 // The overlapping half of `confirm_reservations`: orders grouped per instrument, credited in the order
3715 // they were sent.
3716 //
3717 // - **covered**: holdings movement since the first unconfirmed order's baseline on the instrument, in
3718 // the orders' direction, credited in the order they were sent, each up to what it expects. Orders
3719 // on both sides of one instrument are credited only when holdings equal the baseline plus all of
3720 // them, since a movement could be either side's;
3721 // - **listed**: what a listing still shows remaining for the same reference, instrument and side;
3722 // - the row is put back with `expected - covered - listed`, when that is positive, and **never
3723 // spends buying power again** -- the pass that sent the order already did;
3724 // - the entry ends once `covered` reaches what it expects.
3725 void confirm_overlapping(strategy::Portfolio<Tag>& portfolio, std::chrono::system_clock::time_point now) {
3726 const auto zero = Decimal64::parse("0");
3727 std::vector<bool> retire(unconfirmed_.size(), false);
3728 // Settled by history, or past the timeout with no history answer, and still not in a holdings
3729 // read taken a full timeout later: withheld, with what holdings did show credited to it.
3730 std::vector<bool> expired(unconfirmed_.size(), false);
3731 std::vector<bool> done(unconfirmed_.size(), false);
3732 for (std::size_t first = 0; first < unconfirmed_.size(); ++first) {
3733 if (done[first]) {
3734 continue;
3735 }
3736 const auto& instrument = unconfirmed_[first].instrument_;
3737 const auto direction = unconfirmed_[first].side_;
3738 std::vector<std::size_t> group;
3739 bool mixed = false;
3740 for (std::size_t at = first; at < unconfirmed_.size(); ++at) {
3741 if (unconfirmed_[at].instrument_ == instrument) {
3742 group.push_back(at);
3743 done[at] = true;
3744 mixed = mixed || unconfirmed_[at].side_ != direction;
3745 }
3746 }
3747 // `a` signed in the group's direction: what a buy adds to a long holding, a sell takes away.
3748 const auto signed_in = [&](const Unconfirmed& entry, const Decimal64& quantity) {
3749 return entry.side_ == direction ? quantity : decimal_subtract(zero, quantity).value_or(zero);
3750 };
3751
3752 // What a listing still shows of each order: that part cannot have reached holdings.
3753 std::vector<Decimal64> listed(group.size(), zero);
3754 std::vector<Decimal64> fillable(group.size(), zero);
3755 for (std::size_t at = 0; at < group.size(); ++at) {
3756 auto& entry = unconfirmed_[group[at]];
3757 entry.listed_now_ = false;
3758 if (const auto* working = broker_row_for(portfolio, entry)) {
3759 entry.listed_ = true;
3760 entry.listed_now_ = true;
3761 listed[at] =
3762 decimal_subtract(working->order_.quantity_, working->order_.execution_.filled_quantity_).value_or(zero);
3763 }
3764 const auto left = decimal_subtract(entry.expected_, listed[at]).value_or(zero);
3765 fillable[at] = decimal_less(zero, left) ? left : zero;
3766 }
3767
3768 // The holdings movement since the group's baseline -- the first entry's, which a retirement
3769 // below advances -- in the group's direction.
3770 std::optional<Decimal64> moved;
3771 if (const auto held = portfolio.net_quantity_of(instrument)) {
3772 moved = direction == OrderSide::BUY ?
3773 decimal_subtract(*held, unconfirmed_[first].baseline_) :
3774 decimal_subtract(unconfirmed_[first].baseline_, *held);
3775 }
3776 std::vector<Decimal64> covered(group.size(), zero);
3777 if (moved && !mixed) {
3778 // Credited in the order they were sent, each up to the part no listing still shows.
3779 auto left = *moved;
3780 for (std::size_t at = 0; at < group.size() && decimal_less(zero, left); ++at) {
3781 covered[at] = decimal_less(left, fillable[at]) ? left : fillable[at];
3782 left = decimal_subtract(left, covered[at]).value_or(zero);
3783 }
3784 } else if (moved) {
3785 // Both sides: a movement could be either side's, so it counts only when it is exactly what
3786 // all of them would make. A resting order a listing shows in full adds nothing, so a
3787 // protective stop does not hold up the buy beside it.
3788 std::optional<Decimal64> total = zero;
3789 for (std::size_t at = 0; at < group.size() && total; ++at) {
3790 total = decimal_add(*total, signed_in(unconfirmed_[group[at]], fillable[at]));
3791 }
3792 // A sum of zero is no evidence: two opposite orders that have not filled at all look like
3793 // two that both have. They wait for their history, and once it has said what each one
3794 // filled, holdings that did not move are evidence after all. That includes the resting order
3795 // above, which waits for no history (it once held them up until they timed out).
3796 bool all_settled = true;
3797 for (std::size_t at = 0; at < group.size(); ++at) {
3798 all_settled = all_settled && (unconfirmed_[group[at]].settled_ || fillable[at].coefficient() == 0);
3799 }
3800 if (
3801 total && (total->coefficient() != 0 || all_settled) && !decimal_less(*total, *moved) &&
3802 !decimal_less(*moved, *total)
3803 ) {
3804 covered = fillable;
3805 }
3806 }
3807
3808 // Retired entries advance the baseline the rest are measured from, so the movement that
3809 // confirmed one is never counted again for the next.
3810 std::optional<Decimal64> advanced = unconfirmed_[first].baseline_;
3811 for (std::size_t at = 0; at < group.size(); ++at) {
3812 auto& entry = unconfirmed_[group[at]];
3813 if (!decimal_less(covered[at], entry.expected_)) {
3814 retire[group[at]] = true;
3815 if (advanced) {
3816 advanced = direction == OrderSide::BUY ?
3817 decimal_add(*advanced, signed_in(entry, entry.expected_)) :
3818 decimal_subtract(*advanced, signed_in(entry, entry.expected_));
3819 }
3820 continue;
3821 }
3822 auto residual = decimal_subtract(entry.expected_, covered[at]).value_or(zero);
3823 residual = decimal_subtract(residual, listed[at]).value_or(zero);
3824 if (!decimal_less(zero, residual)) {
3825 mark_explained(entry);
3826 continue;
3827 }
3828 entry.residual_ = residual;
3829 if (!entry.unexplained_since_) {
3830 entry.unexplained_since_ = now;
3831 }
3832 // Judged by the holdings read, not the clock: the listing (and so the history) is polled
3833 // before holdings in each iteration, and on a loop polling slower than the timeout the
3834 // clock alone marked a fill one holdings read before it would have shown.
3835 if (
3836 (entry.settled_ || entry.history_missed_) && timed_out(entry, now) &&
3837 portfolio.as_of_ - *entry.unexplained_since_ > confirmation_timeout_
3838 ) {
3839 // A holdings answer read a whole timeout after the quantity became unexplained (or after the
3840 // history settled it) does not show it, and the history either said what it filled or had
3841 // nothing to say: an outside trade, a disagreement or an order nobody here can account for.
3842 // Withheld for the operator.
3843 ++orders_unconfirmed_timed_out_;
3844 if (entry.settled_) {
3845 ledger_.mark(
3846 entry.instrument_,
3847 "an order this runner sent (" + entry.ref_.primary_ +
3848 ") filled by the order history, and holdings did not show it within the confirmation timeout"
3849 );
3850 } else {
3851 const auto named = entry.ref_.primary_.empty() ?
3852 std::string(" (its reply lost, never named by a sweep)") :
3853 " (" + entry.ref_.primary_ + ")";
3854 ledger_.mark(
3855 entry.instrument_,
3856 "an order this runner sent" + named +
3857 " was not confirmed by holdings, the order list or the order history in time"
3858 );
3859 }
3860 expired[group[at]] = true;
3861 // What holdings did show of it stays credited to it, not to the next order.
3862 if (advanced) {
3863 advanced = direction == OrderSide::BUY ?
3864 decimal_add(*advanced, signed_in(entry, covered[at])) :
3865 decimal_subtract(*advanced, signed_in(entry, covered[at]));
3866 }
3867 continue;
3868 }
3869 // Not shown while the ledger holds an order not yet named: no placement on the instrument can
3870 // go out then, and beside the broker's own row for the same order a resting one would count
3871 // twice, so a target would withdraw the real one. The sweep that lifts the hold names it.
3872 if (entry.ref_.primary_.empty() && ledger_.requires_reconcile(entry.instrument_)) {
3873 continue;
3874 }
3875 rebuild_residual_row(portfolio, entry, residual);
3876 }
3877 for (const auto at : group) {
3878 if (!retire[at] && advanced) {
3879 unconfirmed_[at].baseline_ = *advanced;
3880 }
3881 }
3882 }
3883
3884 for (std::size_t at = unconfirmed_.size(); at-- > 0;) {
3885 if (retire[at] || expired[at]) {
3886 unconfirmed_.erase(unconfirmed_.begin() + static_cast<std::ptrdiff_t>(at));
3887 }
3888 }
3889 }
3890
3891 // Carries this pass's reservation into the next one.
3892 //
3893 // **The in-pass view dies with the pass**, so without this a second pass before the next poll
3894 // starts from the broker's last word again and can re-spend what the first pass already
3895 // committed. The fix needs no matcher, because a working-order poll *replaces* what it
3896 // refreshes: `poll_working_orders` assigns `working_` wholesale, so an untracked reservation
3897 // written here is discarded the moment the broker's own listing arrives. (A holdings poll does not: it refreshes
3898 // positions and keeps `working_`.) Nothing has to recognise its own order in a listing -- which is
3899 // the half of reserve-and-match that carries a matcher's failure modes.
3900 //
3901 // **Always, for a runner that sends to a broker which lists working orders.** Target
3902 // reconciliation reads the same portfolio, and an order this runner just sent has to count as
3903 // working there, whatever the limits: a target restated on the next pass would otherwise be sent
3904 // again. It was once scoped to the limits below, and the cold start showed the cost --
3905 // `SessionSource` then fed a whole history read one pass per bar before the next listing, so a
3906 // target strategy under default limits sent one order per history bar (`tests/test-live.cpp`,
3907 // `[own-orders]`). It now feeds history through `feed_warmup`, which sends nothing; the reservation
3908 // still covers every other pass before a listing (a runner fed by hand, two names in one bar
3909 // poll, or bar polls that come faster than the listing's). A listing and holdings bound its life
3910 // (`unconfirmed_orders`), so the loop holds such a run while no listing will come -- the source
3911 // publishes none, no working-order cadence is set, or the last listing is older than the portfolio
3912 // age policy (`PollingLoop::gate_for`).
3913 //
3914 // **Scoped to the limits that read it everywhere else.** A dry run, `live::bind_observer` and a
3915 // custom executor that reaches no broker write a row with no broker reference: a later target
3916 // that opposes it would ask to withdraw an order identified by nothing, and a dry run has no
3917 // listing to replace the row at all. A broker that publishes no working-order inquiry never
3918 // replaces it either. For them the reservation persists only for the limits that size against
3919 // what is outstanding, as before. `max_position_quantity_` is one of those limits: its ceiling
3920 // counts same-side working orders, so an accepted order that stopped being visible at the end of a
3921 // pass would let the next bar place another of the same size.
3922 //
3923 // A custom executor that reaches a broker but reports no reference (`reports_last_ref`) is still
3924 // counted as keeping its orders: a duplicate order is the worse failure, and the listing the loop
3925 // insists on retires the unaddressable row.
3926 //
3927 // A listing replaces `working_` wholesale, and so used to retire the row whether or not it carried the
3928 // order -- a market order that filled at once is in no listing, and holdings lagging the fill did not
3929 // show it either. For a runner that keeps sent orders until listed, the row is now rebuilt
3930 // before every pass from what nothing explains yet (`track_unconfirmed`, `unconfirmed_orders`).
3931 void persist_reservation(
3932 const strategy::PlannedOrder& order, const std::optional<Decimal64>& reference_price,
3933 const std::optional<Currency>& currency, const std::optional<OrderRef<Tag>>& ref
3934 ) {
3935 const bool sells = guard_.limits().enforce_sellable_quantity_ && order.side_ == OrderSide::SELL;
3936 const bool buys = guard_.limits().enforce_buying_power_ && order.side_ == OrderSide::BUY;
3937 const bool capped = guard_.limits().max_position_quantity_.has_value();
3938 // The exposure ceiling reads what is outstanding for the same reason the position ceiling does,
3939 // so it needs the reservation for the same reason. Left out, a caller enabling only this limit
3940 // would get the within-pass fix and not the across-pass one: ten bought on each of two bars,
3941 // with no poll between, passes twice against a ceiling one of them should have reached. That is
3942 // precisely the omission `max_position_quantity_` once had.
3943 const bool exposed = guard_.limits().max_gross_exposure_.has_value();
3944 // A run budget reserves open buys and bounds sells by open sells, for the same reason: on every side, so
3945 // two bars cannot each pass what fits once.
3946 const bool budgeted = guard_.limits().run_budget_.has_value();
3947 // A stop is read by target reconciliation whatever the limits, which refuses a target while one
3948 // rests (`RejectReason::STOP_ORDER_RESTING`). Not persisted, a stop placed on this pass would be
3949 // invisible to a target on the next one until a working-order poll listed it -- and "flatten"
3950 // would then go out beside the stop, both of them sells.
3951 const bool conditional = carries_trigger_price(order.type_);
3952 // A broker that will list the order back, reached by this runner: the listing and holdings
3953 // account for the row (`track_unconfirmed`), so the reservation is always written. See above for
3954 // why every other runner keeps the scoping.
3955 if (!keeps_sent_orders_until_listed && !sells && !buys && !capped && !exposed && !budgeted && !conditional) {
3956 return;
3957 }
3958 // **In place, all or nothing.** `reserve` builds the row in a local first, so the append is its first
3959 // write to the portfolio, and the append either happens whole or leaves the rows as they were; what
3960 // follows it (lowering one buying power) is decimal arithmetic and assignment, which cannot throw.
3961 // Copying the whole portfolio to add one row cost a copy of every position per order placed.
3962 reserve(
3963 context_detail::PortfolioAccess::for_runner_edit(context_), order, reference_price, currency, ref,
3964 guard_.limits().enforce_buying_power_
3965 );
3966 }
3967
3968 // Opens a new run with the budget as its cash, after checking what a budgeted runner needs.
3969 void open_run() {
3970 const auto& limits = guard_.limits();
3971 const auto zero = Decimal64::parse("0");
3972 if (!decimal_less(zero, limits.run_budget_->amount_)) {
3973 throw std::invalid_argument("RiskLimits::run_budget_ must be positive");
3974 }
3975 if (!limits.run_fees_) {
3976 throw std::invalid_argument(
3977 "RiskLimits::run_budget_ needs RiskLimits::run_fees_: a budgeted run refuses to start"
3978 );
3979 }
3980 const auto& fees = *limits.run_fees_;
3981 if (
3982 decimal_less(fees.commission_rate_, zero) || decimal_less(fees.commission_minimum_, zero) ||
3983 (fees.institution_rate_ && decimal_less(*fees.institution_rate_, zero)) ||
3984 (fees.sell_tax_rate_ && decimal_less(*fees.sell_tax_rate_, zero))
3985 ) {
3986 throw std::invalid_argument("RiskLimits::run_fees_ must not state a negative rate or minimum");
3987 }
3988 if constexpr (runner_detail::sends_to_a_broker<Executor>::value) {
3989 // A live run's cash lives in its journal, read at recovery (`open_run_from`); a runner that cannot keep it
3990 // there is refused rather than half-served.
3991 if constexpr (!keeps_run_in_journal) {
3992 throw std::invalid_argument(
3993 "RiskLimits::run_budget_ over an executor that sends to a broker needs a serialized runner that keeps its "
3994 "run in the journal (a JournalingExecutor over a broker that lists working orders)"
3995 );
3996 } else {
3997 return;
3998 }
3999 }
4000 run_.emplace(*limits.run_budget_);
4001 }
4002
4003 // The run's cash less what its open buys commit, for one pass; an order of unknown outcome, or a row that
4004 // cannot be valued, leaves `run_cash_` absent, and every budgeted buy in the pass is refused.
4005 //
4006 // In a replay the queue's rows are the run's open orders. Anywhere else no listing carries this runner's
4007 // orders (a dry run's rows are replaced by the next working-order poll), so what its accepted buys commit is
4008 // kept in `run_committed_`, its own reserved rows are skipped, and the broker's open buys still count. A live
4009 // run keeps its orders as obligations instead (`run_reserved`), restored from its journal after a restart, so
4010 // neither `run_committed_` nor `run_unknown_` is read for it.
4011 void run_pass_inputs(const strategy::Portfolio<Tag>& view, strategy::GuardInputs& inputs) {
4012 if (serialized()) {
4013 // A live run: its own orders, from what it sent, never the account's listing; nothing once its writes stop.
4014 const auto reserved = run_->settled() && !run_journal_latched_ && !run_closing_ ? run_reserved() : std::nullopt;
4015 const auto left = reserved ? decimal_subtract(run_->cash().amount_, *reserved) : std::nullopt;
4016 if (left) {
4017 inputs.run_cash_ = Money{*left, run_->currency()};
4018 }
4019 return;
4020 }
4021 // An unknown outcome holds every buy until the indeterminacy ledger no longer withholds its instrument.
4022 run_unknown_.erase(
4023 std::remove_if(
4024 run_unknown_.begin(), run_unknown_.end(),
4025 [this](const InstrumentId& id) {
4026 return !ledger_.requires_reconcile(id);
4027 }
4028 ),
4029 run_unknown_.end()
4030 );
4031 if (!run_unknown_.empty() || !run_committed_) {
4032 return;
4033 }
4034 const auto& fees = *guard_.limits().run_fees_;
4035 const auto zero = Decimal64::parse("0");
4036 auto cash = run_->cash().amount_;
4037 if (!run_rows_listed_) {
4038 const auto left = decimal_subtract(cash, *run_committed_);
4039 if (!left) {
4040 return;
4041 }
4042 cash = *left;
4043 }
4044 for (const auto& working : view.working_) {
4045 if (working.order_.side_ != OrderSide::BUY || !strategy::order_is_open(working.order_.status_)) {
4046 continue;
4047 }
4048 if (!run_rows_listed_ && working.reserved_) {
4049 continue;
4050 }
4051 // From reference data, never the row's own currency, which may be a default-constructed KRW.
4052 const auto* reference = context_.find_instrument(working.order_.instrument_);
4053 if (!reference) {
4054 return;
4055 }
4056 if (!(reference->currency_ == run_->currency())) {
4057 continue;
4058 }
4059 const auto& price = working.order_.price_;
4060 if (!price || !decimal_less(zero, *price)) {
4061 return;
4062 }
4063 const auto remaining = decimal_subtract(working.order_.quantity_, working.order_.execution_.filled_quantity_);
4064 if (!remaining || decimal_less(*remaining, zero)) {
4065 return;
4066 }
4067 const auto cost = strategy::risk_detail::run_buy_cost(fees, *remaining, *price);
4068 const auto left = cost ? decimal_subtract(cash, *cost) : std::nullopt;
4069 if (!left) {
4070 return;
4071 }
4072 cash = *left;
4073 }
4074 inputs.run_cash_ = Money{cash, run_->currency()};
4075 }
4076
4077 // The run's shares of an instrument less every open sell of the view on it, or nothing if a row's remainder
4078 // is negative or the arithmetic does not fit.
4079 std::optional<Decimal64> run_holding_for(const strategy::Portfolio<Tag>& view, const InstrumentId& instrument) const {
4080 if (serialized()) {
4081 return run_holding_serialized(instrument);
4082 }
4083 const auto zero = Decimal64::parse("0");
4084 std::optional<Decimal64> held = run_->holding(instrument);
4085 for (const auto& working : view.working_) {
4086 if (
4087 working.order_.side_ != OrderSide::SELL || !(working.order_.instrument_ == instrument) ||
4088 !strategy::order_is_open(working.order_.status_)
4089 ) {
4090 continue;
4091 }
4092 const auto remaining = decimal_subtract(working.order_.quantity_, working.order_.execution_.filled_quantity_);
4093 if (!remaining || decimal_less(*remaining, zero)) {
4094 return std::nullopt;
4095 }
4096 held = decimal_subtract(*held, *remaining);
4097 if (!held) {
4098 return std::nullopt;
4099 }
4100 }
4101 return held;
4102 }
4103
4104 // A live run's shares of an instrument less every sell of the run on it not yet booked, whole; nothing while a
4105 // placement on it is held or released unbooked, or a sell of the run on it is unnamed or held.
4106 std::optional<Decimal64> run_holding_serialized(const InstrumentId& instrument) const {
4107 if (run_journal_latched_ || run_closing_ || !run_->settled_on(instrument)) {
4108 return std::nullopt;
4109 }
4110 std::optional<Decimal64> held = run_->holding(instrument);
4111 for (const auto& entry : unconfirmed_) {
4112 if (!entry.run_order_ || entry.side_ != OrderSide::SELL || !(entry.instrument_ == instrument)) {
4113 continue;
4114 }
4115 if (state_of(entry) != ObligationState::NAMED) {
4116 return std::nullopt;
4117 }
4118 held = decimal_subtract(*held, entry.row_.order_.quantity_);
4119 if (!held) {
4120 return std::nullopt;
4121 }
4122 }
4123 return held;
4124 }
4125
4126 // What a live run's open buys reserve: each buy of the run not yet booked, whole, at its own limit price plus
4127 // both estimates (a partial fill is booked only when the order is accounted for, so its filled part stays
4128 // reserved). Nothing while an order of the run is unnamed or held, or a buy cannot be valued.
4129 std::optional<Decimal64> run_reserved() const {
4130 const auto& fees = *guard_.limits().run_fees_;
4131 const auto zero = Decimal64::parse("0");
4132 std::optional<Decimal64> total = zero;
4133 for (const auto& entry : unconfirmed_) {
4134 if (!entry.run_order_) {
4135 continue;
4136 }
4137 if (state_of(entry) != ObligationState::NAMED) {
4138 return std::nullopt;
4139 }
4140 if (entry.side_ != OrderSide::BUY) {
4141 continue;
4142 }
4143 const auto& price = entry.row_.order_.price_;
4144 if (!price || !decimal_less(zero, *price)) {
4145 return std::nullopt;
4146 }
4147 const auto cost = strategy::risk_detail::run_buy_cost(fees, entry.row_.order_.quantity_, *price);
4148 total = cost ? decimal_add(*total, *cost) : std::nullopt;
4149 if (!total) {
4150 return std::nullopt;
4151 }
4152 }
4153 return total;
4154 }
4155
4156 // A run's order as its ledger records it: its journal id, instrument, side and the quantity it was sent for.
4157 static RunPlacement run_placement_of(const Unconfirmed& entry) {
4158 RunPlacement placement;
4159 placement.id_ = entry.journal_ ? entry.journal_->id_ : std::string();
4160 placement.instrument_ = entry.instrument_;
4161 placement.side_ = entry.side_;
4162 placement.quantity_ = entry.journal_ ? entry.journal_->quantity_ : entry.row_.order_.quantity_;
4163 return placement;
4164 }
4165
4166 // What a dated history row of a run's own order says it filled and cost, or nothing: an amount not above zero
4167 // (KIS writes zero on an unfilled row), an average price not above zero, an amount or a fee in another
4168 // currency than the run's, or a fee below zero.
4169 std::optional<RunBooking> run_booking_from(const OrderSnapshot& row, const Decimal64& filled) const {
4170 const auto zero = Decimal64::parse("0");
4171 const auto& execution = row.execution_;
4172 const auto& currency = run_->currency();
4173 if (execution.average_filled_price_ && !decimal_less(zero, *execution.average_filled_price_)) {
4174 return std::nullopt;
4175 }
4176 std::optional<Money> amount = execution.filled_amount_;
4177 if (!amount && execution.average_filled_price_) {
4178 const auto value = decimal_multiply(*execution.average_filled_price_, filled);
4179 if (value) {
4180 amount = Money{*value, row.currency_};
4181 }
4182 }
4183 if (!amount || !(amount->currency_ == currency) || !decimal_less(zero, amount->amount_)) {
4184 return std::nullopt;
4185 }
4186 for (const auto* fee : {&execution.commission_, &execution.tax_}) {
4187 if (*fee && (!((*fee)->currency_ == currency) || decimal_less((*fee)->amount_, zero))) {
4188 return std::nullopt;
4189 }
4190 }
4191 return RunBooking{filled, *amount, execution.commission_, execution.tax_};
4192 }
4193
4194 // Takes a run order's booking from its own dated history rows that filled exactly what it now expects; two
4195 // that disagree, or one that disagrees with the booking held, clear it.
4196 void take_run_booking(const std::vector<OrderSnapshot>& evidence, Unconfirmed& entry) const {
4197 if (entry.expected_.coefficient() == 0) {
4198 return;
4199 }
4200 const auto differ = [](const Decimal64& a, const Decimal64& b) {
4201 return decimal_less(a, b) || decimal_less(b, a);
4202 };
4203 const auto differ_money = [&](const std::optional<Money>& a, const std::optional<Money>& b) {
4204 return a.has_value() != b.has_value() ||
4205 (a && (!(a->currency_ == b->currency_) || differ(a->amount_, b->amount_)));
4206 };
4207 for (const auto& row : evidence) {
4208 if (!own_row(row, entry) || differ(row.execution_.filled_quantity_, entry.expected_)) {
4209 continue;
4210 }
4211 const auto candidate = run_booking_from(row, entry.expected_);
4212 if (!candidate) {
4213 continue;
4214 }
4215 if (
4216 entry.booking_ &&
4217 (differ_money(entry.booking_->amount_, candidate->amount_) ||
4218 differ_money(entry.booking_->commission_, candidate->commission_) ||
4219 differ_money(entry.booking_->tax_, candidate->tax_))
4220 ) {
4221 entry.booking_.reset();
4222 return;
4223 }
4224 entry.booking_ = candidate;
4225 }
4226 }
4227
4228 // The booking of a run's order, or nothing if it cannot be booked yet: an order that filled with no booking
4229 // held for exactly what it filled, a fee estimate that does not fit, or a fill the run's ledger refuses. A fee
4230 // the row states is booked as stated, each component on its own; a missing one is estimated from `run_fees_`.
4231 std::optional<RunBooked> run_booking_of(const Unconfirmed& entry) const {
4232 const auto zero = Decimal64::parse("0");
4233 const auto& fees = *guard_.limits().run_fees_;
4234 auto record = std::make_shared<RunRecord>();
4235 record->run_ = run_->id();
4236 RunBooked booked;
4237 if (entry.expected_.coefficient() == 0) {
4238 record->filled_ = zero;
4239 record->amount_ = Money{zero, run_->currency()};
4240 record->fee_ = zero;
4241 } else {
4242 if (
4243 !entry.booking_ || decimal_less(entry.booking_->filled_, entry.expected_) ||
4244 decimal_less(entry.expected_, entry.booking_->filled_)
4245 ) {
4246 return std::nullopt;
4247 }
4248 const auto& booking = *entry.booking_;
4249 const auto& value = booking.amount_.amount_;
4250 const auto estimated_commission = fees.estimate_commission(value);
4251 const auto estimated_tax = fees.estimate_tax(value, entry.side_);
4252 const auto commission =
4253 booking.commission_ ? std::optional<Decimal64>(booking.commission_->amount_) : estimated_commission;
4254 const auto tax = booking.tax_ ? std::optional<Decimal64>(booking.tax_->amount_) : estimated_tax;
4255 const auto fee = commission && tax ? decimal_add(*commission, *tax) : std::nullopt;
4256 if (!fee) {
4257 return std::nullopt;
4258 }
4259 record->filled_ = booking.filled_;
4260 record->amount_ = booking.amount_;
4261 record->fee_ = *fee;
4262 // Estimated where the schedule supplied a component this side bears: a buy bears no tax.
4263 record->fee_estimated_ = !booking.commission_ || (entry.side_ == OrderSide::SELL && !booking.tax_);
4264 // Booked exactly, never covered by a margin; the operator is told on the line.
4265 const auto estimate =
4266 estimated_commission && estimated_tax ? decimal_add(*estimated_commission, *estimated_tax) : std::nullopt;
4267 if (estimate && decimal_less(*estimate, *fee)) {
4268 booked.note_ = "; its fees " + fee->str() + " are above the " + estimate->str() + " run_fees_ estimates";
4269 }
4270 }
4271 if (!run_->can_book_placement(run_placement_of(entry), *record->filled_, *record->amount_, *record->fee_)) {
4272 return std::nullopt;
4273 }
4274 booked.record_ = std::move(record);
4275 return booked;
4276 }
4277
4278 // A ledger line id no line of the journal carries.
4279 std::string next_ledger_id() {
4280 std::string id;
4281 if constexpr (keeps_run_in_journal) {
4282 // A backward clock step, or two processes in one microsecond, can repeat a prefix.
4283 do {
4284 id = executor_.next_run_id();
4285 } while (!run_ids_.insert(id).second);
4286 }
4287 return id;
4288 }
4289
4290 // A run budget's ledger line; an opening's id, generated at recovery, names its run.
4291 JournalEntry ledger_line(std::shared_ptr<RunRecord> record, std::string detail, std::string id = {}) {
4292 JournalEntry line;
4293 line.id_ = id.empty() ? next_ledger_id() : std::move(id);
4294 line.action_ = JournalAction::LEDGER;
4295 line.outcome_ = JournalOutcome::RECORDED;
4296 line.venue_.reset();
4297 line.detail_ = std::move(detail);
4298 if (record->kind_ == RunRecordKind::OPEN) {
4299 record->run_ = line.id_;
4300 }
4301 line.run_ = std::move(record);
4302 return line;
4303 }
4304
4305 // Records why the run did not open, and halts: the run's buys and sells stay refused.
4306 void refuse_run(RunRecoverySummary& summary, RunRefusal refusal, const std::string& cause, const char* state) {
4307 for (auto& entry : unconfirmed_) {
4308 entry.run_order_ = false;
4309 }
4310 run_.reset();
4311 run_closing_ = false;
4312 run_absent_ = false;
4313 summary.closing_ = false;
4314 summary.refusal_ = refusal;
4315 summary.refused_ = cause + ": " + state;
4316 run_recovery_ = summary;
4317 halt_locally("the run budget's run did not open: " + summary.refused_);
4318 }
4319
4320 // Marks the run open, and every later placement of the executor as the run's.
4321 void run_opened(RunRecoverySummary& summary) {
4322 executor_.set_run(run_->id());
4323 summary.opened_ = true;
4324 summary.id_ = run_->id();
4325 summary.cash_ = run_->cash();
4326 run_recovery_ = summary;
4327 }
4328
4329 // Opens a budgeted serialized runner's run from its journal, as `set_run_opening` said; see
4330 // `restore_obligations`. Resumes the journal's run when stated; otherwise opens a new one, closing the old run
4331 // first (`open_new_run_once_closed`). Every line is written before the run changes in memory; whenever it does not
4332 // open a run the run's buys and sells are refused, and it halts the runner except for `RunRefusal::NO_RUN`.
4333 void open_run_from([[maybe_unused]] const JournalReplay& replay) {
4334 if constexpr (keeps_run_in_journal) {
4335 RunRecoverySummary summary;
4336 const auto opening = run_opening_.value_or(RunOpening{});
4337 const char* reconcile = "reconcile the journal, or start on a new journal";
4338 // **Nothing is folded, opened or written from a journal not read whole**: a line it could not read may be
4339 // the run's opening, a deposit or a booking, and opening again would spend a budget twice.
4340 if (!replay.intact()) {
4341 return refuse_run(summary, RunRefusal::DAMAGED, "the order journal was not read whole", reconcile);
4342 }
4343 for (const auto& entry : replay.entries_) {
4344 if (
4345 (entry.requires_operator_ && !journal_outcome_requires_operator(entry.outcome_)) ||
4346 (entry.action_ != JournalAction::LEDGER && entry.instrument_.symbol_.empty())
4347 ) {
4348 return refuse_run(summary, RunRefusal::DAMAGED, "the order journal holds a damaged line", reconcile);
4349 }
4350 if (entry.id_.compare(0, 4, "run-") == 0) {
4351 run_ids_.insert(entry.id_);
4352 }
4353 }
4354 auto folded = RunLedger::fold(replay);
4355 if (!folded.failure_.empty()) {
4356 return refuse_run(summary, RunRefusal::LEDGER, folded.failure_, reconcile);
4357 }
4358 if (!folded.run_) {
4359 // A run's lines with no opening: the opening was lost, not a journal without a run.
4360 for (const auto& entry : replay.entries_) {
4361 if (entry.run_) {
4362 return refuse_run(summary, RunRefusal::LEDGER, "the run's lines have no opening", reconcile);
4363 }
4364 }
4365 if (opening.resume_) {
4366 // **Not damage**: nothing to spend or sell (figures absent), and the journal writes as without a budget.
4367 run_absent_ = true;
4368 summary.refusal_ = RunRefusal::NO_RUN;
4369 summary.refused_ = "no run to resume in this journal: start without resume to open a new run";
4370 run_recovery_ = summary;
4371 return;
4372 }
4373 return open_new_run(summary);
4374 }
4375 auto run = std::move(*folded.run_);
4376 // The restored orders of the journal's run are its own, reserved and booked as it goes on, or as it closes.
4377 for (auto& entry : unconfirmed_) {
4378 entry.run_order_ = entry.journal_ && journal_run_of(*entry.journal_) == run.id();
4379 }
4380 if (!opening.resume_) {
4381 // **The old run closes first**: its orders are cancelled (or waited for) and booked to it as they end,
4382 // and the new run opens once none is owed. Until then it spends nothing.
4383 run_.emplace(std::move(run));
4384 run_closing_ = true;
4385 summary.closing_ = true;
4386 run_recovery_ = summary;
4387 open_new_run_once_closed();
4388 return;
4389 }
4390 const auto& budget = *guard_.limits().run_budget_;
4391 if (!(run.currency() == budget.currency_)) {
4392 return refuse_run(
4393 summary, RunRefusal::CURRENCY,
4394 "the run is in " + run.currency().str() + ", run_budget_ in " + budget.currency_.str(),
4395 "state run_budget_ in the run's currency"
4396 );
4397 }
4398 // **The whole list is checked before any line is written**, against a copy, in order.
4399 const auto reserved = run.settled() ? run_reserved() : std::nullopt;
4400 auto after = run;
4401 std::vector<RunTransfer> applied;
4402 for (const auto& transfer : opening.transfers_) {
4403 if (const auto* seen = after.transfer_of(transfer.id_)) {
4404 if (seen->withdrawal_ == transfer.withdrawal_ && seen->amount_ == transfer.amount_) {
4405 continue;
4406 }
4407 return refuse_run(
4408 summary, RunRefusal::TRANSFER, "transfer id " + transfer.id_ + " reused, other amount", "state a new id"
4409 );
4410 }
4411 const auto free = reserved ? decimal_subtract(after.cash().amount_, *reserved) : std::nullopt;
4412 if (
4413 transfer.withdrawal_ &&
4414 (!free || decimal_less(after.cash().amount_, Decimal64::parse("0")) ||
4415 decimal_less(*free, transfer.amount_.amount_))
4416 ) {
4417 return refuse_run(
4418 summary, RunRefusal::TRANSFER,
4419 "withdrawal " + transfer.id_ + " over cash " + after.cash().amount_.str() + " less open buys, or unsettled",
4420 "state less, or withdraw once the run is settled"
4421 );
4422 }
4423 if (!after.transfer(transfer)) {
4424 return refuse_run(
4425 summary, RunRefusal::TRANSFER, "the transfer " + transfer.id_ + " is in another currency, or does not fit",
4426 "state it in the run's currency"
4427 );
4428 }
4429 applied.push_back(transfer);
4430 }
4431 for (const auto& transfer : applied) {
4432 auto record = std::make_shared<RunRecord>();
4433 record->run_ = run.id();
4434 record->kind_ = transfer.withdrawal_ ? RunRecordKind::WITHDRAWAL : RunRecordKind::DEPOSIT;
4435 record->amount_ = transfer.amount_;
4436 record->given_ = transfer.id_;
4437 auto line = ledger_line(std::move(record), "a transfer the operator stated");
4438 if (!run_record(line, /*opening=*/true)) {
4439 return refuse_run(summary, RunRefusal::WRITE, "could not record the transfer " + transfer.id_, "restart");
4440 }
4441 ++summary.transfers_applied_;
4442 }
4443 run_.emplace(std::move(after));
4444 summary.resumed_ = true;
4445 run_opened(summary);
4446 }
4447 }
4448
4449 // Writes a new run's opening, labelled by the library, and opens it with `run_budget_`.
4450 void open_new_run(RunRecoverySummary summary) {
4451 auto record = std::make_shared<RunRecord>();
4452 record->kind_ = RunRecordKind::OPEN;
4453 record->amount_ = *guard_.limits().run_budget_;
4454 auto line = ledger_line(std::move(record), "a new run opens with run_budget_");
4455 if (!run_record(line, /*opening=*/true)) {
4456 return refuse_run(summary, RunRefusal::WRITE, "the order journal could not record the run's opening", "restart");
4457 }
4458 run_.emplace(RunLedger(line.id_, *guard_.limits().run_budget_));
4459 run_closing_ = false;
4460 summary.closing_ = false;
4461 summary.budget_used_ = true;
4462 run_opened(summary);
4463 }
4464
4465 // While the old run closes: opens the new run once none of the old run's orders is owed and its ledger is
4466 // settled (none held, or released and not yet booked by `book_run_fill`), never while locally halted or after a
4467 // failed write. Its remaining shares are the account's.
4468 void open_new_run_once_closed() {
4469 if constexpr (keeps_run_in_journal) {
4470 if (
4471 !run_closing_ || run_journal_latched_ || guard_.halted(strategy::HaltReason::LOCAL_FAILURE) || !run_->settled()
4472 ) {
4473 return;
4474 }
4475 for (const auto& entry : unconfirmed_) {
4476 if (entry.run_order_) {
4477 return;
4478 }
4479 }
4480 open_new_run(*run_recovery_);
4481 }
4482 }
4483
4484 // While the old run closes, cancels each of its orders a listing still shows, once, unless the opening said
4485 // to wait for them.
4486 void cancel_closing_run_orders([[maybe_unused]] Report& report) {
4487 if constexpr (keeps_run_in_journal) {
4488 // Not while a withdrawal could not be sent (`send_cancel`'s gates): the one attempt is kept for a cancellation
4489 // that reaches the broker, and is taken again once the hold lifts.
4490 if (
4491 !run_closing_ || run_opening_.value_or(RunOpening{}).wait_for_open_orders_ ||
4492 guard_.halted(strategy::HaltReason::LOCAL_FAILURE) || run_writes_closed() ||
4493 guard_.blocking_reason_for(strategy::InstructionClass::WITHDRAWAL)
4494 ) {
4495 return;
4496 }
4497 // Collected first: a cancellation's outcome may change what is owed. The broker row's own reference, whole:
4498 // a restored order knows only its number, and a broker may need more to cancel it (KIS's branch, Kiwoom's
4499 // symbol); the journal id only keeps each to one attempt.
4500 std::vector<OrderRef<Tag>> refs;
4501 for (const auto& entry : unconfirmed_) {
4502 const auto* row = entry.run_order_ && entry.journal_ ? broker_row_for(context_.portfolio(), entry) : nullptr;
4503 if (row == nullptr) {
4504 continue;
4505 }
4506 const auto& id = entry.journal_->id_;
4507 if (std::find(run_cancels_sent_.begin(), run_cancels_sent_.end(), id) == run_cancels_sent_.end()) {
4508 run_cancels_sent_.push_back(id);
4509 refs.push_back(row->ref_);
4510 }
4511 }
4512 for (const auto& ref : refs) {
4513 send_cancel(ref, report);
4514 }
4515 }
4516 }
4517
4518 // Takes a placed buy's cost out of the pass's run cash, so a later buy in the pass cannot spend it again, and,
4519 // where no listing keeps the order, into `run_committed_` for later passes.
4520 void spend_run_cash(const strategy::PlannedOrder& order, strategy::GuardInputs& inputs) {
4521 if (!run_ || order.side_ != OrderSide::BUY) {
4522 return;
4523 }
4524 // The guard passed it, so the price is there and positive.
4525 const auto cost = strategy::risk_detail::run_buy_cost(*guard_.limits().run_fees_, order.quantity_, *order.price_);
4526 if (!run_rows_listed_ && !serialized() && run_committed_) {
4527 run_committed_ = cost ? decimal_add(*run_committed_, *cost) : std::nullopt;
4528 }
4529 const auto left = cost && inputs.run_cash_ ? decimal_subtract(inputs.run_cash_->amount_, *cost) : std::nullopt;
4530 if (!left) {
4531 inputs.run_cash_.reset();
4532 return;
4533 }
4534 inputs.run_cash_->amount_ = *left;
4535 }
4536
4537 // An order of the run whose outcome is unknown: a buy commits its cost, and every buy is refused, from the rest
4538 // of this pass on, until the indeterminacy ledger no longer withholds the instrument.
4539 void note_run_unknown(const strategy::PlannedOrder& order, strategy::GuardInputs& inputs) {
4540 if (!run_) {
4541 return;
4542 }
4543 spend_run_cash(order, inputs);
4544 // A live run's unnamed order holds every buy as an obligation, which its journal restores (`run_reserved`).
4545 if (!serialized()) {
4546 run_unknown_.push_back(order.instrument_);
4547 }
4548 inputs.run_cash_.reset();
4549 }
4550
4551 // Resolves what every instrument the exposure ceiling must value is denominated in, and marked at.
4552 //
4553 // **This is the half `RiskGuard` cannot do**, which is why the guard takes it as an input rather
4554 // than deriving it. A position states its own currency and last price; a working order on an
4555 // instrument with no position states neither, and an opening buy is exactly that case. The runner
4556 // is where reference data and the quote cache live, so it is where the lookup belongs -- the same
4557 // reasoning that puts `order_currency_` here.
4558 //
4559 // **An instrument this cannot resolve is left out, and leaving it out is how the refusal
4560 // happens.** `projected_gross_exposure` returns nothing when the basis does not cover something
4561 // the portfolio holds or has working, and the guard turns that into `VALUE_NOT_KNOWN`. Inventing
4562 // a currency or a price here would be a silent pass, which this check exists to prevent.
4563 //
4564 // **Only fields somebody explicitly set are read**, which rules out the position's own
4565 // `market_value_.currency_` as a fallback however tempting it is. `Currency` default-constructs to
4566 // KRW and `HoldingPosition::last_price_` to zero, so an untouched position does not read as
4567 // unresolved -- it reads as Korean won marked at nothing, resolves, and contributes zero to the
4568 // sum. That is the silent omission this refusal exists to prevent, wearing the costume of an
4569 // answer. It is the same trap `backtest::ReplayLedger` was in.
4570 //
4571 // So: the currency comes from registered reference data, which is also where `order_currency_`
4572 // comes from, so the two cannot disagree about one instrument. The mark comes from the quote cache
4573 // or from a position's `last_price_` **when that price is not zero** -- a mark of zero is not a
4574 // valuation, and accepting one would value the position at nothing.
4575 //
4576 // The cost, and it is the intended direction: an account holding an instrument the caller never
4577 // registered refuses every order while the ceiling is on. Visible and diagnosable, rather than a
4578 // ceiling quietly measuring part of the portfolio.
4579 std::vector<strategy::InstrumentBasis> exposure_basis_for(
4580 const strategy::Portfolio<Tag>& view, const std::vector<strategy::PlannedOrder>& pending
4581 ) const {
4582 std::vector<InstrumentId> instruments;
4583 const auto note = [&instruments](const InstrumentId& id) {
4584 for (const auto& seen : instruments) {
4585 if (seen == id) {
4586 return;
4587 }
4588 }
4589 instruments.push_back(id);
4590 };
4591 for (const auto& position : view.positions_) {
4592 // Flat rows carry no exposure and are skipped for the reason `projected_gross_exposure` gives:
4593 // a replay keeps a lot after it returns to flat, and requiring a mark for one would let a
4594 // closed position refuse orders in an instrument it has nothing to do with.
4595 if (position.quantity_.coefficient() == 0) {
4596 continue;
4597 }
4598 note(position.instrument_);
4599 }
4600 for (const auto& working : view.working_) {
4601 if (strategy::order_is_open(working.order_.status_)) {
4602 note(working.order_.instrument_);
4603 }
4604 }
4605 for (const auto& order : pending) {
4606 note(order.instrument_);
4607 }
4608
4609 std::vector<strategy::InstrumentBasis> basis;
4610 basis.reserve(instruments.size());
4611 for (const auto& id : instruments) {
4612 const HoldingPosition* position = nullptr;
4613 for (const auto& held : view.positions_) {
4614 if (held.instrument_ == id) {
4615 position = &held;
4616 break;
4617 }
4618 }
4619
4620 const auto* reference = context_.find_instrument(id);
4621 if (!reference) {
4622 continue;
4623 }
4624
4625 // **Positive, not merely non-zero.** `Context::set_last_price` stores whatever a bar or quote
4626 // carried, with no validation, so a malformed price reaches here from market data rather than
4627 // only from a caller mistake. A negative mark would make an instrument's exposure negative and
4628 // let it offset real holdings until the ceiling passed anything at all; zero values the
4629 // position at nothing, which is the silent omission this resolution exists to refuse. Either
4630 // leaves the instrument unresolved, and the guard turns that into `VALUE_NOT_KNOWN`.
4631 const auto zero = Decimal64::parse("0");
4632 const auto quoted = context_.last_price(id);
4633 // **A quote that is present and not a price leaves the instrument unresolved**, rather than
4634 // falling through to the position's older mark. Falling back would be the quiet outcome: the
4635 // ceiling would answer from a stale figure while the current quote said something impossible,
4636 // and nothing would report that the data was wrong. Absent is a different thing from invalid,
4637 // and only absent gets the fallback.
4638 if (quoted && !decimal_less(zero, *quoted)) {
4639 continue;
4640 }
4641 auto price = quoted;
4642 if (!price && position != nullptr && decimal_less(zero, position->last_price_)) {
4643 price = position->last_price_;
4644 }
4645 if (!price) {
4646 continue;
4647 }
4648 basis.push_back(strategy::InstrumentBasis{id, reference->currency_, *price});
4649 }
4650 return basis;
4651 }
4652
4653 // Writes a sellable quantity onto the position for `instrument`, when there is one.
4654 static void write_sellable(
4655 strategy::Portfolio<Tag>& portfolio, const InstrumentId& instrument, const Decimal64& quantity
4656 ) {
4657 for (auto& position : portfolio.positions_) {
4658 if (position.instrument_ == instrument) {
4659 position.sellable_quantity_ = quantity;
4660 // **The inquiry is its own reading, so it carries its own basis -- on this row only.** The
4661 // holdings poll that built this portfolio established nothing about a figure it never
4662 // reported, and the inquiry answered for *this* instrument and no other. Writing the basis to
4663 // the portfolio would let one instrument's declaration certify every other row's figure: a
4664 // populated but undeclared quantity on another instrument would become enforceable, and a
4665 // wrong-sized sell of it would reach the wire. An executor that declares nothing leaves this
4666 // unestablished, and the guard then refuses.
4667 position.sellable_basis_ = runner_detail::sellable_inquiry_basis_of<Executor>();
4668 return;
4669 }
4670 }
4671 }
4672
4673 // Records an accepted order in `view` so the rest of the pass sizes against it.
4674 //
4675 // Written as a working order because that is what it now is, and because the alternative --
4676 // adjusting the position -- would be a lie: nothing has filled.
4677 //
4678 // **It carries the reference the broker just issued**, and that is not cosmetic. No guard reads a
4679 // reference, but reconciliation does: a row opposing the next target is put on the cancel list by
4680 // its `ref_`, and a synthetic row with an empty one would have the runner ask a broker to
4681 // withdraw an order identified by nothing. The shape and the amendable quantity are filled for
4682 // the same reason -- `cancel_all` builds the instruction from them, and a broker that requires a
4683 // quantity would be sent zero. An order just accepted and unfilled is amendable in full.
4684 //
4685 // Where the executor could not supply a reference -- a dry run, a replay, a custom executor
4686 // that does not report one, or an order whose reply was lost (passed no reference on purpose: the
4687 // executor's last one belongs to an earlier order) -- the row is still written, because a limit
4688 // that ignored the order would be the worse failure. Whether such a row can still be withdrawn is the executor's
4689 // question, not this one's: a replay's engine matches a cancellation on instrument and side and
4690 // needs no reference at all, while `live::SessionExecutor` refuses to send one to a broker.
4691 //
4692 // `spends` decides whether a buy also draws down the published buying-power reading, and it is
4693 // the caller's buying-power check rather than anything this function can see. The two were once
4694 // entangled: a caller who had enabled only the position ceiling watched
4695 // `portfolio().buying_power_in()` fall after a buy, which is a public figure a strategy is free
4696 // to size its next order from -- a behaviour change well past enforcing a ceiling.
4697 static void reserve(
4698 strategy::Portfolio<Tag>& view, const strategy::PlannedOrder& order,
4699 const std::optional<Decimal64>& reference_price, const std::optional<Currency>& currency,
4700 const std::optional<OrderRef<Tag>>& ref, bool spends
4701 ) {
4702 WorkingOrder<Tag> working;
4703 working.order_.instrument_ = order.instrument_;
4704 working.order_.side_ = order.side_;
4705 working.order_.status_ = OrderStatus::PENDING;
4706 working.order_.type_ = order.type_;
4707 working.order_.session_ = order.session_;
4708 // The venue this runner asked the order to be routed to, which is
4709 // `PlannedOrder::venue_` -- already resolved against the binding's default
4710 // route before the send -- and **not** the instrument's: the instrument's is
4711 // identity, and an order whose identity carried a route would stop matching
4712 // its own holding. A broker's own listing fills this field from what it
4713 // routed the order to; until one arrives, this row is what `cancel_all`
4714 // reads, and leaving it `UNSPECIFIED` would withdraw the order at the
4715 // broker's default venue rather than at the one it went to.
4716 working.order_.venue_ = order.venue_;
4717 working.order_.price_ = order.price_;
4718 // A stop's trigger, so the reserved row has the shape the broker's listing will report --
4719 // `cancel_all` restates it and `OrderUpdateWatch` compares it.
4720 working.order_.trigger_price_ = order.trigger_price_;
4721 working.order_.time_in_force_ = order.time_in_force_;
4722 working.order_.quantity_ = order.quantity_;
4723 working.order_.execution_.filled_quantity_ = Decimal64::parse("0");
4724 working.amendable_quantity_ = order.quantity_;
4725 if (ref) {
4726 working.ref_ = *ref;
4727 }
4728 // Marked as ours. A limit sizing against what is outstanding must count it; anything inferring
4729 // the broker's own behaviour from the listing must not, because this row is arithmetic rather
4730 // than something the broker said.
4731 working.reserved_ = true;
4732 view.working_.push_back(std::move(working));
4733
4734 // A buy also spends money that the rest of the pass may not spend again. The estimate is the
4735 // same one the guard checked the order against -- its own price, or the last quote for a market
4736 // order -- and it is an *estimate*: a market order fills where it fills, and commission is not
4737 // in it. Under-reserving would be the dangerous direction, and neither of those makes the
4738 // reservation smaller than the order's stated cost.
4739 if (!spends || order.side_ != OrderSide::BUY || !currency) {
4740 return;
4741 }
4742 const auto price = order.price_ ? order.price_ : reference_price;
4743 if (!price) {
4744 return;
4745 }
4746 const auto spent = decimal_multiply(order.quantity_, *price);
4747 if (!spent) {
4748 return;
4749 }
4750 for (auto& reading : view.buying_power_) {
4751 if (!(reading.cash_.currency_ == *currency)) {
4752 continue;
4753 }
4754 if (const auto left = decimal_subtract(reading.cash_.amount_, *spent)) {
4755 reading.cash_.amount_ = *left;
4756 }
4757 return;
4758 }
4759 }
4760
4761 // Returns why a plan derived from the current portfolio must not be acted on, or nothing.
4762 //
4763 // **The policy is evaluated here, against the snapshot in hand, rather than being pushed in as a
4764 // verdict somebody else computed earlier.** A `bool` set by the loop would be a judgement about
4765 // whatever portfolio was current when the loop last looked, and the loop looks at points a source
4766 // callback can get between: `PollingLoop::gate_for` calls `read_order_list` -- which is handed a
4767 // mutable runner and can feed -- before it ever reaches its own age check. A plan settled inside
4768 // that call would be checked against a stale verdict. Asking the question at settlement time makes
4769 // the answer structurally current, and there is no invalidation protocol to get wrong.
4770 // Drops the deferred targets `instructions` supersede.
4771 //
4772 // Every pass, so a target or order the strategy states for an instrument -- in answer to an order
4773 // update, a bar, anything -- replaces the fallback before `retry_deferred` could release it. See
4774 // `deferred_targets` for the whole contract.
4775 void drop_superseded_deferred(const std::vector<Instruction<Tag>>& instructions) {
4776 if (deferred_targets_.empty()) {
4777 return;
4778 }
4779 const auto drop = [this](const InstrumentId& instrument) {
4780 for (auto at = deferred_targets_.begin(); at != deferred_targets_.end(); ++at) {
4781 if (at->target_.instrument_ == instrument) {
4782 deferred_targets_.erase(at);
4783 return;
4784 }
4785 }
4786 };
4787 for (const auto& instruction : instructions) {
4788 if (const auto* target = std::get_if<strategy::TargetPosition>(&instruction)) {
4789 drop(target->instrument_);
4790 } else if (const auto* intent = std::get_if<strategy::OrderIntent>(&instruction)) {
4791 drop(intent->instrument());
4792 }
4793 }
4794 }
4795
4796 // The release loop behind `retry_deferred` and `retry_deferred_on_one_snapshot`. `evidence` is the
4797 // broker's history, or null for a caller whose own ledger decided every stop.
4798 Report release_deferred(const std::vector<OrderSnapshot>* evidence) {
4799 bool released = false;
4800 for (auto at = deferred_targets_.begin(); at != deferred_targets_.end();) {
4801 // Serialized, a stop this runner placed is not done until it is accounted for (`serialized`).
4802 if (stop_listed(at->target_.instrument_) || obligation_state(at->target_.instrument_) != ObligationState::NONE) {
4803 ++at;
4804 continue;
4805 }
4806 if (evidence != nullptr) {
4807 bool decided = true;
4808 bool filled = false;
4809 for (const auto& stop : at->stops_) {
4810 // Matched to the order time its listing showed, where it showed one. Without it (KIS lists no
4811 // time), a row of another day under the same number cannot be told apart unless two rows
4812 // disagree.
4813 std::optional<std::chrono::system_clock::time_point> earliest;
4814 std::optional<std::chrono::system_clock::time_point> latest;
4815 if (stop.ordered_at_) {
4816 earliest = *stop.ordered_at_ - order_time_tolerance_;
4817 latest = *stop.ordered_at_ + order_time_tolerance_;
4818 }
4819 const auto* row =
4820 history_row_for(*evidence, stop.ref_.primary_, at->target_.instrument_, std::nullopt, earliest, latest);
4821 if (row == nullptr) {
4822 decided = false;
4823 continue;
4824 }
4825 if (row->execution_.filled_quantity_.coefficient() != 0) {
4826 filled = true;
4827 } else if (strategy::order_is_open(row->status_)) {
4828 decided = false;
4829 }
4830 }
4831 if (filled) {
4832 ++deferred_dropped_after_fill_;
4833 at = deferred_targets_.erase(at);
4834 continue;
4835 }
4836 if (!decided) {
4837 ++at;
4838 continue;
4839 }
4840 }
4841 context_.submit(at->target_);
4842 at = deferred_targets_.erase(at);
4843 released = true;
4844 }
4845 // **Nothing released, nothing settled.** A pass has effects of its own -- it observes the
4846 // sellable convention from the portfolio -- and this runs on every working-order poll.
4847 if (!released) {
4848 return Report{};
4849 }
4850 // Exempt from `PORTFOLIO_SUPERSEDED` for this pass only; see `plan_withhold_reason`. Scoped, so a
4851 // settle that throws cannot leave the exemption on for every plan after it.
4852 struct Exempt {
4853 bool& flag_;
4854 explicit Exempt(bool& flag) : flag_(flag) {
4855 flag_ = true;
4856 }
4857 ~Exempt() {
4858 flag_ = false;
4859 }
4860 Exempt(const Exempt&) = delete;
4861 Exempt& operator=(const Exempt&) = delete;
4862 } exempt(releasing_deferred_);
4863 return settle();
4864 }
4865
4866 // Drops the retained target on `instrument`, if there is one.
4867 void forget_retained(const InstrumentId& instrument) {
4868 if (instrument.symbol_.empty()) {
4869 return;
4870 }
4871 retained_targets_.erase(
4872 std::remove_if(
4873 retained_targets_.begin(), retained_targets_.end(),
4874 [&](const RetainedTarget& kept) {
4875 return kept.target_.instrument_ == instrument;
4876 }
4877 ),
4878 retained_targets_.end()
4879 );
4880 // Every kept intent for the instrument, not the first: a later statement supersedes all of them.
4881 kept_intents_.erase(
4882 std::remove_if(
4883 kept_intents_.begin(), kept_intents_.end(),
4884 [&](const KeptIntent& kept) {
4885 return kept.intent_.instrument() == instrument;
4886 }
4887 ),
4888 kept_intents_.end()
4889 );
4890 }
4891
4892 // Keeps a target withheld for want of a trustworthy account, to plan again once there is one.
4893 //
4894 // Withheld because the account was never read, is too old, or predates the listing: each is a fact
4895 // about the data, and the next holdings read can change it. One per instrument, the latest kept, as
4896 // for `deferred_targets_`. Returns false, retaining nothing:
4897 //
4898 // - for anything but a `TargetPosition`. An `OrderIntent` states a quantity against the picture that
4899 // was wrong, and replaying it later would act on a decision nobody re-made. (An intent the market
4900 // phase stopped is a different case -- the picture was right, the hour was not -- and is kept by
4901 // `keep_intent_for_phase`, with its holding checked at release.)
4902 // - while a stop, an operator's halt or a local failure holds. What a strategy says then -- `on_stop`
4903 // included -- must not be replayed once the hold lifts.
4904 //
4905 // `until_accounted` keeps it past later holdings reads too, until the instrument owes no order; see
4906 // `withdraws_owed`.
4907 bool retain_withheld(
4908 const Instruction<Tag>& instruction, bool for_phase = false,
4909 std::optional<std::chrono::system_clock::time_point> after = std::nullopt, bool until_accounted = false
4910 ) {
4911 const auto* target = std::get_if<strategy::TargetPosition>(&instruction);
4912 if (target == nullptr) {
4913 return false;
4914 }
4915 if (
4916 guard_.halted(strategy::HaltReason::STOPPING) || guard_.halted(strategy::HaltReason::OPERATOR) ||
4918 ) {
4919 return false;
4920 }
4921 // The latest statement wins, and so does its reason: a target retained for the account and then
4922 // restated and refused for the phase waits for the phase.
4923 for (auto& kept : retained_targets_) {
4924 if (kept.target_.instrument_ == target->instrument_) {
4925 kept = RetainedTarget{*target, for_phase, after, until_accounted};
4926 return true;
4927 }
4928 }
4929 retained_targets_.push_back(RetainedTarget{*target, for_phase, after, until_accounted});
4930 return true;
4931 }
4932
4933 // Whether a serialized target's plan, which places nothing, withdraws an order this runner still owes on
4934 // the target's instrument: its reserved row, or the broker's own row for it.
4935 //
4936 // Such an order has often filled already, so the withdrawal is refused and the picture the plan was made
4937 // from is the stale one. The withdrawal is still sent (the order may be resting), and the target is kept
4938 // until every order on the instrument is accounted for, then planned again against holdings that show
4939 // what it did. Not planned again before that: a second withdrawal of a finished or already withdrawn
4940 // order is refused, and a broker's refusal can read as an unknown outcome that holds the instrument.
4941 //
4942 // Compared by the order's id, instrument and side, as `is_reserved_row_of` and `broker_row_for` do: a
4943 // restored order carries the id alone, while the row the broker lists carries its whole reference.
4944 bool withdraws_owed(const Instruction<Tag>& instruction, const std::vector<OrderRef<Tag>>& cancel) const {
4945 const auto* target = std::get_if<strategy::TargetPosition>(&instruction);
4946 if (target == nullptr || cancel.empty() || unconfirmed_.empty()) {
4947 return false;
4948 }
4949 for (const auto& working : context_.portfolio().working_) {
4950 if (
4951 !(working.order_.instrument_ == target->instrument_) ||
4952 std::find(cancel.begin(), cancel.end(), working.ref_) == cancel.end()
4953 ) {
4954 continue;
4955 }
4956 for (const auto& entry : unconfirmed_) {
4957 const bool listed_row_of = !working.reserved_ && !entry.ref_.primary_.empty() &&
4958 working.ref_.primary_ == entry.ref_.primary_ && working.order_.instrument_ == entry.instrument_ &&
4959 working.order_.side_ == entry.side_;
4960 if (listed_row_of || is_reserved_row_of(working, entry)) {
4961 return true;
4962 }
4963 }
4964 }
4965 return false;
4966 }
4967
4968 // Whether this runner owes an order on `instrument` (sent, and not yet accounted for).
4969 bool owes(const InstrumentId& instrument) const {
4970 return std::any_of(unconfirmed_.begin(), unconfirmed_.end(), [&](const Unconfirmed& entry) {
4971 return entry.instrument_ == instrument;
4972 });
4973 }
4974
4975 // Keeps a target whose order the market phase stopped, for the first permitted phase.
4976 //
4977 // Two routes reach it, both only for a runner that sends to a broker: the phase limit refused an
4978 // order that opens or grows a position, or it admitted one that reduces a position outside the
4979 // phase and the broker (or the binding) refused it -- which is what a broker not taking orders at
4980 // midnight does. See `retry_retained_targets`.
4981 void retain_for_phase(
4982 const Instruction<Tag>& instruction, bool broker_answered = false,
4983 std::optional<std::chrono::system_clock::time_point> after = std::nullopt
4984 ) {
4985 if constexpr (runner_detail::sends_to_a_broker<Executor>::value) {
4986 if (retain_withheld(instruction, /*for_phase=*/true, after)) {
4987 return;
4988 }
4989 keep_intent_for_phase(instruction, broker_answered, after);
4990 } else {
4991 (void)instruction;
4992 (void)broker_answered;
4993 (void)after;
4994 }
4995 }
4996
4997 // Whether the error behind the placement just refused satisfies `predicate` (`broker_unreachable`,
4998 // `broker_rate_limited`).
4999 //
5000 // Read immediately after the send, which is the only moment `last_error()` is this order's. An
5001 // executor that states no error has said nothing about why, so its refusals stay final.
5002 template <typename Predicate>
5003 bool last_error_is(Predicate predicate) const {
5004 if constexpr (runner_detail::states_last_error<Executor>::value) {
5005 const auto& error = executor_.last_error();
5006 return error && predicate(*error);
5007 } else {
5008 (void)predicate;
5009 return false;
5010 }
5011 }
5012
5013 // Keeps an order intent whose order the market phase stopped, for the first permitted phase.
5014 //
5015 // The intent half of `retain_for_phase`: a daily strategy's protective stop, decided on the bar fed
5016 // at midnight and refused by a broker not taking orders then, would otherwise be restated at the
5017 // next midnight and refused again, and the position would never be protected live. Kept once per
5018 // instruction (one instruction can produce two refused orders), in the order stated, with the
5019 // instrument's holding at this moment, which `retry_retained_targets` checks before releasing it;
5020 // any intent carrying a trigger, a stop buy as much as a stop sell, is also dropped there when a stop
5021 // rests on the instrument. **Not** while a stop, an operator's halt or a local failure holds; **not** an intent carrying an
5022 // idempotency key that a broker answered, because a second order would reuse the key.
5023 void keep_intent_for_phase(
5024 const Instruction<Tag>& instruction, bool broker_answered,
5025 std::optional<std::chrono::system_clock::time_point> after = std::nullopt
5026 ) {
5027 const auto* intent = std::get_if<strategy::OrderIntent>(&instruction);
5028 if (intent == nullptr) {
5029 return;
5030 }
5031 if (
5032 guard_.halted(strategy::HaltReason::STOPPING) || guard_.halted(strategy::HaltReason::OPERATOR) ||
5034 ) {
5035 return;
5036 }
5037 if (broker_answered && intent->client_order_id()) {
5038 return;
5039 }
5040 for (const auto* seen : kept_this_pass_) {
5041 if (seen == &instruction) {
5042 return;
5043 }
5044 }
5045 const auto held = context_.portfolio().net_quantity_of(intent->instrument());
5046 if (!held) {
5047 return;
5048 }
5049 kept_this_pass_.push_back(&instruction);
5050 kept_intents_.push_back(KeptIntent{*intent, *held, after});
5051 }
5052
5053 // Returns whether the portfolio lists an open stop order on `instrument`.
5054 bool stop_listed(const InstrumentId& instrument) const {
5055 for (const auto& working : context_.portfolio().working_) {
5056 if (
5057 working.order_.instrument_ == instrument && strategy::order_is_open(working.order_.status_) &&
5058 strategy::is_stop_order(working.order_)
5059 ) {
5060 return true;
5061 }
5062 }
5063 return false;
5064 }
5065
5066 // Keeps a target whose plan is waiting on a stop's withdrawal; see `deferred_targets`.
5067 void defer_if_waiting_on_stop(const Instruction<Tag>& instruction, const strategy::Plan<Tag>& planned) {
5068 const auto* target = std::get_if<strategy::TargetPosition>(&instruction);
5069 if (target == nullptr) {
5070 return;
5071 }
5072 for (const auto& rejection : planned.rejected_) {
5073 if (rejection.reason_ != strategy::RejectReason::STOP_ORDER_RESTING) {
5074 continue;
5075 }
5076 // The stops it waits on, as the listing shows them now -- `PENDING_CANCEL` included, since that
5077 // is exactly a stop whose outcome is not yet known.
5078 DeferredTarget deferred;
5079 deferred.target_ = *target;
5080 deferred.deferred_at_ = context_.now();
5081 for (const auto& working : context_.portfolio().working_) {
5082 if (
5083 working.order_.instrument_ == target->instrument_ && strategy::order_is_open(working.order_.status_) &&
5084 strategy::is_stop_order(working.order_)
5085 ) {
5086 deferred.stops_.push_back({working.ref_, working.order_.ordered_at_});
5087 }
5088 }
5089 for (auto& kept : deferred_targets_) {
5090 if (kept.target_.instrument_ == target->instrument_) {
5091 kept = std::move(deferred);
5092 ++targets_deferred_;
5093 return;
5094 }
5095 }
5096 deferred_targets_.push_back(std::move(deferred));
5097 ++targets_deferred_;
5098 return;
5099 }
5100 }
5101
5102 std::optional<WithheldPlanReason> plan_withhold_reason(bool would_cancel) const {
5103 const auto& portfolio = context_.portfolio();
5104 // **A picture the library can prove is mis-ordered, so no opt-out reaches it.** The opt-outs below
5105 // accept an account nobody read or one read too long ago; this one was read, recently, and before
5106 // the listing it would be reconciled with -- which is the order in which a fill between the two
5107 // reads makes a position vanish. Exempt only while a deferred target is being released: that
5108 // release fires on the stop's own history showing it ended unfilled, so the listing change behind
5109 // it is by construction not a fill.
5110 if (!releasing_deferred_ && portfolio.listing_newer_than_holdings()) {
5112 }
5113 // A default-constructed `Portfolio` carries the epoch, and no broker reports a snapshot taken in
5114 // 1970. The same sentinel the loop uses; both writers of `as_of_` in this library stamp it.
5115 const bool never_read = portfolio.as_of_ == std::chrono::system_clock::time_point{};
5116 const bool too_old =
5117 !never_read && maximum_portfolio_age_ && freshness_instant() - portfolio.as_of_ > *maximum_portfolio_age_;
5118
5119 if (never_read || too_old) {
5120 // **A plan that would withdraw something is stopped whatever was opted out of.** The opt-outs
5121 // say the operator accepts *sizing* against an account this library cannot vouch for. They do
5122 // not say it should withdraw orders it cannot account for, and the two are not the same
5123 // concession: an account that merely looks flat makes a resting protective order look opposed.
5124 if (would_cancel) {
5126 }
5127 // A placement is the half the opt-outs are about, and it is also the half a driving loop's
5128 // hold would otherwise catch -- so it is stopped here only for a run that asked for the
5129 // account to be known.
5130 if (require_known_portfolio_ && !(never_read && allow_absent_portfolio_)) {
5132 }
5133 // **Falls through rather than returning.** An opted-out placement still has to face the hold
5134 // check below: returning early here was a defect, because it let a plan out under an operator's
5135 // halt on the strength of an unrelated opt-out.
5136 }
5137 // Any placement hold, not an enumerated few: the harm is that the replacement will be refused
5138 // while the withdrawal has already gone, and every reason that refuses a placement does that.
5139 if (guard_.blocking_reason()) {
5141 }
5142 return std::nullopt;
5143 }
5144
5145 // Returns the instant a snapshot's age is measured against.
5146 //
5147 // The later of the decision instant and the last clock reading a loop supplied, so neither can be
5148 // used to make an old snapshot look fresh: a late bar cannot rewind the clock, and a loop that has
5149 // not spoken yet cannot erase the decision instant.
5150 std::chrono::system_clock::time_point freshness_instant() const {
5151 return observed_at_ > context_.now() ? observed_at_ : context_.now();
5152 }
5153
5154 // Returns the instant a send is counted at in the order-rate window: the later of the decision
5155 // instant and the loop's reading, or the decision instant alone where no loop has given a reading.
5156 // A replay never does, and its decisions may all lie before the epoch an unset reading equals.
5157 std::chrono::system_clock::time_point send_instant() const {
5158 return observed_at_ == std::chrono::system_clock::time_point{} ? context_.now() : freshness_instant();
5159 }
5160
5161 // Returns the detail recorded with a withheld plan, naming the hold where there is one.
5162 std::string withhold_detail(WithheldPlanReason reason) const {
5163 if (reason != WithheldPlanReason::PLACEMENT_HELD) {
5164 return {};
5165 }
5166 const auto holding = guard_.blocking_reason();
5167 return holding ? std::string(strategy::halt_reason_name(*holding)) : std::string{};
5168 }
5169
5170 // Returns the instrument an instruction is about, for reporting a plan that was not acted on.
5171 static InstrumentId instruction_instrument(const Instruction<Tag>& instruction) {
5172 if (const auto* target = std::get_if<strategy::TargetPosition>(&instruction)) {
5173 return target->instrument_;
5174 }
5175 if (const auto* order = std::get_if<strategy::OrderIntent>(&instruction)) {
5176 return order->instrument();
5177 }
5178 return InstrumentId{};
5179 }
5180
5181 // Returns the tag an instruction carries, so a withheld plan can be attributed to it.
5182 static std::string instruction_tag(const Instruction<Tag>& instruction) {
5183 if (const auto* target = std::get_if<strategy::TargetPosition>(&instruction)) {
5184 return target->tag_;
5185 }
5186 if (const auto* order = std::get_if<strategy::OrderIntent>(&instruction)) {
5187 return order->tag();
5188 }
5189 return {};
5190 }
5191
5192 void send_cancel(const OrderRef<Tag>& ref, Report& report) {
5193 // Gated like a placement, and in the same order. A cancellation is the one instruction that
5194 // cannot make an unresolved *position* worse, which is why the ledger does not gate it -- but it
5195 // still goes through the journal, and a journal that cannot record it must not let it be sent
5196 // unrecorded.
5197 // A budgeted run's stopped journal too: after a failed write it may end in a torn line (`run_writes_closed`).
5198 if (guard_.halted(strategy::HaltReason::LOCAL_FAILURE) || run_writes_closed()) {
5199 ++instructions_unavailable_;
5200 report.unavailable_cancel_.push_back(ref);
5201 return;
5202 }
5203 // And a halt stops this runner *sending*, which a cancellation is -- but only a halt that is
5204 // about this instruction. The argument for refusing here is `StopIntent` reaching this runner
5205 // from a signal and from a file: exempting cancellations wholesale would let
5206 // `echo withdraw > /var/run/atl/stop` send an instruction that an operator's own halt forbade,
5207 // and a kill switch a control file can partly bypass is not one. An operator who wants out
5208 // resumes first, which is one deliberate act and is visible in the report either way.
5209 //
5210 // **That argument covers the holds somebody set, and not the holds that merely mean this runner
5211 // is uninformed.** Refusing to withdraw a resting order because the *holdings* poll failed is
5212 // worse than the exposure it guards: the order keeps resting and can fill, and the reference it
5213 // would be withdrawn by came from a working-order read that succeeded. So the question asked is
5214 // `InstructionClass::WITHDRAWAL`, and `strategy::halt_blocks` holds the division and its
5215 // reasoning. The row is still resolved below, and a reference the snapshot cannot place is
5216 // reported rather than sent blind.
5217 if (const auto holding = guard_.blocking_reason_for(strategy::InstructionClass::WITHDRAWAL)) {
5218 ++cancels_refused_;
5219 report.refused_cancel_.push_back(RefusedCancel<Tag>{ref, *holding});
5220 return;
5221 }
5222 // Resolved against the portfolio first, because building a cancellation needs the order's own
5223 // quantity on a broker that requires one. A reference not in the snapshot means the snapshot is
5224 // stale, and sending a cancellation for an order the runner cannot describe is exactly the kind
5225 // of blind instruction that should be visible instead.
5226 // The broker's own row first: a reserved row for the same order is this runner's arithmetic.
5227 const WorkingOrder<Tag>* working = nullptr;
5228 for (const auto& row : context_.portfolio().working_) {
5229 if (row.ref_ == ref && (working == nullptr || (working->reserved_ && !row.reserved_))) {
5230 working = &row;
5231 }
5232 }
5233 if (working == nullptr) {
5234 ++cancels_unresolved_;
5235 report.unresolved_cancel_.push_back(ref);
5236 return;
5237 }
5238 // **Serialized: a reserved row whose reference the broker did not give is not sent.** A restored
5239 // order, or one a sweep named, carries the order id alone, which some brokers cannot cancel by; and a
5240 // row with no id addresses nothing. Refused as the binding would, before anything is sent.
5241 if (working->reserved_ && serialized() && !cancellable_reservation(*working)) {
5242 ++cancels_rejected_;
5243 report.rejected_cancel_.push_back(RejectedCancel<Tag>{ref, /*by_broker=*/false});
5244 return;
5245 }
5246 const auto outcome = executor_.cancel(*working);
5247 note_executor_failure(send_outcome_is_local_failure(outcome));
5248 // Switched over rather than tested one outcome at a time, deliberately. Three different outcomes
5249 // once fell through to `would_cancel_` -- the bucket that says the
5250 // broker withdrew the order -- because each fix handled the case it was told about and left the
5251 // rest. A switch with no default makes the next added enumerator a compile error in the library's
5252 // test and example builds (`-Werror=switch`), which is the only version of this that stays fixed.
5253 switch (outcome) {
5255 // The broker took the request. Whether the order stops working is a later fact, which only
5256 // its own listing reports: cancellation is asynchronous, and a broker that answers here can
5257 // still reject the withdrawal afterwards.
5258 //
5259 // **Counted against the rate limit, like a placement.** A withdrawal is a request the
5260 // broker counted, and a window that does not see it is not the window the operator
5261 // configured -- a `WITHDRAW` over thirty resting orders is thirty requests the guard was
5262 // blind to, and the next placement is then checked against a window it believes is empty.
5263 // It is still never *refused* by that limit: `send_cancel` calls no `check`, because a rate
5264 // limit must never be the reason an order cannot be withdrawn.
5265 guard_.note_sent(send_instant());
5266 // A sent order still counted may have filled before the withdrawal; its history decides.
5267 note_withdrawal_accepted(ref);
5268 report.would_cancel_.push_back(ref);
5269 return;
5271 // The broker refused the request, which is an answer: nothing needs reconciling. It is not
5272 // a withdrawal that happened, and it is not proof the order is working either -- a fill is
5273 // one of the ordinary reasons a withdrawal is refused. It still spent a request.
5274 guard_.note_sent(send_instant());
5275 ++cancels_rejected_;
5276 report.rejected_cancel_.push_back(RejectedCancel<Tag>{ref, /*by_broker=*/true});
5277 return;
5279 // Marked *and* reported apart from `would_cancel_`. The mark was always here; reporting it
5280 // as a withdrawal that happened was not right beside it, because the order may still be
5281 // resting and a caller reading `would_cancel_` would believe it is not.
5282 ledger_.mark(working->order_.instrument_, "a cancellation request has an unknown outcome");
5283 // Counted like an acceptance, for the same reason a placement is: the request may well have
5284 // reached the broker, and a window that assumes it did not is the one that under-counts.
5285 guard_.note_sent(send_instant());
5286 ++cancels_indeterminate_;
5287 report.indeterminate_cancel_.push_back(ref);
5288 return;
5290 // No `note_sent`, for the reason the placement path gives: nothing was sent, so the broker
5291 // counted nothing, and a rate limit must never become the reason a later order cannot go.
5292 // Reported beside the broker's own refusals because what it means for the order is the
5293 // same -- it was not withdrawn -- while `by_broker_` on the entry says which of the two
5294 // it was. Not `last_error()`: a later instruction in the same pass clears that.
5295 ++cancels_rejected_;
5296 report.rejected_cancel_.push_back(RejectedCancel<Tag>{ref, /*by_broker=*/false});
5297 return;
5299 // Not reported as a withdrawal that happened, because it did not. A cancellation nobody
5300 // sent must not read as one the broker has.
5301 ++instructions_unavailable_;
5302 report.unavailable_cancel_.push_back(ref);
5303 return;
5304 }
5305 }
5306
5307 // Plans a weight-sized intent as the target position it states (`strategy::weight_target`).
5308 //
5309 // **A resting stop refuses it, and nothing is withdrawn.** Target reconciliation withdraws a
5310 // resting stop when a trade is needed and waits for the stop's own history before trading, which
5311 // only a `TargetPosition` in the instruction stream can do (`defer_if_waiting_on_stop`); a weight
5312 // intent is not one, and an intent has never touched a stop. So a weight on an instrument with a
5313 // stop resting is refused `STOP_ORDER_RESTING` and the stop stays -- unless the holding already
5314 // meets it, when nothing is traded or withdrawn at all.
5315 strategy::Plan<Tag> plan_weight(const strategy::OrderIntent& intent, const strategy::ReconcileInputs& inputs) const {
5316 strategy::Plan<Tag> plan;
5317 const auto converted = strategy::weight_target(intent, inputs);
5318 if (!converted.target_) {
5319 plan.rejected_.push_back(
5320 strategy::Rejection{
5321 converted.refused_.value_or(strategy::RejectReason::NOT_REPRESENTABLE), intent.instrument(), intent.tag()
5322 }
5323 );
5324 return plan;
5325 }
5326 if (stop_listed(intent.instrument())) {
5327 // Met already: nothing to trade, and the stop protects what the weight means to hold, which
5328 // is `STOP_ORDER_RESTING`'s own rule for a met target. Unlike a target, nothing else on the
5329 // instrument is withdrawn either.
5330 const auto held = context_.portfolio().net_quantity_of(intent.instrument());
5331 const auto gap = held ? decimal_subtract(*held, converted.target_->target_quantity_) : std::nullopt;
5332 if (gap && gap->coefficient() == 0) {
5333 return plan;
5334 }
5335 plan.rejected_.push_back(
5336 strategy::Rejection{strategy::RejectReason::STOP_ORDER_RESTING, intent.instrument(), intent.tag()}
5337 );
5338 return plan;
5339 }
5340 return strategy::reconcile(*converted.target_, context_.portfolio(), inputs);
5341 }
5342
5343 // Reconciles one queued instruction against the current portfolio.
5344 //
5345 // The reference data is borrowed from the context (`find_instrument`) for the duration of the
5346 // call, as `ReconcileInputs` borrows it in turn, rather than copied: an `Instrument` carries a tick
5347 // table, and copying one per instruction per bar would pay repeatedly for a value that does not
5348 // change. Nothing a plan does changes the context's reference data.
5349 strategy::Plan<Tag> plan_for(const Instruction<Tag>& instruction) {
5350 const auto id = instrument_of(instruction);
5351 const auto* reference = context_.find_instrument(id);
5352 const auto band = band_for(id);
5353
5354 strategy::ReconcileInputs inputs;
5355 inputs.instrument_ = reference;
5356 inputs.reference_price_ = context_.last_price(id);
5357 inputs.limits_ = band.applied_;
5358 inputs.portfolio_value_ = portfolio_value_;
5359 inputs.portfolio_value_currency_ = portfolio_value_currency_;
5360 inputs.tolerance_ = tolerance_;
5361 inputs.reserved_rows_are_unconfirmed_ = keeps_sent_orders_until_listed;
5362 // The pass's index of the rows, while it still describes the portfolio; once anything replaced or edited
5363 // the portfolio, the rest of the pass scans.
5364 if (
5365 pass_rows_ != nullptr &&
5366 (context_detail::PortfolioAccess::replacements(context_) != rows_replacements_ ||
5367 context_detail::PortfolioAccess::runner_edits(context_) != rows_edits_)
5368 ) {
5369 pass_rows_ = nullptr;
5370 }
5371 inputs.rows_ = pass_rows_;
5372
5373 auto plan = [&] {
5374 if (const auto* target = std::get_if<strategy::TargetPosition>(&instruction)) {
5375 return strategy::reconcile(*target, context_.portfolio(), inputs);
5376 }
5377 if (const auto* intent = std::get_if<strategy::OrderIntent>(&instruction)) {
5378 // **A weight is a holding, so it is planned as the position it states.** Reconciled as an
5379 // order it would buy the whole allocation again at every rebalance, which is what
5380 // `SizeKind::TARGET_WEIGHT` promises it does not do; as a target it is diffed against the
5381 // position and the working orders, like any target.
5382 if (strategy::size_kind_is_target(intent->size().kind())) {
5383 return plan_weight(*intent, inputs);
5384 }
5385 return strategy::reconcile(*intent, context_.portfolio(), inputs);
5386 }
5387 return strategy::Plan<Tag>{};
5388 }();
5389
5390 // Counted per plan rather than per order, and counted even when the plan placed nothing: the
5391 // figure answers "how often did this run decline to use a band it was holding", which is a fact
5392 // about the policy. Whether it cost anything is the other counter's question.
5393 if (band.withheld_) {
5394 ++price_bands_withheld_;
5395 mark_withheld_band(plan, *band.withheld_);
5396 }
5397 return plan;
5398 }
5399
5400 // Records what the broker said about `order`, where the executor can say.
5401 //
5402 // Called at the `REJECTED` outcome and nowhere else, which is the only moment the answer is this
5403 // order's: `SessionExecutor::last_error()` is cleared by the next accepted instruction in the same
5404 // pass, so reading it later would attribute somebody else's silence to this refusal -- or nothing
5405 // at all.
5406 void note_broker_refusal(const strategy::PlannedOrder& order) {
5407 if constexpr (runner_detail::states_last_error<Executor>::value) {
5408 const auto& error = executor_.last_error();
5409 if (!error) {
5410 // **Cleared, not left alone.** An executor may answer `REJECTED` and state nothing; the
5411 // counter still moves, and a record kept from an *earlier* refusal would then be handed to
5412 // the next run as though it described this one -- the wrong instrument under the wrong tag.
5413 // `SessionExecutor` always states something on this path, so this is about a binding
5414 // somebody else writes: the contract is "the last refusal, or nothing", never "the last
5415 // refusal that happened to come with words".
5416 last_broker_refusal_.reset();
5417 return;
5418 }
5419 BrokerRefusal refusal;
5420 refusal.code_ = error->broker_code_;
5421 refusal.message_ = error->message_;
5422 refusal.instrument_ = order.instrument_;
5423 refusal.tag_ = order.tag_;
5424 last_broker_refusal_ = std::move(refusal);
5425 } else {
5426 static_cast<void>(order);
5427 }
5428 }
5429
5430 // Returns which instrument a queued instruction concerns.
5431 static InstrumentId instrument_of(const Instruction<Tag>& instruction) {
5432 if (const auto* target = std::get_if<strategy::TargetPosition>(&instruction)) {
5433 return target->instrument_;
5434 }
5435 if (const auto* intent = std::get_if<strategy::OrderIntent>(&instruction)) {
5436 return intent->instrument();
5437 }
5438 return InstrumentId{};
5439 }
5440
5441 // A band and what its age is measured from; see `set_price_limits`.
5442 struct DatedBand {
5443 // The band as the broker published it.
5444 PriceLimits limits_;
5445 // When this runner was told about it, which is all an unstamped band has.
5446 std::chrono::system_clock::time_point received_at_{};
5447 // Returns the instant the band's age is measured from; see `set_price_limits`.
5448 //
5449 // **The exchange's stamp may only make a band look older, never fresher.** It is there to catch
5450 // a successful fetch of a week-old band, which is an ageing question; a stamp *later* than the
5451 // moment this process received it answers nothing -- it is two clocks disagreeing, by ordinary
5452 // skew at best and by a broker's bug at worst -- and taking it at face value would let a band
5453 // date itself into the future and outlive any stated maximum. Capping it at the receipt instant
5454 // keeps the case it exists for and gives the other one no purchase, with no invented tolerance
5455 // for how far apart two clocks may be.
5456 std::chrono::system_clock::time_point as_of() const noexcept {
5457 if (!limits_.exchange_time_) {
5458 return received_at_;
5459 }
5460 return *limits_.exchange_time_ < received_at_ ? *limits_.exchange_time_ : received_at_;
5461 }
5462 };
5463 // Which band a plan may use, and which it was denied; see `band_for`.
5464 struct BandDecision {
5465 // The band to clamp with, when there is one this runner will stand behind.
5466 std::optional<PriceLimits> applied_;
5467 // The band that was held back, when one was, so the decision can be counted.
5468 std::optional<PriceLimits> withheld_;
5469 };
5470
5471 // Returns the band to apply to `id`'s prices, and separately the one that was held back.
5472 //
5473 // Exactly one of the two is filled when a band is registered, and neither when none is. The
5474 // withheld half exists so the decision can be counted and reported: a band silently dropped is
5475 // the same failure as a band silently applied.
5476 BandDecision band_for(const InstrumentId& id) const {
5477 BandDecision decision;
5478 const auto found = price_limits_.find(id);
5479 if (found == price_limits_.end()) {
5480 return decision;
5481 }
5482 if (!maximum_price_limits_age_ && !allow_unbounded_price_limits_age_) {
5483 // No policy stated. Not applied, and deliberately not the same as an absent band: the caller
5484 // asked for clamping and is getting none, which `price_bands_withheld` reports and a driving
5485 // loop names in its notes.
5486 decision.withheld_ = found->second.limits_;
5487 return decision;
5488 }
5489 // **A band dated after the instant it is being aged at is not applied, whatever the policy.**
5490 // `as_of` can no longer exceed the receipt stamp, so the only way here is a caller moving
5491 // `set_observed_at` backwards -- reporting day 20, registering a band, then reporting day 10.
5492 // The subtraction below would then be negative and pass every positive maximum, so a band from
5493 // the caller's own future would clamp. A duration this runner cannot compute is not an age, and
5494 // a band whose age is unknown is the case the whole policy exists for.
5495 if (found->second.as_of() > freshness_instant()) {
5496 decision.withheld_ = found->second.limits_;
5497 return decision;
5498 }
5499 if (maximum_price_limits_age_ && freshness_instant() - found->second.as_of() > *maximum_price_limits_age_) {
5500 decision.withheld_ = found->second.limits_;
5501 return decision;
5502 }
5503 decision.applied_ = found->second.limits_;
5504 return decision;
5505 }
5506
5507 // Marks the orders in `plan` whose price the band that was **not** applied would have moved.
5508 //
5509 // A statement about the planned price, not a prediction about the wire: clamping happens before
5510 // tick rounding (`reconcile_detail::prepare_price`), so a bound that binds here could in principle
5511 // round back to the same price. What the flag says is the checkable thing -- this order's price
5512 // lies outside the withheld band on the side the clamp corrects.
5513 static void mark_withheld_band(strategy::Plan<Tag>& plan, const PriceLimits& withheld) {
5514 for (auto& order : plan.place_) {
5515 if (!order.price_) {
5516 continue;
5517 }
5518 bool would_move = false;
5519 static_cast<void>(strategy::reconcile_detail::clamp_to_limits(
5520 *order.price_, order.side_, std::optional<PriceLimits>(withheld), would_move
5521 ));
5522 order.price_would_have_been_clamped_ = would_move;
5523 }
5524 }
5525
5526 Strategy strategy_;
5527 strategy::RiskGuard guard_;
5528 // Placements sent that may have left an order resting; see `placements_at_broker`.
5529 std::size_t placements_at_broker_{0};
5530 // Orders sent under a phase the limits did not permit; see `sends_outside_permitted_phase`.
5531 std::size_t sends_outside_permitted_phase_{0};
5532 // How old a snapshot may be before a plan derived from it is withheld; see the setter.
5533 std::optional<std::chrono::nanoseconds> maximum_portfolio_age_;
5534 // The last wall-clock instant a driving loop reported; see `set_observed_at`.
5535 std::chrono::system_clock::time_point observed_at_{};
5536 // Whether the caller stated this runner may act with no snapshot at all; see the setter.
5537 bool allow_absent_portfolio_{false};
5538 // Whether a placement needs a portfolio that has actually been read; see the setter.
5539 //
5540 // Defaulted from the executor: a runner that can reach a broker requires it, and one that cannot
5541 // does not. That is what makes the rule hold for a live runner assembled by hand rather than only
5542 // for one the binding factories produced.
5543 bool require_known_portfolio_{runner_detail::sends_to_a_broker<Executor>::value};
5544 bool probing_sellable_{false};
5545 strategy::SellableConventionProbe<Tag> sellable_probe_;
5546 Context context_;
5547 // Records the first local failure, keeping it rather than overwriting with a later one.
5548 void note_local_failure(std::string detail) {
5549 // The *first* reason is kept, not the latest: a storage failure cascades, and the reason the
5550 // cascade started is the one an operator needs. Taking the hold again would only replace it.
5552 guard_.halt(strategy::HaltReason::LOCAL_FAILURE, std::move(detail));
5553 }
5554 }
5555
5556 // Makes the executor's own local failure sticky on the runner, if it reported one.
5557 //
5558 // Called after every send rather than only after a refusal, because the two are not the same
5559 // event. A *pre-send* journal write that fails produces `UNAVAILABLE` and nothing was sent. A
5560 // *terminal* journal write that fails happens after the broker has already answered: the send
5561 // really did happen, so the outcome passed back stays the broker's, and only this call records
5562 // that the journal is no longer trustworthy.
5563 void note_executor_failure(bool refused) {
5564 const auto failures = executor_journal_failures();
5565 if (failures > acknowledged_journal_failures_) {
5566 // A placement's or a cancellation's line may be on disk whole, in part, or not at all.
5567 note_run_journal_write_failed();
5568 auto detail = executor_journal_error();
5569 note_local_failure(detail.empty() ? std::string("the order journal could not be written") : std::move(detail));
5570 return;
5571 }
5572 if (refused && failures == 0) {
5573 // An executor with no journal behind it can still refuse locally, and it reports no count.
5574 // Nothing to acknowledge, so a refusal always halts and a resume that does not fix the cause
5575 // simply halts again on the next send -- which is the truthful outcome.
5576 note_local_failure("local machinery refused to send");
5577 }
5578 }
5579
5580 // Returns how many journal writes the executor has had fail, or zero when it cannot say.
5581 std::size_t executor_journal_failures() const {
5582 return executor_journal_failures_impl(0);
5583 }
5584
5585 template <typename E = Executor>
5586 auto executor_journal_failures_impl(int) const -> decltype(std::declval<const E&>().journal_failures()) {
5587 return executor_.journal_failures();
5588 }
5589
5590 std::size_t executor_journal_failures_impl(...) const {
5591 return 0;
5592 }
5593
5594 // Returns what the executor says went wrong, or empty when it reports nothing or cannot.
5595 std::string executor_journal_error() const {
5596 return executor_journal_error_impl(0);
5597 }
5598
5599 template <typename E = Executor>
5600 auto executor_journal_error_impl(int) const
5601 -> decltype(std::declval<const E&>().last_journal_error(), std::string()) {
5602 return executor_.last_journal_error();
5603 }
5604
5605 std::string executor_journal_error_impl(...) const {
5606 return {};
5607 }
5608
5609 Executor executor_;
5610 IndeterminacyLedger ledger_;
5611 // The run's cash and own shares, only with `RiskLimits::run_budget_`; a runner that keeps its run in a journal
5612 // opens it at recovery (`open_run_from`).
5613 std::optional<RunLedger> run_;
5614 // What the run's accepted buys commit where no listing keeps them (see `run_pass_inputs`); empty once the sum
5615 // does not fit, which refuses every later buy.
5616 std::optional<Decimal64> run_committed_{Decimal64(0, 0)};
5617 // Whether a replay's queue rows carry the run's open orders (`runner_detail::ReplayAccess::rows_listed`).
5618 bool run_rows_listed_{false};
5619 // The instruments of the run's orders of unknown outcome, while the indeterminacy ledger withholds them.
5620 std::vector<InstrumentId> run_unknown_;
5621 std::optional<RunOpening> run_opening_;
5622 std::optional<RunRecoverySummary> run_recovery_;
5623 // A resume found an intact journal with no run: nothing is spent or sold, and the journal writes as without a budget.
5624 bool run_absent_{false};
5625 // A new run waits while `run_` is the old run, closing: its orders are booked to it, and it spends nothing.
5626 bool run_closing_{false};
5627 // The old run's orders whose cancellation was sent, by journal id, so each is sent once per process.
5628 std::vector<std::string> run_cancels_sent_;
5629 // Set at a budgeted runner's first failed journal write, for the process's life (`run_writes_closed`).
5630 bool run_journal_latched_{false};
5631 // Every ledger-shaped id the journal holds, so a generated one never repeats it.
5632 std::unordered_set<std::string> run_ids_;
5633 std::size_t acknowledged_journal_failures_{0};
5634 std::map<InstrumentId, DatedBand> price_limits_;
5635 // How old a band may be before it is not applied; see `set_maximum_price_limits_age`.
5636 std::optional<std::chrono::nanoseconds> maximum_price_limits_age_;
5637 // Whether the caller stated this runner applies a band of any age; see the setter.
5638 bool allow_unbounded_price_limits_age_{false};
5639 // Plans built while a band was held and not applied; see `price_bands_withheld`.
5640 std::size_t price_bands_withheld_{0};
5641 // Sent orders a broker refused after a withheld band would have moved them; see the accessor.
5642 std::size_t unclamped_orders_rejected_{0};
5643 // Orders nothing sent to a broker while carrying an unclamped price; see the accessor.
5644 std::size_t unclamped_orders_refused_{0};
5645 // Instructions that failed by each origin, and refusals a broker made; see the accessors.
5646 std::size_t orders_unbuildable_{0};
5647 // @copydoc Runner::orders_unbuildable_
5648 std::size_t orders_reconcile_withheld_{0};
5649 // @copydoc Runner::orders_unbuildable_
5650 std::size_t orders_guard_refused_{0};
5651 // @copydoc Runner::orders_unbuildable_
5652 std::size_t orders_binding_refused_{0};
5653 // @copydoc Runner::orders_unbuildable_
5654 std::size_t orders_broker_refused_{0};
5655 // @copydoc Runner::orders_unbuildable_
5656 std::size_t orders_indeterminate_{0};
5657 // Withdrawals that failed, by origin; see `cancels_rejected`.
5658 std::size_t cancels_rejected_{0};
5659 // @copydoc Runner::cancels_rejected_
5660 std::size_t cancels_refused_{0};
5661 // @copydoc Runner::cancels_rejected_
5662 std::size_t cancels_unresolved_{0};
5663 // @copydoc Runner::cancels_rejected_
5664 std::size_t cancels_indeterminate_{0};
5665 // Plans held back whole, for any of three reasons; see `plans_withheld`.
5666 std::size_t plans_withheld_{0};
5667 std::size_t warmup_instructions_discarded_{0};
5668 // Whether `start` has run; see `start`.
5669 bool started_{false};
5670 // A stop a deferred target waits on, with the order time its listing showed (if any) to tell it from
5671 // another day's order under the same number.
5672 struct DeferredStop {
5673 OrderRef<Tag> ref_;
5674 std::optional<std::chrono::system_clock::time_point> ordered_at_;
5675 };
5676 // One target waiting for a stop's withdrawal, and when a listing first showed the stop gone.
5677 struct DeferredTarget {
5678 // The target, exactly as the strategy stated it.
5679 strategy::TargetPosition target_;
5680 // The stops it waits on, whose own history rows decide its release.
5681 std::vector<DeferredStop> stops_;
5682 // When it was deferred, which bounds the history that can hold those rows.
5683 std::chrono::system_clock::time_point deferred_at_{};
5684 };
5685 // Targets waiting for a stop's withdrawal; see `deferred_targets`.
5686 std::vector<DeferredTarget> deferred_targets_;
5687
5688 std::vector<Unconfirmed> unconfirmed_;
5689 // Serialized mode; see `serialized`.
5690 static constexpr bool can_serialize = keeps_sent_orders_until_listed && runner_detail::serializes<Executor>::value;
5691 // Whether a run budget's run can live in this runner's journal; a live budgeted runner needs it.
5692 static constexpr bool keeps_run_in_journal =
5693 journals_to_a_broker && can_serialize && runner_detail::can_journal_run<Executor>::value;
5694 bool overlapping_{false};
5695 bool recovered_{false};
5696 std::vector<Boundary> boundaries_;
5697 std::size_t orders_awaiting_confirmation_{0};
5698 std::chrono::nanoseconds confirmation_timeout_{std::chrono::minutes(10)};
5699 std::size_t orders_unconfirmed_timed_out_{0};
5700 // Targets withheld for want of a trustworthy account, one per instrument; see `retry_retained_targets`.
5701 // A retained target, and whether it waits for the market phase rather than for the account.
5702 struct RetainedTarget {
5703 strategy::TargetPosition target_;
5704 bool for_phase_{false};
5705 // Kept because the broker could not be reached: planned again only after a later holdings read.
5706 std::optional<std::chrono::system_clock::time_point> after_;
5707 // Kept behind an order it could only withdraw: planned again only once the instrument owes no order.
5708 bool until_accounted_{false};
5709 };
5710 std::vector<RetainedTarget> retained_targets_;
5711 // An order intent kept for the phase, and the instrument's net holding when it was kept.
5712 struct KeptIntent {
5713 strategy::OrderIntent intent_;
5714 Decimal64 held_;
5715 // As for `RetainedTarget::after_`.
5716 std::optional<std::chrono::system_clock::time_point> after_;
5717 };
5718 std::vector<KeptIntent> kept_intents_;
5719 std::size_t kept_intents_dropped_{0};
5720 // The instructions kept for the phase in the current pass, so each is kept once.
5721 std::vector<const Instruction<Tag>*> kept_this_pass_;
5722 // The index of the portfolio's rows for the planning loop of the pass in progress, or null (`settle`), and the
5723 // context's counts of portfolio replacements and edits when it was built.
5724 const strategy::PortfolioRows* pass_rows_{nullptr};
5725 std::uint64_t rows_replacements_{0};
5726 std::uint64_t rows_edits_{0};
5727 // True only inside a deferred release's settle, which `plan_withhold_reason` exempts.
5728 bool releasing_deferred_{false};
5729 // How many were ever deferred; see `targets_deferred`.
5730 std::size_t targets_deferred_{0};
5731 // How many were dropped after a fill; see `deferred_dropped_after_fill`.
5732 std::size_t deferred_dropped_after_fill_{0};
5733 // Instructions local machinery was unavailable to send; see the accessor.
5734 std::size_t instructions_unavailable_{0};
5735 // What the broker said about the most recent order it refused; see the accessor.
5736 std::optional<BrokerRefusal> last_broker_refusal_;
5737 std::optional<strategy::Rejection> last_unbuildable_;
5738 std::optional<Decimal64> portfolio_value_;
5739 std::optional<Currency> portfolio_value_currency_;
5740 strategy::TradeTolerance tolerance_;
5741
5742 friend struct runner_detail::ReplayAccess;
5743};
5744
5745namespace runner_detail {
5746
5747// How a replay books its executions in a budgeted runner's run (`backtest::Backtester`).
5748struct ReplayAccess {
5749 // Whether the runner keeps a run.
5750 template <typename R>
5751 static bool has_run(const R& runner) noexcept {
5752 return runner.run_.has_value();
5753 }
5754
5755 // Says the replay's queue rows carry the runner's open orders, so the runner keeps no commitment of its own.
5756 template <typename R>
5757 static void rows_listed(R& runner) noexcept {
5758 runner.run_rows_listed_ = true;
5759 }
5760
5761 // Books one execution in the runner's run, which must be open; `false` if `RunLedger::book` refuses it.
5762 template <typename R>
5763 static bool book(
5764 R& runner, const InstrumentId& instrument, OrderSide side, const Decimal64& filled, const Money& amount,
5765 const Decimal64& fee
5766 ) {
5767 return runner.run_->book(instrument, side, filled, amount, fee);
5768 }
5769};
5770
5771} // namespace runner_detail
5772
5790template <typename Strategy, typename CapsType = strategy::NoCaps>
5792
5793} // namespace runner
5794} // namespace algotradelib
An exact signed decimal: an int64 coefficient times 10^-scale.
Definition types.hpp:443
Decimal64()=default
Constructs zero.
static Decimal64 parse(std::string_view input)
Parses a decimal string exactly (no binary floating point).
Definition types.hpp:468
What a strategy's handlers receive as ctx: everything the strategy may read, and where it queues what...
Definition context.hpp:257
The instruments with an order of unknown outcome, where nothing may be placed until the broker's orde...
An executor that sends nothing and records what it was given (the dry run's default).
RunLedger(Money opening)
Opens a new run.
Runs one strategy: feeds it events, reconciles what it asks for, checks the risk limits,...
Definition runner.hpp:305
std::size_t cancels_rejected() const noexcept
Returns how many cancellations were refused, by the broker or the binding (RejectedCancel::by_broker_...
Definition runner.hpp:1686
bool run_writes_closed() const noexcept
Tests whether a budgeted runner that keeps its run in a journal has stopped writing to it: its run is...
Definition runner.hpp:831
void resume_after_local_failure()
Clears the local-failure hold, after an operator has fixed the cause.
Definition runner.hpp:447
std::size_t intents_kept_for_phase() const noexcept
Returns how many order intents are kept for the market phase, an unreachable broker or a rate limit; ...
Definition runner.hpp:1566
std::vector< RunPlacement > run_unsettled() const
Lists the run's placements that leave its ledger unsettled: held for an operator, or released by one ...
Definition runner.hpp:774
Report feed(const strategy::BarEvent &event)
Feeds one bar: caches it, sets the last price and the clock to the bar's period end,...
Definition runner.hpp:1868
std::optional< Money > run_cash() const
Returns the run's cash, with RiskLimits::run_budget_ set.
Definition runner.hpp:752
std::optional< std::string > local_failure() const
Returns why local machinery stopped sending, if it did.
Definition runner.hpp:434
const std::optional< BrokerRefusal > & last_broker_refusal() const noexcept
Returns the broker's code and message for the most recent order it refused (SendOutcome::REJECTED; at...
Definition runner.hpp:1719
Report notify_stop()
Calls on_stop and settles what it asked for while PollingLoop's STOPPING hold stands,...
Definition runner.hpp:1840
const std::optional< RunRecoverySummary > & run_recovery() const noexcept
Returns how runner::recover_runner opened the run, or why it did not, or that a new run waits for the...
Definition runner.hpp:816
std::size_t kept_intents_dropped() const noexcept
Returns how many kept intents were dropped at release, because the holding they were decided against ...
Definition runner.hpp:1575
void require_known_portfolio(bool required)
Sets whether placing requires holdings to have been read and fresh.
Definition runner.hpp:507
void clear_deferred_targets() noexcept
Discards every target waiting on a resting stop (deferred_targets). The orders this runner owes are n...
Definition runner.hpp:1611
bool started() const noexcept
Tests whether start has been called.
Definition runner.hpp:1817
void note_run_journal_write_failed() noexcept
Records that a write to a budgeted runner's journal failed, which stops its writes for the process's ...
Definition runner.hpp:844
std::size_t cancels_refused() const noexcept
Returns how many cancellations a hold refused before sending.
Definition runner.hpp:1693
std::size_t cancels_unresolved() const noexcept
Returns how many cancellations named an order the portfolio does not list.
Definition runner.hpp:1700
void probe_sellable_convention(bool enabled=true)
Turns on the strategy::SellableConventionProbe, which infers whether the broker's sellable figure alr...
Definition runner.hpp:554
void set_portfolio_value(Decimal64 value)
Sets the portfolio's total value, which a weight-sized intent needs live.
Definition runner.hpp:1762
std::chrono::system_clock::time_point observed_at() const noexcept
Returns the instant last set by set_observed_at.
Definition runner.hpp:483
std::size_t orders_broker_refused() const noexcept
Returns how many orders the broker refused (SendOutcome::REJECTED; a request was spent); see last_bro...
Definition runner.hpp:907
std::vector< Obligation > obligations(const InstrumentId &instrument) const
Lists the orders a serialized runner still owes on an instrument, for an operator.
Definition runner.hpp:1183
void set_maximum_portfolio_age(std::optional< std::chrono::nanoseconds > age)
Sets how old the holdings may be before a reconciliation plan computed from them is held back (Withhe...
Definition runner.hpp:462
std::size_t plans_withheld() const noexcept
Returns how many whole reconciliation plans were held back (any WithheldPlanReason: holdings absent,...
Definition runner.hpp:925
Report feed(const strategy::QuoteEvent &event)
Feeds one quote: sets the last price and the clock, calls on_quote, and settles.
Definition runner.hpp:1997
void set_observed_at(std::chrono::system_clock::time_point at)
Sets the current wall-clock instant, used to measure the age of holdings and price bands.
Definition runner.hpp:475
Report retry_deferred(const std::vector< OrderSnapshot > &evidence)
Decides each waiting target against the broker's order history, and settles what it released.
Definition runner.hpp:999
void resolve_indeterminate_placement(const InstrumentId &instrument, OrderSide side, const std::optional< std::string > &order_id, const std::string &journal_id={})
Tells the runner what a reconciliation sweep found for an order of unknown outcome.
Definition runner.hpp:1055
Strategy & strategy() noexcept
Returns the strategy.
Definition runner.hpp:592
std::size_t placements_at_broker() const noexcept
Returns how many placements may have left an order at the broker (accepted or of unknown outcome).
Definition runner.hpp:527
std::size_t orders_guard_refused() const noexcept
Returns how many orders the risk guard refused, for a limit or a hold; see orders_unbuildable.
Definition runner.hpp:740
void allow_unbounded_price_limits_age()
Applies price bands of any age (replacing a stated maximum).
Definition runner.hpp:669
std::size_t orders_awaiting_confirmation() const noexcept
Returns how many orders a serialized runner withheld because another order on the instrument was not ...
Definition runner.hpp:1308
void feed_warmup(const strategy::BarEvent &event)
Feeds one bar as history: like feed, but whatever the strategy asks for is discarded (counted in warm...
Definition runner.hpp:1895
Context & context() noexcept
Returns the context, to arrange its state (instruments, portfolio) before feeding events.
Definition runner.hpp:607
Report feed(const OrderSnapshot &event)
Feeds one order update: calls on_order_update and settles.
Definition runner.hpp:2044
const Executor & executor() const noexcept
Returns the executor.
Definition runner.hpp:397
Runner(Strategy strategy={}, strategy::RiskLimits limits={}, std::size_t series_capacity=512, Executor executor={})
Constructs a runner.
Definition runner.hpp:376
Report start()
Calls on_start and settles what it asked for, the first time it is called.
Definition runner.hpp:1799
const strategy::SellableConventionProbe< Tag > & sellable_convention() const noexcept
Returns the sellable-convention probe.
Definition runner.hpp:577
std::size_t orders_unbuildable() const noexcept
Returns how many orders reconciliation could not build (any strategy::RejectReason before sending,...
Definition runner.hpp:725
void feed_warmup(const strategy::BarSlice &slice)
Delivers one period's bars as history: like feed(const strategy::BarSlice&), but whatever the strateg...
Definition runner.hpp:1960
void allow_absent_portfolio()
Lets this runner place orders before holdings have ever been read.
Definition runner.hpp:493
strategy::RiskGuard & guard() noexcept
Returns the risk guard, to halt or resume trading.
Definition runner.hpp:622
std::size_t warmup_instructions_discarded() const noexcept
Returns how many instructions feed_warmup discarded.
Definition runner.hpp:1988
Report retry_retained_targets()
Re-submits retained targets and kept intents once they can be acted on, and settles them.
Definition runner.hpp:1480
Report retry_deferred_on_one_snapshot()
Releases and settles every waiting target whose stops are no longer listed, without reading history.
Definition runner.hpp:1670
std::size_t orders_indeterminate() const noexcept
Returns how many orders had an unknown outcome (SendOutcome::INDETERMINATE, which at KIS,...
Definition runner.hpp:915
Report feed(const strategy::Fill &event)
Feeds one execution: calls on_fill and settles.
Definition runner.hpp:2033
void allow_overlapping_orders()
Lets several orders on one instrument be outstanding at once, as an unjournaled runner does,...
Definition runner.hpp:1145
bool book_run_fill(const std::string &placement_id, const Decimal64 &filled, const Money &amount, const Decimal64 &fee, const std::string &reason)
Books, on an operator's word, what a placement of the run released without a booking filled.
Definition runner.hpp:863
Report stop()
Calls on_stop and settles what it asked for.
Definition runner.hpp:1829
void set_minimum_trade(Decimal64 quantity)
Sets only the share-count floor of the trade tolerance.
Definition runner.hpp:1750
std::size_t unconfirmed_orders() const noexcept
Returns how many sent orders are still counted as reserved until the broker accounts for them.
Definition runner.hpp:1024
void set_maximum_price_limits_age(std::optional< std::chrono::nanoseconds > age)
Sets how old a price band may be and still be applied to an order's price.
Definition runner.hpp:662
std::size_t targets_retained_for_phase() const noexcept
Returns how many retained targets wait for the market phase, an unreachable broker or a rate limit.
Definition runner.hpp:1592
bool release_obligations(const InstrumentId &instrument, const std::string &reason)
Accounts for every order a serialized runner still owes on an instrument, on an operator's word.
Definition runner.hpp:1236
std::vector< strategy::TargetPosition > deferred_targets() const
Returns the targets waiting for a stop on their instrument to be cancelled (at most one per instrumen...
Definition runner.hpp:947
const std::optional< strategy::Rejection > & last_unbuildable() const noexcept
Returns why reconciliation could not build the most recent instruction it refused.
Definition runner.hpp:1731
std::size_t targets_deferred() const noexcept
Returns how many targets have waited for a stop's cancellation; see deferred_targets.
Definition runner.hpp:960
void halt_locally(std::string detail)
Stops this runner sending, with the LOCAL_FAILURE hold, until resume_after_local_failure.
Definition runner.hpp:519
void observe_sellable_convention()
Shows the current portfolio to the sellable-convention probe, if it is on.
Definition runner.hpp:564
void set_confirmation_timeout(std::chrono::nanoseconds timeout)
Sets how long a sent order's quantity may stay unexplained before it is counted as timed out (ten min...
Definition runner.hpp:1346
void restore_obligations(const JournalReplay &replay)
Restores the orders a previous process left unaccounted for; runner::recover_runner calls it,...
Definition runner.hpp:1285
Report settle_closing()
Settles instructions already queued on the context, without calling a handler.
Definition runner.hpp:1852
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
std::optional< Decimal64 > run_holding(const InstrumentId &instrument) const
Returns the run's own shares of an instrument, with RiskLimits::run_budget_ set.
Definition runner.hpp:762
std::vector< Obligation > obligations() const
Lists every order a serialized runner still owes, on any instrument.
Definition runner.hpp:1201
bool serialized() const noexcept
Tests whether this runner is serialized: at most one order per instrument that holdings have not yet ...
Definition runner.hpp:1129
const strategy::RiskGuard & guard() const noexcept
Returns the risk guard.
Definition runner.hpp:615
std::size_t sends_outside_permitted_phase() const noexcept
Returns how many orders were sent in a market phase RiskLimits::permitted_phases_ does not permit,...
Definition runner.hpp:541
Report feed(strategy::MarketPhase phase)
Feeds a market phase change: sets it on the context, calls on_phase, and settles.
Definition runner.hpp:2055
IndeterminacyLedger & ledger() noexcept
Returns the ledger, so an operator who has read the broker's order list can clear an entry.
Definition runner.hpp:422
std::size_t targets_retained() const noexcept
Returns how many targets are retained, for any reason; see retry_retained_targets.
Definition runner.hpp:1583
Report feed(const strategy::DataEvent< T > &event)
Feeds one record: sets the clock to when it became known, calls on_data, and settles.
Definition runner.hpp:2016
void set_portfolio_value(Money value)
Sets the portfolio's total value and its currency.
Definition runner.hpp:1775
const Context & context() const noexcept
Returns the context.
Definition runner.hpp:600
std::size_t obligations_awaiting_account() const noexcept
Returns how many orders a serialized runner owes that a later read could account for without anything...
Definition runner.hpp:1625
Executor & executor() noexcept
Returns the executor.
Definition runner.hpp:404
bool withdrawal_accepted_for(const WorkingOrder< Tag > &working) const
Tests whether working is a row of an order this runner sent whose withdrawal the broker has already a...
Definition runner.hpp:1647
std::size_t obligations_unexplained() const noexcept
Returns how many orders a serialized runner owes that nothing yet explains: no listing shows them res...
Definition runner.hpp:1320
Report feed(const strategy::BarSlice &slice)
Delivers one period's bars to on_bars and settles what the strategy asked for.
Definition runner.hpp:1945
const IndeterminacyLedger & ledger() const noexcept
Returns the ledger of instruments withheld pending reconciliation or an operator: an order of unknown...
Definition runner.hpp:415
std::size_t orders_binding_refused() const noexcept
Returns how many orders the binding refused to send (no request made); see orders_unbuildable.
Definition runner.hpp:898
std::size_t deferred_dropped_after_fill() const noexcept
Returns how many waiting targets were dropped because a stop they waited on had filled.
Definition runner.hpp:968
std::size_t orders_reconcile_withheld() const noexcept
Returns how many orders were held back because the instrument was in the ledger (an order of unknown ...
Definition runner.hpp:733
void clear_retained_targets() noexcept
Discards every retained target and kept intent (PollingLoop does this when stopping).
Definition runner.hpp:1601
void set_run_opening(RunOpening opening)
Sets how runner::recover_runner opens a budgeted runner's run from its journal: a new run by default,...
Definition runner.hpp:790
std::size_t orders_unconfirmed_timed_out() const noexcept
Returns how many sent orders timed out unconfirmed; see set_confirmation_timeout.
Definition runner.hpp:1354
ObligationState obligation_state(const InstrumentId &instrument) const
Returns what a serialized runner still owes on an instrument.
Definition runner.hpp:1161
std::optional< std::chrono::system_clock::time_point > unconfirmed_awaiting_evidence()
Returns from when the broker's order history must be read to settle sent orders.
Definition runner.hpp:1371
std::size_t instructions_unavailable() const noexcept
Returns how many instructions (placements and cancellations) were not sent because local machinery wa...
Definition runner.hpp:1678
std::size_t price_bands_withheld() const noexcept
Returns how many plans were built while a band was known for the instrument but not applied (counted ...
Definition runner.hpp:678
void record_history_only(const strategy::BarEvent &event)
Caches one bar without moving the last price or the clock, and without calling a handler.
Definition runner.hpp:1931
std::size_t unclamped_orders_refused() const noexcept
Returns how many orders carrying a price a withheld band would have clamped were refused before sendi...
Definition runner.hpp:708
void feed_warmup(const strategy::DataEvent< T > &event)
Feeds one record as history: like feed(const strategy::DataEvent<T>&), but whatever the strategy asks...
Definition runner.hpp:1973
void refresh_unconfirmed()
Rebuilds the reserved working rows against the portfolio as it is now.
Definition runner.hpp:1033
bool price_limits_age_policy_stated() const noexcept
Tests whether a price-band age policy has been stated (a maximum, or any age).
Definition runner.hpp:686
void confirm_from_history(const std::vector< OrderSnapshot > &evidence)
Settles reserved orders against the broker's order history; sends nothing.
Definition runner.hpp:1401
std::size_t cancels_indeterminate() const noexcept
Returns how many cancellations had an unknown outcome (the order may or may not have been cancelled).
Definition runner.hpp:1707
void set_trade_tolerance(strategy::TradeTolerance tolerance)
Sets how small a drift from a target is not worth an order; see strategy::TradeTolerance.
Definition runner.hpp:1739
strategy::strategy_detail::data_record_t< Strategy > DataRecord
Definition runner.hpp:317
const Strategy & strategy() const noexcept
Returns the strategy, to read the state it kept.
Definition runner.hpp:585
std::optional< std::chrono::system_clock::time_point > deferred_awaiting_evidence() const
Returns from when the broker's order history must be read to decide waiting targets.
Definition runner.hpp:977
void clear_portfolio_value() noexcept
Forgets the portfolio value, so weighted intents are refused again.
Definition runner.hpp:1781
std::size_t unclamped_orders_rejected() const noexcept
Returns how many sent orders the broker refused while carrying a price a withheld band would have cla...
Definition runner.hpp:699
const std::string & tag() const noexcept
Returns the tag.
Definition intent.hpp:417
const SizeSpec & size() const noexcept
Returns how much to trade.
Definition intent.hpp:393
const InstrumentId & instrument() const noexcept
Returns the instrument to trade.
Definition intent.hpp:361
Checks planned orders against RiskLimits, holds trading stopped, and counts orders sent.
Definition risk.hpp:879
void halt() noexcept
Takes the operator's hold (HaltReason::OPERATOR): no order or cancellation is sent until resume().
Definition risk.hpp:956
bool halted() const noexcept
Tests whether any hold is in force.
Definition risk.hpp:1000
Infers a broker's SellableConvention from successive portfolios.
SizeKind kind() const noexcept
Returns how the size is expressed.
Definition intent.hpp:200
#define ATL_ASSERT_STRATEGY(S, Ctx)
Asserts at compile time that S is a strategy a runner with context Ctx can drive.
Definition concept.hpp:866
std::vector< Fold > folds(std::size_t count, const FoldLengths &lengths, const Scheme &scheme=Scheme{})
Lists the folds over a time index of count positions.
Definition folds.hpp:114
Runs a strategy: the runner, the polling loop, the order journal, and stopping.
Definition clock.hpp:7
bool broker_unreachable(const BrokerError &error) noexcept
Tests whether an error means the broker could not be reached (as opposed to the binding refusing the ...
constexpr bool journal_outcome_answers_send(JournalOutcome outcome) noexcept
Tests whether a line with this outcome answers the send itself (the broker's reply,...
Definition journal.hpp:265
Runner< Strategy, CapsType, DryTag, RecordingExecutor< DryTag > > DryRunner
A runner that sends nothing: handlers fire and instructions are recorded by a RecordingExecutor.
Definition runner.hpp:5791
constexpr bool journal_outcome_is_closing_account(JournalOutcome outcome) noexcept
Tests whether a line with this outcome is a serialized runner's closing account of a placement (it co...
Definition journal.hpp:329
constexpr bool send_outcome_reached_broker(SendOutcome outcome) noexcept
Tests whether an outcome means a request reached the broker.
SendOutcome
What became of one instruction (a placement or a cancellation) an executor was asked to send.
Definition execution.hpp:30
@ UNAVAILABLE
Local machinery failed (such as the order journal not being writable), so nothing was sent.
Definition execution.hpp:55
@ INDETERMINATE
The outcome is unknown (see outcome_of): the request failed in transit or was cancelled,...
Definition execution.hpp:48
@ REJECTED
The broker refused the instruction (for a placement, the order does not exist); nothing needs reconci...
Definition execution.hpp:34
@ ACCEPTED
The broker accepted the instruction (for a placement, the order exists).
Definition execution.hpp:32
@ REFUSED_LOCALLY
The binding refused the instruction before sending it (such as an idempotency key at a broker without...
Definition execution.hpp:63
WithheldPlanReason
Why the runner held back a whole reconciliation plan (cancellations and placements) before sending an...
@ PLACEMENT_HELD
A hold stops placements, so the plan's cancellations are held too (a reprice must not become a bare c...
@ PORTFOLIO_ABSENT
No holdings have been read, so the plan was computed against an account that looks flat (and could ca...
@ AWAITING_CONFIRMATION
A serialized runner may not place on the instrument yet, so the plan's cancellations are held too: an...
@ PORTFOLIO_STALE
The holdings the plan was computed from are older than the configured maximum age.
@ PORTFOLIO_SUPERSEDED
The working-order listing is newer than the holdings the plan was sized against (see strategy::Portfo...
@ OPEN
A run begins; its amount is the budget, the run's first deposit, and its line's id is the run's id.
Definition journal.hpp:393
@ WITHDRAWAL
Cash taken from the run, under the operator's id (RunRecord::given_).
Definition journal.hpp:397
@ DEPOSIT
Cash added to the run, under the operator's id (RunRecord::given_).
Definition journal.hpp:395
@ FILL
An operator's booking of a placement released without one (runner::Runner::book_run_fill).
Definition journal.hpp:399
RunRefusal
Why recovery opened no run (RunRecoverySummary::refusal_).
@ DAMAGED
The journal was not read whole, or holds a damaged line.
@ CURRENCY
The journal's run is in another currency than strategy::RiskLimits::run_budget_.
@ LEDGER
The run's records do not add up (a repeated opening, a double booking, an invalid booking or transfer...
@ WRITE
A line of the opening could not be written.
@ NO_RUN
A resume found an intact journal with no run: no halt, buys and sells refused, withdrawals as usual.
@ TRANSFER
A stated transfer was refused (an id reused with another amount, a withdrawal past free cash,...
JournalOutcome
What a journal line says about an instruction.
Definition journal.hpp:113
@ CONFIRMED
A serialized runner accounted for the placement: holdings showed what it filled, its history showed i...
Definition journal.hpp:144
@ INDETERMINATE
The outcome is unknown (SendOutcome::INDETERMINATE: a failure in transit, an unreadable reply,...
Definition journal.hpp:128
@ RESOLVED
A recovery sweep read the broker's order list and closed the question.
Definition journal.hpp:136
@ REJECTED
The instruction was refused, by the broker or before it was sent, so it does not exist.
Definition journal.hpp:123
@ ACCEPTED
The broker accepted the instruction; it exists.
Definition journal.hpp:117
@ HELD
Evidence contradicted the placement (holdings moved past what it can explain), so only an operator ma...
Definition journal.hpp:149
@ PENDING
Written before the send; whether the instruction exists is not yet known.
Definition journal.hpp:115
@ RECORDED
A run budget's ledger record (JournalAction::LEDGER); it answers no instruction.
Definition journal.hpp:151
constexpr bool journal_outcome_requires_operator(JournalOutcome outcome) noexcept
Tests whether a line with this outcome is written with requires_operator_ by design,...
Definition journal.hpp:351
@ LOCAL_FAILURE
Local machinery cannot send (see SendOutcome::UNAVAILABLE).
@ AWAITING_CONFIRMATION
A serialized runner already has an order on this instrument that holdings have not yet accounted for ...
@ RECONCILE_REQUIRED
An earlier instruction for this instrument has an unknown outcome; nothing is sent until the broker's...
std::string_view journal_run_of(const JournalEntry &entry) noexcept
Returns the run budget's run a journal line belongs to.
Definition journal.hpp:559
constexpr bool send_outcome_is_local_failure(SendOutcome outcome) noexcept
Tests whether an outcome means the runner's own machinery failed (not the broker, and not a check tha...
@ LEDGER
A record of a run budget's ledger (RunRecord), not an instruction: it sends nothing and names no orde...
Definition journal.hpp:42
ObligationState
What a serialized runner still owes on an instrument (Runner::obligation_state).
@ NAMED
An order the broker named, waiting for its history and holdings to account for it.
@ OPERATOR
An order only an operator may account for (Runner::release_obligations).
@ NONE
Nothing: an order may be placed.
@ UNNAMED
An order whose existence is unknown (its reply was lost and no sweep named it).
constexpr int obligation_weight(ObligationState state) noexcept
Returns how much an obligation state weighs when one instrument owes several orders: the instrument r...
bool broker_rate_limited(const BrokerError &error) noexcept
Tests whether an error is the broker's rate-limit refusal (such as KIS EGW00201).
std::variant< OrderIntent, TargetPosition, CancelIntent< Broker > > Instruction
One request a strategy queued: an order, a target position or a cancellation.
Definition context.hpp:49
void stop(S &strategy, Ctx &context)
Calls strategy.on_stop(context) if the strategy declares on_stop; otherwise does nothing.
Definition concept.hpp:259
What a strategy sees and emits: events, intents, the portfolio, reconciliation and risk limits.
Definition concept.hpp:16
@ PHASE_NOT_PERMITTED
The market phase is not in RiskLimits::permitted_phases_.
Definition risk.hpp:192
MarketPhase
Where the clock stands relative to the trading session.
Definition event.hpp:33
bool order_is_open(OrderStatus status)
Tests whether an order in a given status may still trade.
Definition portfolio.hpp:22
@ WITHDRAWAL
A cancellation of an order the caller named.
Definition risk.hpp:105
WeightTarget weight_target(const OrderIntent &intent, const ReconcileInputs &inputs)
Converts a weight-sized intent into the target position it states.
constexpr bool market_phase_session_ended(MarketPhase phase) noexcept
Tests whether a phase means the day's session is over (or never opened), so a day order no longer wor...
Definition event.hpp:90
@ BROKER_REFUSED
The broker refused the instruction (a request was sent).
Definition reconcile.hpp:57
@ NOT_REPRESENTABLE
The decimal arithmetic did not fit, or the portfolio's rows did not add up.
Definition reconcile.hpp:46
@ STOP_ORDER_RESTING
A target needs a trade while a stop order rests on the instrument; the stop is cancelled first and no...
Definition reconcile.hpp:80
@ BINDING_REFUSED
The binding refused to send the instruction, so no request was made.
Definition reconcile.hpp:64
constexpr std::string_view halt_reason_name(HaltReason reason) noexcept
Returns a lowercase name for a hold, such as "portfolio_stale", for logs.
Definition risk.hpp:149
constexpr bool size_kind_is_target(SizeKind kind) noexcept
Tests whether a size states a holding to reach (a target), rather than an amount to trade.
Definition intent.hpp:122
bool is_stop_order(const OrderSnapshot &order)
Tests whether a working order is a stop order: a trigger-price type, or one carrying a trigger price.
Plan< Broker > reconcile(const TargetPosition &target, const Portfolio< Broker > &portfolio, const ReconcileInputs &inputs)
Plans the cancellations and the order that move a holding to a target position.
HaltReason
Who or what is holding trading stopped.
Definition risk.hpp:30
@ LOCAL_FAILURE
Local machinery failed, such as the order journal not being writable; nothing is sent.
Definition risk.hpp:40
@ OPERATOR
A person stopped trading with RiskGuard::halt(); only RiskGuard::resume() clears it.
Definition risk.hpp:32
@ 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.
OrderStatus
Where an order stands in its lifecycle.
Definition types.hpp:2170
std::optional< Decimal64 > decimal_add(const Decimal64 &lhs, const Decimal64 &rhs)
Adds two decimals exactly.
Definition types.hpp:760
constexpr bool carries_trigger_price(OrderType type) noexcept
Tests whether an order type takes a trigger price.
Definition types.hpp:2065
std::optional< Decimal64 > decimal_subtract(const Decimal64 &lhs, const Decimal64 &rhs)
Subtracts two decimals exactly.
Definition types.hpp:783
constexpr bool time_in_force_expires_at_close(TimeInForce condition) noexcept
Tests whether an order with this condition expires at the session's close, so its filled quantity is ...
Definition types.hpp:2113
Venue
A trading venue: an exchange, or the combined view across exchanges.
Definition types.hpp:45
bool decimal_less(const Decimal64 &lhs, const Decimal64 &rhs)
Compares two decimals numerically, whatever their scales.
Definition types.hpp:926
std::optional< Decimal64 > decimal_multiply(const Decimal64 &lhs, const Decimal64 &rhs)
Multiplies two decimals exactly; the scales add.
Definition types.hpp:826
OrderSide
The side of an order: its economic direction, buy or sell.
Definition types.hpp:1974
Reconciliation: turning a strategy's intents and targets into the orders and cancellations to send.
Decimal64 close_
The last trade price.
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
A broker's reference to one order, used to amend or cancel it.
Definition types.hpp:2402
The state of one order, as a broker listing reported it.
Definition types.hpp:2299
std::string order_id_
The broker's order number.
Definition types.hpp:2301
The highest and lowest price an instrument may trade at today.
Decimal64 last_price_
The last traded price, as the broker reported it.
Definition types.hpp:1147
std::chrono::system_clock::time_point received_at_
When this process received the quote, on this machine's clock.
Definition types.hpp:1153
InstrumentId instrument_
The instrument.
Definition types.hpp:1145
An order still open to modification or cancellation.
Definition types.hpp:2582
OrderRef< Broker > ref_
The reference to amend or cancel the order with.
Definition types.hpp:2586
OrderSnapshot order_
The order's state.
Definition types.hpp:2584
The broker's own code and message for a refusal, kept for diagnosis.
What one runner pass decided and did, sorted by outcome (returned by Runner::feed).
Definition runner.hpp:202
bool quiet() const noexcept
Tests whether the pass did nothing at all.
Definition runner.hpp:270
std::vector< OrderRef< BrokerTag > > indeterminate_cancel_
Cancellations with an unknown outcome; the order may or may not still rest.
Definition runner.hpp:245
std::vector< OrderRef< BrokerTag > > unavailable_cancel_
Cancellations not sent because local machinery was unavailable.
Definition runner.hpp:254
std::vector< strategy::Rejection > rejected_
Instructions not placed: reconciliation could not build them, the broker refused them (BROKER_REFUSED...
Definition runner.hpp:218
std::vector< WithheldOrder > withheld_
Orders held back because an earlier order on the instrument has an unknown outcome (RECONCILE_REQUIRE...
Definition runner.hpp:227
std::vector< strategy::GuardRejection > refused_
Instructions the risk guard refused (a limit or a hold).
Definition runner.hpp:220
std::vector< RefusedCancel< BrokerTag > > refused_cancel_
Cancellations refused by a hold that blocks withdrawals (OPERATOR, STOPPING; see strategy::halt_block...
Definition runner.hpp:262
std::vector< strategy::PlannedOrder > would_place_
Orders that passed every check and were sent (in a dry run, would have been).
Definition runner.hpp:204
std::vector< RejectedCancel< BrokerTag > > rejected_cancel_
Cancellations that were refused, by the broker or the binding.
Definition runner.hpp:243
std::vector< OrderRef< BrokerTag > > unresolved_cancel_
Cancellations naming an order the portfolio does not list; not sent.
Definition runner.hpp:247
std::vector< WithheldPlan< BrokerTag > > withheld_plans_
Whole plans (cancellations and placements) held back before any part was sent; see WithheldPlanReason...
Definition runner.hpp:232
std::vector< WithheldOrder > unavailable_
Orders not sent because local machinery was unavailable (SendOutcome::UNAVAILABLE,...
Definition runner.hpp:252
std::vector< std::string > log_
Lines the strategy logged during the pass.
Definition runner.hpp:264
std::vector< OrderRef< BrokerTag > > would_cancel_
Cancellations the broker accepted.
Definition runner.hpp:211
std::vector< strategy::PlannedOrder > indeterminate_
Orders whose outcome is unknown (SendOutcome::INDETERMINATE, which at KIS, Toss and Kiwoom includes m...
Definition runner.hpp:237
The broker tag of a dry run, whose order references reach no broker.
Definition runner.hpp:280
static constexpr std::string_view name
The name an order reference prints: "dryrun".
Definition runner.hpp:282
One journal line: an instruction and what was known about it when the line was written.
Definition journal.hpp:482
std::string id_
Links an answering line to its PENDING line.
Definition journal.hpp:488
The contents of a journal, including what could not be read.
Definition journal.hpp:600
One order a serialized runner still owes (Runner::obligations).
std::string order_id_
The broker's order id; empty while unnamed.
Decimal64 quantity_
The quantity holdings must still account for.
ObligationState state_
Its state: NAMED, UNNAMED or OPERATOR.
std::chrono::system_clock::time_point sent_at_
When it was sent, on the journal's clock.
InstrumentId instrument_
The instrument.
std::string journal_id_
The id of the order's journal lines.
A cancellation a hold refused (nothing was sent), and which hold.
Definition runner.hpp:171
strategy::HaltReason reason_
The hold that stopped it.
Definition runner.hpp:175
OrderRef< BrokerTag > ref_
The order that was to be cancelled.
Definition runner.hpp:173
A cancellation that was refused, by the broker or before it was sent.
Definition runner.hpp:183
bool by_broker_
true if the broker refused it; false if it was refused before sending (by the binding,...
Definition runner.hpp:190
OrderRef< BrokerTag > ref_
The order that was to be cancelled.
Definition runner.hpp:185
How a budgeted runner opens its run when runner::recover_runner reads its journal (Runner::set_run_op...
bool resume_
Resume the journal's latest run instead of opening a new one (none: RunRefusal::NO_RUN).
std::vector< RunTransfer > transfers_
Deposits and withdrawals for a resumed run, each applied once by its id, in order.
A placement of a run, as its ledger knows it.
std::string id_
The placement's journal id.
How recovery opened a budgeted runner's run, or why it did not (RecoveryReport::run_).
One bar, delivered to on_bar.
Definition event.hpp:313
std::chrono::system_clock::time_point period_end_
When the bar's period ended: the earliest moment the bar could be known.
Definition event.hpp:329
InstrumentId instrument_
The instrument the bar is for.
Definition event.hpp:315
Every instrument's bar of one interval for one period end, delivered to on_bars.
Definition event.hpp:569
A record of data from outside the broker, delivered to on_data.
Definition event.hpp:856
std::chrono::system_clock::time_point known_at_
When the record became known: the earliest moment a strategy may see it, as BarEvent::period_end_ is ...
Definition event.hpp:864
One execution of an order the strategy placed, delivered to on_fill.
Definition event.hpp:886
MarketPhase phase_
The market phase the order would be sent in.
Definition risk.hpp:524
std::chrono::system_clock::time_point now_
The current instant; RiskLimits::rate_window_ counts back from it.
Definition risk.hpp:522
std::optional< Currency > order_currency_
The currency the order is priced in, from its reference data.
Definition risk.hpp:541
std::optional< Decimal64 > reference_price_
A price to value a market order, which carries none.
Definition risk.hpp:526
std::vector< InstrumentBasis > exposure_basis_
The currency and mark of every instrument held or working, plus the order's.
Definition risk.hpp:534
std::optional< Decimal64 > run_holding_
The run's own shares of the order's instrument less its open sells, read by a budgeted sell.
Definition risk.hpp:554
std::optional< Money > run_cash_
The run's cash less what its open buys reserve, read by a budgeted buy (RiskLimits::run_budget_).
Definition risk.hpp:548
A capability set in which the broker implements nothing optional.
Definition concept.hpp:473
std::vector< PlannedOrder > place_
The orders to place, after the cancellations.
std::vector< Rejection > rejected_
The instructions not placed, with reasons.
TimeInForce time_in_force_
How long the order stays valid.
OrderSession session_
The trading session.
Venue venue_
Where to route the order; see OrderRequest::venue_.
bool price_would_have_been_clamped_
Whether a price band was known but not applied (too old), and would have clamped this price.
std::string tag_
The tag of the intent or target the order came from.
std::optional< Decimal64 > trigger_price_
The trigger price of a STOP_LIMIT order, exactly as stated; empty otherwise.
OrderType type_
The order type.
InstrumentId instrument_
The instrument to trade.
std::optional< Decimal64 > price_
The limit price, after clamping and rounding; empty for a market order.
Decimal64 quantity_
The quantity, after rounding onto the lot.
std::vector< WorkingOrder< Broker > > working_
Orders still outstanding at the broker.
std::optional< Decimal64 > net_quantity_of(const InstrumentId &instrument) const
Returns the net quantity held of an instrument, summed over every row.
std::vector< BuyingPower > buying_power_
What may be spent, per currency.
std::chrono::system_clock::time_point as_of_
When the holdings were received, on this machine's clock.
std::vector< HoldingPosition > positions_
Every position row the broker reported.
Definition portfolio.hpp:88
bool listing_newer_than_holdings() const noexcept
Tests whether the working-order listing is newer than the holdings.
A quote the runner has just read, delivered to on_quote.
Definition event.hpp:841
QuoteSnapshot quote_
The quote, as the broker reported it.
Definition event.hpp:843
std::optional< Currency > portfolio_value_currency_
The currency of portfolio_value_; absent means the instrument's currency.
const PortfolioRows * rows_
Where each instrument's rows are in the portfolio being reconciled, or a null pointer to scan for the...
std::optional< Decimal64 > reference_price_
A price to size a notional or weight against, such as the last trade.
std::optional< PriceLimits > limits_
The day's price band, if the broker publishes one.
bool reserved_rows_are_unconfirmed_
Whether the portfolio's reserved rows (WorkingOrder::reserved_) are orders this runner sent that the ...
std::optional< Decimal64 > portfolio_value_
The total portfolio value, for weight sizing.
TradeTolerance tolerance_
How small a drift from a target is not worth an order.
const Instrument * instrument_
The instrument's reference data (tick grid, lot size, currency); required.
The limits the operator sets for RiskGuard.
Definition risk.hpp:412
std::optional< Money > run_budget_
The run's starting cash, in one currency: buys spend it, sells return their proceeds,...
Definition risk.hpp:498
std::optional< RunFees > run_fees_
The fees a run budget estimates for each order; required with run_budget_, unread without it.
Definition risk.hpp:500
How small a difference from a target is not worth an order.