5#include "../strategy/portfolio.hpp"
7#include <algotradelib/core>
9#if defined(ATL_HAS_EIGEN)
10#include <algotradelib/analytics>
20#include <unordered_map>
29using strategy::BarEvent;
30using strategy::CancelIntent;
31using strategy::DataEvent;
34using strategy::OrderIntent;
35using strategy::Portfolio;
36using strategy::QuoteEvent;
37using strategy::SessionWindow;
38using strategy::TargetPosition;
48template <
typename Broker>
49using Instruction = std::variant<OrderIntent, TargetPosition, CancelIntent<Broker>>;
51template <
typename Strategy,
typename CapsType,
typename BrokerTag,
typename Executor>
57template <
typename Strategy,
typename CapsType>
62namespace context_detail {
69 std::uint64_t value_{0};
72 Revision(
const Revision&) =
delete;
73 Revision& operator=(
const Revision&) =
delete;
74 Revision(Revision&& other) noexcept : value_(other.value_ + 1) {
77 Revision& operator=(Revision&& other)
noexcept {
78 value_ = (value_ > other.value_ ? value_ : other.value_) + 1;
91class PortfolioAccess {
92 template <
typename Strategy,
typename CapsType,
typename BrokerTag,
typename Executor>
93 friend class runner::Runner;
94 template <
typename Strategy,
typename CapsType>
95 friend class backtest::Backtester;
98 template <
typename Ctx>
99 static auto& for_runner_edit(Ctx& context)
noexcept {
100 ++context.runner_edits_;
101 return context.portfolio_;
105 template <
typename Ctx>
106 static auto& for_replay_sync(Ctx& context)
noexcept {
107 return context.portfolio_;
110 template <
typename Ctx>
111 static std::uint64_t replacements(
const Ctx& context)
noexcept {
112 return context.replacements_.value_;
115 template <
typename Ctx>
116 static std::uint64_t runner_edits(
const Ctx& context)
noexcept {
117 return context.runner_edits_;
120 template <
typename Ctx>
121 static std::uint64_t reference_changes(
const Ctx& context)
noexcept {
122 return context.reference_changes_;
127 template <
typename Ctx>
128 static Decimal64& set_price(Ctx& context,
const InstrumentId&
id,
const Decimal64& price) {
129 return context.prices_.insert_or_assign(
id, price).first->second;
132#if defined(ATL_HAS_EIGEN)
135 template <
typename Ctx>
136 static analytics::SeriesBuffer& series_for(Ctx& context,
const BarEvent& event) {
137 return context.series_for(event);
142 template <
typename Ctx>
143 static std::optional<std::chrono::system_clock::time_point>& bar_time_for(Ctx& context,
const BarEvent& event) {
144 return context.bar_time_for(event);
149 static void advance_bar_time(std::optional<std::chrono::system_clock::time_point>& newest,
const BarEvent& event) {
151 throw std::invalid_argument(
"a series buffer observation must be later than the last");
153 newest =
event.bar_.timestamp_;
157 template <
typename Ctx>
158 static void stop_bar_history(Ctx& context) {
159 context.history_.stop_keeping();
164#if defined(ATL_HAS_EIGEN)
174 std::optional<analytics::SeriesBuffer> series_;
177 std::optional<std::chrono::system_clock::time_point> newest_;
179 using ByInterval = std::map<BarInterval, Entry>;
182 std::unordered_map<InstrumentId, ByInterval, id_detail::InstrumentIdHash> entries_;
185 BarHistory() =
default;
186 BarHistory(
const BarHistory&) =
delete;
187 BarHistory& operator=(
const BarHistory&) =
delete;
188 BarHistory(BarHistory&&) =
default;
189 BarHistory& operator=(BarHistory&& other)
noexcept {
190 entries_ = std::move(other.entries_);
198 void stop_keeping() noexcept {
205 void keep_times_only() noexcept {
206 for (
auto& [
id, by_interval] : entries_) {
207 for (
auto& [interval, entry] : by_interval) {
208 if (entry.series_ && !entry.series_->empty()) {
209 const auto newest = entry.series_->newest_instant();
210 if (!entry.newest_ || *entry.newest_ < newest) {
211 entry.newest_ = newest;
214 entry.series_.reset();
256template <
typename BrokerTag,
typename CapsType>
286 void note(std::string_view message) {
287 if (lines_.size() >= capacity_) {
288 lines_.erase(lines_.begin());
290 lines_.emplace_back(message);
297 const std::vector<std::string>&
lines() const noexcept {
305 std::vector<std::string>
take() {
306 std::vector<std::string> taken;
313 static constexpr std::size_t capacity_ = 4096;
314 std::vector<std::string> lines_;
322 explicit Context(std::size_t series_capacity = 512) : series_capacity_(series_capacity) {}
330 std::chrono::system_clock::time_point
now() const noexcept {
376 const auto found = instruments_.find(
id);
377 if (found == instruments_.end()) {
380 return found->second;
393 const auto found = instruments_.find(
id);
394 return found == instruments_.end() ? nullptr : &found->second;
403 const auto found = prices_.find(
id);
404 if (found == prices_.end()) {
407 return found->second;
410#if defined(ATL_HAS_EIGEN)
425 require_bar_history();
426 const auto found = history_.entries_.find(
id);
427 if (found == history_.entries_.end()) {
430 const auto entry = found->second.find(interval);
431 if (entry == found->second.end() || !entry->second.series_) {
434 return &*entry->second.series_;
453 queued_.emplace_back(std::move(intent));
461 queued_.emplace_back(std::move(target));
479 const std::vector<Instruction<BrokerTag>>&
queued() const noexcept {
487 std::vector<Instruction<BrokerTag>>
drain() {
488 std::vector<Instruction<BrokerTag>> taken;
497 void set_now(std::chrono::system_clock::time_point when)
noexcept {
536 ++replacements_.value_;
544 auto key = reference.
id_;
545 instruments_.insert_or_assign(std::move(key), std::move(reference));
546 ++reference_changes_;
555 prices_.insert_or_assign(
id, std::move(price));
558#if defined(ATL_HAS_EIGEN)
566 void record_bar(
const BarEvent& event) {
567 require_bar_history();
568 series_for(event).push(event.
bar_);
573 friend class context_detail::PortfolioAccess;
577 using InstrumentHash = id_detail::InstrumentIdHash;
579#if defined(ATL_HAS_EIGEN)
585 auto& entry = entry_for(event);
586 if (!entry.series_) {
587 entry.series_.emplace(series_capacity_);
589 if (entry.newest_ && entry.series_->empty() && !(*entry.newest_ < event.
bar_.
timestamp_)) {
590 throw std::invalid_argument(
"a series buffer observation must be later than the last");
592 return *entry.series_;
596 std::optional<std::chrono::system_clock::time_point>& bar_time_for(
const BarEvent& event) {
597 return entry_for(event).newest_;
600 context_detail::BarHistory::Entry& entry_for(
const BarEvent& event) {
601 auto found = history_.entries_.find(event.
instrument_);
602 if (found == history_.entries_.end()) {
603 found = history_.entries_.emplace(event.
instrument_, context_detail::BarHistory::ByInterval{}).first;
605 return found->second[
event.interval_];
608 void require_bar_history()
const {
609 if (!history_.kept_) {
610 throw std::logic_error(
611 "ctx.bars() read by a strategy declaring reads_bar_history = false, so its runner keeps no bar "
612 "history; remove the declaration or declare it true"
618 std::size_t series_capacity_;
619 std::chrono::system_clock::time_point now_{};
622 TradingCalendar calendar_;
623 Portfolio<BrokerTag> portfolio_;
626 context_detail::Revision replacements_;
627 std::uint64_t runner_edits_{0};
628 std::uint64_t reference_changes_{0};
629 std::unordered_map<InstrumentId, Instrument, InstrumentHash> instruments_;
630 std::unordered_map<InstrumentId, Decimal64, InstrumentHash> prices_;
631#if defined(ATL_HAS_EIGEN)
633 context_detail::BarHistory history_;
635 std::vector<Instruction<BrokerTag>> queued_;
An exact signed decimal: an int64 coefficient times 10^-scale.
The most recent observations of a few fields, for a strategy fed one bar at a time.
A log that keeps lines in memory for the runner to emit or a test to read.
std::vector< std::string > take()
Removes and returns the recorded lines.
void note(std::string_view message)
Records one line; when 4096 lines are held, the oldest is dropped.
const std::vector< std::string > & lines() const noexcept
Returns the lines recorded since the last take.
Context(Context &&)=default
Move constructor: takes the state of the context passed in, which is left valid but unspecified.
void set_phase(MarketPhase phase) noexcept
Sets the market phase (for runners).
std::optional< Decimal64 > last_price(const InstrumentId &id) const
Returns the latest price seen for an instrument (a quote's last price or a bar's close).
std::chrono::system_clock::time_point now() const noexcept
Returns the instant the runner is acting at.
const TradingCalendar & calendar() const noexcept
Returns the trading calendar the runner last read.
std::optional< Instrument > instrument(const InstrumentId &id) const
Returns an instrument's reference data, including its price grid.
Log & log() noexcept
Returns the log.
void set_session(SessionWindow session)
Sets the session window (for runners).
Context & operator=(const Context &)=delete
Deleted: a context cannot be copied.
void submit(TargetPosition target)
Queues a target position; the runner trades the difference from the portfolio.
const Instrument * find_instrument(const InstrumentId &id) const
Returns an instrument's reference data without copying it.
const std::vector< Instruction< BrokerTag > > & queued() const noexcept
Returns the queued requests without removing them (for runners).
void set_portfolio(Portfolio< BrokerTag > portfolio)
Replaces the portfolio (for runners).
const SessionWindow & session() const noexcept
Returns the session window the runner derives phases from, for strategy::SessionEdges.
Context(const Context &)=delete
Deleted: a context cannot be copied, so a handler cannot take it by value.
CapsType caps
The broker capabilities, for if constexpr (Ctx::caps::has_depth) and the like.
MarketPhase phase() const noexcept
Returns the market phase.
void cancel(const OrderRef< BrokerTag > &ref, std::string tag={})
Queues a cancellation of a working order.
Context & operator=(Context &&)=default
Move assignment: takes the other context's state.
void set_now(std::chrono::system_clock::time_point when) noexcept
Sets the current instant (for runners).
void set_calendar(TradingCalendar calendar)
Replaces the trading calendar (for runners and sources, not strategies).
std::vector< Instruction< BrokerTag > > drain()
Removes and returns the queued requests (for runners).
BrokerTag Broker
The broker tag of the order references.
const Portfolio< BrokerTag > & portfolio() const noexcept
Returns the portfolio: positions, buying power and the orders still working.
void submit(OrderIntent intent)
Queues an order; the runner checks and sends it after the handler returns.
Context(std::size_t series_capacity=512)
Constructs a context.
void set_instrument(Instrument reference)
Adds or replaces an instrument's reference data.
void set_last_price(const InstrumentId &id, Decimal64 price)
Records an instrument's latest price, used to value market orders and size notionals.
Runs one strategy: feeds it events, reconciles what it asks for, checks the risk limits,...
One order a strategy asks the runner to place.
The events a runner delivers to a strategy's handlers, and the market phase.
What a strategy asks the runner for: orders (OrderIntent), target positions (TargetPosition) and canc...
Replays a strategy over stored bars: fill and cost models, the replay ledger, and the report.
Runs a strategy: the runner, the polling loop, the order journal, and stopping.
std::variant< OrderIntent, TargetPosition, CancelIntent< Broker > > Instruction
One request a strategy queued: an order, a target position or a cancellation.
MarketPhase
Where the clock stands relative to the trading session.
The library: broker-neutral types (core), and the modules below.
BarInterval
The period one bar covers.
std::chrono::system_clock::time_point timestamp_
The instant marking the period; BarSeries::stamp_ says which edge.
Identifies an instrument: its country, venue and symbol.
Reference data for one instrument.
InstrumentId id_
The instrument.
A broker's reference to one order, used to amend or cancel it.
The trading days a broker reported for one market, ascending by date.
One bar, delivered to on_bar.
InstrumentId instrument_
The instrument the bar is for.
Identifies one cached bar series: an instrument at one bar interval.
InstrumentId instrument_
The instrument.
friend bool operator<(const SeriesKey &lhs, const SeriesKey &rhs)
Orders keys by instrument, then interval, so they can key a map.
BarInterval interval_
The bar interval; one instrument at two intervals is two series.
static SessionWindow krx()
Returns the KRX regular session, 09:00-15:30 KST.
One bar, delivered to on_bar.
A request to cancel one working order.
What the account holds and which orders are still working, as a strategy sees it.
The intraday session of a market, as the operator states it.
The position a strategy wants to hold in one instrument.