317 using DataRecord = strategy::strategy_detail::data_record_t<Strategy>;
320 static constexpr bool takes_records = strategy::strategy_detail::declares_on_data<Strategy>;
330 runner_detail::sends_to_a_broker<Executor>::value && strategy::strategy_detail::declares_on_fill<Strategy>;
337 static constexpr bool takes_bar_slices = strategy::strategy_detail::declares_on_bars<Strategy>;
354 runner_detail::sends_to_a_broker<Executor>::value && CapsType::has_working_orders;
361 runner_detail::sends_to_a_broker<Executor>::value && runner_detail::journals<Executor>::value;
380 guard_(std::move(limits)),
381 context_(series_capacity),
383#if defined(ATL_HAS_EIGEN)
385 context_detail::PortfolioAccess::stop_bar_history(context_);
388 if (guard_.limits().run_budget_) {
449 acknowledged_journal_failures_ = executor_journal_failures();
463 maximum_portfolio_age_ = age;
483 std::chrono::system_clock::time_point
observed_at() const noexcept {
494 allow_absent_portfolio_ =
true;
508 require_known_portfolio_ = required;
520 note_local_failure(std::move(detail));
528 return placements_at_broker_;
542 return sends_outside_permitted_phase_;
555 probing_sellable_ = enabled;
568 if (probing_sellable_ && !context_.portfolio().listing_newer_than_holdings()) {
569 sellable_probe_.observe(context_.portfolio());
578 return sellable_probe_;
641 dated.received_at_ = observed_at_;
642 dated.limits_ = std::move(limits);
643 price_limits_.insert_or_assign(
id, std::move(dated));
663 maximum_price_limits_age_ = age;
665 allow_unbounded_price_limits_age_ =
false;
670 allow_unbounded_price_limits_age_ =
true;
671 maximum_price_limits_age_.reset();
679 return price_bands_withheld_;
687 return maximum_price_limits_age_.has_value() || allow_unbounded_price_limits_age_;
700 return unclamped_orders_rejected_;
709 return unclamped_orders_refused_;
726 return orders_unbuildable_;
734 return orders_reconcile_withheld_;
741 return orders_guard_refused_;
753 return run_ && !run_closing_ ? std::optional<Money>(run_->cash()) : std::nullopt;
763 return run_ && !run_closing_ ? std::optional<Decimal64>(run_->holding(instrument)) : std::nullopt;
775 return run_ ? run_->unsettled() : std::vector<RunPlacement>{};
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");
795 throw std::invalid_argument(
"a new run takes its cash from run_budget_: transfers apply to a resumed run");
797 for (std::size_t at = 0; at < opening.
transfers_.size(); ++at) {
798 const auto& transfer = opening.
transfers_[at];
800 throw std::invalid_argument(
"a run's transfer needs an id and an amount above zero");
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_);
808 run_opening_ = std::move(opening);
816 const std::optional<RunRecoverySummary>&
run_recovery() const noexcept {
817 return run_recovery_;
832 if constexpr (keeps_run_in_journal) {
833 return guard_.limits().run_budget_.has_value() && ((!run_ && !run_absent_) || run_journal_latched_);
845 run_journal_latched_ = run_journal_latched_ || guard_.limits().run_budget_.has_value();
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
868 if constexpr (keeps_run_in_journal) {
872 !run_->can_book_released(placement_id, filled, amount, fee)
876 auto record = std::make_shared<RunRecord>();
877 record->run_ = run_->id();
879 record->of_ = placement_id;
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)) {
888 open_new_run_once_closed();
899 return orders_binding_refused_;
908 return orders_broker_refused_;
916 return orders_indeterminate_;
926 return plans_withheld_;
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_);
961 return targets_deferred_;
969 return deferred_dropped_after_fill_;
978 std::optional<std::chrono::system_clock::time_point> earliest;
979 for (
const auto& deferred : deferred_targets_) {
980 if (stop_listed(deferred.target_.instrument_)) {
983 if (!earliest || deferred.deferred_at_ < *earliest) {
984 earliest = deferred.deferred_at_;
1000 return release_deferred(&evidence);
1025 return unconfirmed_.size();
1034 confirm_reservations();
1057 [[maybe_unused]]
const std::optional<std::string>& order_id, [[maybe_unused]]
const std::string& journal_id = {}
1060 if (order_id && order_id->empty()) {
1063 const auto found =
serialized() ? unnamed_by_journal_id(journal_id) : newest_unnamed(instrument, side);
1065 if (found == unconfirmed_.end() || (
serialized() && !order_id)) {
1070 drop_reserved_row(*found);
1074 found->ref_.primary_ = *order_id;
1075 found->row_.ref_.primary_ = *order_id;
1077 found->history_missed_ =
false;
1078 if (found->unexplained_since_) {
1079 found->unexplained_since_ = freshness_instant();
1082 unconfirmed_.erase(found);
1084 confirm_reservations();
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");
1149 if (placements_at_broker_ != 0 || recovered_) {
1150 throw std::logic_error(
"allow_overlapping_orders must be chosen before recovery and before trading");
1152 overlapping_ =
true;
1166 for (
const auto& entry : unconfirmed_) {
1167 if (!(entry.instrument_ == instrument)) {
1170 const auto owed = state_of(entry);
1187 owed.begin(), owed.end(),
1189 return !(one.instrument_ == instrument);
1202 std::vector<Obligation> owed;
1206 for (
const auto& entry : unconfirmed_) {
1209 obligation.
journal_id_ = entry.journal_ ? entry.journal_->id_ : std::string();
1210 obligation.
order_id_ = entry.ref_.primary_;
1211 obligation.
side_ = entry.side_;
1213 obligation.
sent_at_ = entry.sent_at_;
1214 obligation.
state_ = state_of(entry);
1215 owed.push_back(std::move(obligation));
1237 [[maybe_unused]]
const InstrumentId& instrument, [[maybe_unused]]
const std::string& reason
1239 bool written =
true;
1240 if constexpr (can_serialize) {
1244 for (
auto at = unconfirmed_.begin(); at != unconfirmed_.end();) {
1245 if (!(at->instrument_ == instrument)) {
1250 if (!run_record(line)) {
1255 set_boundary(instrument, line.recorded_at_,
true);
1256 drop_reserved_row(*at);
1258 if (run_ && at->run_order_) {
1259 run_->release(run_placement_of(*at));
1261 at = unconfirmed_.erase(at);
1263 confirm_reservations();
1287 if constexpr (can_serialize) {
1291 restore_from(replay);
1293 if constexpr (keeps_run_in_journal) {
1294 if (guard_.limits().run_budget_) {
1295 open_run_from(replay);
1298 confirm_reservations();
1309 return orders_awaiting_confirmation_;
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_;
1347 confirmation_timeout_ = timeout;
1355 return orders_unconfirmed_timed_out_;
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)) {
1381 if (!earliest || entry.sent_at_ < *earliest) {
1382 earliest = entry.sent_at_;
1403 confirm_serialized_from_history(evidence);
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_) {
1414 if (entry.ref_.primary_.empty()) {
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_
1422 if (
decimal_less(row->execution_.filled_quantity_, entry.expected_)) {
1423 entry.expected_ = row->execution_.filled_quantity_;
1425 entry.settled_ =
true;
1427 entry.unexplained_since_ = now;
1434 for (
auto& entry : unconfirmed_) {
1435 if (entry.consulted_ && !entry.settled_ && timed_out(entry, now)) {
1436 entry.history_missed_ =
true;
1440 confirm_reservations();
1483 confirm_reservations();
1485 retained_targets_.erase(
1487 retained_targets_.begin(), retained_targets_.end(),
1488 [](
const RetainedTarget& kept) {
1489 return kept.for_phase_;
1492 retained_targets_.end()
1494 kept_intents_.clear();
1500 for (
const auto& queued : context_.queued()) {
1501 forget_retained(instruction_instrument(queued));
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()
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_;
1515 const auto awaiting_broker = [&](
const auto& entry) {
1516 return entry.after_ && !(*entry.after_ < as_of);
1518 for (
auto& entry : retained_targets_) {
1520 (entry.for_phase_ && !phase_permits) || awaiting_broker(entry) ||
1521 (entry.until_accounted_ && owes(entry.target_.instrument_))
1523 kept.push_back(std::move(entry));
1526 context_.submit(std::move(entry.target_));
1529 retained_targets_ = std::move(kept);
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));
1540 const auto held = context_.portfolio().net_quantity_of(entry.intent_.instrument());
1541 const auto gap = held ?
decimal_subtract(*held, entry.held_) : std::nullopt;
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_;
1551 context_.submit(std::move(entry.intent_));
1567 return kept_intents_.size();
1576 return kept_intents_dropped_;
1584 return retained_targets_.size();
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_;
1602 retained_targets_.clear();
1603 kept_intents_.clear();
1612 deferred_targets_.clear();
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_);
1649 for (
const auto& entry : unconfirmed_) {
1651 entry.withdrawn_ && !entry.ref_.primary_.empty() && working.
ref_.primary_ == entry.ref_.primary_ &&
1671 return release_deferred(
nullptr);
1679 return instructions_unavailable_;
1687 return cancels_rejected_;
1694 return cancels_refused_;
1701 return cancels_unresolved_;
1708 return cancels_indeterminate_;
1720 return last_broker_refusal_;
1732 return last_unbuildable_;
1740 tolerance_ = std::move(tolerance);
1751 tolerance_.minimum_quantity_ = std::move(quantity);
1763 portfolio_value_ = std::move(value);
1764 portfolio_value_currency_.reset();
1776 portfolio_value_ = std::move(value.
amount_);
1777 portfolio_value_currency_ = std::move(value.
currency_);
1782 portfolio_value_.reset();
1783 portfolio_value_currency_.reset();
1804 dispatch::start(strategy_, context_);
1807 if (context_.queued().empty()) {
1830 dispatch::stop(strategy_, context_);
1841 dispatch::stop(strategy_, context_);
1872 confirm_reservations();
1873 dispatch::bar(strategy_, context_, event);
1899 dispatch::bar(strategy_, context_, event);
1900 warmup_instructions_discarded_ += context_.drain().size();
1946 confirm_reservations();
1947 dispatch::bars(strategy_, context_, slice);
1961 dispatch::bars(strategy_, context_, slice);
1962 warmup_instructions_discarded_ += context_.drain().size();
1972 template <
typename T>
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"
1978 static_assert(std::is_same_v<T, DataRecord>,
"a record must be of the strategy's data_type");
1980 dispatch::data(strategy_, context_, event);
1981 warmup_instructions_discarded_ += context_.drain().size();
1989 return warmup_instructions_discarded_;
2000 confirm_reservations();
2001 dispatch::quote(strategy_, context_, event);
2015 template <
typename T>
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"
2021 static_assert(std::is_same_v<T, DataRecord>,
"a record must be of the strategy's data_type");
2023 confirm_reservations();
2024 dispatch::data(strategy_, context_, event);
2034 confirm_reservations();
2035 dispatch::fill(strategy_, context_, event);
2045 confirm_reservations();
2046 dispatch::order_update(strategy_, context_, event);
2056 context_.set_phase(phase);
2061 for (
auto& entry : unconfirmed_) {
2063 entry.session_ended_ =
true;
2067 confirm_reservations();
2068 dispatch::phase(strategy_, context_, phase);
2075#if defined(ATL_HAS_EIGEN)
2077 context_.record_bar(event);
2079 using Access = context_detail::PortfolioAccess;
2080 Access::advance_bar_time(Access::bar_time_for(context_, event), event);
2083 static_cast<void>(event);
2105 confirm_reservations();
2108 cancel_closing_run_orders(report);
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_);
2121 const strategy::PortfolioRows*& rows_;
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;
2134 std::vector<const Instruction<Tag>*> origin;
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) {
2165 std::vector<OrderRef<Tag>> attempted;
2166 const auto attempt_cancel = [
this, &attempted, &report](
const OrderRef<Tag>& ref) {
2169 if (!ref.primary_.empty() || !ref.secondary_.empty()) {
2170 for (
const auto& seen : attempted) {
2175 attempted.push_back(ref);
2177 send_cancel(ref, report);
2181 std::vector<InstrumentId> claimed;
2183 for (
const auto& instruction : instructions) {
2187 forget_retained(instruction_instrument(instruction));
2188 if (
const auto* cancel = std::get_if<strategy::CancelIntent<Tag>>(&instruction)) {
2189 attempt_cancel(cancel->ref_);
2193 const auto planned = plan_for(instruction);
2204 const bool would_cancel = !planned.cancel_.empty();
2205 if (
const auto reason = plan_withhold_reason(would_cancel)) {
2223 if (data_is_missing || would_cancel) {
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";
2238 std::holds_alternative<strategy::OrderIntent>(instruction)
2240 detail =
"dropped: an order intent states a size against the mis-ordered picture";
2243 report.withheld_plans_.push_back(
2246 instruction_instrument(instruction),
2247 instruction_tag(instruction),
2249 planned.place_.size(),
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;
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);
2274 if (!hold && defers) {
2275 hold = serial_hold(instruction_instrument(instruction), claimed);
2279 if (retain_withheld(instruction,
false, context_.portfolio().as_of_)) {
2280 *hold +=
"; retained for a later holdings read";
2282 report.withheld_plans_.push_back(
2285 instruction_instrument(instruction),
2286 instruction_tag(instruction),
2288 planned.place_.size(),
2294 for (
const auto& order : planned.place_) {
2295 claimed.push_back(order.instrument_);
2298 claimed.push_back(instruction_instrument(instruction));
2303 if (
serialized() && planned.place_.empty() && !defers && withdraws_owed(instruction, planned.cancel_)) {
2304 retain_withheld(instruction,
false, context_.portfolio().as_of_,
true);
2306 for (
const auto& ref : planned.cancel_) {
2307 attempt_cancel(ref);
2309 defer_if_waiting_on_stop(instruction, planned);
2310 for (
const auto& rejection : planned.rejected_) {
2315 ++orders_unbuildable_;
2316 last_unbuildable_ = rejection;
2317 report.rejected_.push_back(rejection);
2319 for (
const auto& order : planned.place_) {
2320 pending.push_back(order);
2321 origin.push_back(&instruction);
2325 pass_rows_ =
nullptr;
2327 strategy::GuardInputs inputs;
2331 inputs.
now_ = send_instant();
2332 inputs.
phase_ = context_.phase();
2356 std::optional<strategy::Portfolio<Tag>> reserved_view;
2357 const auto view = [&]() ->
const strategy::Portfolio<Tag>& {
2358 return reserved_view ? *reserved_view : context_.portfolio();
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()) {
2367 guard_.limits().enforce_buying_power_
2374 if (!pending.empty() && guard_.limits().max_gross_exposure_) {
2377 if (run_ && !pending.empty()) {
2378 run_pass_inputs(view(), inputs);
2380 for (std::size_t at = 0; at < pending.size(); ++at) {
2381 auto& order = pending[at];
2382 const auto& source_instruction = *origin[at];
2392 ++instructions_unavailable_;
2393 report.unavailable_.push_back(
2402 if (ledger_.requires_reconcile(order.instrument_)) {
2407 ++orders_reconcile_withheld_;
2408 std::string detail(ledger_.detail(order.instrument_));
2414 serialized() && !restated_later(source_instruction) &&
2415 retain_withheld(source_instruction,
false, context_.portfolio().as_of_)
2417 detail +=
"; retained for a later holdings read";
2426 std::optional<Decimal64> baseline;
2428 if (
auto hold = serial_hold(order.instrument_, {})) {
2429 ++orders_awaiting_confirmation_;
2430 if (retain_withheld(source_instruction,
false, context_.portfolio().as_of_)) {
2431 *hold +=
"; retained for a later holdings read";
2436 baseline = context_.portfolio().net_quantity_of(order.instrument_);
2439 fill_sellable_if_needed(reserved_view, pending.size() - at, order);
2445 const auto* reference = context_.find_instrument(order.instrument_);
2446 inputs.
order_currency_ = reference ? std::optional<Currency>(reference->currency_) : std::nullopt;
2450 order.side_ == OrderSide::SELL ? run_holding_for(view(), order.instrument_) : std::nullopt;
2457 auto decision = guard_.evaluate(order, view(), inputs);
2458 if (decision.rejection_) {
2463 if (order.price_would_have_been_clamped_) {
2464 ++unclamped_orders_refused_;
2466 ++orders_guard_refused_;
2468 retain_for_phase(source_instruction);
2470 report.refused_.push_back(std::move(*decision.rejection_));
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);
2485 order.venue_ = requested_route(order.venue_);
2486 const auto outcome = place_order(order, baseline);
2496 ++sends_outside_permitted_phase_;
2507 if (order.price_would_have_been_clamped_) {
2509 ++unclamped_orders_rejected_;
2511 ++unclamped_orders_refused_;
2522 guard_.note_sent(inputs.
now_);
2523 ++placements_at_broker_;
2526 spend_run_cash(order, inputs);
2527 reserve_for_later(at, order, last_ref());
2529 track_unconfirmed(order, last_ref(),
false, baseline);
2530 report.would_place_.push_back(std::move(order));
2535 guard_.note_sent(inputs.
now_);
2536 ++orders_broker_refused_;
2539 if (decision.admitted_outside_phase_) {
2540 retain_for_phase(source_instruction,
true);
2547 retain_for_phase(source_instruction,
true, context_.portfolio().as_of_);
2549 note_broker_refusal(order);
2550 report.rejected_.push_back(
2555 guard_.note_sent(inputs.
now_);
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);
2573 if (
serialized() || runner_detail::reports_last_ref<Executor>::value) {
2574 reserve_for_later(at, order, std::nullopt);
2576 track_unconfirmed(order, std::nullopt,
true, baseline);
2579 report.indeterminate_.push_back(std::move(order));
2590 ++orders_binding_refused_;
2591 if (decision.admitted_outside_phase_) {
2592 retain_for_phase(source_instruction);
2603 retain_for_phase(source_instruction,
false, context_.portfolio().as_of_);
2605 report.rejected_.push_back(
2614 ++instructions_unavailable_;
2615 report.unavailable_.push_back(
2621 std::string(
"local machinery refused to send"),
2629 kept_this_pass_.clear();
2630 report.log_ = context_.log().take();
2653 void fill_sellable_if_needed(
2654 std::optional<strategy::Portfolio<Tag>>& reserved_view, std::size_t orders_left,
const strategy::PlannedOrder& order
2656 if constexpr (runner_detail::fills_sellable<Executor>::value) {
2657 if (!guard_.limits().enforce_sellable_quantity_ || order.
side_ != OrderSide::SELL) {
2660 if ((reserved_view ? *reserved_view : context_.portfolio()).sellable_quantity_of(order.
instrument_)) {
2664 if (!reserved_view) {
2665 reserved_view = context_.portfolio();
2666 reserved_view->working_.reserve(reserved_view->working_.size() + orders_left);
2668 const auto answered = executor_.sellable_quantity(order.
instrument_);
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));
2679 static_cast<void>(reserved_view);
2680 static_cast<void>(orders_left);
2681 static_cast<void>(order);
2687 const strategy::PlannedOrder& order, [[maybe_unused]]
const std::optional<Decimal64>& baseline
2689 if constexpr (can_serialize) {
2691 return executor_.place(order, baseline);
2694 return executor_.place(order);
2699 if constexpr (runner_detail::resolves_route<Executor>::value) {
2700 return executor_.requested_route(asked);
2710 std::optional<OrderRef<Tag>> last_ref()
const {
2711 if constexpr (runner_detail::reports_last_ref<Executor>::value) {
2712 return executor_.last_ref();
2714 return std::nullopt;
2725 std::optional<Money> commission_;
2726 std::optional<Money> tax_;
2731 std::shared_ptr<const RunRecord> record_;
2737 struct Unconfirmed {
2740 InstrumentId instrument_;
2743 Decimal64 expected_;
2745 Decimal64 baseline_;
2747 WorkingOrder<Tag> row_;
2748 std::chrono::system_clock::time_point sent_at_{};
2750 bool listed_{
false};
2751 bool listed_now_{
false};
2753 bool withdrawn_{
false};
2755 bool settled_{
false};
2757 bool session_ended_{
false};
2759 bool consulted_{
false};
2761 bool history_missed_{
false};
2763 Decimal64 residual_;
2764 std::optional<std::chrono::system_clock::time_point> unexplained_since_;
2767 std::optional<JournalEntry> journal_;
2770 bool broker_ref_{
false};
2772 bool restored_{
false};
2774 bool operator_only_{
false};
2776 bool noticed_{
false};
2779 bool identified_{
false};
2781 std::chrono::system_clock::time_point baseline_at_{};
2783 std::string unwritten_hold_;
2785 bool run_order_{
false};
2787 bool awaiting_booking_{
false};
2789 std::optional<RunBooking> booking_;
2802 void track_serialized(
2803 const strategy::PlannedOrder& order,
const std::optional<OrderRef<Tag>>& ref,
bool indeterminate,
2804 const Decimal64& baseline
2806 const auto& portfolio = context_.portfolio();
2808 if (ref && !indeterminate) {
2810 entry.broker_ref_ = !ref->primary_.empty();
2811 entry.identified_ = entry.broker_ref_;
2813 entry.baseline_at_ = portfolio.as_of_;
2815 entry.side_ = order.
side_;
2817 entry.baseline_ = baseline;
2818 entry.row_ = portfolio.working_.back();
2819 entry.sent_at_ = freshness_instant();
2821 entry.journal_ = executor_.last_entry();
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_;
2827 unconfirmed_.push_back(std::move(entry));
2831 bool cancellable_reservation(
const WorkingOrder<Tag>& working)
const {
2832 if (working.ref_.primary_.empty()) {
2835 for (
const auto& entry : unconfirmed_) {
2836 if (is_reserved_row_of(working, entry)) {
2837 return entry.broker_ref_;
2850 void confirm_serialized(strategy::Portfolio<Tag>& portfolio, std::chrono::system_clock::time_point now) {
2852 const auto epoch = std::chrono::system_clock::time_point{};
2853 const auto equal = [](
const Decimal64& a,
const Decimal64& b) {
2856 for (
auto at = unconfirmed_.begin(); at != unconfirmed_.end();) {
2858 persist_hold(entry);
2859 entry.awaiting_booking_ =
false;
2861 const bool read = portfolio.
as_of_ != epoch && !(portfolio.
as_of_ < entry.baseline_at_);
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;
2870 decimal_subtract(working->order_.quantity_, working->order_.execution_.filled_quantity_).value_or(zero);
2871 listed_filled = working->order_.execution_.filled_quantity_;
2877 listed_filled && !entry.operator_only_ &&
2878 (
decimal_less(entry.row_.order_.quantity_, *listed_filled) ||
2879 (entry.settled_ &&
decimal_less(entry.expected_, *listed_filled)))
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")
2889 std::optional<Decimal64> held;
2890 std::optional<Decimal64> moved;
2894 moved = entry.side_ == OrderSide::BUY ?
2899 const bool is_named = !entry.ref_.primary_.empty();
2900 if (!entry.operator_only_ && is_named && entry.identified_ && !entry.listed_now_) {
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);
2910 }
else if (moved && equal(*moved, entry.expected_)) {
2911 if (run_ && entry.run_order_ && !booked) {
2912 entry.awaiting_booking_ =
true;
2916 "holdings show " + held->str() +
": its baseline " + entry.baseline_.str() +
" and the " +
2917 entry.expected_.str() +
" it filled",
2921 set_boundary(entry.instrument_, portfolio.
as_of_,
false);
2922 at = unconfirmed_.erase(at);
2925 }
else if (moved &&
decimal_less(entry.expected_, *moved)) {
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"
2935 Decimal64 covered = zero;
2936 const auto fillable =
decimal_subtract(entry.expected_, listed).value_or(zero);
2938 covered =
decimal_less(*moved, fillable) ? *moved : fillable;
2940 auto residual =
decimal_subtract(fillable, covered).value_or(entry.expected_);
2943 if (explained && !entry.awaiting_booking_) {
2944 mark_explained(entry);
2948 entry.residual_ = explained ? zero : residual;
2950 if (!entry.unexplained_since_ && now != epoch) {
2951 entry.unexplained_since_ = now;
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_
2962 entry.noticed_ =
true;
2963 ++orders_unconfirmed_timed_out_;
2967 "an order this runner sent" + named(entry) +
2968 " was not accounted for by holdings within the confirmation timeout; it still holds the instrument"
2973 if (!is_named && ledger_.requires_reconcile(entry.instrument_)) {
2978 rebuild_residual_row(portfolio, entry, residual);
2988 InstrumentId instrument_;
2989 std::chrono::system_clock::time_point at_{};
2990 bool strict_{
false};
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)) {
2999 boundary.strict_ = strict;
3004 boundaries_.push_back(Boundary{instrument, at, strict});
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");
3014 return std::string(
"the holding's rows do not add up, so the order would have no baseline");
3016 for (
const auto& boundary : boundaries_) {
3018 boundary.instrument_ == instrument &&
3019 (boundary.strict_ ? !(boundary.at_ < portfolio.
as_of_) : portfolio.
as_of_ < boundary.at_)
3022 "the holdings were read before the last order on this instrument was accounted for; waiting for a "
3027 return std::nullopt;
3032 std::optional<std::string> serial_hold(
3033 const InstrumentId& instrument,
const std::vector<InstrumentId>& claimed
3035 if (!can_serialize) {
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"
3042 return std::string(
"nothing is placed before runner::recover_runner has run");
3044 for (
const auto& entry : unconfirmed_) {
3045 if (!(entry.instrument_ == instrument)) {
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");
3057 return "an order on this instrument" + named(entry) +
" is not yet accounted for by holdings";
3059 for (
const auto&
id : claimed) {
3060 if (
id == instrument) {
3061 return std::string(
"an earlier instruction in this pass places on this instrument");
3064 return baseline_missing(instrument);
3067 static std::string named(
const Unconfirmed& entry) {
3068 return entry.ref_.primary_.empty() ? std::string() :
" (" + entry.ref_.primary_ +
")";
3073 static bool ends_the_order(
OrderStatus status)
noexcept {
3075 case OrderStatus::FILLED:
3076 case OrderStatus::CANCELED:
3077 case OrderStatus::REJECTED:
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:
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_);
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_) {
3111 if (row.ordered_at_ && !own_row(row, entry)) {
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_)))
3130 return entry.operator_only_ ?
3132 entry.ref_.primary_.empty() ?
3144 void examine_evidence(
const std::vector<OrderSnapshot>& evidence) {
3148 const auto now = freshness_instant();
3149 const auto differ = [](
const Decimal64& a,
const Decimal64& b) {
3152 for (
auto& entry : unconfirmed_) {
3153 if (entry.operator_only_ || entry.ref_.primary_.empty()) {
3156 std::optional<std::string> contradiction;
3157 for (
const auto& row : evidence) {
3158 if (!own_row(row, entry)) {
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";
3168 (
decimal_less(entry.expected_, filled) || (ends_the_order(row.status_) && differ(entry.expected_, filled)))
3170 contradiction =
"its history rows report " + filled.str() +
" filled after reporting it ended with " +
3171 entry.expected_.str();
3173 if (contradiction) {
3177 if (contradiction) {
3178 hold_for_operator(entry,
"an order this runner sent" + named(entry) +
": " + *contradiction);
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();
3187 entry.unexplained_since_ = now;
3191 if (run_ && entry.run_order_) {
3192 take_run_booking(evidence, entry);
3200 void confirm_serialized_from_history(
const std::vector<OrderSnapshot>& evidence) {
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;
3213 confirm_reservations();
3217 bool awaits_evidence_serialized(
const Unconfirmed& entry, std::chrono::system_clock::time_point now)
const {
3223 if (entry.operator_only_ || entry.ref_.primary_.empty()) {
3227 if (!entry.identified_) {
3231 if (entry.awaiting_booking_) {
3232 return !entry.history_missed_;
3234 if (entry.residual_.coefficient() == 0 || entry.settled_ || entry.history_missed_) {
3237 if (timed_out(entry, now)) {
3241 return !entry.listed_now_ && (entry.listed_ || entry.withdrawn_ || entry.restored_);
3245 static JournalEntry closing_line(
3246 const Unconfirmed& entry,
JournalOutcome outcome, std::optional<Decimal64> holding, std::string detail
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);
3260 bool run_record([[maybe_unused]] JournalEntry& line, [[maybe_unused]]
bool opening =
false) {
3261 if constexpr (can_serialize) {
3265 if (executor_.record(line)) {
3269 note_executor_failure(
false);
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
3280 if constexpr (can_serialize) {
3282 if (run_ && entry.run_order_ && !booked) {
3287 line.run_ = booked->record_;
3288 line.detail_ += booked->note_;
3290 if (run_record(line)) {
3292 run_->book_placement(
3293 run_placement_of(entry), *booked->record_->filled_, *booked->record_->amount_, *booked->record_->fee_
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);
3313 void persist_hold([[maybe_unused]] Unconfirmed& entry) {
3314 if constexpr (can_serialize) {
3315 if (entry.unwritten_hold_.empty()) {
3319 if (run_record(line)) {
3320 entry.unwritten_hold_.clear();
3321 if (run_ && entry.run_order_) {
3322 run_->hold(run_placement_of(entry));
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();
3337 void restore_from(
const JournalReplay& replay) {
3338 const auto same = [](
const std::optional<Decimal64>& a,
const std::optional<Decimal64>& b) {
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_) &&
3351 std::chrono::system_clock::time_point sent_at_{};
3354 bool accepted_{
false};
3356 bool operator_only_{
false};
3359 std::vector<Fold>
folds;
3361 std::unordered_map<std::string, std::size_t> fold_of;
3362 for (
const auto& line : replay.entries_) {
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());
3374 fold->line_.baseline_.reset();
3377 if (!closing && !same_instruction(fold->line_, line)) {
3378 fold->operator_only_ =
true;
3379 fold->why_ =
"its journal lines disagree about the order";
3381 if (line.recorded_at_ < fold->sent_at_) {
3382 fold->sent_at_ = line.recorded_at_;
3386 fold->operator_only_ =
true;
3387 fold->why_ = line.detail_.empty() ? std::string(
"a damaged journal line") : line.detail_;
3389 switch (line.outcome_) {
3392 if (!line.order_id_.empty()) {
3393 fold->name_ = line.order_id_;
3400 set_boundary(line.instrument_, line.recorded_at_,
true);
3406 fold->operator_only_ =
true;
3407 fold->why_ = line.detail_;
3416 std::vector<Unconfirmed> restored;
3418 std::vector<std::string> why;
3419 for (
auto& fold : folds) {
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_;
3430 entry.sent_at_ = fold.sent_at_;
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)";
3441 strategy::PlannedOrder order;
3443 order.
side_ = fold.line_.side_;
3444 order.
type_ = fold.line_.type_;
3446 order.
session_ = fold.line_.session_;
3447 order.
venue_ = fold.line_.venue_.value_or(Venue::UNSPECIFIED);
3449 order.
price_ = fold.line_.price_;
3451 strategy::Portfolio<Tag> scratch;
3452 reserve(scratch, order, std::nullopt, std::nullopt, entry.ref_,
false);
3453 entry.row_ = scratch.
working_.back();
3454 restored.push_back(std::move(entry));
3455 why.push_back(fold.why_);
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";
3467 for (std::size_t at = 0; at < restored.size(); ++at) {
3468 if (restored[at].operator_only_) {
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"
3475 unconfirmed_.push_back(std::move(restored[at]));
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
3489 if constexpr (can_serialize) {
3490 if (
serialized() && baseline && !context_.portfolio().working_.empty()) {
3491 track_serialized(order, ref, indeterminate, *baseline);
3495 track_overlapping(order, ref, indeterminate);
3506 void track_overlapping(
3507 const strategy::PlannedOrder& order,
const std::optional<OrderRef<Tag>>& ref,
bool indeterminate
3509 const auto& portfolio = context_.portfolio();
3511 (!indeterminate && (!ref || ref->primary_.empty())) ||
3512 portfolio.
as_of_ == std::chrono::system_clock::time_point{} || portfolio.
working_.empty()
3525 entry.side_ = order.
side_;
3527 entry.baseline_ = *held;
3528 entry.row_ = portfolio.
working_.back();
3529 entry.sent_at_ = freshness_instant();
3531 entry.unexplained_since_ = entry.sent_at_;
3532 unconfirmed_.push_back(std::move(entry));
3536 void note_withdrawal_accepted(
const OrderRef<Tag>& ref) {
3537 for (
auto& entry : unconfirmed_) {
3539 if (!entry.ref_.primary_.empty() && entry.ref_.primary_ == ref.primary_) {
3540 entry.withdrawn_ =
true;
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_;
3553 static constexpr std::chrono::hours order_time_tolerance_{1};
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
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)) {
3570 if (row.ordered_at_ && ((earliest && *row.ordered_at_ < *earliest) || (latest && *latest < *row.ordered_at_))) {
3573 if (found ==
nullptr) {
3576 decimal_less(found->execution_.filled_quantity_, row.execution_.filled_quantity_) ||
3577 decimal_less(row.execution_.filled_quantity_, found->execution_.filled_quantity_) ||
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);
3591 bool awaits_evidence_overlapping(
const Unconfirmed& entry, std::chrono::system_clock::time_point now)
const {
3600 entry.residual_.coefficient() == 0 || entry.settled_ || entry.history_missed_ || entry.operator_only_ ||
3601 (entry.ref_.primary_.empty() && ledger_.requires_reconcile(entry.instrument_))
3605 if (timed_out(entry, now)) {
3608 return !entry.listed_now_ && (entry.listed_ || entry.withdrawn_ || entry.restored_);
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_;
3618 static const WorkingOrder<Tag>* broker_row_for(
const strategy::Portfolio<Tag>& portfolio,
const Unconfirmed& entry) {
3619 if (entry.ref_.primary_.empty()) {
3622 for (
const auto& working : portfolio.
working_) {
3624 !working.reserved_ && working.ref_.primary_ == entry.ref_.primary_ &&
3625 working.order_.instrument_ == entry.instrument_ && working.order_.side_ == entry.side_ &&
3635 static void rebuild_residual_row(
3636 strategy::Portfolio<Tag>& portfolio,
const Unconfirmed& entry,
const Decimal64& residual
3638 auto row = entry.row_;
3639 row.order_.quantity_ = residual;
3640 row.amendable_quantity_ = residual;
3641 portfolio.
working_.push_back(std::move(row));
3646 static void mark_explained(Unconfirmed& entry) {
3648 entry.unexplained_since_.reset();
3649 entry.history_missed_ =
false;
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;
3658 return newest == unconfirmed_.rend() ? unconfirmed_.end() : std::prev(newest.base());
3662 void drop_reserved_row(
const Unconfirmed& entry) {
3663 auto portfolio = context_.portfolio();
3667 [&](
const WorkingOrder<Tag>& working) {
3668 return is_reserved_row_of(working, entry);
3673 context_.set_portfolio(std::move(portfolio));
3681 void confirm_reservations() {
3683 open_new_run_once_closed();
3688 const auto now = freshness_instant();
3689 auto portfolio = context_.portfolio();
3694 [&](
const WorkingOrder<Tag>& working) {
3695 for (const auto& entry : unconfirmed_) {
3696 if (is_reserved_row_of(working, entry)) {
3706 confirm_serialized(portfolio, now);
3708 confirm_overlapping(portfolio, now);
3710 context_.set_portfolio(std::move(portfolio));
3725 void confirm_overlapping(strategy::Portfolio<Tag>& portfolio, std::chrono::system_clock::time_point now) {
3727 std::vector<bool> retire(unconfirmed_.size(),
false);
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) {
3736 const auto& instrument = unconfirmed_[first].instrument_;
3737 const auto direction = unconfirmed_[first].side_;
3738 std::vector<std::size_t> group;
3740 for (std::size_t at = first; at < unconfirmed_.size(); ++at) {
3741 if (unconfirmed_[at].instrument_ == instrument) {
3742 group.push_back(at);
3744 mixed = mixed || unconfirmed_[at].side_ != direction;
3748 const auto signed_in = [&](
const Unconfirmed& entry,
const Decimal64& quantity) {
3749 return entry.side_ == direction ? quantity :
decimal_subtract(zero, quantity).value_or(zero);
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;
3762 decimal_subtract(working->order_.quantity_, working->order_.execution_.filled_quantity_).value_or(zero);
3764 const auto left =
decimal_subtract(entry.expected_, listed[at]).value_or(zero);
3770 std::optional<Decimal64> moved;
3772 moved = direction == OrderSide::BUY ?
3776 std::vector<Decimal64> covered(group.size(), zero);
3777 if (moved && !mixed) {
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];
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]));
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);
3801 total && (total->coefficient() != 0 || all_settled) && !
decimal_less(*total, *moved) &&
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]];
3814 retire[group[at]] =
true;
3816 advanced = direction == OrderSide::BUY ?
3817 decimal_add(*advanced, signed_in(entry, entry.expected_)) :
3822 auto residual =
decimal_subtract(entry.expected_, covered[at]).value_or(zero);
3825 mark_explained(entry);
3828 entry.residual_ = residual;
3829 if (!entry.unexplained_since_) {
3830 entry.unexplained_since_ = now;
3836 (entry.settled_ || entry.history_missed_) && timed_out(entry, now) &&
3837 portfolio.
as_of_ - *entry.unexplained_since_ > confirmation_timeout_
3843 ++orders_unconfirmed_timed_out_;
3844 if (entry.settled_) {
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"
3851 const auto named = entry.ref_.primary_.empty() ?
3852 std::string(
" (its reply lost, never named by a sweep)") :
3853 " (" + entry.ref_.primary_ +
")";
3856 "an order this runner sent" + named +
3857 " was not confirmed by holdings, the order list or the order history in time"
3860 expired[group[at]] =
true;
3863 advanced = direction == OrderSide::BUY ?
3864 decimal_add(*advanced, signed_in(entry, covered[at])) :
3872 if (entry.ref_.primary_.empty() && ledger_.requires_reconcile(entry.instrument_)) {
3875 rebuild_residual_row(portfolio, entry, residual);
3877 for (
const auto at : group) {
3878 if (!retire[at] && advanced) {
3879 unconfirmed_[at].baseline_ = *advanced;
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));
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
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();
3943 const bool exposed = guard_.limits().max_gross_exposure_.has_value();
3946 const bool budgeted = guard_.limits().run_budget_.has_value();
3955 if (!keeps_sent_orders_until_listed && !sells && !buys && !capped && !exposed && !budgeted && !conditional) {
3963 context_detail::PortfolioAccess::for_runner_edit(context_), order, reference_price, currency, ref,
3964 guard_.limits().enforce_buying_power_
3970 const auto& limits = guard_.limits();
3973 throw std::invalid_argument(
"RiskLimits::run_budget_ must be positive");
3976 throw std::invalid_argument(
3977 "RiskLimits::run_budget_ needs RiskLimits::run_fees_: a budgeted run refuses to start"
3983 (fees.institution_rate_ &&
decimal_less(*fees.institution_rate_, zero)) ||
3984 (fees.sell_tax_rate_ &&
decimal_less(*fees.sell_tax_rate_, zero))
3986 throw std::invalid_argument(
"RiskLimits::run_fees_ must not state a negative rate or minimum");
3988 if constexpr (runner_detail::sends_to_a_broker<Executor>::value) {
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)"
4011 void run_pass_inputs(
const strategy::Portfolio<Tag>& view, strategy::GuardInputs& inputs) {
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;
4017 inputs.
run_cash_ = Money{*left, run_->currency()};
4024 run_unknown_.begin(), run_unknown_.end(),
4025 [
this](
const InstrumentId&
id) {
4026 return !ledger_.requires_reconcile(id);
4031 if (!run_unknown_.empty() || !run_committed_) {
4034 const auto& fees = *guard_.limits().run_fees_;
4036 auto cash = run_->cash().amount_;
4037 if (!run_rows_listed_) {
4044 for (
const auto& working : view.
working_) {
4048 if (!run_rows_listed_ && working.reserved_) {
4052 const auto* reference = context_.find_instrument(working.order_.instrument_);
4056 if (!(reference->currency_ == run_->currency())) {
4059 const auto& price = working.order_.price_;
4063 const auto remaining =
decimal_subtract(working.order_.quantity_, working.order_.execution_.filled_quantity_);
4067 const auto cost = strategy::risk_detail::run_buy_cost(fees, *remaining, *price);
4074 inputs.
run_cash_ = Money{cash, run_->currency()};
4079 std::optional<Decimal64> run_holding_for(
const strategy::Portfolio<Tag>& view,
const InstrumentId& instrument)
const {
4081 return run_holding_serialized(instrument);
4084 std::optional<Decimal64> held = run_->holding(instrument);
4085 for (
const auto& working : view.
working_) {
4087 working.order_.side_ != OrderSide::SELL || !(working.order_.instrument_ == instrument) ||
4092 const auto remaining =
decimal_subtract(working.order_.quantity_, working.order_.execution_.filled_quantity_);
4094 return std::nullopt;
4098 return std::nullopt;
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;
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)) {
4116 return std::nullopt;
4120 return std::nullopt;
4129 std::optional<Decimal64> run_reserved()
const {
4130 const auto& fees = *guard_.limits().run_fees_;
4132 std::optional<Decimal64> total = zero;
4133 for (
const auto& entry : unconfirmed_) {
4134 if (!entry.run_order_) {
4138 return std::nullopt;
4140 if (entry.side_ != OrderSide::BUY) {
4143 const auto& price = entry.row_.order_.price_;
4145 return std::nullopt;
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;
4150 return std::nullopt;
4157 static RunPlacement run_placement_of(
const Unconfirmed& entry) {
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_;
4169 std::optional<RunBooking> run_booking_from(
const OrderSnapshot& row,
const Decimal64& filled)
const {
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;
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);
4180 amount = Money{*value, row.currency_};
4183 if (!amount || !(amount->currency_ == currency) || !
decimal_less(zero, amount->amount_)) {
4184 return std::nullopt;
4186 for (
const auto* fee : {&execution.commission_, &execution.tax_}) {
4187 if (*fee && (!((*fee)->currency_ == currency) ||
decimal_less((*fee)->amount_, zero))) {
4188 return std::nullopt;
4191 return RunBooking{filled, *amount, execution.commission_, execution.tax_};
4196 void take_run_booking(
const std::vector<OrderSnapshot>& evidence, Unconfirmed& entry)
const {
4197 if (entry.expected_.coefficient() == 0) {
4200 const auto differ = [](
const Decimal64& a,
const Decimal64& b) {
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_)));
4207 for (
const auto& row : evidence) {
4208 if (!own_row(row, entry) || differ(row.execution_.filled_quantity_, entry.expected_)) {
4211 const auto candidate = run_booking_from(row, entry.expected_);
4217 (differ_money(entry.booking_->amount_, candidate->amount_) ||
4218 differ_money(entry.booking_->commission_, candidate->commission_) ||
4219 differ_money(entry.booking_->tax_, candidate->tax_))
4221 entry.booking_.reset();
4224 entry.booking_ = candidate;
4231 std::optional<RunBooked> run_booking_of(
const Unconfirmed& entry)
const {
4233 const auto& fees = *guard_.limits().run_fees_;
4234 auto record = std::make_shared<RunRecord>();
4235 record->run_ = run_->id();
4237 if (entry.expected_.coefficient() == 0) {
4238 record->filled_ = zero;
4239 record->amount_ = Money{zero, run_->currency()};
4240 record->fee_ = zero;
4243 !entry.booking_ ||
decimal_less(entry.booking_->filled_, entry.expected_) ||
4246 return std::nullopt;
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;
4257 return std::nullopt;
4259 record->filled_ = booking.filled_;
4260 record->amount_ = booking.amount_;
4261 record->fee_ = *fee;
4263 record->fee_estimated_ = !booking.commission_ || (entry.side_ == OrderSide::SELL && !booking.tax_);
4265 const auto estimate =
4266 estimated_commission && estimated_tax ?
decimal_add(*estimated_commission, *estimated_tax) : std::nullopt;
4268 booked.note_ =
"; its fees " + fee->str() +
" are above the " + estimate->str() +
" run_fees_ estimates";
4271 if (!run_->can_book_placement(run_placement_of(entry), *record->filled_, *record->amount_, *record->fee_)) {
4272 return std::nullopt;
4274 booked.record_ = std::move(record);
4279 std::string next_ledger_id() {
4281 if constexpr (keeps_run_in_journal) {
4284 id = executor_.next_run_id();
4285 }
while (!run_ids_.insert(
id).second);
4291 JournalEntry ledger_line(std::shared_ptr<RunRecord> record, std::string detail, std::string
id = {}) {
4293 line.
id_ =
id.empty() ? next_ledger_id() : std::move(id);
4296 line.venue_.reset();
4297 line.detail_ = std::move(detail);
4299 record->run_ = line.id_;
4301 line.run_ = std::move(record);
4307 for (
auto& entry : unconfirmed_) {
4308 entry.run_order_ =
false;
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_);
4322 executor_.set_run(run_->id());
4323 summary.opened_ =
true;
4324 summary.id_ = run_->id();
4325 summary.cash_ = run_->cash();
4326 run_recovery_ = summary;
4333 void open_run_from([[maybe_unused]]
const JournalReplay& replay) {
4334 if constexpr (keeps_run_in_journal) {
4336 const auto opening = run_opening_.value_or(
RunOpening{});
4337 const char*
reconcile =
"reconcile the journal, or start on a new journal";
4340 if (!replay.intact()) {
4341 return refuse_run(summary,
RunRefusal::DAMAGED,
"the order journal was not read whole", reconcile);
4343 for (
const auto& entry : replay.entries_) {
4348 return refuse_run(summary,
RunRefusal::DAMAGED,
"the order journal holds a damaged line", reconcile);
4350 if (entry.id_.compare(0, 4,
"run-") == 0) {
4351 run_ids_.insert(entry.id_);
4354 auto folded = RunLedger::fold(replay);
4355 if (!folded.failure_.empty()) {
4360 for (
const auto& entry : replay.entries_) {
4362 return refuse_run(summary,
RunRefusal::LEDGER,
"the run's lines have no opening", reconcile);
4365 if (opening.resume_) {
4369 summary.refused_ =
"no run to resume in this journal: start without resume to open a new run";
4370 run_recovery_ = summary;
4373 return open_new_run(summary);
4375 auto run = std::move(*folded.run_);
4377 for (
auto& entry : unconfirmed_) {
4378 entry.run_order_ = entry.journal_ &&
journal_run_of(*entry.journal_) == run.id();
4380 if (!opening.resume_) {
4383 run_.emplace(std::move(run));
4384 run_closing_ =
true;
4385 summary.closing_ =
true;
4386 run_recovery_ = summary;
4387 open_new_run_once_closed();
4390 const auto& budget = *guard_.limits().run_budget_;
4391 if (!(run.currency() == budget.currency_)) {
4394 "the run is in " + run.currency().str() +
", run_budget_ in " + budget.currency_.str(),
4395 "state run_budget_ in the run's currency"
4399 const auto reserved = run.settled() ? run_reserved() : std::nullopt;
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_) {
4408 summary,
RunRefusal::TRANSFER,
"transfer id " + transfer.id_ +
" reused, other amount",
"state a new id"
4411 const auto free = reserved ?
decimal_subtract(after.cash().amount_, *reserved) : std::nullopt;
4413 transfer.withdrawal_ &&
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"
4423 if (!after.transfer(transfer)) {
4425 summary,
RunRefusal::TRANSFER,
"the transfer " + transfer.id_ +
" is in another currency, or does not fit",
4426 "state it in the run's currency"
4429 applied.push_back(transfer);
4431 for (
const auto& transfer : applied) {
4432 auto record = std::make_shared<RunRecord>();
4433 record->run_ = run.id();
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,
true)) {
4439 return refuse_run(summary,
RunRefusal::WRITE,
"could not record the transfer " + transfer.id_,
"restart");
4441 ++summary.transfers_applied_;
4443 run_.emplace(std::move(after));
4444 summary.resumed_ =
true;
4445 run_opened(summary);
4451 auto record = std::make_shared<RunRecord>();
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,
true)) {
4456 return refuse_run(summary,
RunRefusal::WRITE,
"the order journal could not record the run's opening",
"restart");
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);
4468 void open_new_run_once_closed() {
4469 if constexpr (keeps_run_in_journal) {
4475 for (
const auto& entry : unconfirmed_) {
4476 if (entry.run_order_) {
4480 open_new_run(*run_recovery_);
4486 void cancel_closing_run_orders([[maybe_unused]] Report& report) {
4487 if constexpr (keeps_run_in_journal) {
4491 !run_closing_ || run_opening_.value_or(
RunOpening{}).wait_for_open_orders_ ||
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) {
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_);
4512 for (
const auto& ref : refs) {
4513 send_cancel(ref, report);
4520 void spend_run_cash(
const strategy::PlannedOrder& order, strategy::GuardInputs& inputs) {
4521 if (!run_ || order.
side_ != OrderSide::BUY) {
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;
4539 void note_run_unknown(
const strategy::PlannedOrder& order, strategy::GuardInputs& inputs) {
4543 spend_run_cash(order, inputs);
4545 if (!serialized()) {
4579 std::vector<strategy::InstrumentBasis> exposure_basis_for(
4580 const strategy::Portfolio<Tag>& view,
const std::vector<strategy::PlannedOrder>& pending
4582 std::vector<InstrumentId> instruments;
4583 const auto note = [&instruments](
const InstrumentId& id) {
4584 for (
const auto& seen : instruments) {
4589 instruments.push_back(
id);
4591 for (
const auto& position : view.
positions_) {
4595 if (position.quantity_.coefficient() == 0) {
4598 note(position.instrument_);
4600 for (
const auto& working : view.
working_) {
4602 note(working.order_.instrument_);
4605 for (
const auto& order : pending) {
4609 std::vector<strategy::InstrumentBasis> basis;
4610 basis.reserve(instruments.size());
4611 for (
const auto&
id : instruments) {
4612 const HoldingPosition* position =
nullptr;
4614 if (held.instrument_ ==
id) {
4620 const auto* reference = context_.find_instrument(
id);
4632 const auto quoted = context_.last_price(
id);
4641 auto price = quoted;
4642 if (!price && position !=
nullptr &&
decimal_less(zero, position->last_price_)) {
4643 price = position->last_price_;
4648 basis.push_back(strategy::InstrumentBasis{id, reference->currency_, *price});
4654 static void write_sellable(
4655 strategy::Portfolio<Tag>& portfolio,
const InstrumentId& instrument,
const Decimal64& quantity
4657 for (
auto& position : portfolio.
positions_) {
4658 if (position.instrument_ == instrument) {
4659 position.sellable_quantity_ = quantity;
4667 position.sellable_basis_ = runner_detail::sellable_inquiry_basis_of<Executor>();
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
4702 WorkingOrder<Tag> working;
4704 working.order_.side_ = order.
side_;
4705 working.order_.status_ = OrderStatus::PENDING;
4706 working.order_.type_ = order.
type_;
4707 working.order_.session_ = order.
session_;
4716 working.order_.venue_ = order.
venue_;
4717 working.order_.price_ = order.
price_;
4722 working.order_.quantity_ = order.
quantity_;
4724 working.amendable_quantity_ = order.
quantity_;
4726 working.ref_ = *ref;
4731 working.reserved_ =
true;
4732 view.
working_.push_back(std::move(working));
4739 if (!spends || order.
side_ != OrderSide::BUY || !currency) {
4742 const auto price = order.
price_ ? order.
price_ : reference_price;
4751 if (!(reading.cash_.currency_ == *currency)) {
4755 reading.cash_.amount_ = *left;
4775 void drop_superseded_deferred(
const std::vector<
Instruction<Tag>>& instructions) {
4776 if (deferred_targets_.empty()) {
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);
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());
4798 Report release_deferred(
const std::vector<OrderSnapshot>* evidence) {
4799 bool released =
false;
4800 for (
auto at = deferred_targets_.begin(); at != deferred_targets_.end();) {
4802 if (stop_listed(at->target_.instrument_) || obligation_state(at->target_.instrument_) !=
ObligationState::NONE) {
4806 if (evidence !=
nullptr) {
4807 bool decided =
true;
4808 bool filled =
false;
4809 for (
const auto& stop : at->stops_) {
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_;
4820 history_row_for(*evidence,
stop.ref_.primary_, at->target_.instrument_, std::nullopt, earliest, latest);
4821 if (row ==
nullptr) {
4825 if (row->execution_.filled_quantity_.coefficient() != 0) {
4832 ++deferred_dropped_after_fill_;
4833 at = deferred_targets_.erase(at);
4841 context_.submit(at->target_);
4842 at = deferred_targets_.erase(at);
4854 explicit Exempt(
bool& flag) : flag_(flag) {
4860 Exempt(
const Exempt&) =
delete;
4861 Exempt& operator=(
const Exempt&) =
delete;
4862 } exempt(releasing_deferred_);
4867 void forget_retained(
const InstrumentId& instrument) {
4868 if (instrument.symbol_.empty()) {
4871 retained_targets_.erase(
4873 retained_targets_.begin(), retained_targets_.end(),
4874 [&](
const RetainedTarget& kept) {
4875 return kept.target_.instrument_ == instrument;
4878 retained_targets_.end()
4881 kept_intents_.erase(
4883 kept_intents_.begin(), kept_intents_.end(),
4884 [&](
const KeptIntent& kept) {
4885 return kept.intent_.instrument() == instrument;
4907 bool retain_withheld(
4909 std::optional<std::chrono::system_clock::time_point> after = std::nullopt,
bool until_accounted =
false
4911 const auto* target = std::get_if<strategy::TargetPosition>(&instruction);
4912 if (target ==
nullptr) {
4923 for (
auto& kept : retained_targets_) {
4924 if (kept.target_.instrument_ == target->instrument_) {
4925 kept = RetainedTarget{*target, for_phase, after, until_accounted};
4929 retained_targets_.push_back(RetainedTarget{*target, for_phase, after, until_accounted});
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()) {
4949 for (
const auto& working : context_.portfolio().working_) {
4951 !(working.order_.instrument_ == target->instrument_) ||
4952 std::find(cancel.begin(), cancel.end(), working.ref_) == cancel.end()
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)) {
4969 bool owes(
const InstrumentId& instrument)
const {
4970 return std::any_of(unconfirmed_.begin(), unconfirmed_.end(), [&](
const Unconfirmed& entry) {
4971 return entry.instrument_ == instrument;
4981 void retain_for_phase(
4983 std::optional<std::chrono::system_clock::time_point> after = std::nullopt
4985 if constexpr (runner_detail::sends_to_a_broker<Executor>::value) {
4986 if (retain_withheld(instruction,
true, after)) {
4989 keep_intent_for_phase(instruction, broker_answered, after);
4992 (void)broker_answered;
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);
5023 void keep_intent_for_phase(
5025 std::optional<std::chrono::system_clock::time_point> after = std::nullopt
5027 const auto* intent = std::get_if<strategy::OrderIntent>(&instruction);
5028 if (intent ==
nullptr) {
5037 if (broker_answered && intent->client_order_id()) {
5040 for (
const auto* seen : kept_this_pass_) {
5041 if (seen == &instruction) {
5045 const auto held = context_.portfolio().net_quantity_of(intent->instrument());
5049 kept_this_pass_.push_back(&instruction);
5050 kept_intents_.push_back(KeptIntent{*intent, *held, after});
5054 bool stop_listed(
const InstrumentId& instrument)
const {
5055 for (
const auto& working : context_.portfolio().working_) {
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) {
5072 for (
const auto& rejection : planned.
rejected_) {
5078 DeferredTarget deferred;
5079 deferred.target_ = *target;
5080 deferred.deferred_at_ = context_.now();
5081 for (
const auto& working : context_.portfolio().working_) {
5086 deferred.stops_.push_back({working.ref_, working.order_.ordered_at_});
5089 for (
auto& kept : deferred_targets_) {
5090 if (kept.target_.instrument_ == target->instrument_) {
5091 kept = std::move(deferred);
5092 ++targets_deferred_;
5096 deferred_targets_.push_back(std::move(deferred));
5097 ++targets_deferred_;
5102 std::optional<WithheldPlanReason> plan_withhold_reason(
bool would_cancel)
const {
5103 const auto& portfolio = context_.portfolio();
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_;
5119 if (never_read || too_old) {
5130 if (require_known_portfolio_ && !(never_read && allow_absent_portfolio_)) {
5139 if (guard_.blocking_reason()) {
5142 return std::nullopt;
5150 std::chrono::system_clock::time_point freshness_instant()
const {
5151 return observed_at_ > context_.now() ? observed_at_ : context_.now();
5157 std::chrono::system_clock::time_point send_instant()
const {
5158 return observed_at_ == std::chrono::system_clock::time_point{} ? context_.now() : freshness_instant();
5166 const auto holding = guard_.blocking_reason();
5171 static InstrumentId instruction_instrument(
const Instruction<Tag>& instruction) {
5172 if (
const auto* target = std::get_if<strategy::TargetPosition>(&instruction)) {
5173 return target->instrument_;
5175 if (
const auto* order = std::get_if<strategy::OrderIntent>(&instruction)) {
5176 return order->instrument();
5178 return InstrumentId{};
5183 if (
const auto* target = std::get_if<strategy::TargetPosition>(&instruction)) {
5184 return target->tag_;
5186 if (
const auto* order = std::get_if<strategy::OrderIntent>(&instruction)) {
5187 return order->tag();
5192 void send_cancel(
const OrderRef<Tag>& ref, Report& report) {
5199 ++instructions_unavailable_;
5200 report.unavailable_cancel_.push_back(ref);
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_))) {
5233 if (working ==
nullptr) {
5234 ++cancels_unresolved_;
5235 report.unresolved_cancel_.push_back(ref);
5241 if (working->reserved_ && serialized() && !cancellable_reservation(*working)) {
5242 ++cancels_rejected_;
5246 const auto outcome = executor_.cancel(*working);
5265 guard_.note_sent(send_instant());
5267 note_withdrawal_accepted(ref);
5268 report.would_cancel_.push_back(ref);
5274 guard_.note_sent(send_instant());
5275 ++cancels_rejected_;
5282 ledger_.mark(working->order_.instrument_,
"a cancellation request has an unknown outcome");
5285 guard_.note_sent(send_instant());
5286 ++cancels_indeterminate_;
5287 report.indeterminate_cancel_.push_back(ref);
5295 ++cancels_rejected_;
5301 ++instructions_unavailable_;
5302 report.unavailable_cancel_.push_back(ref);
5315 strategy::Plan<Tag> plan_weight(
const strategy::OrderIntent& intent,
const strategy::ReconcileInputs& inputs)
const {
5316 strategy::Plan<Tag> plan;
5318 if (!converted.target_) {
5320 strategy::Rejection{
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) {
5350 const auto id = instrument_of(instruction);
5351 const auto* reference = context_.find_instrument(
id);
5352 const auto band = band_for(
id);
5354 strategy::ReconcileInputs inputs;
5357 inputs.
limits_ = band.applied_;
5365 pass_rows_ !=
nullptr &&
5366 (context_detail::PortfolioAccess::replacements(context_) != rows_replacements_ ||
5367 context_detail::PortfolioAccess::runner_edits(context_) != rows_edits_)
5369 pass_rows_ =
nullptr;
5371 inputs.
rows_ = pass_rows_;
5374 if (
const auto* target = std::get_if<strategy::TargetPosition>(&instruction)) {
5377 if (
const auto* intent = std::get_if<strategy::OrderIntent>(&instruction)) {
5383 return plan_weight(*intent, inputs);
5387 return strategy::Plan<Tag>{};
5393 if (band.withheld_) {
5394 ++price_bands_withheld_;
5395 mark_withheld_band(plan, *band.withheld_);
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();
5416 last_broker_refusal_.reset();
5420 refusal.code_ = error->broker_code_;
5421 refusal.message_ = error->message_;
5423 refusal.tag_ = order.
tag_;
5424 last_broker_refusal_ = std::move(refusal);
5426 static_cast<void>(order);
5432 if (
const auto* target = std::get_if<strategy::TargetPosition>(&instruction)) {
5433 return target->instrument_;
5435 if (
const auto* intent = std::get_if<strategy::OrderIntent>(&instruction)) {
5438 return InstrumentId{};
5444 PriceLimits limits_;
5446 std::chrono::system_clock::time_point received_at_{};
5456 std::chrono::system_clock::time_point as_of() const noexcept {
5457 if (!limits_.exchange_time_) {
5458 return received_at_;
5460 return *limits_.exchange_time_ < received_at_ ? *limits_.exchange_time_ : received_at_;
5464 struct BandDecision {
5466 std::optional<PriceLimits> applied_;
5468 std::optional<PriceLimits> withheld_;
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()) {
5482 if (!maximum_price_limits_age_ && !allow_unbounded_price_limits_age_) {
5486 decision.withheld_ = found->second.limits_;
5495 if (found->second.as_of() > freshness_instant()) {
5496 decision.withheld_ = found->second.limits_;
5499 if (maximum_price_limits_age_ && freshness_instant() - found->second.as_of() > *maximum_price_limits_age_) {
5500 decision.withheld_ = found->second.limits_;
5503 decision.applied_ = found->second.limits_;
5513 static void mark_withheld_band(strategy::Plan<Tag>& plan,
const PriceLimits& withheld) {
5514 for (
auto& order : plan.
place_) {
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
5527 strategy::RiskGuard guard_;
5529 std::size_t placements_at_broker_{0};
5531 std::size_t sends_outside_permitted_phase_{0};
5533 std::optional<std::chrono::nanoseconds> maximum_portfolio_age_;
5535 std::chrono::system_clock::time_point observed_at_{};
5537 bool allow_absent_portfolio_{
false};
5543 bool require_known_portfolio_{runner_detail::sends_to_a_broker<Executor>::value};
5544 bool probing_sellable_{
false};
5545 strategy::SellableConventionProbe<Tag> sellable_probe_;
5548 void note_local_failure(std::string detail) {
5563 void note_executor_failure(
bool refused) {
5564 const auto failures = executor_journal_failures();
5565 if (failures > acknowledged_journal_failures_) {
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));
5572 if (refused && failures == 0) {
5576 note_local_failure(
"local machinery refused to send");
5581 std::size_t executor_journal_failures()
const {
5582 return executor_journal_failures_impl(0);
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();
5590 std::size_t executor_journal_failures_impl(...)
const {
5595 std::string executor_journal_error()
const {
5596 return executor_journal_error_impl(0);
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();
5605 std::string executor_journal_error_impl(...)
const {
5613 std::optional<RunLedger> run_;
5616 std::optional<Decimal64> run_committed_{
Decimal64(0, 0)};
5618 bool run_rows_listed_{
false};
5620 std::vector<InstrumentId> run_unknown_;
5621 std::optional<RunOpening> run_opening_;
5622 std::optional<RunRecoverySummary> run_recovery_;
5624 bool run_absent_{
false};
5626 bool run_closing_{
false};
5628 std::vector<std::string> run_cancels_sent_;
5630 bool run_journal_latched_{
false};
5632 std::unordered_set<std::string> run_ids_;
5633 std::size_t acknowledged_journal_failures_{0};
5634 std::map<InstrumentId, DatedBand> price_limits_;
5636 std::optional<std::chrono::nanoseconds> maximum_price_limits_age_;
5638 bool allow_unbounded_price_limits_age_{
false};
5640 std::size_t price_bands_withheld_{0};
5642 std::size_t unclamped_orders_rejected_{0};
5644 std::size_t unclamped_orders_refused_{0};
5646 std::size_t orders_unbuildable_{0};
5648 std::size_t orders_reconcile_withheld_{0};
5650 std::size_t orders_guard_refused_{0};
5652 std::size_t orders_binding_refused_{0};
5654 std::size_t orders_broker_refused_{0};
5656 std::size_t orders_indeterminate_{0};
5658 std::size_t cancels_rejected_{0};
5660 std::size_t cancels_refused_{0};
5662 std::size_t cancels_unresolved_{0};
5664 std::size_t cancels_indeterminate_{0};
5666 std::size_t plans_withheld_{0};
5667 std::size_t warmup_instructions_discarded_{0};
5669 bool started_{
false};
5672 struct DeferredStop {
5674 std::optional<std::chrono::system_clock::time_point> ordered_at_;
5677 struct DeferredTarget {
5679 strategy::TargetPosition target_;
5681 std::vector<DeferredStop> stops_;
5683 std::chrono::system_clock::time_point deferred_at_{};
5686 std::vector<DeferredTarget> deferred_targets_;
5688 std::vector<Unconfirmed> unconfirmed_;
5690 static constexpr bool can_serialize = keeps_sent_orders_until_listed && runner_detail::serializes<Executor>::value;
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};
5702 struct RetainedTarget {
5703 strategy::TargetPosition target_;
5704 bool for_phase_{
false};
5706 std::optional<std::chrono::system_clock::time_point> after_;
5708 bool until_accounted_{
false};
5710 std::vector<RetainedTarget> retained_targets_;
5713 strategy::OrderIntent intent_;
5716 std::optional<std::chrono::system_clock::time_point> after_;
5718 std::vector<KeptIntent> kept_intents_;
5719 std::size_t kept_intents_dropped_{0};
5721 std::vector<const Instruction<Tag>*> kept_this_pass_;
5724 const strategy::PortfolioRows* pass_rows_{
nullptr};
5725 std::uint64_t rows_replacements_{0};
5726 std::uint64_t rows_edits_{0};
5728 bool releasing_deferred_{
false};
5730 std::size_t targets_deferred_{0};
5732 std::size_t deferred_dropped_after_fill_{0};
5734 std::size_t instructions_unavailable_{0};
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_;
5742 friend struct runner_detail::ReplayAccess;