7#include "../runner/order_updates.hpp"
8#include "../runner/runner.hpp"
10#include <algotradelib/core>
22#include <unordered_map>
43template <
typename BrokerTag>
61 std::optional<std::chrono::system_clock::time_point>
decided_at_;
102template <
typename BrokerTag>
106 using ByInstrument = std::unordered_map<InstrumentId, std::vector<std::uint64_t>, id_detail::InstrumentIdHash>;
128 : by_instrument_(std::move(other.by_instrument_)),
129 slots_(std::move(other.slots_)),
131 last_ref_(std::move(other.last_ref_)),
132 issued_(other.issued_),
134 changes_(other.changes_ + 1),
135 deciding_at_(other.deciding_at_),
136 decision_is_exact_(other.decision_is_exact_) {
137 other.forget_queue();
146 if (
this != &other) {
147 slots_ = std::move(other.slots_);
149 by_instrument_ = std::move(other.by_instrument_);
150 last_ref_ = std::move(other.last_ref_);
151 issued_ = other.issued_;
154 changes_ = (changes_ > other.changes_ ? changes_ : other.changes_) + 1;
155 deciding_at_ = other.deciding_at_;
156 decision_is_exact_ = other.decision_is_exact_;
157 other.forget_queue();
169 if (
this != &other) {
171 *
this = std::move(copy);
195 if (serials.size() == serials.capacity()) {
196 serials.reserve(std::max<std::size_t>(4, 2 * serials.capacity()));
199 slot.entry_.order_ = order;
200 slot.serial_ = issued_ + 1;
201 slot.entry_.ref_.primary_ = std::to_string(slot.serial_);
202 slot.entry_.accepted_on_ = bar_;
203 slot.entry_.decided_at_ = deciding_at_;
204 slot.entry_.decision_is_exact_ = decision_is_exact_;
205 auto last = slot.entry_.ref_;
206 slots_.push_back(std::move(slot));
207 serials.push_back(slots_.back().serial_);
210 last_ref_ = std::move(last);
230 switch (order.type_) {
233 return order.trigger_price_.has_value() && order.price_.has_value() && order.time_in_force_ ==
TimeInForce::DAY;
238 case OrderType::UNKNOWN:
261 case TimeInForce::UNKNOWN:
284 std::optional<OrderRef<BrokerTag>>
last_ref()
const {
350 return lhs.at_ == rhs.at_;
359 return lhs.at_ != rhs.at_;
367 void skip() noexcept {
368 while (at_ != end_ && !at_->live_) {
372 const Slot* at_{
nullptr};
373 const Slot* end_{
nullptr};
394 std::size_t
size() const noexcept {
414 Queue(
const Slot* first,
const Slot* last, std::size_t
size) noexcept : first_(first), last_(last), size_(
size) {}
425 return Queue(slots_.data(), slots_.data() + slots_.size(), live_);
436 template <
typename Each>
438 const auto found = by_instrument_.find(instrument);
439 if (found == by_instrument_.end()) {
442 for (
const auto serial : found->second) {
443 each(slots_[*slot_of(serial)].entry_);
453 const auto at = live_slot_of(ref);
454 return at ? &slots_[*at].entry_ :
nullptr;
463 if (
const auto at = live_slot_of(ref)) {
464 slots_[*at].entry_.session_ = session;
474 const auto at = live_slot_of(ref);
482 auto& slot = slots_[*at];
485 auto& serials = by_instrument_.find(slot.entry_.order_.instrument_)->second;
486 serials.erase(std::find(serials.begin(), serials.end(), slot.serial_));
488 if (slots_.size() - live_ > live_) {
500 const auto at = live_slot_of(ref);
504 slots_[*at].entry_.released_ =
true;
519 std::uint64_t
bar() const noexcept {
539 template <
typename PriceOf>
541 for (
auto slot = slots_.rbegin(); slot != slots_.rend() && !slot->priced_; ++slot) {
542 slot->priced_ =
true;
543 auto [price, at] = price_of(slot->entry_.order_.instrument_);
544 slot->entry_.decision_price_ = std::move(price);
545 slot->entry_.decision_price_at_ = at;
554 void deciding_at(std::chrono::system_clock::time_point at,
bool exact =
true) {
556 decision_is_exact_ = exact;
564 std::uint64_t serial_{0};
571 std::optional<std::size_t> slot_of(std::uint64_t serial)
const noexcept {
573 std::lower_bound(slots_.begin(), slots_.end(), serial, [](
const Slot& slot, std::uint64_t wanted) {
574 return slot.serial_ < wanted;
576 if (found == slots_.end() || found->serial_ != serial) {
579 return static_cast<std::size_t
>(found - slots_.begin());
585 std::optional<std::size_t> live_slot_of(
const OrderRef<BrokerTag>& ref)
const noexcept {
586 const auto& text = ref.primary_;
587 std::uint64_t serial = 0;
588 const auto parsed = std::from_chars(text.data(), text.data() + text.size(), serial);
589 if (parsed.ec != std::errc{} || parsed.ptr != text.data() + text.size()) {
592 const auto at = slot_of(serial);
593 if (!at || !slots_[*at].live_ || !(slots_[*at].entry_.ref_ == ref)) {
600 void forget_queue() noexcept {
602 by_instrument_.clear();
609 void compact() noexcept {
612 slots_.begin(), slots_.end(),
613 [](
const Slot& slot) {
622 ByInstrument by_instrument_;
623 std::vector<Slot> slots_;
624 std::size_t live_{0};
625 std::optional<OrderRef<BrokerTag>> last_ref_;
626 std::uint64_t issued_{0};
627 std::uint64_t bar_{0};
628 std::uint64_t changes_{0};
629 std::optional<std::chrono::system_clock::time_point> deciding_at_;
630 bool decision_is_exact_{
true};
661 std::chrono::system_clock::time_point
at_{};
842template <
typename Strategy,
typename CapsType = strategy::NoCaps>
859 : config_(std::move(config)),
860 fills_(std::move(
fills)),
862 clock_(config_.session_),
863 runner_(std::move(
strategy), config_.limits_, config_.series_capacity_) {
865 runner_.context().set_instrument(reference);
870 runner::runner_detail::ReplayAccess::rows_listed(runner_);
881 return runner_.strategy();
917 return runner_.run_cash();
926 return runner_.run_holding(instrument);
966 if (result_.halted_) {
970 const bool history = is_history(event.
period_end_);
974 if (latest_record_at_ && event.
period_end_ < *latest_record_at_) {
975 throw std::invalid_argument(
976 "a bar that ended before a record already fed: feed records and bars in time order, a record before "
977 "the bars of its instant"
988 check_slice_order(event, slot);
989 if (!pending_.empty() && pending_.period_end() < event.
period_end_) {
991 if (result_.halted_) {
1000 ++result_.history_bars_;
1001 set_price(slot, event);
1003 collect_for_slice(event, slot);
1005 install_portfolio();
1006 runner_.feed_warmup(event);
1011 history_over_ =
true;
1021 runner_.executor().open_bar();
1033 runner_.executor().deciding_at(event.
period_end_, period_end_is_exact(event));
1038 if (period_point_ && *period_point_ != event.
period_end_) {
1039 record_point(*period_point_);
1041 settle_queued_against(event, slot);
1048 if (result_.halted_) {
1057 if (slot.lot_ && !ledger_.mark_lot(*slot.lot_, event.
bar_.
close_)) {
1062 error.
message_ =
"a position in " +
event.instrument_.symbol_ +
1063 " could not be valued at the "
1064 "bar's close without leaving an exact decimal, so the replay stopped rather than let a "
1065 "strategy decide on a position one bar behind its price";
1066 result_.halted_ = std::move(error);
1078 set_price(slot, event);
1080 if (clock_.advance(event, trading_day)) {
1081 runner_.context().set_phase(clock_.phase());
1093 install_portfolio();
1094 drain_reports(runner_.feed(clock_.phase()));
1096 runner_.context().set_phase(clock_.phase());
1100 collect_for_slice(event, slot);
1102 install_portfolio();
1103 drain_reports(runner_.feed(event));
1107 publish_order_updates();
1117 if (history_over_ || result_.halted_) {
1121 if (!pending_.empty() && is_history(pending_.period_end())) {
1125 history_over_ =
true;
1153 if (result_.halted_) {
1158 throw std::invalid_argument(
"a quote before trade_from_: a replay feeds no quote as history");
1163 const auto at =
event.quote_.received_at_;
1164 if (!pending_.empty() && at < pending_.period_end()) {
1165 throw std::invalid_argument(
1166 "a quote earlier than bars already fed: with on_bars, feed quotes and bars in time order"
1169 if (pending_.empty() && delivered_through_ && at < *delivered_through_) {
1170 throw std::invalid_argument(
1171 "a quote earlier than a period already delivered: with on_bars, feed quotes and bars in time order"
1174 if (!pending_.empty()) {
1176 if (result_.halted_) {
1181 history_over_ =
true;
1199 const bool phase_changed = clock_.advance_to(event.
quote_.
received_at_, trading_day);
1200 runner_.context().set_phase(clock_.phase());
1201 if (phase_changed) {
1209 install_portfolio();
1210 drain_reports(runner_.feed(clock_.phase()));
1216 install_portfolio();
1217 drain_reports(runner_.feed(event));
1223 publish_order_updates();
1250 template <
typename T>
1253 strategy::strategy_detail::declares_on_data<Strategy>,
1254 "a record fed to a strategy that declares no on_data would vanish: declare on_data, or feed no records"
1256 static_assert(std::is_same_v<T, typename Runner::DataRecord>,
"a record must be of the strategy's data_type");
1257 if (result_.halted_) {
1261 const auto at =
event.known_at_;
1262 const bool history = is_history(at);
1265 if (latest_record_at_ && at < *latest_record_at_) {
1266 throw std::invalid_argument(
"a record earlier than a record already fed: feed records in time order");
1268 if (previous_ && at < previous_->second) {
1269 throw std::invalid_argument(
1270 "a record earlier than a bar already fed: feed records and bars in time order, a record before the bars "
1275 if (!pending_.empty() && at < pending_.period_end()) {
1276 throw std::invalid_argument(
1277 "a record earlier than bars already fed: with on_bars, feed records and bars in time order"
1280 if (pending_.empty() && delivered_through_ && at < *delivered_through_) {
1281 throw std::invalid_argument(
1282 "a record earlier than a period already delivered: with on_bars, feed records and bars in time order"
1287 if (!pending_.empty() && pending_.period_end() < at) {
1289 if (result_.halted_) {
1295 latest_record_at_ = at;
1299 install_portfolio();
1300 runner_.feed_warmup(event);
1303 history_over_ =
true;
1304 runner_.executor().deciding_at(at);
1306 const bool phase_changed = clock_.advance_to(at, trading_day);
1307 runner_.context().set_phase(clock_.phase());
1308 if (phase_changed) {
1309 runner_.context().set_now(at);
1310 install_portfolio();
1311 drain_reports(runner_.feed(clock_.phase()));
1313 install_portfolio();
1314 drain_reports(runner_.feed(event));
1315 publish_order_updates();
1328 if (result_.halted_) {
1342 if (!pending_.empty()) {
1344 if (result_.halted_) {
1350 if (period_point_) {
1351 record_point(*period_point_);
1353 install_portfolio();
1354 drain_reports(runner_.stop());
1357 publish_order_updates();
1358 result_.unfilled_ = runner_.executor().queued().size();
1370 struct InstrumentSlot {
1376 std::optional<std::chrono::system_clock::time_point>
pending_;
1377#if defined(ATL_HAS_EIGEN)
1381 std::optional<std::chrono::system_clock::time_point>* bar_time_{
nullptr};
1385 std::optional<std::size_t> lot_;
1389 std::optional<std::chrono::system_clock::time_point> priced_at_;
1391 std::vector<ByInterval> intervals_;
1399 for (
auto& entry : intervals_) {
1400 if (entry.interval_ == interval) {
1406 intervals_.push_back(added);
1407 return intervals_.back();
1412 void collect_for_slice(
const strategy::BarEvent& event, InstrumentSlot& slot) {
1413 auto& by_interval = slot.interval(event.
interval_);
1414#if defined(ATL_HAS_EIGEN)
1415 using Access = runner::context_detail::PortfolioAccess;
1416 forget_pointers_if_replaced();
1418 if (by_interval.series_ ==
nullptr) {
1419 by_interval.series_ = &Access::series_for(runner_.context(), event);
1421 by_interval.series_->push(event.
bar_);
1423 if (by_interval.bar_time_ ==
nullptr) {
1424 by_interval.bar_time_ = &Access::bar_time_for(runner_.context(), event);
1426 Access::advance_bar_time(*by_interval.bar_time_, event);
1430 pending_.add_checked(event);
1431 by_interval.pending_ =
event.period_end_;
1435 bool is_history(std::chrono::system_clock::time_point at)
const {
1436 if (!config_.trade_from_ || !(at < *config_.trade_from_)) {
1439 if (history_over_) {
1440 throw std::invalid_argument(
"an event before trade_from_ after history ended: feed history first");
1449 void check_slice_order(
const strategy::BarEvent& event, InstrumentSlot& slot) {
1450 if (delivered_through_ && !(*delivered_through_ < event.
period_end_)) {
1451 throw std::invalid_argument(
1452 "a bar for a period already delivered to on_bars: feed every bar of a period before anything "
1453 "later (a bar of the next period, a quote at or after it, or finish)"
1456 if (pending_.empty()) {
1460 throw std::invalid_argument(
1461 "a bar earlier than bars already fed: with on_bars, feed bars in period-end order across "
1466 throw std::invalid_argument(
1467 "a second bar of one instrument and interval for the same period end: on_bars receives one bar "
1479 void deliver_pending() {
1480 const auto end = pending_.period_end();
1481 auto slices = pending_.take();
1482 delivered_through_ = end;
1483 const bool history = config_.trade_from_ && end < *config_.trade_from_;
1484 for (
const auto& slice : slices) {
1485 if (result_.halted_) {
1489 install_portfolio();
1490 runner_.feed_warmup(slice);
1494 for (
const auto& bar : slice.bars_) {
1495 exact = exact || period_end_is_exact(bar);
1497 runner_.executor().deciding_at(end, exact);
1498 install_portfolio();
1499 drain_reports(runner_.feed(slice));
1500 publish_order_updates();
1510 void abort_queue() {
1513 std::vector<OrderRef<Tag>> remaining;
1514 remaining.reserve(runner_.executor().queued().size());
1515 for (
const auto& entry : runner_.executor().queued()) {
1516 remaining.push_back(entry.ref_);
1518 for (
const auto& ref : remaining) {
1519 runner_.executor().withdraw(ref);
1521 result_.aborted_ = remaining.size();
1537 static bool period_end_is_exact(
const strategy::BarEvent& event)
noexcept {
1566 std::optional<std::chrono::system_clock::time_point> period_start_of(
const strategy::BarEvent& event)
const {
1573 void start_strategy() {
1574 if (runner_.started()) {
1577 install_portfolio();
1578 drain_reports(runner_.start());
1579 publish_order_updates();
1619 bool may_fill(
const QueuedOrder<Tag>& entry,
const strategy::BarEvent& event) {
1620 if (!entry.decided_at_) {
1623 if (
const auto start = period_start_of(event)) {
1624 if (!(*start < *entry.decided_at_)) {
1629 if (entry.decision_is_exact_) {
1635 ++result_.unchecked_fill_causality_;
1638 ++result_.unchecked_fill_causality_;
1651 void settle_queued_against(
const strategy::BarEvent& event, InstrumentSlot& slot) {
1654 if (runner_.executor().queued().empty()) {
1655 publish_order_updates();
1658 const auto bar_date = clock_.session().local_date(event.
bar_.
timestamp_);
1661 expire_day_orders(event, bar_date,
false);
1662 std::vector<OrderRef<Tag>> eligible;
1663 std::vector<OrderRef<Tag>> first_session;
1667 runner_.executor().for_each_queued_in(event.
instrument_, [&](
const QueuedOrder<Tag>& entry) {
1668 if (entry.accepted_on_ >= runner_.executor().bar()) {
1677 if (!may_fill(entry, event)) {
1680 eligible.push_back(entry.ref_);
1688 first_session.push_back(entry.ref_);
1691 for (
const auto& ref : first_session) {
1692 runner_.executor().assign_session(ref, bar_date);
1695 for (
const auto& ref : eligible) {
1696 const auto* entry = runner_.executor().find(ref);
1697 if (entry ==
nullptr) {
1701 const auto order = entry->order_;
1702 const auto& rule = rule_for(order.instrument_);
1707 std::optional<Date>(clock_.session().local_date(event.
bar_.
timestamp_)) :
1709 auto decision = fills_.decide(
1710 order, event, rule, clock_.session().local_date(event.
period_end_), open_date, entry->released_,
1711 entry->decision_price_, entry->decision_price_at_, entry->decided_at_
1713 if (decision.released_) {
1716 runner_.executor().release(ref);
1717 ++result_.stop_releases_;
1719 if (decision.costing_error_) {
1723 runner_.executor().withdraw(ref);
1724 result_.halted_ = std::move(*decision.costing_error_);
1731 if (!decision.execution_) {
1732 if (!decision.still_working_) {
1735 runner_.executor().withdraw(ref);
1741 runner_.executor().withdraw(ref);
1744 decision.execution_->currency_ = currency_for(order.instrument_);
1746 decision.execution_->fill_.order_id_ = ref.primary_;
1747 if (!ledger_.apply(*decision.execution_, currency_for(order.instrument_))) {
1756 error.reached_broker_ =
false;
1757 error.broker_code_ =
"execution_not_representable";
1759 "an execution's cash arithmetic does not fit an exact decimal, so the "
1760 "ledger could not record a fill the model produced";
1761 result_.halted_ = std::move(error);
1769 slot.lot_ = ledger_.lot_of(order.instrument_);
1771 note_overdraft(*decision.execution_);
1772 if (decision.intrabar_release_fill_) {
1773 ++result_.stop_fills_intrabar_;
1775 if (decision.bounded_) {
1776 ++result_.limit_fills_bounded_;
1778 if (decision.priced_by_rule_) {
1779 ++result_.market_fills_by_rule_;
1783 result_.executions_.push_back(std::move(*decision.execution_));
1786 if (runner::runner_detail::ReplayAccess::has_run(runner_) && !book_run(result_.executions_.back())) {
1789 error.reached_broker_ =
false;
1790 error.broker_code_ =
"execution_not_representable";
1791 error.message_ =
"the run budget's ledger could not book an execution the model produced";
1792 result_.halted_ = std::move(error);
1796 if constexpr (strategy::strategy_detail::declares_on_fill<Strategy>) {
1797 const auto& recorded = result_.executions_.back();
1802 install_portfolio();
1803 drain_reports(runner_.feed(recorded.fill_));
1806 expire_day_orders(event, bar_date,
true);
1809 publish_order_updates();
1813 bool book_run(
const Execution& execution) {
1814 const auto&
fill = execution.fill_;
1816 auto fee =
decimal_add(execution.commission_, execution.tax_);
1817 if (fee && execution.institution_fee_) {
1818 fee =
decimal_add(*fee, *execution.institution_fee_);
1820 if (!amount || !fee) {
1823 return runner::runner_detail::ReplayAccess::book(
1824 runner_,
fill.instrument_,
fill.side_,
fill.quantity_, Money{*amount, execution.currency_}, *fee
1829 void note_overdraft(
const Execution& execution) {
1830 if (!(execution.currency_ == result_.currency_)) {
1833 const auto cash = ledger_.cash_in(execution.currency_);
1837 if (!result_.lowest_cash_ ||
decimal_less(*cash, result_.lowest_cash_->amount_)) {
1838 result_.lowest_cash_ = Money{*cash, execution.currency_};
1839 result_.lowest_cash_at_ = execution.fill_.at_;
1854 void expire_day_orders(
const strategy::BarEvent& event,
const Date& bar_date,
bool after_fills) {
1858 clock_.session().opens_at(event.
bar_.
timestamp_) - clock_.session().open_ + clock_.session().close_;
1859 const bool ends_session = after_fills && (daily_or_longer || !(
event.period_end_ < closes));
1860 std::vector<OrderRef<Tag>> expired;
1862 if (!entry.session_ || !time_in_force_expires_at_close(entry.order_.time_in_force_)) {
1865 if (*entry.session_ < bar_date || (*entry.session_ == bar_date && ends_session)) {
1866 expired.push_back(entry.ref_);
1869 for (
const auto& ref : expired) {
1870 runner_.executor().withdraw(ref);
1871 ++result_.expired_day_orders_;
1877 if (
const auto cash = ledger_.cash_in(config_.currency_); cash && cash->coefficient() < 0) {
1878 ++result_.overdrawn_bars_;
1879 if (!result_.first_overdrawn_) {
1880 result_.first_overdrawn_ =
event.period_end_;
1883 const auto equity = ledger_.equity();
1884#if defined(ATL_REPLAY_CHECK_EQUITY)
1885 ATL_REPLAY_CHECK_EQUITY(equity, ledger_.equity_in(config_.currency_));
1891 ++result_.unvalued_bars_;
1892 if (!result_.first_unvalued_) {
1893 result_.first_unvalued_ =
event.period_end_;
1897 switch (config_.equity_curve_) {
1898 case EquityCurve::PER_BAR:
1903 case EquityCurve::PER_PERIOD:
1904 period_point_ =
event.period_end_;
1906 case EquityCurve::NONE:
1912 void record_point(std::chrono::system_clock::time_point at) {
1913 period_point_.reset();
1914 if (
const auto equity = ledger_.equity()) {
1915 record_point(at, *equity);
1922 void record_point(std::chrono::system_clock::time_point at,
const Decimal64& equity) {
1925 point.equity_ = equity;
1930 const bool after_gap = equity_gap_;
1931 equity_gap_ =
false;
1932 if (!result_.equity_.empty() && !after_gap) {
1933 const auto& previous = result_.equity_.back().equity_;
1936 if (previous.coefficient() > 0) {
1941 point.period_return_ = analytics_to_scalar(*ratio);
1946 result_.equity_.push_back(point);
1958 for (std::uint8_t at = 0; at < value.scale(); ++at) {
1961 return static_cast<math::Scalar>(value.coefficient()) / divisor;
2018 void publish_order_updates() {
2019 if (result_.halted_) {
2024 if constexpr (!strategy::strategy_detail::declares_on_order_update<Strategy>) {
2032 publish_to_handler();
2037 void publish_to_handler() {
2039 if (runner_.executor().queued().empty() && updates_.tracked_orders() == 0) {
2043 std::vector<WorkingOrder<Tag>> rows;
2044 rows.reserve(runner_.executor().queued().size());
2045 for (
const auto& entry : runner_.executor().queued()) {
2046 rows.push_back(working_row(entry));
2048 for (
const auto& update : updates_.changed(rows)) {
2057 const auto* still_queued = find_queued(update);
2058 if (still_queued ==
nullptr) {
2061 install_portfolio();
2062 drain_reports(runner_.feed(update));
2063 if (result_.halted_) {
2078 const QueuedOrder<Tag>* find_queued(
const OrderSnapshot& update)
const {
2079 for (
const auto& entry : runner_.executor().queued()) {
2080 if (entry.ref_.primary_ != update.order_id_) {
2083 const auto row = working_row(entry);
2084 if (runner::order_update_detail::same_observable_state(row.order_, update)) {
2093 void forget_pointers_if_replaced() noexcept {
2094 const auto revision = runner::context_detail::PortfolioAccess::replacements(runner_.context());
2095 if (revision == slots_context_) {
2098 for (
auto& entry : slots_) {
2099 entry.second.price_ =
nullptr;
2100#if defined(ATL_HAS_EIGEN)
2101 for (
auto& by_interval : entry.second.intervals_) {
2102 by_interval.series_ =
nullptr;
2103 by_interval.bar_time_ =
nullptr;
2107 slots_context_ = revision;
2110 InstrumentSlot& slot_for(
const InstrumentId& instrument) {
2111 auto found = slots_.find(instrument);
2112 if (found == slots_.end()) {
2113 found = slots_.emplace(instrument, InstrumentSlot{}).first;
2115 return found->second;
2120 forget_pointers_if_replaced();
2121 slot.priced_at_ =
event.period_end_;
2122 if (slot.price_ !=
nullptr) {
2123 *slot.price_ =
event.bar_.close_;
2126 &runner::context_detail::PortfolioAccess::set_price(runner_.context(), event.
instrument_, event.
bar_.
close_);
2130 void install_portfolio() {
2134 if (
const auto equity = ledger_.equity()) {
2135 runner_.set_portfolio_value(
Money{*equity, config_.currency_});
2137 runner_.clear_portfolio_value();
2139 using Access = runner::context_detail::PortfolioAccess;
2140 auto& context = runner_.context();
2141 const auto& queued = runner_.executor().queued();
2150 if (!installed_ || Access::replacements(context) != replacements_seen_) {
2151 auto portfolio = ledger_.snapshot<Tag>(clock_.now());
2152 portfolio.working_.reserve(queued.size());
2153 for (
const auto& entry : queued) {
2154 portfolio.working_.push_back(working_row(entry));
2155 commit_open_buy(portfolio, entry);
2157 context.set_portfolio(std::move(portfolio));
2158 ledger_.clear_changed();
2162 const bool rows_stale = runner_.executor().changes() != queue_seen_ ||
2163 Access::runner_edits(context) != edits_seen_ || Access::reference_changes(context) != references_seen_;
2164 auto& portfolio = Access::for_replay_sync(context);
2165 ledger_.update(portfolio, clock_.now());
2166 if (rows_stale && Access::reference_changes(context) != references_seen_) {
2167 portfolio.working_.clear();
2168 for (
const auto& entry : queued) {
2169 portfolio.working_.push_back(working_row(entry));
2171 }
else if (rows_stale) {
2172 refresh_rows(portfolio.working_, queued);
2176 if (config_.limits_.enforce_buying_power_) {
2177 for (
const auto& entry : queued) {
2178 commit_open_buy(portfolio, entry);
2183 replacements_seen_ = Access::replacements(context);
2184 edits_seen_ = Access::runner_edits(context);
2185 references_seen_ = Access::reference_changes(context);
2186 queue_seen_ = runner_.executor().changes();
2187#if defined(ATL_REPLAY_CHECK_PORTFOLIO)
2191 auto fresh = ledger_.snapshot<Tag>(clock_.now());
2192 for (
const auto& entry : queued) {
2193 fresh.working_.push_back(working_row(entry));
2194 commit_open_buy(fresh, entry);
2196 ATL_REPLAY_CHECK_PORTFOLIO(context.portfolio(), fresh, ledger_.equity(), ledger_.equity_in(config_.currency_));
2207 template <
typename Queue>
2208 void refresh_rows(std::vector<
WorkingOrder<Tag>>& rows,
const Queue& queued)
const {
2209 std::size_t built = 0;
2210 while (built < rows.size() && !rows[built].reserved_) {
2213 std::size_t kept = 0;
2214 std::size_t next = 0;
2215 auto entry = queued.begin();
2216 for (; entry != queued.end(); ++entry) {
2217 while (next < built && !(rows[next].ref_ == entry->ref_)) {
2220 if (next == built) {
2224 rows[kept] = std::move(rows[next]);
2229 rows.erase(rows.begin() +
static_cast<std::ptrdiff_t
>(kept), rows.end());
2230 for (; entry != queued.end(); ++entry) {
2231 rows.push_back(working_row(*entry));
2245 row.
ref_ = entry.ref_;
2251 row.order_.order_id_ = entry.ref_.primary_;
2252 row.order_.instrument_ = entry.order_.instrument_;
2253 row.order_.side_ = entry.order_.side_;
2254 row.order_.type_ = entry.order_.type_;
2255 row.order_.time_in_force_ = entry.order_.time_in_force_;
2256 row.order_.session_ = entry.order_.session_;
2257 row.order_.venue_ = entry.order_.venue_;
2258 row.order_.price_ = entry.order_.price_;
2261 row.order_.trigger_price_ = entry.order_.trigger_price_;
2262 row.order_.quantity_ = entry.order_.quantity_;
2263 row.order_.currency_ = currency_for(entry.order_.instrument_);
2266 row.order_.status_ = OrderStatus::PENDING;
2268 row.amendable_quantity_ = entry.order_.quantity_;
2293 if (!config_.limits_.enforce_buying_power_ || entry.order_.side_ != OrderSide::BUY) {
2297 entry.order_.price_ ? entry.order_.price_ : runner_.context().last_price(entry.order_.instrument_);
2305 const auto currency = currency_for(entry.order_.instrument_);
2307 if (!(reading.cash_.currency_ == currency)) {
2311 reading.cash_.amount_ = *left;
2319 const auto* reference = runner_.context().find_instrument(instrument);
2320 return reference !=
nullptr ? reference->currency_ : config_.currency_;
2324 const auto* reference = runner_.context().find_instrument(instrument);
2325 return reference !=
nullptr ? reference->price_rule_ : unknown_rule_;
2329 template <
typename Report>
2330 void drain_reports(
const Report& report) {
2333 if (fills_.has_market_price_rule()) {
2334 runner_.executor().stamp_decision_prices([
this](
const InstrumentId&
id) {
2335 return std::make_pair(runner_.context().last_price(
id), slot_for(
id).priced_at_);
2342 template <
typename Report>
2343 void collect(
const Report& report) {
2344 for (
const auto& rejection : report.rejected_) {
2345 result_.rejected_.push_back(rejection);
2347 for (
const auto& refusal : report.refused_) {
2348 result_.refused_.push_back(refusal);
2363 void settle_deferred() {
2364 if (runner_.deferred_targets().empty()) {
2367 install_portfolio();
2368 collect(runner_.retry_deferred_on_one_snapshot());
2371 ReplayConfig config_;
2372 NextBarFillModel fills_;
2373 ReplayLedger ledger_;
2378 ReplayResult result_;
2380 bool equity_gap_{
false};
2382 std::unordered_map<InstrumentId, InstrumentSlot, id_detail::InstrumentIdHash> slots_;
2383 std::uint64_t slots_context_{0};
2386 std::optional<std::chrono::system_clock::time_point> period_point_;
2391 bool installed_{
false};
2392 std::uint64_t replacements_seen_{0};
2393 std::uint64_t edits_seen_{0};
2394 std::uint64_t references_seen_{0};
2395 std::uint64_t queue_seen_{0};
2397 std::optional<std::pair<BarInterval, std::chrono::system_clock::time_point>> previous_;
2400 strategy::slice_detail::Bucket pending_;
2401 std::optional<std::chrono::system_clock::time_point> delivered_through_;
2403 std::optional<std::chrono::system_clock::time_point> latest_record_at_;
2405 bool history_over_{
false};
Bar-interval arithmetic and the replay clock.
A three-letter currency code, such as KRW or USD (ISO 4217 style).
An exact signed decimal: an int64 coefficient times 10^-scale.
static Decimal64 parse(std::string_view input)
Parses a decimal string exactly (no binary floating point).
The most recent observations of a few fields, for a strategy fed one bar at a time.
std::optional< Money > run_cash() const
Returns the run's cash, with RiskLimits::run_budget_ set (runner::Runner::run_cash).
std::optional< Decimal64 > run_holding(const InstrumentId &instrument) const
Returns the run's own shares of an instrument, with RiskLimits::run_budget_ set.
const ReplayLedger & ledger() const noexcept
Returns the ledger: positions, cash and realized profit.
void feed(const strategy::DataEvent< T > &event, std::optional< bool > trading_day=true)
Replays one record: moves the clock to when it became known, re-derives the phase (calling on_phase o...
Backtester(Strategy strategy={}, ReplayConfig config={}, NextBarFillModel fills=NextBarFillModel{})
Constructs a replay.
const ReplayResult & result() const noexcept
Returns what the replay has produced so far.
void feed(const strategy::QuoteEvent &event, std::optional< bool > trading_day=true)
Replays one quote: moves the price and the clock to it, re-derives the phase (calling on_phase on a c...
const NextBarFillModel & fills() const noexcept
Returns the fill model, for summarize.
void feed(const strategy::BarEvent &event, std::optional< bool > trading_day=true)
Replays one bar.
QueueingExecutor< Tag > Executor
The executor type.
runner::Runner< Strategy, CapsType, Tag, Executor > Runner
The runner::Runner the replay drives, the same type a live session uses.
void finish()
Ends the replay: calls on_stop (with the current portfolio, including orders from the last bar),...
void finish_history()
Ends history now (ReplayConfig::trade_from_): delivers a pending history period to on_bars,...
const Strategy & strategy() const noexcept
Returns the strategy, to read the state it kept.
BacktestTag Tag
The order-reference tag.
The fill model: market orders at the next bar's open, limit orders when the next bar's range reaches ...
const std::string & market_price_rule() const noexcept
Returns the market-price rule's name.
Walks the outstanding orders, oldest first.
const_iterator & operator++() noexcept
Moves to the next outstanding order.
friend bool operator!=(const const_iterator &lhs, const const_iterator &rhs) noexcept
Compares two positions in one queue.
std::ptrdiff_t difference_type
The distance between two positions.
pointer operator->() const noexcept
Points at the order here.
const QueuedOrder< BrokerTag > * pointer
A pointer to an order.
reference operator*() const noexcept
Returns the order here.
std::forward_iterator_tag iterator_category
A forward iterator.
friend bool operator==(const const_iterator &lhs, const const_iterator &rhs) noexcept
Compares two positions in one queue.
const_iterator operator++(int) noexcept
Moves to the next outstanding order.
const_iterator()=default
An iterator past the end of an empty queue.
QueuedOrder< BrokerTag > value_type
An outstanding order.
const QueuedOrder< BrokerTag > & reference
A reference to an order.
Every outstanding order, oldest first: a view over the queue, valid until the queue changes.
bool empty() const noexcept
Returns whether no order is outstanding.
const_iterator begin() const noexcept
Returns the oldest outstanding order's position.
std::size_t size() const noexcept
Returns how many orders are outstanding.
const QueuedOrder< BrokerTag > & front() const noexcept
Returns the oldest outstanding order; the queue must not be empty.
const_iterator end() const noexcept
Returns the position past the newest.
The replay's executor: accepts orders and holds them until they fill or are withdrawn.
void deciding_at(std::chrono::system_clock::time_point at, bool exact=true)
Sets the decision instant stamped on orders accepted from now on.
std::uint64_t changes() const noexcept
Returns how many times the queue gained or lost an order (place, cancel, withdraw).
static constexpr bool models_time_in_force(TimeInForce condition) noexcept
QueueingExecutor(const QueueingExecutor &other)=default
Copies an executor and its queue.
std::optional< OrderRef< BrokerTag > > last_ref() const
Returns the reference issued to the most recently accepted order.
void stamp_decision_prices(PriceOf &&price_of)
Stamps the orders accepted since the last call with their instrument's price now, and when it was obs...
std::uint64_t bar() const noexcept
Returns the bar being replayed.
Queue queued() const noexcept
Returns every outstanding order, oldest first.
runner::SendOutcome cancel(const WorkingOrder< BrokerTag > &working)
Withdraws the order a working row names, matched by reference.
QueueingExecutor & operator=(QueueingExecutor &&other) noexcept
Replaces this executor with a move of another, which is left with nothing queued.
void for_each_queued_in(const InstrumentId &instrument, Each &&each) const
Calls each with every outstanding order in one instrument, oldest first.
static constexpr bool reaches_a_broker
bool release(const OrderRef< BrokerTag > &ref)
Marks a queued stop-limit order as released.
void assign_session(const OrderRef< BrokerTag > &ref, Date session)
Records the session date of a queued order; see QueuedOrder::session_.
QueueingExecutor(QueueingExecutor &&other) noexcept(std::is_nothrow_move_constructible< ByInstrument >::value)
Moves an executor; the source is left with nothing queued.
static bool can_model(const strategy::PlannedOrder &order) noexcept
const QueuedOrder< BrokerTag > * find(const OrderRef< BrokerTag > &ref) const
Finds an outstanding order.
runner::SendOutcome place(const strategy::PlannedOrder &order)
Accepts and queues an order, issuing it a reference.
bool withdraw(const OrderRef< Tag > &ref)
void open_bar() noexcept
Starts the next bar; orders accepted from now on cannot fill against it.
QueueingExecutor & operator=(const QueueingExecutor &other)
Replaces this executor with a copy of another, entirely or not at all.
QueueingExecutor()=default
An executor with nothing queued.
static bool contiguous(const strategy::BarEvent &previous, const strategy::BarEvent &event)
Tests whether a bar follows the previous one with no gap.
Positions, cash and realized profit, updated by each execution of a replay.
void set_session(SessionWindow session)
Sets the session window (for runners).
void set_calendar(TradingCalendar calendar)
Replaces the trading calendar (for runners and sources, not strategies).
Turns successive working-order listings into order updates: the rows that changed since the previous ...
Runs one strategy: feeds it events, reconciles what it asks for, checks the risk limits,...
static constexpr bool takes_bar_slices
static constexpr bool takes_records
const Context & context() const noexcept
Returns the context.
static constexpr bool records_bar_history
The backtest fill model: whether a queued order trades against the next bar, and at what price and co...
The replay ledger: positions, cash and realized profit a backtest keeps, in exact decimals.
Replays a strategy over stored bars: fill and cost models, the replay ledger, and the report.
EquityCurve
Which points a replay records on its equity curve (ReplayResult::equity_); see ReplayConfig::equity_c...
@ PER_PERIOD
One point per period end, after the last bar of that period: one a day for daily bars,...
@ PER_BAR
One point per bar fed. A replay of many instruments records one per instrument per period,...
@ NONE
No points, for a run that does not read the curve; summarize then reports no ratio.
ExecutionHistory
Whether a ReplayLedger keeps the executions it applies.
std::optional< std::chrono::seconds > interval_duration(BarInterval interval)
Returns the fixed duration of an interval (bar_interval_length).
double Scalar
The floating-point type the analytics and math layers compute in (double).
Scalar missing()
Returns the value that stands for "no observation" (a quiet NaN).
SendOutcome
What became of one instruction (a placement or a cancellation) an executor was asked to send.
@ REJECTED
The broker refused the instruction (for a placement, the order does not exist); nothing needs reconci...
@ ACCEPTED
The broker accepted the instruction (for a placement, the order exists).
@ REFUSED_LOCALLY
The binding refused the instruction before sending it (such as an idempotency key at a broker without...
void fill(S &strategy, Ctx &context, const Fill &event)
Calls strategy.on_fill(context, event) if the strategy declares on_fill; otherwise does nothing.
What a strategy sees and emits: events, intents, the portfolio, reconciliation and risk limits.
std::optional< std::chrono::system_clock::time_point > bar_period_start(const BarEvent &event, const SessionWindow &session)
Returns when a bar's period began, where the bar says so.
The library: broker-neutral types (core), and the modules below.
@ CLOSE
The timestamp is the instant the period ended.
@ OPEN
The timestamp is the first instant of the period.
constexpr std::optional< std::chrono::seconds > bar_interval_length(BarInterval interval) noexcept
Returns an interval's fixed length, for an intraday interval.
std::optional< Decimal64 > decimal_add(const Decimal64 &lhs, const Decimal64 &rhs)
Adds two decimals exactly.
@ INVALID_ARGUMENT
The request was invalid, refused by the client before sending or by the broker.
@ LIMIT
지정가: fills at the stated price or better.
@ BEST_LIMIT
최유리지정가: priced at the best quote on the opposite side.
@ PRIMARY_LIMIT
최우선지정가: priced at the best quote on the order's own side.
@ CONDITIONAL_LIMIT
조건부지정가: a limit that becomes a market order at the close.
@ MID_PRICE
중간가: priced at the midpoint of the spread.
@ STOP_LIMIT
스톱지정가: a limit released when a trigger price is reached.
@ CLOSING_PRICE
시간외종가: priced at a session's closing price.
@ MARKET
시장가: fills at whatever the book offers.
@ REGULAR
The continuous regular session.
std::optional< Decimal64 > decimal_subtract(const Decimal64 &lhs, const Decimal64 &rhs)
Subtracts two decimals exactly.
std::optional< Decimal64 > decimal_divide(const Decimal64 &lhs, const Decimal64 &rhs, std::uint8_t scale)
Divides two decimals, truncating toward zero at a given scale.
constexpr bool time_in_force_expires_at_close(TimeInForce condition) noexcept
Tests whether an order with this condition expires at the session's close, so its filled quantity is ...
bool decimal_less(const Decimal64 &lhs, const Decimal64 &rhs)
Compares two decimals numerically, whatever their scales.
std::optional< Decimal64 > decimal_multiply(const Decimal64 &lhs, const Decimal64 &rhs)
Multiplies two decimals exactly; the scales add.
BarInterval
The period one bar covers.
TimeInForce
How long an order stays valid and what happens to an unfilled remainder.
@ FILL_OR_KILL
Fills entirely and immediately, or not at all.
@ DAY
Rests until the session ends; an unfilled remainder is cancelled then.
@ IMMEDIATE_OR_CANCEL
Fills what it can immediately and cancels the remainder.
Decimal64 close_
The last trade price.
std::chrono::system_clock::time_point timestamp_
The instant marking the period; BarSeries::stamp_ says which edge.
The error a broker or transport operation returns.
std::string message_
A human-readable description, for logs; do not parse it.
ErrorCategory category_
The kind of failure; the field to branch on.
std::string broker_code_
The broker's own error code, verbatim (for example KIS's EGW00201).
bool reached_broker_
Whether a request was sent before this error.
A calendar date with no time of day or time zone.
Identifies an instrument: its country, venue and symbol.
An exact amount of money in one currency.
A broker's reference to one order, used to amend or cancel it.
The state of one order, as a broker listing reported it.
The price grid (tick sizes) an instrument's order prices must sit on.
static PriceRule unknown(std::string reason)
Returns a rule that knows no grid and refuses to round.
Decimal64 last_price_
The last traded price, as the broker reported it.
std::chrono::system_clock::time_point received_at_
When this process received the quote, on this machine's clock.
InstrumentId instrument_
The instrument.
The trading days a broker reported for one market, ascending by date.
An order still open to modification or cancellation.
OrderRef< Broker > ref_
The reference to amend or cancel the order with.
The broker tag of a replay's order references (they reach no broker).
What is kept per interval of the instrument.
BarInterval interval_
The interval.
std::optional< std::chrono::system_clock::time_point > pending_
The period end of its bar in the period being collected, if it has one there.
One point on a replay's equity curve: per period end, or per bar (EquityCurve).
Decimal64 equity_
Cash plus positions marked at the latest closes, in the replay's currency.
math::Scalar period_return_
The return since the previous point; missing() on the first point, after an unvalued bar,...
std::chrono::system_clock::time_point at_
The period end of the bar it was recorded after.
One execution a backtest produced, and what it cost.
One order a replay accepted and has not yet filled or withdrawn.
std::optional< std::chrono::system_clock::time_point > decided_at_
When the strategy decided the order, if known.
std::optional< Date > session_
The market-local date of the session a DAY order lives in, once known (the date of the first bar it c...
bool released_
Whether a stop-limit order has been released, so it now rests as its limit.
bool decision_is_exact_
Whether decided_at_ is enforced strictly, or only a nominal upper bound (the period end of an open-st...
strategy::PlannedOrder order_
The order as reconciliation planned it.
std::uint64_t accepted_on_
The bar it was accepted during; it cannot fill against that bar.
std::optional< std::chrono::system_clock::time_point > decision_price_at_
When decision_price_ was observed: the period end of the bar, or the time of the quote,...
OrderRef< BrokerTag > ref_
The reference the replay issued for it.
std::optional< Decimal64 > decision_price_
The order's instrument's last price when the strategy decided it, for a market-price rule (NextBarFil...
A replay's settings, besides the strategy and the bars.
EquityCurve equity_curve_
Which points the equity curve records: one per period end (the default), one per bar,...
std::optional< std::chrono::system_clock::time_point > trade_from_
Where trading starts: an event earlier than it is history; empty, none is.
strategy::RiskLimits limits_
The risk limits, applied as they are live.
Decimal64 cash_
The starting cash, in currency_.
TradingCalendar calendar_
The calendar ctx.calendar() returns, for a strategy asking about dates it has no bar for (such as whe...
Currency currency_
The accounting currency; the equity curve is in this currency only.
std::vector< Instrument > instruments_
Reference data for every instrument replayed; orders on an instrument without it are refused.
std::size_t series_capacity_
How many trailing bars the context caches per series, for indicators; must be positive....
strategy::SessionWindow session_
The session window phases are derived from and DAY orders expire at; one for the whole replay.
Everything a replay produced; summarize turns it into a Report.
std::size_t unvalued_bars_
Bars whose equity total did not fit an exact decimal, so they have no curve point.
std::size_t stop_releases_
Stop-limit orders a bar released; see ReportCaveats::stop_releases_.
std::size_t bars_
The bars replayed; bars fed as history (ReplayConfig::trade_from_) are in history_bars_.
std::size_t limit_fills_bounded_
Limit-type fills moved to stay in range; see ReportCaveats::limit_fills_bounded_.
std::size_t unchecked_fill_causality_
How many fill decisions could not be checked for causality; see ReportCaveats::unchecked_fill_causali...
std::optional< std::chrono::system_clock::time_point > first_unvalued_
The period end of the first unvalued bar, if any.
std::vector< strategy::GuardRejection > refused_
Instructions a risk guard refused.
std::vector< strategy::Rejection > rejected_
Instructions not placed: reconciliation could not build them, or the replay cannot model them (BINDIN...
std::size_t records_
The records fed to on_data.
std::vector< Execution > executions_
Every execution, in order.
std::size_t gaps_
Bars that did not follow their predecessor; gaps are not interpolated.
std::size_t expired_day_orders_
DAY orders withdrawn unfilled when their session ended, as a broker does at the close.
std::size_t unfilled_
Orders still queued when finish ran.
std::optional< BrokerError > halted_
Why the replay stopped early, if it did.
std::size_t stop_fills_intrabar_
Fills of stops released inside a bar; see ReportCaveats::stop_fills_intrabar_.
std::string market_price_rule_
The fill model's market-price rule, or empty; see ReportCaveats::market_price_rule_.
std::size_t market_fills_by_rule_
Fills priced by the fill model's market-price rule; see ReportCaveats::market_fills_by_rule_.
std::size_t quotes_
The quotes fed; see ReportCaveats::quotes_ for what quote-driven orders mean in a replay.
Currency currency_
The currency of the equity curve (the replay's accounting currency).
std::size_t history_bars_
The bars fed as history, before ReplayConfig::trade_from_.
std::optional< std::chrono::system_clock::time_point > first_overdrawn_
The first bar end at which cash was below zero, if any.
std::size_t aborted_
Orders still working when the replay halted, cleared from the queue (unlike unfilled_).
std::optional< Money > lowest_cash_
The lowest cash any execution left in currency_, if below zero (checked at every fill).
std::optional< std::chrono::system_clock::time_point > lowest_cash_at_
When lowest_cash_ was reached (that execution's Fill::at_).
std::vector< EquityPoint > equity_
The equity curve, in order: one point per period end, or per bar, or none (ReplayConfig::equity_curve...
std::size_t overdrawn_bars_
Bars that closed with cash below zero in currency_ (counted per bar fed, so two instruments count bot...
One bar, delivered to on_bar.
std::chrono::system_clock::time_point period_end_
When the bar's period ended: the earliest moment the bar could be known.
InstrumentId instrument_
The instrument the bar is for.
BarInterval interval_
The period length the bar covers.
A record of data from outside the broker, delivered to on_data.
One order the runner is to place.
InstrumentId instrument_
The instrument to trade.
What the account holds and which orders are still working, as a strategy sees it.
std::vector< BuyingPower > buying_power_
What may be spent, per currency.
A quote the runner has just read, delivered to on_quote.
QuoteSnapshot quote_
The quote, as the broker reported it.
The limits the operator sets for RiskGuard.
The intraday session of a market, as the operator states it.
static SessionWindow krx()
Returns the KRX regular session, 09:00-15:30 KST.