1067 : runner_(&
runner), source_(&source), schedule_(std::move(
schedule)), clock_(std::move(
clock)) {
1070 runner_->
context().set_session(session_window_);
1102 struct InstructionOutcomes {
1103 std::size_t unbuildable_{0};
1104 std::size_t unconfirmed_timed_out_{0};
1105 std::size_t reconcile_withheld_{0};
1106 std::size_t guard_refused_{0};
1107 std::size_t binding_refused_{0};
1108 std::size_t broker_refused_{0};
1109 std::size_t indeterminate_{0};
1110 std::size_t cancels_rejected_{0};
1111 std::size_t cancels_refused_{0};
1112 std::size_t cancels_unresolved_{0};
1113 std::size_t cancels_indeterminate_{0};
1114 std::size_t plans_withheld_{0};
1115 std::size_t instructions_unavailable_{0};
1119 InstructionOutcomes instruction_outcomes()
const {
1120 InstructionOutcomes at;
1121 at.unbuildable_ = runner_->orders_unbuildable();
1122 at.unconfirmed_timed_out_ = runner_->orders_unconfirmed_timed_out();
1123 at.reconcile_withheld_ = runner_->orders_reconcile_withheld();
1124 at.guard_refused_ = runner_->orders_guard_refused();
1125 at.binding_refused_ = runner_->orders_binding_refused();
1126 at.broker_refused_ = runner_->orders_broker_refused();
1127 at.indeterminate_ = runner_->orders_indeterminate();
1128 at.cancels_rejected_ = runner_->cancels_rejected();
1129 at.cancels_refused_ = runner_->cancels_refused();
1130 at.cancels_unresolved_ = runner_->cancels_unresolved();
1131 at.cancels_indeterminate_ = runner_->cancels_indeterminate();
1132 at.plans_withheld_ = runner_->plans_withheld();
1133 at.instructions_unavailable_ = runner_->instructions_unavailable();
1138 static void note_instruction_outcomes(
1139 LoopReport& report,
const InstructionOutcomes& before,
const InstructionOutcomes& after
1141 report.orders_unbuildable_ = after.unbuildable_ - before.unbuildable_;
1142 report.orders_unconfirmed_timed_out_ = after.unconfirmed_timed_out_ - before.unconfirmed_timed_out_;
1143 report.orders_reconcile_withheld_ = after.reconcile_withheld_ - before.reconcile_withheld_;
1144 report.orders_guard_refused_ = after.guard_refused_ - before.guard_refused_;
1145 report.orders_binding_refused_ = after.binding_refused_ - before.binding_refused_;
1146 report.orders_broker_refused_ = after.broker_refused_ - before.broker_refused_;
1147 report.orders_indeterminate_ = after.indeterminate_ - before.indeterminate_;
1148 report.cancels_rejected_ = after.cancels_rejected_ - before.cancels_rejected_;
1149 report.cancels_refused_ = after.cancels_refused_ - before.cancels_refused_;
1150 report.cancels_unresolved_ = after.cancels_unresolved_ - before.cancels_unresolved_;
1151 report.cancels_indeterminate_ = after.cancels_indeterminate_ - before.cancels_indeterminate_;
1152 report.plans_withheld_ = after.plans_withheld_ - before.plans_withheld_;
1153 report.instructions_unavailable_ = after.instructions_unavailable_ - before.instructions_unavailable_;
1168 maximum_portfolio_age_ = age;
1173 runner_->set_maximum_portfolio_age(age);
1207 closing_wait_ = limit;
1261 owed_order_limit_ = limit;
1275 allow_unbounded_portfolio_age_ =
true;
1276 maximum_portfolio_age_.reset();
1277 runner_->set_maximum_portfolio_age(std::nullopt);
1286 runner_->set_maximum_price_limits_age(age);
1291 runner_->allow_unbounded_price_limits_age();
1302 allow_absent_portfolio_ =
true;
1306 runner_->allow_absent_portfolio();
1319 runner_->context().set_session(window);
1320 session_window_ = std::move(window);
1328 return session_window_;
1336 failure_policy_ = std::move(policy);
1356 std::function<std::optional<std::vector<typename Runner::DataRecord>>(std::chrono::system_clock::time_point)> poll
1360 "a data poll for a strategy that declares no on_data would read records that vanish: declare on_data"
1362 data_poll_ = std::move(poll);
1370 control_ = std::move(channel);
1406 const auto outside_phase_before = runner_->sends_outside_permitted_phase();
1408 const auto bands_withheld_before = runner_->price_bands_withheld();
1409 const auto unclamped_rejected_before = runner_->unclamped_orders_rejected();
1410 const auto unclamped_refused_before = runner_->unclamped_orders_refused();
1415 const auto outcomes_before = instruction_outcomes();
1416 auto outcomes_after = outcomes_before;
1420 std::optional<BrokerRefusal> refusal_at_boundary;
1421 std::optional<strategy::Rejection> unbuildable_at_boundary;
1424 const auto charged_before = [&]() {
1426 return source_->charged_costs();
1431 for (
auto& due : next_due_) {
1434 for (
auto& count : consecutive_failures_) {
1438 warmup_discarded_at_start_ = warmup_discarded();
1440 kept_dropped_at_start_ = runner_->kept_intents_dropped();
1443 while (max_iterations == 0 || report.
iterations_ < max_iterations) {
1444 const auto iteration = step(stop, report);
1446 if (iteration.gate_) {
1451 if (iteration.phase_changed_) {
1458 outcomes_after = instruction_outcomes();
1459 refusal_at_boundary = runner_->last_broker_refusal();
1460 unbuildable_at_boundary = runner_->last_unbuildable();
1464 runner_->clear_retained_targets();
1465 if (
const auto intent = stop.intent()) {
1466 interrupt_stop(*intent, report);
1467 }
else if (owed_past_limit(clock_.now())) {
1472 report.
final_gate_ = runner_->guard().blocking_reason();
1476 if (
const auto intent = stop.intent()) {
1481 outcomes_after = instruction_outcomes();
1482 refusal_at_boundary = runner_->last_broker_refusal();
1483 unbuildable_at_boundary = runner_->last_unbuildable();
1487 const bool last_iteration = max_iterations != 0 && report.
iterations_ >= max_iterations;
1488 if (!last_iteration && closing_should_wait(*intent, report)) {
1489 clock_.wait_for(closing_until_next());
1492 finish_stop(*intent, report);
1496 clock_.wait_for(until_next(iteration.at_));
1512 outcomes_after = instruction_outcomes();
1513 refusal_at_boundary = runner_->last_broker_refusal();
1514 unbuildable_at_boundary = runner_->last_unbuildable();
1516 note_instruction_outcomes(report, outcomes_before, outcomes_after);
1538 if (report.
price_bands_withheld_ > 0 && !runner_->price_limits_age_policy_stated() && !said_no_band_age_policy_) {
1539 said_no_band_age_policy_ =
true;
1540 report.
notes_.emplace_back(
1541 "no price band age policy: call set_maximum_price_limits_age or "
1542 "allow_unbounded_price_limits_age"
1548 note_sellable_convention(report);
1549 note_unestablished_phase(report);
1550 note_on_fill_never_fires(report);
1551 note_listing_outpaces_holdings(report);
1552 note_warmup_discarded(report);
1553 note_kept_intents_dropped(report);
1575 void note_sellable_convention(
LoopReport& report)
const {
1577 if (evidence.total() == 0) {
1582 std::to_string(evidence.net_) +
" net, " + std::to_string(evidence.gross_) +
" gross)"
1587 std::size_t warmup_discarded()
const {
1588 if constexpr (runner_counts_warmup<Runner>::value) {
1601 void note_warmup_discarded(LoopReport& report)
const {
1602 const auto discarded = warmup_discarded() - warmup_discarded_at_start_;
1603 if (discarded == 0) {
1606 report.notes_.push_back(
1607 std::to_string(discarded) +
1608 " instruction(s) decided on bars fed as history were not sent: "
1609 "only the newest bar of each instrument's read may send (poll bars no slower than their interval)"
1614 void note_kept_intents_dropped(LoopReport& report)
const {
1615 if constexpr (runner_counts_kept_drops<Runner>::value) {
1616 const auto dropped = runner_->kept_intents_dropped() - kept_dropped_at_start_;
1618 report.notes_.push_back(
1619 std::to_string(dropped) +
1620 " order intent(s) kept for the market phase were not sent at the "
1621 "open: the instrument's holding had changed since they were decided, or a stop now rested"
1625 static_cast<void>(report);
1633 void note_on_fill_never_fires(LoopReport& report)
const {
1635 report.notes_.push_back(
1636 "strategy defines on_fill; it never fires on this runner (fills are not observed live: "
1637 "read positions from holdings, see writing-a-strategy.md)"
1640 static_cast<void>(report);
1650 void note_listing_outpaces_holdings(LoopReport& report)
const {
1651 const auto& listing = schedule_.working_orders_;
1652 const auto& holdings = schedule_.holdings_;
1653 if (listing && holdings && *listing < *holdings) {
1654 report.notes_.push_back(
1655 "working orders are polled more often than holdings; plans made between a listing and the "
1656 "next holdings read are withheld as portfolio_superseded"
1662 IterationReport step(StopSource& stop, LoopReport& report) {
1663 IterationReport iteration;
1664 iteration.at_ = clock_.now();
1668 check_control_file(stop, report);
1671 if (
stop.requested()) {
1672 runner_->clear_retained_targets();
1689 install_phase(iteration);
1696 runner_->set_observed_at(iteration.at_);
1700 runner_->require_known_portfolio(!allow_absent_portfolio_);
1716 if (!runner_->started()) {
1717 const auto before = held_;
1718 hold(gate_for(stop, iteration.at_, report,
false));
1719 if (runner_->context().now() < iteration.at_) {
1720 runner_->context().set_now(iteration.at_);
1722 const auto watch = watch_phase(iteration);
1724 note_revised_phase(
"on_start handler", watch, report);
1727 hold(gate_for(stop, iteration.at_, report,
true));
1730 if (!is_due(kind, iteration.at_)) {
1745 install_phase(iteration);
1751 hold(gate_for(stop, iteration.at_, report,
false));
1752 const auto watch = watch_phase(iteration);
1760 const auto placements_before_poll = runner_->placements_at_broker();
1761 const auto outcome = kind ==
PollKind::DATA ? poll_data(iteration.at_) : source_->poll(kind, *runner_);
1763 working_asked_at_ = clock_.monotonic_now();
1765 holdings_asked_at_ = clock_.monotonic_now();
1767 note_revised_phase(std::string(
poll_kind_name(kind)) +
" poll", watch, report);
1772 note_working_orders_read(iteration.at_, placements_before_poll);
1774 ++report.attempted_[
static_cast<int>(kind)];
1775 iteration.polls_.emplace_back(kind, outcome);
1776 schedule_next(kind, iteration.at_);
1777 note_outcome(kind, outcome, report);
1779 iteration.fed_ =
true;
1781 if (report.abandoned_) {
1784 iteration.gate_ = runner_->guard().blocking_reason();
1793 runner_->observe_sellable_convention();
1801 install_phase(iteration);
1802 hold(gate_for(stop, iteration.at_, report,
false));
1806 if (announced_ != iteration.phase_) {
1824 if (runner_->context().now() < iteration.at_) {
1825 runner_->context().set_now(iteration.at_);
1827 announced_ = iteration.phase_;
1828 iteration.phase_changed_ =
true;
1831 const auto watch = watch_phase(iteration);
1832 runner_->feed(iteration.phase_);
1833 note_revised_phase(
"on_phase handler", watch, report);
1843 runner_->retry_retained_targets();
1848 iteration.gate_ = runner_->guard().blocking_reason();
1854 std::chrono::system_clock::time_point at_{};
1856 std::size_t sends_{0};
1860 PhaseWatch watch_phase(
const IterationReport& iteration)
const {
1861 return PhaseWatch{iteration.at_, iteration.phase_, runner_->guard().total_sent()};
1881 void note_revised_phase(
const std::string& what,
const PhaseWatch& before, LoopReport& report) {
1882 if (runner_->guard().total_sent() == before.sends_) {
1885 if (phase_at(before.at_) == before.phase_) {
1888 ++report.sends_under_a_revised_phase_;
1889 if (report.sends_under_a_revised_phase_ == 1) {
1897 report.notes_.push_back(
1899 " changed the market phase and sent a request in the same call; check whether "
1900 "that request used the earlier phase. Only the calendar poll may write the trading calendar, "
1901 "and it must not send"
1924 void install_phase(IterationReport& iteration) {
1925 iteration.phase_ = phase_at(iteration.at_);
1929 phase_ever_known_ =
true;
1931 runner_->context().set_phase(iteration.phase_);
1951 const auto& calendar = runner_->context().calendar();
1952 if constexpr (source_states_calendar_sessions<Source>::value) {
1955 if (undeclared_hours()) {
1958 return session_window_.phase(at, calendar.is_trading_day(session_window_.local_date(at)));
1964 bool undeclared_hours()
const {
1965 if constexpr (source_states_calendar_sessions<Source>::value) {
1968 const auto& days = runner_->context().calendar().days_;
1969 return std::any_of(days.begin(), days.end(), [](
const TradingDay& day) {
1970 return day.open_ && day.regular_.has_value();
1980 std::string unreadable_calendar_rows()
const {
1981 const auto unreadable = runner_->context().calendar().unreadable_days_;
1982 if (unreadable == 0) {
1985 return "; the broker sent " + std::to_string(unreadable) +
" calendar row" + (unreadable == 1 ?
"" :
"s") +
1986 " whose date could not be read";
2000 void note_unestablished_phase(LoopReport& report)
const {
2014 const bool ever_known = phase_ever_known_;
2020 if (undeclared_hours()) {
2023 "the calendar states session hours but the source does not declare states_calendar_sessions; declare it, "
2024 "or forward it from the SessionSource it wraps";
2025 }
else if (!schedule_.calendar_) {
2026 reason =
"no calendar cadence is configured";
2028 reason =
"every calendar poll failed";
2029 }
else if (runner_->context().calendar().days_.empty()) {
2033 reason =
"a calendar poll succeeded but no calendar arrived (this broker may publish none)";
2034 reason += unreadable_calendar_rows();
2035 }
else if (source_states_calendar_sessions<Source>::value) {
2036 reason =
"the calendar's session hours do not decide " +
format_iso8601_utc(last_.at_);
2037 reason += unreadable_calendar_rows();
2041 const auto date = session_window_.local_date(last_.at_);
2042 reason =
"the calendar does not cover " + std::to_string(date.year_) +
"-" + std::to_string(date.month_) +
"-" +
2043 std::to_string(date.day_);
2044 reason += unreadable_calendar_rows();
2046 report.notes_.push_back(
2048 ever_known ?
"the market phase stopped being established (" :
"the market phase was never established ("
2050 reason +
"); a guard permitting only known phases refused every placement opening a position" +
2051 (ever_known ?
" after that" :
"")
2058 bool read_order_list_once(std::chrono::system_clock::time_point at, LoopReport& report) {
2062 const auto watch = PhaseWatch{at, phase_at(at), runner_->guard().total_sent()};
2066 const auto placements_before_read = runner_->placements_at_broker();
2067 const auto outcome = source_->read_order_list(*runner_);
2069 working_asked_at_ = clock_.monotonic_now();
2070 note_revised_phase(
"order-list read", watch, report);
2074 order_list_read_ =
true;
2075 report.order_list_read_ =
true;
2076 order_list_at_ = at;
2080 note_working_orders_read(at, placements_before_read);
2098 std::optional<strategy::HaltReason> gate_for(
2099 StopSource& stop, std::chrono::system_clock::time_point at, LoopReport& report,
bool may_read
2101 if (
stop.requested()) {
2114 const auto intent =
stop.intent();
2119 intent &&
stop_intent_closes(*intent) && !order_list_read_ && may_read && on_the_floor &&
2123 read_order_list_once(at, report);
2127 if (!order_list_read_) {
2136 const bool owed = owed_past_limit(clock_.now());
2143 }
else if (
const auto configured = buying_power_configuration_hold(report)) {
2147 if (!read_order_list_once(at, report)) {
2159 if (
auto owed = owed_too_long()) {
2160 report.notes_.push_back(owed_stop_note(*owed));
2161 report.owed_stop_ = std::move(owed);
2165 if (owed_past_limit(clock_.now())) {
2172 const auto as_of = runner_->context().portfolio().as_of_;
2173 if (as_of == std::chrono::system_clock::time_point{}) {
2189 if (!allow_absent_portfolio_) {
2208 if (!maximum_portfolio_age_ && !allow_unbounded_portfolio_age_) {
2209 if (!said_no_age_policy_) {
2210 said_no_age_policy_ =
true;
2211 report.notes_.emplace_back(
2212 "no portfolio age policy: call set_maximum_portfolio_age or allow_unbounded_portfolio_age"
2218 maximum_portfolio_age_ && as_of != std::chrono::system_clock::time_point{} && at - as_of > *maximum_portfolio_age_
2230 if constexpr (runner_keeps_sent_orders<Runner>::value) {
2231 if (
const auto missing = listing_missing(at)) {
2232 if ((said_listing_ &
missing->first) == 0) {
2233 said_listing_ |=
missing->first;
2234 report.notes_.emplace_back(
missing->second);
2239 if constexpr (!source_reports_buying_power<Source>::value) {
2240 return buying_power_configuration_hold(report);
2242 if (runner_->guard().limits().enforce_buying_power_) {
2245 if (
const auto unread = buying_power_unread(at)) {
2249 return std::nullopt;
2261 std::optional<strategy::HaltReason> buying_power_unread(std::chrono::system_clock::time_point at)
const {
2262 const auto& readings = runner_->context().portfolio().buying_power_;
2265 const auto usable = [&](
const BuyingPower& reading) {
2266 return !maximum_buying_power_age_ || at - reading.received_at_ <= *maximum_buying_power_age_;
2268 if constexpr (source_names_buying_power_currencies<Source>::value) {
2269 const auto& wanted = source_->buying_power_currencies();
2270 if (!wanted.empty()) {
2271 for (
const auto& currency : wanted) {
2273 for (
const auto& reading : readings) {
2274 if (reading.cash_.currency_ == currency && usable(reading)) {
2283 return std::nullopt;
2286 if (readings.empty()) {
2289 for (
const auto& reading : readings) {
2290 if (!usable(reading)) {
2294 return std::nullopt;
2302 std::optional<strategy::HaltReason> buying_power_configuration_hold(LoopReport& report) {
2303 if constexpr (source_reports_buying_power<Source>::value) {
2305 return std::nullopt;
2307 constexpr bool declared = loop_detail::source_declares_buying_power<Source>::value;
2308 const auto& limits = runner_->guard().limits();
2309 if (!limits.run_budget_) {
2310 say_buying_power_once(
2313 "the broker reports no buying power: set RiskLimits::run_budget_, the run's starting cash" :
2314 "the source does not declare reports_buying_power: declare or forward it, or set run_budget_"
2318 if (limits.enforce_buying_power_) {
2319 say_buying_power_once(
2322 "the broker reports no buying power: turn enforce_buying_power_ off; run_budget_ limits buys" :
2323 "the source does not declare reports_buying_power: declare or forward it for enforce_buying_power_"
2327 return std::nullopt;
2332 void say_buying_power_once(
unsigned bit, LoopReport& report,
const char* note) {
2333 if ((said_buying_power_ & bit) == 0) {
2334 said_buying_power_ |= bit;
2335 report.notes_.emplace_back(note);
2354 maximum_buying_power_age_ = age;
2363 if (
const auto intent = control_.
poll()) {
2364 stop.request(*intent);
2370 report.
notes_.push_back(
"control file names no intent: '" + control_.
unrecognized() +
"'");
2376 const int at =
static_cast<int>(kind);
2378 ++report.failed_[at];
2379 ++consecutive_failures_[at];
2380 if (consecutive_failures_[at] >= failure_policy_.consecutive_limit_) {
2381 report.abandoned_ =
true;
2382 report.abandoned_kind_ = kind;
2383 report.notes_.push_back(
2384 std::string(
"gave up after repeated failures polling ") + std::string(
poll_kind_name(kind))
2401 consecutive_failures_[at] = 0;
2408 void begin_stop(LoopReport& report) {
2409 closing_ = ClosingWait{};
2410 closing_->began_ = clock_.monotonic_now();
2411 closing_->deadline_ = closing_->began_ +
2412 std::chrono::duration_cast<std::chrono::steady_clock::duration>(
2413 closing_wait_ > std::chrono::nanoseconds::zero() ? closing_wait_ : std::chrono::nanoseconds::zero()
2419 runner_->clear_retained_targets();
2420 runner_->clear_deferred_targets();
2439 const auto parting = runner_->notify_stop();
2444 report.stop_handler_refused_ = parting.refused_.size() + parting.refused_cancel_.size() + parting.rejected_.size() +
2445 parting.withheld_.size() + parting.withheld_plans_.size() + parting.unavailable_.size();
2446 report.stop_handler_sent_ = parting.would_place_.size() + parting.would_cancel_.size();
2452 void interrupt_stop(
StopIntent intent, LoopReport& report) {
2456 runner_->clear_deferred_targets();
2457 report.stopped_by_ = intent;
2459 report.closing_waited_ =
2460 std::chrono::duration_cast<std::chrono::nanoseconds>(clock_.monotonic_now() - closing_->began_);
2463 report.closing_interrupted_ =
true;
2464 report.notes_.push_back(
2465 std::string(
"the run was abandoned for failing polls with a ") + std::string(
stop_intent_name(intent)) +
2466 " pending: its closing pass did not run, nothing was withdrawn or closed by it, and the runner is"
2467 " left unable to send; read the broker's order list and holdings"
2473 void finish_stop(
StopIntent intent, LoopReport& report) {
2474 report.closing_waited_ =
2475 std::chrono::duration_cast<std::chrono::nanoseconds>(clock_.monotonic_now() - closing_->began_);
2476 closing_->reads_wanted_ =
false;
2484 const auto stale = runner_->settle_closing();
2485 report.stop_handler_refused_ += stale.refused_.size() + stale.refused_cancel_.size() + stale.rejected_.size() +
2486 stale.withheld_.size() + stale.withheld_plans_.size() + stale.unavailable_.size();
2487 report.stop_handler_sent_ += stale.would_place_.size() + stale.would_cancel_.size();
2491 runner_->clear_retained_targets();
2492 runner_->clear_deferred_targets();
2505 report.closing_source_unverified_ = !closing_source_verified(clock_.now());
2509 runner_->refresh_unconfirmed();
2512 report.closing_unconfirmed_ = runner_->obligations_unexplained();
2513 const auto& portfolio = runner_->context().portfolio();
2515 for (
const auto& working : portfolio.working_) {
2517 if (runner_->withdrawal_accepted_for(working)) {
2520 runner_->context().cancel(working.ref_,
"stop-withdraw");
2521 ++report.withdrawn_;
2540 for (
const auto& working : portfolio.working_) {
2541 if (runner_->withdrawal_accepted_for(working)) {
2544 runner_->context().cancel(working.ref_,
"stop-flatten");
2545 ++report.withdrawn_;
2555 std::vector<InstrumentId> closed;
2556 for (
const auto& position : portfolio.positions_) {
2558 for (
const auto& already : closed) {
2559 if (already == position.instrument_) {
2567 closed.push_back(position.instrument_);
2571 const auto net = portfolio.net_quantity_of(position.instrument_);
2575 ++report.closing_unsizable_;
2578 if (net->coefficient() == 0) {
2584 if (report.closing_source_unverified_) {
2594 ++report.closing_contended_;
2597 const bool held_long =
decimal_less(Decimal64{}, *net);
2598 const auto magnitude = held_long ? std::optional<Decimal64>(*net) :
decimal_subtract(Decimal64{}, *net);
2605 ++report.closing_unsizable_;
2608 const OrderSide closing_side = held_long ? OrderSide::SELL : OrderSide::BUY;
2609 const auto contending = portfolio.working_quantity(position.instrument_, closing_side);
2617 ++report.closing_unsizable_;
2620 if (contending.coefficient() != 0) {
2624 ++report.closing_contended_;
2626 if (
decimal_less(*sendable, Decimal64{}) || sendable->coefficient() == 0) {
2631 runner_->context().submit(
2635 ++report.flattened_;
2650 hold(buying_power_configuration_hold(report));
2659 const auto closing_at = clock_.now();
2660 runner_->context().set_phase(phase_at(closing_at));
2661 const auto watch = PhaseWatch{closing_at, phase_at(closing_at), runner_->guard().total_sent()};
2662 const auto closing = runner_->settle_closing();
2663 note_revised_phase(
"closing pass", watch, report);
2667 runner_->clear_retained_targets();
2668 runner_->clear_deferred_targets();
2670 report.closing_placed_ = closing.would_place_.size();
2674 report.closing_rejected_ = closing.rejected_.size() + closing.rejected_cancel_.size();
2675 report.closing_refused_ = closing.refused_.size() + closing.refused_cancel_.size();
2677 report.closing_withheld_ = closing.withheld_.size() + closing.withheld_plans_.size();
2678 report.closing_indeterminate_ = closing.indeterminate_.size() + closing.indeterminate_cancel_.size();
2679 report.closing_unavailable_ = closing.unavailable_.size() + closing.unavailable_cancel_.size();
2680 report.closing_unresolved_ = closing.unresolved_cancel_.size();
2684 if (!closing.refused_.empty() || !closing.refused_cancel_.empty()) {
2685 report.notes_.push_back(
2686 "a guard refused " + std::to_string(report.closing_refused_) +
2687 " closing instruction(s); the position is still held"
2690 if (!closing.rejected_.empty()) {
2696 report.notes_.push_back(
2697 std::to_string(closing.rejected_.size()) +
" closing instruction(s) were not placed; the position is still held"
2700 if (!closing.rejected_cancel_.empty()) {
2701 report.notes_.push_back(
2702 std::to_string(closing.rejected_cancel_.size()) +
2703 " closing cancellation(s) were refused; read the broker's order list for their state"
2706 if (report.closing_withheld_ != 0) {
2707 report.notes_.push_back(
2708 "withheld " + std::to_string(report.closing_withheld_) +
2709 " closing instruction(s) pending reconciliation, or until an earlier order is accounted for;"
2710 " read the broker's order list"
2713 if (report.closing_unconfirmed_ != 0) {
2714 report.notes_.push_back(
2715 std::to_string(report.closing_unconfirmed_) +
2716 " order(s) this runner sent were not yet accounted for by holdings or a listing, so the closing pass"
2717 " could not withdraw or size around them; read the broker's order list and holdings"
2720 if (report.closing_wait_expired_) {
2721 report.notes_.push_back(
2722 "the stop waited " +
2723 std::to_string(std::chrono::duration_cast<std::chrono::seconds>(report.closing_waited_).count()) +
2724 " s for holdings and the order list to account for this runner's orders, or for a marked"
2725 " instrument to be resolved, and that did not happen; the closing pass was built from what was in"
2726 " hand (set_closing_wait)"
2729 if (report.closing_indeterminate_ != 0) {
2730 report.notes_.push_back(
2731 std::to_string(report.closing_indeterminate_) +
2732 " closing instruction(s) have an unknown outcome; read the broker's order list"
2735 if (report.closing_unavailable_ != 0) {
2736 report.notes_.push_back(
2737 "local machinery could not send " + std::to_string(report.closing_unavailable_) +
2738 " closing instruction(s); no broker was asked and the position is still held"
2741 if (report.stop_handler_refused_ != 0) {
2742 report.notes_.push_back(
2743 "the strategy's on_stop asked for " + std::to_string(report.stop_handler_refused_) +
2744 " instruction(s) during the stop; none were sent, because an operator's stop is not a"
2745 " moment for a strategy to trade"
2748 if (report.closing_contended_ != 0) {
2749 report.notes_.push_back(
2750 report.closing_source_unverified_ ?
2751 "no closing order was sent for " + std::to_string(report.closing_contended_) +
2752 " position(s), because an order this loop cannot see could close them too; they are"
2753 " still held and the withdrawals above are all that went" :
2754 std::to_string(report.closing_contended_) +
2755 " position(s) were closed only for the part no working order was already selling or"
2756 " buying; if those withdrawals succeed, part of the position is still held"
2759 if (report.closing_unsizable_ != 0) {
2768 report.notes_.push_back(
2769 "no closing order could be sized for " + std::to_string(report.closing_unsizable_) +
2770 " position(s): the holdings quantities would not add up or fit, or could not be combined"
2771 " with what is already working on the closing side; nothing was sent for them and they are"
2775 if (report.closing_source_unverified_) {
2776 report.notes_.push_back(
2777 std::string(
"the stop could not verify what was outstanding: ") + unverified_source_reason() +
2778 "; orders or positions a previous process left may remain"
2781 if (report.closing_unresolved_ != 0) {
2782 report.notes_.push_back(
2783 std::to_string(report.closing_unresolved_) +
2784 " closing cancellation(s) named an order the portfolio does not hold; read the broker's"
2800 void hold(std::optional<strategy::HaltReason> gate) {
2801 if (gate && !owns(*gate)) {
2804 if (held_ == gate) {
2808 runner_->guard().resume(*held_);
2811 runner_->guard().halt(*gate);
2818 std::optional<std::pair<unsigned, std::string>> listing_missing(std::chrono::system_clock::time_point at)
const {
2819 if constexpr (!source_provides_working_orders<Source>::value) {
2821 return std::make_pair(
2824 "this runner keeps the orders it sends until a working-order listing or holdings account for "
2825 "them, and the source publishes no listing: placing holds (declare provides_working_orders and "
2830 if (!schedule_.working_orders_) {
2831 return std::make_pair(
2834 "no working-order cadence: this runner keeps the orders it sends until a working-order "
2835 "listing or holdings account for them, so placing holds until PollSchedule::working_orders_ "
2840 if (maximum_portfolio_age_ && working_orders_at_ && at - *working_orders_at_ > *maximum_portfolio_age_) {
2841 return std::make_pair(
2844 "working-order listing older than the portfolio age policy: poll working orders "
2845 "(PollSchedule::working_orders_) more often than that age, by at least a tick; placing "
2846 "holds until it is read"
2850 return std::nullopt;
2857 std::optional<Obligation> owed_longer_than_limit(std::chrono::system_clock::time_point at)
const {
2858 std::optional<Obligation> oldest;
2859 if (owed_order_limit_ <= std::chrono::nanoseconds::zero()) {
2862 for (
auto& owed : runner_->obligations()) {
2866 if (at - owed.sent_at_ > owed_order_limit_ && (!oldest || owed.sent_at_ < oldest->sent_at_)) {
2867 oldest = std::move(owed);
2874 bool owed_past_limit(std::chrono::system_clock::time_point now)
const {
2875 return owed_longer_than_limit(now).has_value();
2883 std::optional<Obligation> owed_too_long()
const {
2884 if (!order_list_read_ || !order_list_at_) {
2885 return std::nullopt;
2887 return owed_longer_than_limit(*order_list_at_);
2891 static std::string owed_stop_note(
const Obligation& owed) {
2892 return "stopped placing: the " + std::string(owed.side_ == OrderSide::BUY ?
"buy" :
"sell") +
" of " +
2893 owed.quantity_.str() +
" " + owed.instrument_.symbol_ +
" sent " +
format_iso8601_utc(owed.sent_at_) +
2894 " (journal id " + owed.journal_id_ +
") is still owed, and " +
2896 ". Nothing was cancelled or closed. Read the broker's order list and holdings for it, then account for "
2897 "it with Runner::release_obligations; until then every start stops here again";
2905 bool closing_should_wait(
StopIntent intent, LoopReport& report) {
2906 if (!
stop_intent_closes(intent) || closing_wait_ <= std::chrono::nanoseconds::zero()) {
2911 if constexpr (!source_provides_working_orders<Source>::value) {
2921 const auto monotonic = clock_.monotonic_now();
2922 report.closing_waited_ = std::chrono::duration_cast<std::chrono::nanoseconds>(monotonic - closing_->began_);
2924 runner_->refresh_unconfirmed();
2925 closing_->reads_wanted_ = closing_needs_evidence(clock_.now());
2926 if (!closing_->reads_wanted_) {
2929 if (monotonic >= closing_->deadline_) {
2930 report.closing_wait_expired_ =
true;
2931 closing_->reads_wanted_ =
false;
2939 bool closing_needs_evidence(std::chrono::system_clock::time_point at)
const {
2940 if (!closing_source_verified(at) || runner_->obligations_awaiting_account() != 0) {
2945 const auto& portfolio = runner_->context().portfolio();
2946 for (
const auto& position : portfolio.positions_) {
2947 const auto net = portfolio.net_quantity_of(position.instrument_);
2949 (!net || net->coefficient() != 0) && runner_->ledger().requires_reconcile(position.instrument_) &&
2962 bool closing_read_due(
PollKind kind)
const {
2963 if (!closing_ || !closing_->reads_wanted_) {
2966 return !asked_within_floor(kind);
2970 bool asked_within_floor(
PollKind kind)
const {
2972 return asked && clock_.monotonic_now() - *asked < closing_reread_;
2978 std::chrono::nanoseconds closing_until_next()
const {
2979 auto wait = schedule_.tick_;
2980 const auto wall = clock_.now();
2982 const auto& due = next_due_[
static_cast<int>(kind)];
2986 wait = std::min(wait, std::chrono::duration_cast<std::chrono::nanoseconds>(*due - wall));
2988 const auto monotonic = clock_.monotonic_now();
2989 const auto until = [&](std::chrono::steady_clock::time_point when) {
2990 return std::chrono::duration_cast<std::chrono::nanoseconds>(when - monotonic);
2992 wait = std::min(wait, until(closing_->deadline_));
2993 for (
const auto* asked : {&working_asked_at_, &holdings_asked_at_}) {
2994 wait = std::min(wait, *asked ? until(**asked + closing_reread_) : std::chrono::nanoseconds::zero());
2996 return wait > std::chrono::nanoseconds::zero() ? wait : std::chrono::nanoseconds::zero();
3008 bool closing_source_verified(std::chrono::system_clock::time_point at)
const {
3009 if (!order_list_read_) {
3016 if (!working_orders_at_) {
3022 if (runner_->placements_at_broker() != placements_at_working_read_) {
3025 if (maximum_portfolio_age_ && at - *working_orders_at_ > *maximum_portfolio_age_) {
3028 const auto as_of = runner_->context().portfolio().as_of_;
3029 if (as_of == std::chrono::system_clock::time_point{}) {
3034 if (runner_->context().portfolio().listing_newer_than_holdings()) {
3037 return !maximum_portfolio_age_ || at - as_of <= *maximum_portfolio_age_;
3045 void note_working_orders_read(std::chrono::system_clock::time_point at, std::size_t placements_before_poll) {
3046 if constexpr (source_provides_working_orders<Source>::value) {
3047 working_orders_at_ = at;
3048 order_list_at_ = at;
3052 placements_at_working_read_ = placements_before_poll;
3055 (void)placements_before_poll;
3060 std::string unverified_source_reason()
const {
3061 if constexpr (!source_provides_working_orders<Source>::value) {
3062 return "this source does not publish the broker's outstanding orders";
3064 if (!order_list_read_ || !working_orders_at_) {
3065 return "the broker's order list has not been read";
3067 if (runner_->placements_at_broker() != placements_at_working_read_) {
3068 return "an order was sent after the working orders were last read";
3070 if (runner_->context().portfolio().as_of_ == std::chrono::system_clock::time_point{}) {
3071 return "no holdings snapshot has arrived";
3073 if (runner_->context().portfolio().listing_newer_than_holdings()) {
3074 return "the holdings were read before the working orders, so a fill between them is in neither";
3076 if (maximum_portfolio_age_ && clock_.now() - *working_orders_at_ > *maximum_portfolio_age_) {
3077 return "the working orders were read longer ago than the configured maximum";
3079 return "the holdings snapshot is older than the configured maximum";
3083 PollOutcome poll_data(std::chrono::system_clock::time_point at) {
3085 auto records = data_poll_(at);
3089 if (records->empty()) {
3092 for (
auto& record : *records) {
3093 runner_->feed(strategy::DataEvent<typename Runner::DataRecord>{at, std::move(record)});
3097 static_cast<void>(at);
3103 bool is_due(
PollKind kind, std::chrono::system_clock::time_point at)
const {
3108 return closing_read_due(kind);
3110 const auto interval = schedule_.interval_for(kind);
3114 const auto& due = next_due_[
static_cast<int>(kind)];
3115 return !due || at >= *due;
3119 void schedule_next(
PollKind kind, std::chrono::system_clock::time_point at) {
3120 const auto interval = schedule_.interval_for(kind);
3124 next_due_[
static_cast<int>(kind)] = at + std::chrono::duration_cast<std::chrono::system_clock::duration>(*interval);
3132 std::chrono::nanoseconds until_next(std::chrono::system_clock::time_point at)
const {
3133 auto wait = schedule_.tick_;
3135 const auto& due = next_due_[
static_cast<int>(kind)];
3139 const auto remaining = std::chrono::duration_cast<std::chrono::nanoseconds>(*due - at);
3140 if (remaining < wait) {
3144 return wait > std::chrono::nanoseconds::zero() ? wait : std::chrono::nanoseconds::zero();
3150 std::function<std::optional<std::vector<typename Runner::DataRecord>>(std::chrono::system_clock::time_point)>
3152 PollSchedule schedule_;
3154 FileStopChannel control_;
3155 FailurePolicy failure_policy_;
3164 bool phase_ever_known_{
false};
3165 std::optional<std::chrono::nanoseconds> maximum_portfolio_age_;
3168 std::chrono::nanoseconds closing_wait_{std::chrono::seconds(30)};
3169 std::chrono::nanoseconds owed_order_limit_{std::chrono::minutes(10)};
3170 static constexpr std::chrono::seconds closing_reread_{5};
3173 struct ClosingWait {
3174 std::chrono::steady_clock::time_point began_{};
3175 std::chrono::steady_clock::time_point deadline_{};
3176 bool reads_wanted_{
false};
3178 std::optional<ClosingWait> closing_;
3181 std::optional<std::chrono::steady_clock::time_point> working_asked_at_;
3182 std::optional<std::chrono::steady_clock::time_point> holdings_asked_at_;
3184 bool said_no_band_age_policy_{
false};
3186 bool allow_unbounded_portfolio_age_{
false};
3188 bool allow_absent_portfolio_{
false};
3190 bool said_no_age_policy_{
false};
3192 unsigned said_listing_{0};
3194 unsigned said_buying_power_{0};
3196 std::size_t warmup_discarded_at_start_{0};
3198 std::size_t kept_dropped_at_start_{0};
3199 std::optional<std::chrono::nanoseconds> maximum_buying_power_age_;
3200 std::optional<std::chrono::system_clock::time_point> next_due_[
poll_kind_count];
3202 bool order_list_read_{
false};
3222 std::optional<std::chrono::system_clock::time_point> working_orders_at_;
3226 std::optional<std::chrono::system_clock::time_point> order_list_at_;
3228 std::size_t placements_at_working_read_{0};
3231 std::optional<strategy::HaltReason> held_;
3232 IterationReport last_;