177 using Caps =
typename Session::Caps;
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>"
220 : session_(&session), market_data_(&session), universe_(std::move(universe)) {}
229 SessionSource(Session& session, MarketData& market_data, std::vector<InstrumentId> universe)
230 : session_(&session), market_data_(&market_data), universe_(std::move(universe)) {}
270 currencies_ = std::move(currencies);
290 return bars_not_yet_closed_;
299 return bars_fed_as_warmup_;
314 return bars_not_delivered_;
323 interval_ = interval;
336 calendar_country_ = country;
344 return calendar_country_;
356 const std::optional<BrokerError>&
last_error() const noexcept {
378 template <
typename Runner>
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);
414 template <
typename Runner>
416 if constexpr (Caps::has_working_orders) {
427 return poll_working_orders(runner_instance,
false);
430 if constexpr (Caps::has_history_limit) {
432 query.
limit_ = history_limit_;
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);
442 last_error_ = result.error();
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();
450 }
else if constexpr (Caps::has_history_cursor) {
451 query.
cursor_ = result.value().next_cursor_;
464 reconcile(runner_instance, rows);
486 template <
typename Runner>
488 if constexpr (session_source_detail::takes_slices<Runner>::value) {
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"
499 if (universe_.empty()) {
509 std::size_t instrument_{0};
510 strategy::BarEvent event_;
513 std::vector<Collected> collected;
514 for (std::size_t at = 0; at < universe_.size(); ++at) {
515 const auto& instrument = universe_[at];
517 query.instrument_ = instrument;
518 query.interval_ = interval_;
519 query.count_ = count_;
521 auto result = market_data_->bars(query);
523 last_error_ = result.error();
526 const auto& series = result.value();
527 if (series.bars_.empty()) {
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 ||
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) {
565 auto& held = held_bar_[instrument.symbol_];
566 if (!held || !(*held ==
bar.timestamp_)) {
567 held =
bar.timestamp_;
568 ++bars_not_yet_closed_;
581 if (collected.size() > first) {
582 collected.back().newest_ =
true;
586 std::stable_sort(collected.begin(), collected.end(), [](
const Collected& a,
const Collected& b) {
587 return a.event_.period_end_ < b.event_.period_end_;
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_;
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"
608 if (collected.empty()) {
611 if constexpr (session_source_detail::takes_slices<Runner>::value) {
620 strategy::slice_detail::Bucket bucket;
621 bool bucket_is_history =
false;
623 for (
const auto& item : collected) {
624 const auto& instrument = universe_[item.instrument_];
625 const auto&
event = item.event_;
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_;
634 if (!bucket.empty() && bucket.period_end() < event.period_end_) {
635 deliver(runner_instance, bucket, bucket_is_history);
637 if (bucket.holds(event)) {
638 last_bar_[instrument.symbol_] =
event.bar_.timestamp_;
639 ++bars_not_delivered_;
642 const bool history = !item.newest_ || (latest_history && !(*latest_history <
event.period_end_));
643 runner_instance.record(event);
645 bucket_is_history = history;
646 last_bar_[instrument.symbol_] =
event.bar_.timestamp_;
648 ++bars_fed_as_warmup_;
651 deliver(runner_instance, bucket, bucket_is_history);
652 }
catch (
const std::exception& error) {
653 interrupted_ = error.what();
656 interrupted_ =
"an unknown exception";
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_;
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_;
678 template <
typename Runner>
679 void deliver(Runner& runner_instance, strategy::slice_detail::Bucket& bucket,
bool history) {
680 while (!bucket.empty()) {
683 const auto slice = bucket.take_first();
684 delivered_through_ = slice.period_end_;
686 runner_instance.feed_warmup(slice);
688 runner_instance.feed(slice);
694 template <
typename Runner>
696 if (universe_.empty()) {
700 for (
const auto& instrument : universe_) {
701 auto result = market_data_->quote(instrument);
703 last_error_ = result.error();
706 strategy::QuoteEvent event;
707 event.quote_ = result.value();
708 runner_instance.feed(event);
720 template <
typename Runner>
722 auto result = session_->holdings();
724 last_error_ = result.error();
729 auto portfolio = runner_instance.context().portfolio();
730 portfolio.positions_ = result.value().positions_;
737 portfolio.sellable_basis_ = result.value().sellable_basis_;
742 portfolio.as_of_ = result.value().received_at_;
743 runner_instance.context().set_portfolio(std::move(portfolio));
753 template <
typename Runner>
755 if constexpr (!Caps::has_buying_power) {
756 static_cast<void>(runner_instance);
759 if (currencies_.empty()) {
762 auto portfolio = runner_instance.context().portfolio();
763 bool updated =
false;
765 std::optional<BrokerError> outright;
766 std::optional<BrokerError> throttled;
767 for (
const auto& currency : currencies_) {
768 auto result = session_->buying_power(currency);
782 outright = result.error();
784 }
else if (!throttled) {
785 throttled = result.error();
789 bool replaced =
false;
790 for (
auto& reading : portfolio.buying_power_) {
791 if (reading.cash_.currency_ == currency) {
792 reading = result.value();
798 portfolio.buying_power_.push_back(result.value());
803 runner_instance.context().set_portfolio(std::move(portfolio));
805 const auto& reason = outright ? outright : throttled;
807 last_error_ = *reason;
845 template <
typename Runner>
847 if constexpr (!MarketData::Caps::has_price_limits) {
850 static_cast<void>(runner_instance);
853 if (universe_.empty()) {
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);
864 outright = result.error();
866 }
else if (!throttled) {
867 throttled = result.error();
871 runner_instance.set_price_limits(instrument, std::move(result.value()));
874 const auto& reason = outright ? outright : throttled;
876 last_error_ = *reason;
906 template <
typename Runner>
908 if constexpr (!MarketData::Caps::has_calendar) {
912 static_cast<void>(runner_instance);
915 auto result = market_data_->calendar(calendar_country_);
917 last_error_ = result.error();
921 runner_instance.context().set_calendar(std::move(result.value()));
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_;
952 auto held = charged_seen_.find(row.order_id_);
953 if (held == charged_seen_.end()) {
956 charged_seen_.emplace(row.order_id_, std::move(fresh));
957 held = charged_seen_.find(row.order_id_);
959 ++charged_.orders_stating_cost_;
964 ++charged_.orders_stating_none_;
966 }
else if (states_cost && !held->second.counted_cost_) {
967 held->second.counted_cost_ =
true;
968 ++charged_.orders_stating_cost_;
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_);
975 for (
const auto& previous : charged_listing_) {
976 bool still_there =
false;
977 for (
const auto&
id : present) {
978 if (
id == previous) {
986 ++charged_.working_list_disappearances_;
989 charged_listing_ = std::move(present);
998 std::vector<runner::ChargedCosts::StatedTotal>& totals,
ObservedFigure& held,
const std::optional<Money>& now,
999 const Decimal64& quantity
1006 if (!held.amount_) {
1007 if (charged_.add(totals, *now)) {
1009 held.at_ = quantity;
1013 if (!(held.amount_->currency_ == now->currency_)) {
1016 ++charged_.conflicting_restatements_;
1020 if (!(held.amount_->amount_ == now->amount_)) {
1022 ++charged_.conflicting_restatements_;
1032 ++charged_.unrepresentable_sums_;
1035 if (charged_.add(totals, Money{*moved, now->currency_})) {
1037 held.at_ = quantity;
1042 template <
typename Runner>
1044 if constexpr (Caps::has_working_orders) {
1045 auto result = session_->working_orders();
1047 last_error_ = result.error();
1050 last_error_.reset();
1052 auto portfolio = runner_instance.context().portfolio();
1053 portfolio.working_ = result.value().orders_;
1056 portfolio.working_as_of_ = result.value().received_at_;
1057 runner_instance.context().set_portfolio(std::move(portfolio));
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_);
1070 observe_charged(rows);
1071 reconcile(runner_instance, rows);
1088 for (
const auto& update : updates_.changed(result.value().orders_)) {
1089 runner_instance.feed(update);
1092 updates_.adopt(result.value().orders_);
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 ?
1111 std::min(*deferred_since, *unconfirmed_since);
1112 std::vector<OrderSnapshot> evidence;
1117 const auto until = std::max({runner_instance.context().now(), runner_instance.observed_at(), since});
1118 if (!read_evidence(since, until, evidence)) {
1121 if (unconfirmed_since) {
1122 runner_instance.confirm_from_history(evidence);
1124 if (deferred_since) {
1125 runner_instance.retry_deferred(evidence);
1134 (void)runner_instance;
1150 template <
typename Runner>
1151 void reconcile(Runner& runner_instance,
const std::vector<OrderSnapshot>& rows) {
1152 if (journal_ ==
nullptr || runner_instance.run_writes_closed()) {
1155 const auto& replay = journal_->replay();
1158 reconcile_ = runner::ReconcileReport{};
1159 }
else if (!sweep(runner_instance, replay, open, rows)) {
1162 search_again(runner_instance, replay, open, rows);
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;
1187 template <
typename Runner>
1189 Runner& runner_instance,
const runner::JournalReplay& replay,
const std::vector<runner::OpenInstruction>& open,
1190 const std::vector<OrderSnapshot>& rows
1192 auto candidates = rows;
1203 std::vector<OrderSnapshot> history;
1204 if (!read_history(open, history)) {
1208 open,
"the order history could not be read, so nothing could be concluded from absence"
1212 if constexpr (Caps::history_requires_range) {
1222 const auto note = runner_instance.serialized() ?
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)"
1229 " (the order list and the order history of its send); that does not establish that no order was "
1232 const auto now = sweep_instant(runner_instance);
1233 if (runner_instance.guard().limits().run_budget_) {
1235 RunJournalWrites<Runner> writes{journal_, &runner_instance};
1242 if (reconcile_.unrecorded_) {
1246 runner_instance.halt_locally(
"the order journal could not record a reconciliation, so the hold stands");
1252 for (
const auto& match : reconcile_.matches_) {
1256 for (
const auto& instruction : open) {
1260 runner_instance.resolve_indeterminate_placement(
1261 instruction.entry_.instrument_, instruction.entry_.side_,
1263 instruction.entry_.id_
1280 template <
typename Runner>
1282 Runner& runner_instance,
const runner::JournalReplay& replay,
const std::vector<runner::OpenInstruction>& open,
1283 const std::vector<OrderSnapshot>& rows
1285 if (!runner_instance.serialized()) {
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_;
1294 ids.push_back(owed.journal_id_);
1301 std::vector<OrderSnapshot> history;
1302 if (!read_history(late, history)) {
1307 const auto dated = [](std::vector<OrderSnapshot> all) {
1310 all.begin(), all.end(),
1311 [](
const OrderSnapshot& row) {
1312 return !row.ordered_at_;
1319 auto candidates = dated(rows);
1324 candidates.begin(), candidates.end(),
1325 [](
const OrderSnapshot& row) {
1326 return row.ordered_date_assumed_;
1332 const auto now = sweep_instant(runner_instance);
1333 for (
const auto& instruction : late) {
1339 if (runner_instance.run_writes_closed()) {
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");
1347 runner_instance.resolve_indeterminate_placement(
1348 instruction.entry_.instrument_, instruction.entry_.side_, std::optional<std::string>(match.order_id_),
1349 instruction.entry_.id_
1354 const auto& withheld = reconcile_.withheld_;
1356 std::find(withheld.begin(), withheld.end(), match.instrument_) == withheld.end() &&
1359 runner_instance.ledger().resolve_after_reading_orders(match.instrument_);
1373 bool read_history(
const std::vector<runner::OpenInstruction>& all, std::vector<OrderSnapshot>& into) {
1376 std::vector<runner::OpenInstruction> open;
1377 for (
const auto& instruction : all) {
1378 if (!instruction.entry_.requires_operator_) {
1379 open.push_back(instruction);
1385 if constexpr (Caps::history_requires_range) {
1392 auto earliest = open.front().opened_at_;
1394 for (
const auto& instruction : open) {
1395 if (instruction.opened_at_ < earliest) {
1396 earliest = instruction.opened_at_;
1399 if (sent_by > latest) {
1403 return read_history_days(earliest, latest, into);
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
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_) {
1420 days.push_back(day);
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)) {
1431 for (
const auto& day : days) {
1432 std::vector<OrderSnapshot> page;
1433 if (!read_history_in({day, day}, page,
true)) {
1436 for (
const auto& row : page) {
1438 for (
const auto& held : into) {
1439 if (same_history_row(held, row)) {
1445 into.push_back(row);
1463 std::chrono::system_clock::time_point since, std::chrono::system_clock::time_point now,
1464 std::vector<OrderSnapshot>& into
1466 if constexpr (Caps::history_requires_range) {
1467 return read_history_in(
1474 return read_history_days(since, now, into);
1480 bool read_history_in(
1481 const std::pair<Date, Date>& range, std::vector<OrderSnapshot>& into,
bool dated = Caps::history_requires_range
1483 OrderHistoryQuery query;
1484 if constexpr (Caps::has_history_limit) {
1488 query.limit_ = history_limit_;
1491 query.from_ = range.first;
1492 query.to_ = range.second;
1495 for (
int page = 0; page < maximum_history_pages_; ++page) {
1496 auto result = session_->order_history(query);
1498 last_error_ = result.error();
1503 for (
const auto& row : result.value().orders_) {
1505 for (
const auto& held : into) {
1506 if (same_history_row(held, row)) {
1512 into.push_back(row);
1515 const bool more = result.value().next_cursor_ && !result.value().next_cursor_->empty();
1519 if constexpr (Caps::has_history_cursor) {
1520 query.cursor_ = result.value().next_cursor_;
1536 static bool same_history_row(
const OrderSnapshot& a,
const OrderSnapshot& b) {
1538 !
decimal_less(a.execution_.filled_quantity_, b.execution_.filled_quantity_) &&
1539 !
decimal_less(b.execution_.filled_quantity_, a.execution_.filled_quantity_);
1543 MarketData* market_data_;
1544 std::vector<InstrumentId> universe_;
1545 std::vector<Currency> currencies_;
1547 runner::ChargedCosts charged_;
1549 std::map<std::string, ObservedCharge> charged_seen_;
1551 std::vector<std::string> charged_listing_;
1552 Country calendar_country_{Country::KR};
1555 template <
typename Runner>
1556 struct RunJournalWrites {
1559 bool append(
const runner::JournalEntry& entry) {
1560 if (runner_->run_writes_closed()) {
1563 if (journal_->append(entry)) {
1566 runner_->note_run_journal_write_failed();
1571 Journal* journal_{
nullptr};
1572 int maximum_history_pages_{20};
1573 runner::MatchWindow window_;
1574 runner::ReconcileReport reconcile_;
1576 runner::OrderUpdateWatch<BrokerTag> updates_;
1579 std::size_t bars_not_yet_closed_{0};
1580 std::size_t bars_fed_as_warmup_{0};
1583 std::size_t bars_not_delivered_{0};
1584 std::optional<std::chrono::system_clock::time_point> delivered_through_;
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_;