algotradelib 0.0.0.9000
C++ header-only library for algorithmic trading
Loading...
Searching...
No Matches
session_source.hpp
1#pragma once
2
3#include "../runner/loop.hpp"
4#include "../runner/order_updates.hpp"
5#include "../runner/reconcile_orders.hpp"
6
7#include <algorithm>
8#include <algotradelib/broker>
9
10#include <chrono>
11#include <cstddef>
12#include <iterator>
13#include <map>
14#include <optional>
15#include <stdexcept>
16#include <string>
17#include <string_view>
18#include <type_traits>
19#include <utility>
20#include <vector>
21
22namespace algotradelib {
23namespace live {
24
39
51inline BrokerError incomplete_history(std::string code, std::string message) {
52 BrokerError error;
54 error.reached_broker_ = true;
55 error.broker_code_ = std::move(code);
56 error.message_ = std::move(message);
57 return error;
58}
59
66 return incomplete_history(
67 "history_not_continued",
68 "the broker returned another history page, and this adapter declares no cursor to read it "
69 "(has_history_cursor is false): the history is incomplete"
70 );
71}
72
79 return incomplete_history(
80 "history_page_limit",
81 "the order history ran past " + std::to_string(pages) +
82 " pages and the last still said there is more: "
83 "the history is incomplete"
84 );
85}
86
87namespace session_source_detail {
88
89// Whether `Runner` delivers bars in slices (`Runner::takes_bar_slices`, a strategy declaring `on_bars`).
90// A runner of one's own without the constant takes bars one at a time, as before.
91template <typename Runner, typename = void>
92struct takes_slices : std::false_type {};
93
94template <typename Runner>
95struct takes_slices<Runner, std::enable_if_t<Runner::takes_bar_slices>> : std::true_type {};
96
97// Whether `Runner` can be fed `Event` as history.
98template <typename Runner, typename Event, typename = void>
99struct feeds_warmup_of : std::false_type {};
100
101template <typename Runner, typename Event>
102struct feeds_warmup_of<
103 Runner, Event, std::void_t<decltype(std::declval<Runner&>().feed_warmup(std::declval<const Event&>()))>
104> : std::true_type {};
105
106// Whether `Runner` can be fed history on the route it takes, which every `runner::Runner` can: a slice
107// for a strategy declaring `on_bars`, a bar otherwise. Required by `poll_bars`: a runner without it would
108// send what was decided on a cold start's history.
109template <typename Runner>
110struct feeds_warmup
111: feeds_warmup_of<Runner, std::conditional_t<takes_slices<Runner>::value, strategy::BarSlice, strategy::BarEvent>> {};
112
113} // namespace session_source_detail
114
155template <typename Session, typename Journal = runner::MemoryJournal, typename MarketData = Session>
157public:
161 std::optional<Money> amount_;
164 };
165
175
177 using Caps = typename Session::Caps;
179 using BrokerTag = typename Session::BrokerTag;
180
181 // The trading session is read for holdings, the order listing and history, which a market-data source
182 // does not have; it belongs in `MarketData`, which this does not check.
183 static_assert(
184 !Caps::data_only,
185 "SessionSource's first session is the trading session (holdings, orders), and this one's client is a "
186 "market-data source (DataOnlyTraits): pass a broker's session first and the data source as the "
187 "market-data session, SessionSource<Trading, Journal, MarketData>"
188 );
189
196 static constexpr bool provides_working_orders = Caps::has_working_orders;
197
206 static constexpr bool reports_buying_power = Caps::has_buying_power;
207
212 static constexpr bool states_calendar_sessions = MarketData::Caps::has_calendar_sessions;
213
219 SessionSource(Session& session, std::vector<InstrumentId> universe)
220 : session_(&session), market_data_(&session), universe_(std::move(universe)) {}
221
229 SessionSource(Session& session, MarketData& market_data, std::vector<InstrumentId> universe)
230 : session_(&session), market_data_(&market_data), universe_(std::move(universe)) {}
231
241 void set_journal(Journal& journal) {
242 journal_ = &journal;
243 }
244
251 window_ = window;
252 }
253
258 const runner::ReconcileReport& last_reconcile() const noexcept {
259 return reconcile_;
260 }
261
269 void set_buying_power_currencies(std::vector<Currency> currencies) {
270 currencies_ = std::move(currencies);
271 }
272
278 const std::vector<Currency>& buying_power_currencies() const noexcept {
279 return currencies_;
280 }
281
289 std::size_t bars_not_yet_closed() const noexcept {
290 return bars_not_yet_closed_;
291 }
292
298 std::size_t bars_fed_as_warmup() const noexcept {
299 return bars_fed_as_warmup_;
300 }
301
313 std::size_t bars_not_delivered() const noexcept {
314 return bars_not_delivered_;
315 }
316
322 void set_bar_query(BarInterval interval, int count) {
323 interval_ = interval;
324 count_ = count;
325 }
326
336 calendar_country_ = country;
337 }
338
343 Country calendar_country() const noexcept {
344 return calendar_country_;
345 }
346
356 const std::optional<BrokerError>& last_error() const noexcept {
357 return last_error_;
358 }
359
378 template <typename Runner>
379 runner::PollOutcome poll(runner::PollKind kind, Runner& runner_instance) {
380 switch (kind) {
382 return poll_calendar(runner_instance);
384 return poll_bars(runner_instance);
386 return poll_quotes(runner_instance);
388 return poll_holdings(runner_instance);
390 return poll_working_orders(runner_instance);
392 return poll_buying_power(runner_instance);
394 return poll_price_limits(runner_instance);
396 // Records come from the loop's data poll (`PollingLoop::set_data_poll`), never from a session.
398 }
400 }
401
414 template <typename Runner>
415 runner::PollOutcome read_order_list(Runner& runner_instance) {
416 if constexpr (Caps::has_working_orders) {
417 // **No order updates from this read, and the reason is a hazard rather than a preference.**
418 // This runs inside `PollingLoop::gate_for`, which the loop calls *before* it applies the
419 // startup hold, and it is handed a mutable runner -- so a `Runner::feed` here would dispatch
420 // to a strategy that can still submit, against the picture the gate exists to withhold. The
421 // listing is adopted as the baseline instead, which is also the honest reading of it: a
422 // predecessor's resting order is initial state, not a change, and it is installed on
423 // `Portfolio::working_` by the same call, which is where a strategy reads what it inherited.
424 //
425 // The cost is stated rather than hidden: an order present at startup that fills or is
426 // cancelled before the first scheduled poll produces no update at all.
427 return poll_working_orders(runner_instance, /*publish=*/false);
428 } else {
429 OrderHistoryQuery query;
430 if constexpr (Caps::has_history_limit) {
431 // Gated as `read_history_in` gates it: a broker that cannot honour a limit may refuse the query.
432 query.limit_ = history_limit_;
433 }
434 // Rows are kept as listed, page after page, with no de-duplication: this listing is undated, and
435 // two orders on different days can share a number. Nothing reaches `reconcile` unless the whole
436 // history was read.
437 std::vector<OrderSnapshot> rows;
438 bool complete = false;
439 for (int page = 0; page < maximum_history_pages_ && !complete; ++page) {
440 auto result = session_->order_history(query);
441 if (!result) {
442 last_error_ = result.error();
443 return poll_outcome_of(*last_error_);
444 }
445 auto& listed = result.value().orders_;
446 rows.insert(rows.end(), std::make_move_iterator(listed.begin()), std::make_move_iterator(listed.end()));
447 const bool more = result.value().next_cursor_ && !result.value().next_cursor_->empty();
448 if (!more) {
449 complete = true;
450 } else if constexpr (Caps::has_history_cursor) {
451 query.cursor_ = result.value().next_cursor_;
452 } else {
453 last_error_ = history_not_continued();
454 return poll_outcome_of(*last_error_);
455 }
456 }
457 if (!complete) {
458 last_error_ = history_page_limit(maximum_history_pages_);
459 return poll_outcome_of(*last_error_);
460 }
461 last_error_.reset();
462 // What this call establishes, with or without a journal, is the thing the gate actually needs:
463 // that this process has looked at the broker's own record before sending.
464 reconcile(runner_instance, rows);
466 }
467 }
468
478 const runner::ChargedCosts& charged_costs() const noexcept {
479 return charged_;
480 }
481
482private:
483 // Fetches bars for each instrument and feeds only those not seen before, in period-end order
484 // across the universe; only each instrument's newest may send (older ones are fed as history, see
485 // `Runner::feed_warmup`).
486 template <typename Runner>
487 runner::PollOutcome poll_bars(Runner& runner_instance) {
488 if constexpr (session_source_detail::takes_slices<Runner>::value) {
489 if (interrupted_) {
490 throw std::logic_error(
491 "a bar poll for on_bars was interrupted by an exception (" + *interrupted_ +
492 "); its period may be "
493 "partly recorded and partly delivered, so this source does not continue: restart the program with a "
494 "fresh runner and source; older periods warm up the strategy, and the newest eligible period may trade"
495 );
496 }
497 }
498 // Nothing configured is nothing read: `last_error()` is left as it was, as the other polls leave it.
499 if (universe_.empty()) {
501 }
502 // **Every instrument is read before anything is fed**, and then the new bars of all of them are
503 // fed in period-end order, ties in universe order -- the order a replay feeds them. Fed one
504 // instrument at a time, a cold start handed a cross-sectional strategy all of one name's history
505 // and then the next name's from its beginning, so the decision instant ran backwards between
506 // names and the strategy's state diverged from a replay's. A query that fails feeds nothing this
507 // poll; the next poll reads everything again.
508 struct Collected {
509 std::size_t instrument_{0};
510 strategy::BarEvent event_;
511 bool newest_{false};
512 };
513 std::vector<Collected> collected;
514 for (std::size_t at = 0; at < universe_.size(); ++at) {
515 const auto& instrument = universe_[at];
516 BarQuery query;
517 query.instrument_ = instrument;
518 query.interval_ = interval_;
519 query.count_ = count_;
520
521 auto result = market_data_->bars(query);
522 if (!result) {
523 last_error_ = result.error();
524 return poll_outcome_of(*last_error_);
525 }
526 const auto& series = result.value();
527 if (series.bars_.empty()) {
528 continue;
529 }
530
531 // Only bars newer than the last one fed, and in order. A poll returning the same closed bar
532 // again is the normal case between closes, and feeding it twice would double every signal
533 // derived from it.
534 //
535 // **And only bars whose period has ended.** Every shipped adapter's daily query runs up to
536 // today, and the broker answers today's row while the session is still trading -- KIS
537 // documents `mod_yn` for "the current business day" on `inquire-daily-itemchartprice`, and
538 // Kiwoom's daily close field is `cur_prc`, the current price. Fed, that bar reached the
539 // strategy with the price so far as its close, `last_bar_` moved past it, and the session's
540 // real close was never fed. So a bar ending after the instant the loop reported is left for
541 // a later poll, which reads it again. Its period end is `bar_period_end`'s, the instant the
542 // runner would have stamped the decision with, so the decision is never dated ahead of the
543 // clock either.
544 //
545 // The instant is the later of the loop's (`Runner::observed_at`) and when this machine
546 // received the series (`BarSeries::received_at_`, which every shipped adapter stamps), so a
547 // source driven by hand still has one, and one a finished `run` left behind cannot hold back a
548 // bar received closed since; with neither, every bar is fed, as before. **Only where the
549 // period end is known**: a close-stamped bar states it, and a day or an intraday bar stamped at its
550 // open ends one interval later. A week, a month or a year stamped at its open is fed as
551 // before, because no adapter's convention for those stamps has been observed and a wrong
552 // guess would hold every closed week back by a week.
553 const auto instant = std::max(runner_instance.observed_at(), series.received_at_);
554 const bool knowable = series.stamp_ == BarStamp::CLOSE || series.interval_ == BarInterval::ONE_DAY ||
555 bar_interval_length(series.interval_).has_value();
556 const bool timed = knowable && instant != std::chrono::system_clock::time_point{};
557 const auto& seen = last_bar_[instrument.symbol_];
558 const auto first = collected.size();
559 for (const auto& bar : series.bars_) {
560 if (seen && bar.timestamp_ <= *seen) {
561 continue;
562 }
563 if (timed && instant < strategy::bar_period_end(bar, series.interval_, series.stamp_)) {
564 // Counted once per bar, not once per poll: a daily bar is met by every poll of its session.
565 auto& held = held_bar_[instrument.symbol_];
566 if (!held || !(*held == bar.timestamp_)) {
567 held = bar.timestamp_;
568 ++bars_not_yet_closed_;
569 }
570 break;
571 }
572 collected.push_back(
573 Collected{at, strategy::make_bar_event(instrument, series.interval_, series.stamp_, bar), false}
574 );
575 }
576 // **Only the newest bar of an instrument's read may send.** The ones before it -- a cold
577 // start's history, a backlog after an outage -- are history: the strategy is shown them, so its
578 // state evolves as a replay's does, and what it decides on them is discarded
579 // (`Runner::feed_warmup`). Otherwise a restart acts on every signal in its history at today's
580 // price, which for an event-triggered strategy is a trade nobody decided today.
581 if (collected.size() > first) {
582 collected.back().newest_ = true;
583 }
584 }
585
586 std::stable_sort(collected.begin(), collected.end(), [](const Collected& a, const Collected& b) {
587 return a.event_.period_end_ < b.event_.period_end_;
588 });
589 // **And not at or before another instrument's history.** An instrument whose read ends early --
590 // a name suspended today, or for days -- has a newest bar no later than the other names' older
591 // ones; sent there, a cross-sectional strategy would act on a stale cross-section at today's
592 // price. So a newest bar sends only when its period ended strictly after every history bar of the
593 // read; one that did not is history too, and that instrument's decision waits for its next bar.
594 // Strictly: a tie with a history bar is the same stale session whichever name the universe lists
595 // first.
596 std::optional<std::chrono::system_clock::time_point> latest_history;
597 for (const auto& item : collected) {
598 if (!item.newest_ && (!latest_history || *latest_history < item.event_.period_end_)) {
599 latest_history = item.event_.period_end_;
600 }
601 }
602 static_assert(
603 session_source_detail::feeds_warmup<Runner>::value,
604 "SessionSource feeds a read's older bars through Runner::feed_warmup; a runner without it "
605 "would send decisions made on history"
606 );
607 auto outcome = runner::PollOutcome::UPDATED;
608 if (collected.empty()) {
610 }
611 if constexpr (session_source_detail::takes_slices<Runner>::value) {
612 // **One delivery per period end and interval.** The bars are in period-end order, so a period is
613 // complete when a later one starts. Within one read a period is all history or all live (a newest
614 // bar tying a history bar is history), so the whole bucket goes one way.
615 //
616 // **An exception stops the source** (a bar the cache refuses, a handler that throws). The period
617 // being collected may then be partly recorded and partly delivered, and resuming it in a later poll
618 // would have to reconcile it with that poll's history and order; every later poll throws instead,
619 // so nothing is lost or delivered twice in silence. A restart builds a fresh runner and source.
620 strategy::slice_detail::Bucket bucket;
621 bool bucket_is_history = false;
622 try {
623 for (const auto& item : collected) {
624 const auto& instrument = universe_[item.instrument_];
625 const auto& event = item.event_;
626 // **A period already delivered is not reopened.** The bar keeps its own series complete, but an
627 // older bar must not overwrite a newer price or turn the clock back.
628 if (delivered_through_ && !(*delivered_through_ < event.period_end_)) {
629 runner_instance.record_history_only(event);
630 last_bar_[instrument.symbol_] = event.bar_.timestamp_;
631 ++bars_not_delivered_;
632 continue;
633 }
634 if (!bucket.empty() && bucket.period_end() < event.period_end_) {
635 deliver(runner_instance, bucket, bucket_is_history);
636 }
637 if (bucket.holds(event)) {
638 last_bar_[instrument.symbol_] = event.bar_.timestamp_;
639 ++bars_not_delivered_;
640 continue;
641 }
642 const bool history = !item.newest_ || (latest_history && !(*latest_history < event.period_end_));
643 runner_instance.record(event);
644 bucket.add(event);
645 bucket_is_history = history;
646 last_bar_[instrument.symbol_] = event.bar_.timestamp_;
647 if (history) {
648 ++bars_fed_as_warmup_;
649 }
650 }
651 deliver(runner_instance, bucket, bucket_is_history);
652 } catch (const std::exception& error) {
653 interrupted_ = error.what();
654 throw;
655 } catch (...) {
656 interrupted_ = "an unknown exception";
657 throw;
658 }
659 } else {
660 for (const auto& item : collected) {
661 const auto& instrument = universe_[item.instrument_];
662 if (!item.newest_ || (latest_history && !(*latest_history < item.event_.period_end_))) {
663 runner_instance.feed_warmup(item.event_);
664 ++bars_fed_as_warmup_;
665 last_bar_[instrument.symbol_] = item.event_.bar_.timestamp_;
666 continue;
667 }
668 runner_instance.context().set_last_price(instrument, item.event_.bar_.close_);
669 runner_instance.feed(item.event_);
670 last_bar_[instrument.symbol_] = item.event_.bar_.timestamp_;
671 }
672 }
673 last_error_.reset();
674 return outcome;
675 }
676
677 // Delivers one period's slices, one interval at a time, as history or live.
678 template <typename Runner>
679 void deliver(Runner& runner_instance, strategy::slice_detail::Bucket& bucket, bool history) {
680 while (!bucket.empty()) {
681 // **Const, so a runner can only read it.** The delivered slice carries the bucket's table of where each
682 // bar is (`BarSlice::find`); a runner offering an overload for a mutable slice must not be handed this one.
683 const auto slice = bucket.take_first();
684 delivered_through_ = slice.period_end_;
685 if (history) {
686 runner_instance.feed_warmup(slice);
687 } else {
688 runner_instance.feed(slice);
689 }
690 }
691 }
692
693 // Fetches a quote per instrument and feeds each one.
694 template <typename Runner>
695 runner::PollOutcome poll_quotes(Runner& runner_instance) {
696 if (universe_.empty()) {
698 }
699 auto outcome = runner::PollOutcome::UNCHANGED;
700 for (const auto& instrument : universe_) {
701 auto result = market_data_->quote(instrument);
702 if (!result) {
703 last_error_ = result.error();
704 return poll_outcome_of(*last_error_);
705 }
706 strategy::QuoteEvent event;
707 event.quote_ = result.value();
708 runner_instance.feed(event);
710 }
711 last_error_.reset();
712 return outcome;
713 }
714
715 // Refreshes positions, keeping whatever working orders the context already holds.
716 //
717 // The two inquiries are separate calls on their own cadences, so each must merge rather than
718 // replace: rebuilding the portfolio from a holdings snapshot alone would silently drop every
719 // working order, and reconciliation would then place orders it had already placed.
720 template <typename Runner>
721 runner::PollOutcome poll_holdings(Runner& runner_instance) {
722 auto result = session_->holdings();
723 if (!result) {
724 last_error_ = result.error();
725 return poll_outcome_of(*last_error_);
726 }
727 last_error_.reset();
728
729 auto portfolio = runner_instance.context().portfolio();
730 portfolio.positions_ = result.value().positions_;
731 // **The basis travels with the rows it describes, and both directions of leaving it behind are
732 // defects.** Keeping the previous basis would let a snapshot that established nothing be measured
733 // against an older read's declaration -- a third-party source's undeclared figure authorizing a
734 // sell. Dropping it would leave the portfolio unestablished after a broker that *did* declare, so
735 // every checked sell would refuse at both shipped adapters. It is assigned, not merged, for the
736 // same reason `positions_` is: this is one read, and its figures mean what this read says.
737 portfolio.sellable_basis_ = result.value().sellable_basis_;
738 // When the snapshot arrived, which is the best the adapters can do: none gets a time from the
739 // broker for a holdings answer, so `received_at_` is this machine's clock at parse time. The loop's staleness
740 // gate therefore measures time since arrival, and understates the age of the figures by the
741 // request's own latency.
742 portfolio.as_of_ = result.value().received_at_;
743 runner_instance.context().set_portfolio(std::move(portfolio));
745 }
746
747 // Refreshes what may be spent, per configured currency, keeping everything else.
748 //
749 // One request per currency, on the holdings cadence. A currency whose answer fails leaves the
750 // previous reading in place and reports the failure, rather than dropping a figure the guard is
751 // about to size against -- the loop's own staleness gate is what decides when an old reading
752 // stops being good enough, and it can only do that if the reading is still there.
753 template <typename Runner>
754 runner::PollOutcome poll_buying_power(Runner& runner_instance) {
755 if constexpr (!Caps::has_buying_power) {
756 static_cast<void>(runner_instance);
758 } else {
759 if (currencies_.empty()) {
761 }
762 auto portfolio = runner_instance.context().portfolio();
763 bool updated = false;
764 // Kept apart so the winning outcome and the reason reported for it stay the same currency's.
765 std::optional<BrokerError> outright;
766 std::optional<BrokerError> throttled;
767 for (const auto& currency : currencies_) {
768 auto result = session_->buying_power(currency);
769 if (!result) {
770 // **A real failure outranks a rate-limit refusal**, wherever in the sweep each landed.
771 // They are not the same news: the limiter refusing is the limiter working, and the loop
772 // deliberately does not count it against a poll kind, while an outage must count. Taking
773 // whichever came last would let a currency that fails every sweep be reported as merely
774 // throttled the moment another currency was throttled behind it, and the failing budget
775 // would age on unnoticed.
776 //
777 // The reason is kept beside its outcome rather than overwritten, because `last_error()`
778 // promises why the last failing poll failed: reporting `FAILED` next to a rate-limit
779 // reason would send a reader after the wrong currency.
780 if (poll_outcome_of(result.error()) == runner::PollOutcome::FAILED) {
781 if (!outright) {
782 outright = result.error();
783 }
784 } else if (!throttled) {
785 throttled = result.error();
786 }
787 continue;
788 }
789 bool replaced = false;
790 for (auto& reading : portfolio.buying_power_) {
791 if (reading.cash_.currency_ == currency) {
792 reading = result.value();
793 replaced = true;
794 break;
795 }
796 }
797 if (!replaced) {
798 portfolio.buying_power_.push_back(result.value());
799 }
800 updated = true;
801 }
802 if (updated) {
803 runner_instance.context().set_portfolio(std::move(portfolio));
804 }
805 const auto& reason = outright ? outright : throttled;
806 if (reason) {
807 last_error_ = *reason;
808 } else {
809 last_error_.reset();
810 }
811 // **A partial answer is a failed poll**, even though the currencies that answered were still
812 // applied. Reporting `UPDATED` because *something* arrived would reset the loop's consecutive
813 // failure count, and a currency failing every time would then never abandon the run: the loop
814 // would report healthy polls indefinitely while orders in that currency were sized against a
815 // figure from hours ago. The readings are kept because the alternative -- dropping a budget
816 // the guard is about to size against -- is worse, and the staleness gate is what decides when
817 // an old reading stops being good enough. `last_error_` survives for the same reason.
818 if (outright) {
820 }
821 if (throttled) {
822 return poll_outcome_of(*throttled);
823 }
825 }
826 }
827
828 // Refreshes today's permitted price band for each instrument, and records it on the runner.
829 //
830 // The second poll whose result is not an event, and the second that **installs and feeds nothing**
831 // -- `runner::PollKind::PRICE_LIMITS` states that obligation and why it is stated for a poll that
832 // cannot break it. The band lands in `Runner::set_price_limits`, which dates it, and
833 // reconciliation reads it when a plan is built.
834 //
835 // Swept per instrument, with the partial-failure rules `poll_buying_power` argues in full and for
836 // the same reasons: **a real failure outranks a rate-limit refusal** wherever in the sweep each
837 // landed, the reason is kept beside its own outcome so `last_error()` describes the failure it
838 // reports, and **a partial answer is a failed poll** even though the instruments that answered are
839 // still installed.
840 //
841 // **A failure leaves the previous band in place**, as the calendar and the budget both do. Erasing
842 // it would turn a timed-out request into an unclamped order, which is the opposite of the
843 // direction a failure should push; the runner's age policy is what decides when the band that is
844 // still there has stopped being usable, and it can only decide that if it is still there.
845 template <typename Runner>
846 runner::PollOutcome poll_price_limits(Runner& runner_instance) {
847 if constexpr (!MarketData::Caps::has_price_limits) {
848 // A broker that publishes no band compiles no request, and a loop with this cadence set
849 // against one simply never reads a band: the capability is absent, and absent is not faked.
850 static_cast<void>(runner_instance);
852 } else {
853 if (universe_.empty()) {
855 }
856 bool updated = false;
857 std::optional<BrokerError> outright;
858 std::optional<BrokerError> throttled;
859 for (const auto& instrument : universe_) {
860 auto result = market_data_->price_limits(instrument);
861 if (!result) {
862 if (poll_outcome_of(result.error()) == runner::PollOutcome::FAILED) {
863 if (!outright) {
864 outright = result.error();
865 }
866 } else if (!throttled) {
867 throttled = result.error();
868 }
869 continue;
870 }
871 runner_instance.set_price_limits(instrument, std::move(result.value()));
872 updated = true;
873 }
874 const auto& reason = outright ? outright : throttled;
875 if (reason) {
876 last_error_ = *reason;
877 } else {
878 last_error_.reset();
879 }
880 if (outright) {
882 }
883 if (throttled) {
884 return poll_outcome_of(*throttled);
885 }
887 }
888 }
889
890 // Refreshes which dates the market trades, and puts the answer where the loop and a strategy read it.
891 //
892 // The only poll whose result is not an event. It lands in `Context::set_calendar`, from which
893 // `runner::PollingLoop` derives the market phase and a strategy answers "does tomorrow trade" --
894 // one copy, one owner, and no way for the loop and the strategy to be looking at different
895 // calendars.
896 //
897 // `from` is left absent so each broker supplies its own "today", which is today *there*: KIS dates
898 // every request in Korean local time and its traits layer fills that in. Asking with a date derived
899 // from this process's clock would consult the wrong day for the hours either side of local midnight.
900 //
901 // **A failure leaves the previous calendar in place**, exactly as `poll_buying_power` leaves the
902 // previous budget. Erasing it would take a run that knew today was a trading day and make it
903 // `UNKNOWN` because a reference-data request timed out, which refuses every order; the loop's own
904 // reasoning about an uncovered date is what decides when an old answer has stopped being usable,
905 // and it can only do that if the answer is still there.
906 template <typename Runner>
907 runner::PollOutcome poll_calendar(Runner& runner_instance) {
908 if constexpr (!MarketData::Caps::has_calendar) {
909 // A broker that publishes no calendar compiles no request. The loop then never establishes a
910 // phase, which it reports rather than guesses at: the capability is absent, and absent is not
911 // faked.
912 static_cast<void>(runner_instance);
914 } else {
915 auto result = market_data_->calendar(calendar_country_);
916 if (!result) {
917 last_error_ = result.error();
918 return poll_outcome_of(*last_error_);
919 }
920 last_error_.reset();
921 runner_instance.context().set_calendar(std::move(result.value()));
923 }
924 }
925
926 // Accumulates what the broker stated it charged, from one working-order listing.
927 //
928 // **One invariant holds the arithmetic together: what `charged_seen_` holds for a figure is
929 // exactly what has been contributed to the totals for it, and at which filled quantity.** Every
930 // rule below exists to keep that true, and each was a place it was once broken.
931 //
932 // - **A figure is cumulative per order**, so a total moves by the *delta* against what is held
933 // rather than by the whole figure again.
934 // - **A reading that states nothing withdraws nothing**, and does not move the quantity the held
935 // figure belongs to. Silence that advanced the quantity made the next real fee look like a
936 // disagreement about the previous one, and it was dropped.
937 // - **A figure for a quantity this figure has not been accepted at is new information**, whether
938 // the order was silent in between or this is its first figure at all.
939 // - **Two present figures at one quantity are a conflict**, and the held one stands: nothing in a
940 // snapshot says which the broker sent later.
941 // - **An order does not change the currency of its own charge**, so a reading that does is a
942 // conflict rather than a replacement that would strand what was accumulated in the first.
943 // - **Absence is not zero.** An order stating nothing contributes to no currency's total.
944 void observe_charged(const std::vector<OrderSnapshot>& rows) {
945 std::vector<std::string> present;
946 present.reserve(rows.size());
947 for (const auto& row : rows) {
948 present.push_back(row.order_id_);
949 const auto& execution = row.execution_;
950 const auto states_cost = execution.commission_ || execution.tax_;
951
952 auto held = charged_seen_.find(row.order_id_);
953 if (held == charged_seen_.end()) {
954 ObservedCharge fresh;
955 fresh.counted_cost_ = states_cost;
956 charged_seen_.emplace(row.order_id_, std::move(fresh));
957 held = charged_seen_.find(row.order_id_);
958 if (states_cost) {
959 ++charged_.orders_stating_cost_;
960 } else {
961 // Counted once, at first sight, and never taken back when a figure arrives later: both
962 // counters are monotone so that differencing them across runs cannot underflow, and an
963 // order that began without a figure is in both counts by design.
964 ++charged_.orders_stating_none_;
965 }
966 } else if (states_cost && !held->second.counted_cost_) {
967 held->second.counted_cost_ = true;
968 ++charged_.orders_stating_cost_;
969 }
970
971 take_figure(charged_.commission_, held->second.commission_, execution.commission_, execution.filled_quantity_);
972 take_figure(charged_.tax_, held->second.tax_, execution.tax_, execution.filled_quantity_);
973 }
974
975 for (const auto& previous : charged_listing_) {
976 bool still_there = false;
977 for (const auto& id : present) {
978 if (id == previous) {
979 still_there = true;
980 break;
981 }
982 }
983 if (!still_there) {
984 // A row that was there and is not. It says nothing about *why*, and nothing about whether a
985 // charge was missed -- see the field's own documentation.
986 ++charged_.working_list_disappearances_;
987 }
988 }
989 charged_listing_ = std::move(present);
990 }
991
992 // Moves one running total by a new reading, keeping `held` in step with what the total was given.
993 //
994 // `quantity` is how much of the order had filled when the broker stated `now`. A figure is taken
995 // when that exceeds the quantity this figure was last accepted at; at or below it, two present
996 // amounts that differ are a conflict and the held one stands.
997 void take_figure(
998 std::vector<runner::ChargedCosts::StatedTotal>& totals, ObservedFigure& held, const std::optional<Money>& now,
999 const Decimal64& quantity
1000 ) {
1001 if (!now) {
1002 // Silence withdraws nothing, and leaves this figure where it was -- including the quantity it
1003 // belongs to, so a fee arriving later for the filled quantity is still new information.
1004 return;
1005 }
1006 if (!held.amount_) {
1007 if (charged_.add(totals, *now)) {
1008 held.amount_ = now;
1009 held.at_ = quantity;
1010 }
1011 return;
1012 }
1013 if (!(held.amount_->currency_ == now->currency_)) {
1014 // An order does not change the currency of its own charge. Replacing it would strand what was
1015 // accumulated in the first currency and base every later delta on the second.
1016 ++charged_.conflicting_restatements_;
1017 return;
1018 }
1019 if (!decimal_less(held.at_, quantity)) {
1020 if (!(held.amount_->amount_ == now->amount_)) {
1021 // Two present figures for one filled quantity, and nothing says which is later.
1022 ++charged_.conflicting_restatements_;
1023 }
1024 return;
1025 }
1026 const auto moved = decimal_subtract(now->amount_, held.amount_->amount_);
1027 if (!moved) {
1028 // The delta between two figures the broker stated does not fit -- a held five quintillion
1029 // restated at a tenth of a won reaches it. Counted for the same reason a failed sum is: the
1030 // figure is not contributed, and a reader has to be able to see that rather than read the
1031 // total as complete.
1032 ++charged_.unrepresentable_sums_;
1033 return;
1034 }
1035 if (charged_.add(totals, Money{*moved, now->currency_})) {
1036 held.amount_ = now;
1037 held.at_ = quantity;
1038 }
1039 }
1040
1041 // Refreshes working orders, keeping positions. Compiles to nothing without the capability.
1042 template <typename Runner>
1043 runner::PollOutcome poll_working_orders(Runner& runner_instance, bool publish = true) {
1044 if constexpr (Caps::has_working_orders) {
1045 auto result = session_->working_orders();
1046 if (!result) {
1047 last_error_ = result.error();
1048 return poll_outcome_of(*last_error_);
1049 }
1050 last_error_.reset();
1051
1052 auto portfolio = runner_instance.context().portfolio();
1053 portfolio.working_ = result.value().orders_;
1054 // Stamped with the listing, so a plan sized before the next holdings read can tell the account
1055 // is older than the orders it is reconciled with; see `Portfolio::listing_newer_than_holdings`.
1056 portfolio.working_as_of_ = result.value().received_at_;
1057 runner_instance.context().set_portfolio(std::move(portfolio));
1058
1059 // Swept from the rows just fetched, so reconciliation costs no request of its own. A
1060 // `WorkingOrder` carries the normalized snapshot the matcher reads; nothing broker-specific
1061 // reaches it.
1062 std::vector<OrderSnapshot> rows;
1063 rows.reserve(result.value().orders_.size());
1064 for (const auto& working : result.value().orders_) {
1065 rows.push_back(working.order_);
1066 }
1067 // **Observed here because this is where the rows exist.** `Source::poll` hands the loop a
1068 // `PollOutcome` and nothing else, and these rows are swept into reconciliation and dropped --
1069 // so a cost accumulated in the loop could only ever be accumulated from nothing.
1070 observe_charged(rows);
1071 reconcile(runner_instance, rows);
1072
1073 // **Last, and after reconciliation, deliberately.** `Runner::feed` settles, so an order can
1074 // leave the process from inside this call -- and a strategy answering an update must do so
1075 // against the portfolio this poll installed, with reconciliation already done and any local
1076 // failure it raised already standing as a hold. Feeding earlier would let a strategy act on a
1077 // poll whose own conclusions were still being drawn.
1078 //
1079 // `publish` is false only for the startup read; see `read_order_list` for why that is a
1080 // hazard rather than a preference.
1081 //
1082 // **No halt check between updates, which the replay does have, and the asymmetry is the
1083 // point.** A hold here refuses what a strategy *sends* and does not make what the broker
1084 // *said* untrue -- a runner that has stopped trading still wants its handler told that a
1085 // resting order filled. A halted replay is the opposite case: the engine can no longer model
1086 // what it is being asked to, so no callback may run at all.
1087 if (publish) {
1088 for (const auto& update : updates_.changed(result.value().orders_)) {
1089 runner_instance.feed(update);
1090 }
1091 } else {
1092 updates_.adopt(result.value().orders_);
1093 }
1094 // **After** the updates, so a strategy's own `on_order_update` has spoken first. This listing is
1095 // the only thing that sees a stop leave, and a disappearance feeds no callback -- so where a
1096 // deferred target's stops are all gone, the broker's own record of them is read here, on demand,
1097 // and decides it. A failed read leaves the target waiting and reports like any poll failure. See
1098 // `Runner::deferred_targets`.
1099 //
1100 // The same read serves an order this runner sent that only the history can settle now (one a
1101 // listing carried and no longer does, one it withdrew, one restored that no listing carries, one
1102 // past the confirmation timeout, one a sweep named; see `Runner::unconfirmed_awaiting_evidence`). Settled first, so a released target is planned against
1103 // what the history said became of it.
1104 const auto deferred_since = runner_instance.deferred_awaiting_evidence();
1105 const auto unconfirmed_since = runner_instance.unconfirmed_awaiting_evidence();
1106 if (deferred_since || unconfirmed_since) {
1107 const auto since = !deferred_since ?
1108 *unconfirmed_since :
1109 !unconfirmed_since ?
1110 *deferred_since :
1111 std::min(*deferred_since, *unconfirmed_since);
1112 std::vector<OrderSnapshot> evidence;
1113 // Read through the later of the decision instant and the loop's clock, and never before
1114 // `since`: a sent order's `since` is the loop's clock, and on daily bars the decision instant
1115 // is the last session's end -- after a weekend that ended the range before the day the order
1116 // was sent, and the order could never be found.
1117 const auto until = std::max({runner_instance.context().now(), runner_instance.observed_at(), since});
1118 if (!read_evidence(since, until, evidence)) {
1119 return poll_outcome_of(*last_error_);
1120 }
1121 if (unconfirmed_since) {
1122 runner_instance.confirm_from_history(evidence);
1123 }
1124 if (deferred_since) {
1125 runner_instance.retry_deferred(evidence);
1126 }
1127 }
1129 } else {
1130 (void)publish;
1131 // Unreachable through the loop, which never schedules a kind the caller left unset, and a
1132 // caller who sets a cadence for an inquiry this broker lacks gets a poll that does nothing
1133 // rather than a compile error -- the cadence is data, not a capability claim.
1134 (void)runner_instance;
1136 }
1137 }
1138
1139 // Resolves what `rows` settle, leaving withheld whatever they do not.
1140 //
1141 // Does nothing at all without a journal, which is what keeps the pre-existing behaviour exactly
1142 // as it was: a source with no journal reads the list, lifts the gate, and matches nothing.
1143 //
1144 // `now` comes from the runner's own context rather than from the page's `received_at_`. The two
1145 // are different clocks -- the context's is local, like the journal's stamps, and the page's is the
1146 // broker's -- and the matcher already widens for that difference in one place. Measuring the
1147 // window against the broker's clock as well would apply the allowance twice.
1148 //
1149 // A budgeted runner's stopped journal (`Runner::run_writes_closed`) is not written either.
1150 template <typename Runner>
1151 void reconcile(Runner& runner_instance, const std::vector<OrderSnapshot>& rows) {
1152 if (journal_ == nullptr || runner_instance.run_writes_closed()) {
1153 return;
1154 }
1155 const auto& replay = journal_->replay();
1156 const auto open = runner::unresolved_instructions(replay);
1157 if (open.empty()) {
1158 reconcile_ = runner::ReconcileReport{};
1159 } else if (!sweep(runner_instance, replay, open, rows)) {
1160 return;
1161 }
1162 search_again(runner_instance, replay, open, rows);
1163 }
1164
1165 // The instant a sweep measures the matching window against.
1166 //
1167 // The later of the decision instant and the loop's last reading of the wall clock. The decision
1168 // instant alone moves only with bars, quotes and phase changes: on daily bars, or with a stop
1169 // pending, an order that is plainly absent from every listing stayed "not enough time has passed"
1170 // until the next bar, and its instrument stayed withheld. Both have to be wall time on the journal's
1171 // clock: the decision instant comes from a bar's or quote's own time or from the caller, the other
1172 // from whoever drives the runner. One that runs ahead of the journal, or a wall clock set forward,
1173 // shortens the window; nothing here makes the sweep safe against a clock that is wrong.
1174 //
1175 // Before anything was fed and without a loop both are the epoch, as at the startup read after a
1176 // restart. A resolution stamped there reads back as damage and halts the next start, so the wall
1177 // clock stands in.
1178 template <typename Runner>
1179 static std::chrono::system_clock::time_point sweep_instant(const Runner& runner_instance) {
1180 const auto now = std::max(runner_instance.context().now(), runner_instance.observed_at());
1181 return now == std::chrono::system_clock::time_point{} ? std::chrono::system_clock::now() : now;
1182 }
1183
1184 // The journal's own sweep: decides what `rows` settle of `open`. Returns `false` where nothing
1185 // further may be concluded from this read (the history did not arrive, or a resolution could not be
1186 // written).
1187 template <typename Runner>
1188 bool sweep(
1189 Runner& runner_instance, const runner::JournalReplay& replay, const std::vector<runner::OpenInstruction>& open,
1190 const std::vector<OrderSnapshot>& rows
1191 ) {
1192 auto candidates = rows;
1193 if (runner::any_placement(open)) {
1194 // **An open-orders listing cannot answer the placement question.** Each broker's working-order
1195 // inquiry returns only what is still resting -- Toss maps it to its `OPEN` scope, KIS to the
1196 // modifiable set, Kiwoom to its unfilled-order list -- and a market or aggressive limit order can fill and leave that listing
1197 // before the first sweep. Matching against it alone would then find nothing, and after the
1198 // window closed would report `NOT_PLACED` and clear the ledger for an order that existed and
1199 // executed. So a sweep with any placement owed reads the history as well.
1200 //
1201 // Paid for only when something is actually owed, which is rare: the normal sweep still costs
1202 // no request of its own.
1203 std::vector<OrderSnapshot> history;
1204 if (!read_history(open, history)) {
1205 // Seeing part of the picture is worse than seeing none. `NOT_PLACED` is a conclusion drawn
1206 // from absence, and absence from a listing that failed to arrive is not evidence.
1207 reconcile_ = runner::decide_nothing(
1208 open, "the order history could not be read, so nothing could be concluded from absence"
1209 );
1210 return false;
1211 }
1212 if constexpr (Caps::history_requires_range) {
1213 runner::merge_rows(candidates, history);
1214 } else {
1215 // A history that takes no range (Kiwoom reads one date at a time, Toss a cursor); see
1216 // `runner::merge_dated_history`.
1217 runner::merge_dated_history(candidates, history);
1218 }
1219 }
1220
1221 // The line says what was found; this says what was read, and what the runner then does about it.
1222 const auto note = runner_instance.serialized() ?
1223 std::string_view(
1224 " (the order list and the order history of its send); that does not establish that no order was "
1225 "placed, and a serialized runner keeps the order owed until dated evidence accounts for it or an "
1226 "operator releases it (Runner::release_obligations)"
1227 ) :
1228 std::string_view(
1229 " (the order list and the order history of its send); that does not establish that no order was "
1230 "placed"
1231 );
1232 const auto now = sweep_instant(runner_instance);
1233 if (runner_instance.guard().limits().run_budget_) {
1234 // A budgeted run's sweep stops at its first failed append, which stops the runner's writes too.
1235 RunJournalWrites<Runner> writes{journal_, &runner_instance};
1236 reconcile_ =
1237 runner::reconcile_against(open, candidates, replay, now, runner_instance.ledger(), writes, window_, note);
1238 } else {
1239 reconcile_ =
1240 runner::reconcile_against(open, candidates, replay, now, runner_instance.ledger(), *journal_, window_, note);
1241 }
1242 if (reconcile_.unrecorded_) {
1243 // The sweep decided, and the decision could not be written down. Trading on a resolution that
1244 // exists only in memory is how a restart re-opens a question that was already answered -- and
1245 // a journal that cannot be written will not manage the next order either.
1246 runner_instance.halt_locally("the order journal could not record a reconciliation, so the hold stands");
1247 return false;
1248 }
1249 // **A placement whose reply was lost, now answered**: the runner has counted it since the
1250 // send, and keeps counting a matched one until holdings show it -- the ledger, just cleared, no
1251 // longer withholds the instrument, and a filled market order is in no listing.
1252 for (const auto& match : reconcile_.matches_) {
1253 if (match.verdict_ != runner::MatchVerdict::MATCHED && match.verdict_ != runner::MatchVerdict::NOT_PLACED) {
1254 continue;
1255 }
1256 for (const auto& instruction : open) {
1257 if (instruction.entry_.id_ != match.entry_id_ || instruction.entry_.action_ != runner::JournalAction::PLACE) {
1258 continue;
1259 }
1260 runner_instance.resolve_indeterminate_placement(
1261 instruction.entry_.instrument_, instruction.entry_.side_,
1262 match.verdict_ == runner::MatchVerdict::MATCHED ? std::optional<std::string>(match.order_id_) : std::nullopt,
1263 instruction.entry_.id_
1264 );
1265 break;
1266 }
1267 }
1268 return true;
1269 }
1270
1271 // Looks again for the placements a serialized runner still owes without a name after a sweep closed
1272 // the journal's question about them (`Runner::serialized`): a row can reach the broker's lists after
1273 // that sweep, and nothing else would ever name the order.
1274 //
1275 // Positive evidence only. A row must be dated inside the send's window to count, since this runs for
1276 // as long as the order is owed and an undated row of the same shape may be another day's order; and a
1277 // row that could be another placement's as well (an order of the same shape sent just before or after,
1278 // whatever number the journal has for it) is nobody's here. Anything but one row left changes nothing
1279 // and writes nothing: no order is forgotten here.
1280 template <typename Runner>
1281 void search_again(
1282 Runner& runner_instance, const runner::JournalReplay& replay, const std::vector<runner::OpenInstruction>& open,
1283 const std::vector<OrderSnapshot>& rows
1284 ) {
1285 if (!runner_instance.serialized()) {
1286 return;
1287 }
1288 std::vector<std::string> ids;
1289 for (const auto& owed : runner_instance.obligations()) {
1290 const bool still_open = std::any_of(open.begin(), open.end(), [&](const runner::OpenInstruction& instruction) {
1291 return instruction.entry_.id_ == owed.journal_id_;
1292 });
1293 if (owed.state_ == runner::ObligationState::UNNAMED && !owed.journal_id_.empty() && !still_open) {
1294 ids.push_back(owed.journal_id_);
1295 }
1296 }
1297 const auto late = runner::placements_of(replay, ids);
1298 if (late.empty()) {
1299 return;
1300 }
1301 std::vector<OrderSnapshot> history;
1302 if (!read_history(late, history)) {
1303 return;
1304 }
1305 // Undated rows go before the two lists are merged: a listing row with no date (KIS real dates none)
1306 // would otherwise stand in for the dated history row of the same order, and then be set aside.
1307 const auto dated = [](std::vector<OrderSnapshot> all) {
1308 all.erase(
1309 std::remove_if(
1310 all.begin(), all.end(),
1311 [](const OrderSnapshot& row) {
1312 return !row.ordered_at_;
1313 }
1314 ),
1315 all.end()
1316 );
1317 return all;
1318 };
1319 auto candidates = dated(rows);
1320 runner::merge_dated_history(candidates, dated(history));
1321 // A listing row whose day the history did not establish is undated here too.
1322 candidates.erase(
1323 std::remove_if(
1324 candidates.begin(), candidates.end(),
1325 [](const OrderSnapshot& row) {
1326 return row.ordered_date_assumed_;
1327 }
1328 ),
1329 candidates.end()
1330 );
1331 runner::drop_rows_fitting_another_placement(candidates, replay, late, window_);
1332 const auto now = sweep_instant(runner_instance);
1333 for (const auto& instruction : late) {
1334 const auto match = runner::match_against(instruction, candidates, now, window_);
1335 if (match.verdict_ != runner::MatchVerdict::MATCHED) {
1336 continue;
1337 }
1338 // Written before the runner hears of it, as every resolution is: a restart restores the name.
1339 if (runner_instance.run_writes_closed()) {
1340 return;
1341 }
1342 if (!journal_->append(runner::resolution_entry(instruction, match, now))) {
1343 runner_instance.note_run_journal_write_failed();
1344 runner_instance.halt_locally("the order journal could not record a reconciliation, so the hold stands");
1345 return;
1346 }
1347 runner_instance.resolve_indeterminate_placement(
1348 instruction.entry_.instrument_, instruction.entry_.side_, std::optional<std::string>(match.order_id_),
1349 instruction.entry_.id_
1350 );
1351 // The ledger: what may have marked the instrument meanwhile is this order's own timeout, which a
1352 // named order does not carry. Lifted unless this sweep left something undecided on the instrument,
1353 // or the runner still owes there an order no sweep named or one held for an operator.
1354 const auto& withheld = reconcile_.withheld_;
1355 if (
1356 std::find(withheld.begin(), withheld.end(), match.instrument_) == withheld.end() &&
1357 runner_instance.obligation_state(match.instrument_) == runner::ObligationState::NAMED
1358 ) {
1359 runner_instance.ledger().resolve_after_reading_orders(match.instrument_);
1360 }
1361 }
1362 }
1363
1364 // Fills `into` with the order history covering everything `open` could have reached the broker in.
1365 //
1366 // Returns whether the whole range was read. A partial read is a failure, not a smaller success,
1367 // because every row this misses is one the matcher will count as absent.
1368 //
1369 // Both broker differences are handled here rather than pushed onto the caller: a calendar range
1370 // where the broker requires one, and cursor paging where the broker offers one. The page cap is a
1371 // guard against a cursor that never terminates, and exhausting it is reported as a failure for the
1372 // same reason -- a truncated listing is a listing with holes in it.
1373 bool read_history(const std::vector<runner::OpenInstruction>& all, std::vector<OrderSnapshot>& into) {
1374 // **An operator-only instruction sets no bound.** A sweep cannot resolve it, and one salvaged from a
1375 // torn line carries no time, which reads as the epoch: counted, it would ask for every day since 1970.
1376 std::vector<runner::OpenInstruction> open;
1377 for (const auto& instruction : all) {
1378 if (!instruction.entry_.requires_operator_) {
1379 open.push_back(instruction);
1380 }
1381 }
1382 if (open.empty()) {
1383 return true;
1384 }
1385 if constexpr (Caps::history_requires_range) {
1386 return read_history_in(runner::history_range_for(open, window_), into);
1387 } else {
1388 // **One stated date at a time** for a broker whose history takes a single date -- Kiwoom's
1389 // `kt00007` requires it and refuses a range, so an undated sweep failed every time and a journalled
1390 // Kiwoom runner could resolve nothing. The days are the ones `history_range_for` spans: a day
1391 // either side of the instructions' own window, in UTC, which contains every market-local day.
1392 auto earliest = open.front().opened_at_;
1393 auto latest = runner::instruction_sent_by(open.front(), window_);
1394 for (const auto& instruction : open) {
1395 if (instruction.opened_at_ < earliest) {
1396 earliest = instruction.opened_at_;
1397 }
1398 const auto sent_by = runner::instruction_sent_by(instruction, window_);
1399 if (sent_by > latest) {
1400 latest = sent_by;
1401 }
1402 }
1403 return read_history_days(earliest, latest, into);
1404 }
1405 }
1406
1407 // Reads the history one stated date at a time, for every UTC day from the day before `from` to the
1408 // day after `to`: a broker's order date is its own market's, and that span contains it.
1409 bool read_history_days(
1410 std::chrono::system_clock::time_point from, std::chrono::system_clock::time_point to,
1411 std::vector<OrderSnapshot>& into
1412 ) {
1413 std::vector<Date> days;
1414 const auto add = [&days](const Date& day) {
1415 for (const auto& seen : days) {
1416 if (seen.year_ == day.year_ && seen.month_ == day.month_ && seen.day_ == day.day_) {
1417 return;
1418 }
1419 }
1420 days.push_back(day);
1421 };
1422 const auto until = to + std::chrono::hours(24);
1423 for (auto at = from - std::chrono::hours(24); at < until; at += std::chrono::hours(24)) {
1424 add(runner::date_of(at));
1425 }
1426 add(runner::date_of(until));
1427 // Pages are concatenated, dropping only an **exact** copy -- the same id and instrument with the
1428 // same order time stated on both. Two days' orders can share a number, so the id alone is not
1429 // identity, and a row with no time is never assumed to be another's copy. See
1430 // `runner::merge_dated_history`.
1431 for (const auto& day : days) {
1432 std::vector<OrderSnapshot> page;
1433 if (!read_history_in({day, day}, page, true)) {
1434 return false;
1435 }
1436 for (const auto& row : page) {
1437 bool copy = false;
1438 for (const auto& held : into) {
1439 if (same_history_row(held, row)) {
1440 copy = true;
1441 break;
1442 }
1443 }
1444 if (!copy) {
1445 into.push_back(row);
1446 }
1447 }
1448 }
1449 return true;
1450 }
1451
1452 // Fills `into` with the history a deferred target's stops can appear in: from the day before it was
1453 // deferred to today.
1454 //
1455 // **Two query shapes, because the brokers that hold stops disagree.** KIS takes a range
1456 // (`history_requires_range`), so one query covers it. Kiwoom's `kt00007` takes **one** date, which it
1457 // requires, and refuses a range -- so each day is asked for on its own, from the day before the
1458 // deferral (or the send) to the day after now, both in UTC so the market-local day is always inside:
1459 // three or four requests within a week, six across a weekend on daily bars, repeated on each listing
1460 // poll while an entry waits. A broker taking neither shape is asked each day as well, which states a
1461 // date it may ignore rather than omitting one it may need.
1462 bool read_evidence(
1463 std::chrono::system_clock::time_point since, std::chrono::system_clock::time_point now,
1464 std::vector<OrderSnapshot>& into
1465 ) {
1466 if constexpr (Caps::history_requires_range) {
1467 return read_history_in(
1468 {runner::date_of(since - std::chrono::hours(24)), runner::date_of(now + std::chrono::hours(24))}, into
1469 );
1470 } else {
1471 // **Through the day after `now` in UTC**, the same upper bound as the ranged query. `date_of` is a
1472 // UTC date and a broker's order date is its own market's: at 08:45 KST it is still the previous
1473 // day in UTC, and stopping at `date_of(now)` never asked for the Korean day the stop was on.
1474 return read_history_days(since, now, into);
1475 }
1476 }
1477
1478 // Fills `into` with the order history over `range` where the broker takes one, or wherever `dated`
1479 // asks for the dates to be stated regardless; see `read_history`.
1480 bool read_history_in(
1481 const std::pair<Date, Date>& range, std::vector<OrderSnapshot>& into, bool dated = Caps::history_requires_range
1482 ) {
1483 OrderHistoryQuery query;
1484 if constexpr (Caps::has_history_limit) {
1485 // Gated, because KIS does not ignore a limit it cannot honour -- it refuses the whole inquiry
1486 // with `limit_unsupported`. An ungated assignment here made every KIS placement sweep take the
1487 // history-failure branch, so a KIS runner recovered nothing and withheld forever.
1488 query.limit_ = history_limit_;
1489 }
1490 if (dated) {
1491 query.from_ = range.first;
1492 query.to_ = range.second;
1493 }
1494
1495 for (int page = 0; page < maximum_history_pages_; ++page) {
1496 auto result = session_->order_history(query);
1497 if (!result) {
1498 last_error_ = result.error();
1499 return false;
1500 }
1501 // A row already read is dropped only as an exact copy (`same_history_row`): a range spans days,
1502 // and two days' orders can share a number.
1503 for (const auto& row : result.value().orders_) {
1504 bool copy = false;
1505 for (const auto& held : into) {
1506 if (same_history_row(held, row)) {
1507 copy = true;
1508 break;
1509 }
1510 }
1511 if (!copy) {
1512 into.push_back(row);
1513 }
1514 }
1515 const bool more = result.value().next_cursor_ && !result.value().next_cursor_->empty();
1516 if (!more) {
1517 return true;
1518 }
1519 if constexpr (Caps::has_history_cursor) {
1520 query.cursor_ = result.value().next_cursor_;
1521 } else {
1522 // The page says there is more and this adapter cannot ask for it. Reading what arrived as the
1523 // whole history would conclude an order absent that may be on the next page.
1524 last_error_ = history_not_continued();
1525 return false;
1526 }
1527 }
1528 // Every `false` carries an error about this read: a caller reports `*last_error_`.
1529 last_error_ = history_page_limit(maximum_history_pages_);
1530 return false;
1531 }
1532
1533 // Whether two history rows are the same report of one order: `runner::exact_copy`, and the same status
1534 // and filled quantity. Two reads that disagree about an order are both kept, so whoever reads them
1535 // sees the disagreement rather than whichever came first.
1536 static bool same_history_row(const OrderSnapshot& a, const OrderSnapshot& b) {
1537 return runner::exact_copy(a, b) && a.status_ == b.status_ &&
1538 !decimal_less(a.execution_.filled_quantity_, b.execution_.filled_quantity_) &&
1539 !decimal_less(b.execution_.filled_quantity_, a.execution_.filled_quantity_);
1540 }
1541
1542 Session* session_;
1543 MarketData* market_data_;
1544 std::vector<InstrumentId> universe_;
1545 std::vector<Currency> currencies_;
1546 // What the broker has stated it charged, across every run made against this source.
1547 runner::ChargedCosts charged_;
1548 // The last accepted reading per order id, so a cumulative figure is not added twice.
1549 std::map<std::string, ObservedCharge> charged_seen_;
1550 // The order ids in the previous working-order listing, for the disappearance diagnostic.
1551 std::vector<std::string> charged_listing_;
1552 Country calendar_country_{Country::KR};
1553 // The journal a budgeted runner's sweep appends through: it refuses every append once the runner's writes are
1554 // closed, and closes them at a failed one, so the sweep writes nothing after it (`Runner::run_writes_closed`).
1555 template <typename Runner>
1556 struct RunJournalWrites {
1557 Journal* journal_;
1558 Runner* runner_;
1559 bool append(const runner::JournalEntry& entry) {
1560 if (runner_->run_writes_closed()) {
1561 return false;
1562 }
1563 if (journal_->append(entry)) {
1564 return true;
1565 }
1566 runner_->note_run_journal_write_failed();
1567 return false;
1568 }
1569 };
1570
1571 Journal* journal_{nullptr};
1572 int maximum_history_pages_{20};
1573 runner::MatchWindow window_;
1574 runner::ReconcileReport reconcile_;
1575 // Turns successive working-order listings into `on_order_update` events.
1576 runner::OrderUpdateWatch<BrokerTag> updates_;
1577 BarInterval interval_{BarInterval::ONE_DAY};
1578 int count_{100};
1579 std::size_t bars_not_yet_closed_{0};
1580 std::size_t bars_fed_as_warmup_{0};
1581 // For a strategy declaring `on_bars`: bars not delivered (a period already delivered, or a second bar
1582 // of one instrument in a period), and the last period end delivered, over the source's life.
1583 std::size_t bars_not_delivered_{0};
1584 std::optional<std::chrono::system_clock::time_point> delivered_through_;
1585 // Set by an exception during a bar poll for `on_bars`; every later bar poll then throws.
1586 std::optional<std::string> interrupted_;
1587 std::map<std::string, std::optional<std::chrono::system_clock::time_point>> held_bar_;
1588 int history_limit_{100};
1589 std::map<std::string, std::optional<std::chrono::system_clock::time_point>> last_bar_;
1590 std::optional<BrokerError> last_error_;
1591};
1592
1593} // namespace live
1594} // namespace algotradelib
An exact signed decimal: an int64 coefficient times 10^-scale.
Definition types.hpp:443
std::size_t bars_not_delivered() const noexcept
Returns how many bars a strategy declaring on_bars was not shown.
SessionSource(Session &session, std::vector< InstrumentId > universe)
Constructs a source that reads everything from one session.
SessionSource(Session &session, MarketData &market_data, std::vector< InstrumentId > universe)
Constructs a source that reads market data from a second session.
typename Session::Caps Caps
The broker's capabilities, from the account session.
const runner::ChargedCosts & charged_costs() const noexcept
Returns the commission and tax the broker stated on the orders this source has seen.
std::size_t bars_fed_as_warmup() const noexcept
Returns how many bars were fed as history (Runner::feed_warmup), so their decisions were discarded.
runner::PollOutcome read_order_list(Runner &runner_instance)
Reads the broker's order list once, which lifts PollingLoop's startup hold.
const runner::ReconcileReport & last_reconcile() const noexcept
Returns what the last check against the journal resolved and left unresolved.
runner::PollOutcome poll(runner::PollKind kind, Runner &runner_instance)
Polls one kind of data and feeds or installs what arrived in the runner.
typename Session::BrokerTag BrokerTag
The broker tag, from the account session.
void set_buying_power_currencies(std::vector< Currency > currencies)
Sets the currencies a buying-power poll asks about (one request per currency).
void set_match_window(runner::MatchWindow window)
Sets the tolerance used to match listed orders to journal entries without a broker reference.
void set_calendar_country(Country country)
Sets the market whose trading calendar the calendar poll asks for (Country::KR by default).
static constexpr bool provides_working_orders
true if an order-list read installs the broker's working orders in the portfolio.
void set_journal(Journal &journal)
Sets the journal each order listing is checked against.
const std::vector< Currency > & buying_power_currencies() const noexcept
Returns the buying-power currencies; with RiskLimits::enforce_buying_power_ on, the loop holds placem...
static constexpr bool states_calendar_sessions
true if the market-data session's adapter fills each open day's session hours in the calendar it inst...
const std::optional< BrokerError > & last_error() const noexcept
Returns the error recorded by the most recent failing read.
std::size_t bars_not_yet_closed() const noexcept
Returns how many bars were left for a later poll because their period had not ended.
void set_bar_query(BarInterval interval, int count)
Sets the bars each poll requests.
static constexpr bool reports_buying_power
true if the trading session's broker reports buying power (BrokerCaps::has_buying_power).
Country calendar_country() const noexcept
Returns the market the calendar poll asks about.
Connects a runner to a broker session for live trading.
Definition bind.hpp:12
BrokerError history_not_continued()
Makes the incomplete-history error for a broker whose adapter cannot read a further page (has_history...
BrokerError incomplete_history(std::string code, std::string message)
Makes the error an order-history read reports when the history is incomplete (a page said there is mo...
BrokerError history_page_limit(int pages)
Makes the incomplete-history error for a history longer than the page limit.
runner::PollOutcome poll_outcome_of(const BrokerError &error) noexcept
Classifies a failed inquiry for a poll.
@ NOT_PLACED
No row corresponds and the window has closed: no order was found.
@ MATCHED
Exactly one row corresponds; the order exists.
void merge_rows(std::vector< OrderSnapshot > &into, const std::vector< OrderSnapshot > &rows)
Adds rows to a listing, skipping any whose order id is already there.
Date date_of(std::chrono::system_clock::time_point at)
Returns the UTC calendar date of an instant.
bool any_placement(const std::vector< OpenInstruction > &open)
Tests whether any instruction is a placement a listing could decide (which needs history,...
void merge_dated_history(std::vector< OrderSnapshot > &into, const std::vector< OrderSnapshot > &rows)
Adds history rows to a working-order listing, dropping established copies (exact_copy) and listing ro...
ReconcileReport decide_nothing(const std::vector< OpenInstruction > &open, std::string detail)
Makes a report that decides nothing, for a sweep that could not see a complete listing.
std::pair< Date, Date > history_range_for(const std::vector< OpenInstruction > &open, const MatchWindow &window)
Returns the date range an order-history inquiry must cover for some instructions.
std::chrono::system_clock::time_point instruction_sent_by(const OpenInstruction &instruction, const MatchWindow &window)
Returns the last instant an instruction could have reached the broker.
PollKind
What a PollingLoop polls for; each has a cadence in PollSchedule.
Definition loop.hpp:31
@ WORKING_ORDERS
Working orders, which reconciliation and cancellation need.
Definition loop.hpp:39
@ BARS
Completed bars.
Definition loop.hpp:33
@ PRICE_LIMITS
Today's price bands, which an aggressive limit price is clamped to; polled second,...
Definition loop.hpp:59
@ HOLDINGS
Holdings, which orders are sized against.
Definition loop.hpp:37
@ QUOTES
Current quotes, for strategies that act between bars.
Definition loop.hpp:35
@ CALENDAR
The trading calendar, from which the loop derives the market phase; polled first, and on by default.
Definition loop.hpp:50
@ BUYING_POWER
Buying power, polled beside holdings (not before each order).
Definition loop.hpp:41
@ DATA
Records for a strategy's on_data, from the data poll PollingLoop::set_data_poll installs; never from ...
Definition loop.hpp:66
PollOutcome
What became of one poll.
Definition loop.hpp:134
@ RATE_LIMITED
The rate limiter refused the poll; not counted as a failure.
Definition loop.hpp:142
@ UNCHANGED
The poll succeeded and there was nothing new.
Definition loop.hpp:138
@ FAILED
The poll failed; counted toward the failure budget.
Definition loop.hpp:140
@ UPDATED
New data arrived and was fed to the runner, or installed in it (a calendar, price bands).
Definition loop.hpp:136
void drop_rows_fitting_another_placement(std::vector< OrderSnapshot > &rows, const JournalReplay &replay, const std::vector< OpenInstruction > &matching, const MatchWindow &window={})
Removes the rows that could be another placement's order as well.
OrderMatch match_against(const OpenInstruction &instruction, const std::vector< OrderSnapshot > &rows, const std::vector< OpenInstruction > &recorded, std::chrono::system_clock::time_point now, const MatchWindow &window={})
Decides what a broker listing says about one instruction of unknown outcome.
ReconcileReport reconcile_against(const std::vector< OpenInstruction > &open, const std::vector< OrderSnapshot > &rows, const JournalReplay &replay, std::chrono::system_clock::time_point now, IndeterminacyLedger &ledger, Journal &journal, const MatchWindow &window={}, std::string_view unplaced_note={})
Resolves what a broker listing settles, records it in the journal, and clears the ledger for each ins...
JournalEntry resolution_entry(const OpenInstruction &instruction, const OrderMatch &match, std::chrono::system_clock::time_point now)
Makes the RESOLVED journal line that records a sweep's verdict.
std::vector< OpenInstruction > placements_of(const JournalReplay &replay, const std::vector< std::string > &ids)
Returns the placements with the given journal ids, each with the span in which it may have reached th...
Definition journal.hpp:732
std::vector< OpenInstruction > unresolved_instructions(const JournalReplay &replay)
Lists the instructions whose outcome is unknown, in the order they were opened.
Definition journal.hpp:673
bool exact_copy(const OrderSnapshot &a, const OrderSnapshot &b)
Tests whether two rows are established copies of one order: the same order id and instrument,...
@ NAMED
An order the broker named, waiting for its history and holdings to account for it.
@ UNNAMED
An order whose existence is unknown (its reply was lost and no sweep named it).
void bar(S &strategy, Ctx &context, const BarEvent &event)
Calls strategy.on_bar(context, event) if the strategy declares on_bar; otherwise does nothing.
Definition concept.hpp:282
BarEvent make_bar_event(InstrumentId instrument, BarInterval interval, BarStamp stamp, Bar bar)
Makes a bar event, computing its period_end_ with bar_period_end.
Definition event.hpp:380
std::chrono::system_clock::time_point bar_period_end(const Bar &bar, BarInterval interval, BarStamp stamp)
Computes the instant a bar's period ended.
Definition event.hpp:343
The library: broker-neutral types (core), and the modules below.
@ CLOSE
The timestamp is the instant the period ended.
constexpr std::optional< std::chrono::seconds > bar_interval_length(BarInterval interval) noexcept
Returns an interval's fixed length, for an intraday interval.
@ PROTOCOL
The reply could not be read, or the broker declared a failure this client does not classify further: ...
Definition types.hpp:965
constexpr bool error_category_is_rate_limit(ErrorCategory category) noexcept
Tests whether an error of this category is a broker asking the caller to slow down,...
Definition types.hpp:983
Country
A country (market) the library supports.
Definition types.hpp:32
std::optional< Decimal64 > decimal_subtract(const Decimal64 &lhs, const Decimal64 &rhs)
Subtracts two decimals exactly.
Definition types.hpp:783
bool decimal_less(const Decimal64 &lhs, const Decimal64 &rhs)
Compares two decimals numerically, whatever their scales.
Definition types.hpp:926
BarInterval
The period one bar covers.
The error a broker or transport operation returns.
Definition types.hpp:1003
std::string message_
A human-readable description, for logs; do not parse it.
Definition types.hpp:1033
ErrorCategory category_
The kind of failure; the field to branch on.
Definition types.hpp:1005
std::string broker_code_
The broker's own error code, verbatim (for example KIS's EGW00201).
Definition types.hpp:1022
bool reached_broker_
Whether a request was sent before this error.
Definition types.hpp:1014
The filter for an order-history inquiry.
Definition types.hpp:2617
std::optional< int > limit_
The most rows to return, where the broker supports a limit.
Definition types.hpp:2627
std::optional< std::string > cursor_
A previous page's next_cursor_, passed back unchanged.
Definition types.hpp:2625
One order's stated charges, as last recorded.
bool counted_cost_
Whether this order was already counted as one that states a cost.
One charge figure of one order, and the filled quantity it was recorded at.
std::optional< Money > amount_
The amount the broker stated, empty until it states one.
Decimal64 at_
The filled quantity amount_ was recorded at.
Commission and tax the broker stated on the orders a loop happened to poll (Toss states them; KIS doe...
Definition loop.hpp:379
The time allowances used when matching journalled instructions against a broker listing.
What one sweep of the broker's order list settled, and what is still withheld.