algotradelib 0.0.0.9000
C++ header-only library for algorithmic trading
Loading...
Searching...
No Matches
context.hpp
1#pragma once
2
5#include "../strategy/portfolio.hpp"
6
7#include <algotradelib/core>
8
9#if defined(ATL_HAS_EIGEN)
10#include <algotradelib/analytics>
11#endif
12
13#include <chrono>
14#include <cstddef>
15#include <cstdint>
16#include <map>
17#include <optional>
18#include <stdexcept>
19#include <string>
20#include <unordered_map>
21#include <utility>
22#include <variant>
23#include <vector>
24
25namespace algotradelib {
26namespace runner {
27
28// The strategy types a runner speaks in, imported from `strategy`.
29using strategy::BarEvent;
30using strategy::CancelIntent;
31using strategy::DataEvent;
32using strategy::Fill;
34using strategy::OrderIntent;
35using strategy::Portfolio;
36using strategy::QuoteEvent;
37using strategy::SessionWindow;
38using strategy::TargetPosition;
39
48template <typename Broker>
49using Instruction = std::variant<OrderIntent, TargetPosition, CancelIntent<Broker>>;
50
51template <typename Strategy, typename CapsType, typename BrokerTag, typename Executor>
52class Runner;
53
54} // namespace runner
55
56namespace backtest {
57template <typename Strategy, typename CapsType>
58class Backtester;
59} // namespace backtest
60
61namespace runner {
62namespace context_detail {
63
64// A count of a context's portfolio replacements that a move also advances. Moving a context's state into
65// another replaces the destination's portfolio, so the destination's count must not merely take the source's
66// value: it rises above both, and the source's (now emptied) count rises too. A replay comparing the count with
67// the one it last saw then rebuilds whatever a move brought in.
68struct Revision {
69 std::uint64_t value_{0};
70
71 Revision() = default;
72 Revision(const Revision&) = delete;
73 Revision& operator=(const Revision&) = delete;
74 Revision(Revision&& other) noexcept : value_(other.value_ + 1) {
75 ++other.value_;
76 }
77 Revision& operator=(Revision&& other) noexcept {
78 value_ = (value_ > other.value_ ? value_ : other.value_) + 1;
79 ++other.value_;
80 return *this;
81 }
82};
83
84// In-place access to a context's caches, for the runner and the replay only.
85//
86// A strategy reads its portfolio through `Context::portfolio()`, a const reference; it gets no mutable
87// one from here, since everything below is private and only `Runner` and `Backtester` are friends. The
88// counts tell a replay what changed since it last brought the portfolio up to date: a replacement
89// (`Context::set_portfolio`, or a move), a runner's edit of its working rows, or new reference data. The price
90// and series entries let a replay that sets them on every bar find them once.
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;
96
97 // For a runner editing working rows and buying power in place; counted as a runner edit.
98 template <typename Ctx>
99 static auto& for_runner_edit(Ctx& context) noexcept {
100 ++context.runner_edits_;
101 return context.portfolio_;
102 }
103
104 // For a replay bringing the portfolio up to date; not counted.
105 template <typename Ctx>
106 static auto& for_replay_sync(Ctx& context) noexcept {
107 return context.portfolio_;
108 }
109
110 template <typename Ctx>
111 static std::uint64_t replacements(const Ctx& context) noexcept {
112 return context.replacements_.value_;
113 }
114
115 template <typename Ctx>
116 static std::uint64_t runner_edits(const Ctx& context) noexcept {
117 return context.runner_edits_;
118 }
119
120 template <typename Ctx>
121 static std::uint64_t reference_changes(const Ctx& context) noexcept {
122 return context.reference_changes_;
123 }
124
125 // Sets an instrument's last price and returns where it is kept, for a replay that sets it again on every bar:
126 // the entry, once made, stays where it is for the context's life (a map node).
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;
130 }
131
132#if defined(ATL_HAS_EIGEN)
133 // The series a bar of `event`'s instrument and interval goes into, made if it is the first; it stays where it
134 // is for the context's life, as `Context::bars` promises.
135 template <typename Ctx>
136 static analytics::SeriesBuffer& series_for(Ctx& context, const BarEvent& event) {
137 return context.series_for(event);
138 }
139
140 // The newest bar time of `event`'s instrument and interval, kept instead of a series when the strategy reads
141 // no history; made empty if it is the first, and it stays where it is for the context's life.
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);
145 }
146
147 // Refuses `event` unless it is later than its series' newest bar, then makes it the newest; the check a series
148 // push makes, without the series.
149 static void advance_bar_time(std::optional<std::chrono::system_clock::time_point>& newest, const BarEvent& event) {
150 if (newest && !(*newest < event.bar_.timestamp_)) {
151 throw std::invalid_argument("a series buffer observation must be later than the last");
152 }
153 newest = event.bar_.timestamp_;
154 }
155
156 // For a runner whose strategy declares it reads no bar history: `Context::bars` throws from now on.
157 template <typename Ctx>
158 static void stop_bar_history(Ctx& context) {
159 context.history_.stop_keeping();
160 }
161#endif
162};
163
164#if defined(ATL_HAS_EIGEN)
165// A context's bar history: each series' trailing bars, or, when the context keeps none, each series' newest bar
166// time only (to refuse a bar that is not later). Whether it keeps them belongs to the context object, not to
167// its contents: a move assignment keeps the destination's, so a context moved into a runner's place cannot turn
168// on reads the runner never records for, and what it brings is converted to the destination's form in place,
169// without allocating, so moving a context still cannot throw.
170struct BarHistory {
171 // One series of an instrument at an interval.
172 struct Entry {
173 // Its bars; never made in a context keeping no history.
174 std::optional<analytics::SeriesBuffer> series_;
175 // Its newest bar time where it has no bars: kept instead of them, or brought by a context keeping none,
176 // when it bounds the first bar pushed.
177 std::optional<std::chrono::system_clock::time_point> newest_;
178 };
179 using ByInterval = std::map<BarInterval, Entry>;
180
181 // Node-based both ways, so an entry never moves once made.
182 std::unordered_map<InstrumentId, ByInterval, id_detail::InstrumentIdHash> entries_;
183 bool kept_{true};
184
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_);
191 if (!kept_) {
192 keep_times_only();
193 }
194 return *this;
195 }
196
197 // For a runner whose strategy reads no history.
198 void stop_keeping() noexcept {
199 kept_ = false;
200 keep_times_only();
201 }
202
203private:
204 // Replaces each series by its newest bar time, keeping the later where both exist.
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;
212 }
213 }
214 entry.series_.reset();
215 }
216 }
217 }
218};
219#endif
220
221} // namespace context_detail
222
224struct SeriesKey {
228 BarInterval interval_{BarInterval::ONE_DAY};
229
236 friend bool operator<(const SeriesKey& lhs, const SeriesKey& rhs) {
237 if (!(lhs.instrument_ == rhs.instrument_)) {
238 return lhs.instrument_ < rhs.instrument_;
239 }
240 return lhs.interval_ < rhs.interval_;
241 }
242};
243
256template <typename BrokerTag, typename CapsType>
257class Context {
258public:
260 using Broker = BrokerTag;
262 using caps = CapsType;
263
265 Context(const Context&) = delete;
270 Context& operator=(const Context&) = delete;
272 Context(Context&&) = default;
277 Context& operator=(Context&&) = default;
278
280 class Log {
281 public:
286 void note(std::string_view message) {
287 if (lines_.size() >= capacity_) {
288 lines_.erase(lines_.begin());
289 }
290 lines_.emplace_back(message);
291 }
292
297 const std::vector<std::string>& lines() const noexcept {
298 return lines_;
299 }
300
305 std::vector<std::string> take() {
306 std::vector<std::string> taken;
307 taken.swap(lines_);
308 return taken;
309 }
310
311 private:
312 // Bounded so a long session cannot grow it without limit.
313 static constexpr std::size_t capacity_ = 4096;
314 std::vector<std::string> lines_;
315 };
316
322 explicit Context(std::size_t series_capacity = 512) : series_capacity_(series_capacity) {}
323
324 // --- What a strategy reads -------------------------------------------------------------
325
330 std::chrono::system_clock::time_point now() const noexcept {
331 return now_;
332 }
333
338 MarketPhase phase() const noexcept {
339 return phase_;
340 }
341
350 const SessionWindow& session() const noexcept {
351 return session_;
352 }
353
358 const TradingCalendar& calendar() const noexcept {
359 return calendar_;
360 }
361
366 const Portfolio<BrokerTag>& portfolio() const noexcept {
367 return portfolio_;
368 }
369
375 std::optional<Instrument> instrument(const InstrumentId& id) const {
376 const auto found = instruments_.find(id);
377 if (found == instruments_.end()) {
378 return std::nullopt;
379 }
380 return found->second;
381 }
382
392 const Instrument* find_instrument(const InstrumentId& id) const {
393 const auto found = instruments_.find(id);
394 return found == instruments_.end() ? nullptr : &found->second;
395 }
396
402 std::optional<Decimal64> last_price(const InstrumentId& id) const {
403 const auto found = prices_.find(id);
404 if (found == prices_.end()) {
405 return std::nullopt;
406 }
407 return found->second;
408 }
409
410#if defined(ATL_HAS_EIGEN)
424 const analytics::SeriesBuffer* bars(const InstrumentId& id, BarInterval interval = BarInterval::ONE_DAY) const {
425 require_bar_history();
426 const auto found = history_.entries_.find(id);
427 if (found == history_.entries_.end()) {
428 return nullptr;
429 }
430 const auto entry = found->second.find(interval);
431 if (entry == found->second.end() || !entry->second.series_) {
432 return nullptr;
433 }
434 return &*entry->second.series_;
435 }
436#endif
437
442 Log& log() noexcept {
443 return log_;
444 }
445
446 // --- What a strategy asks for ---------------------------------------------------------
447
452 void submit(OrderIntent intent) {
453 queued_.emplace_back(std::move(intent));
454 }
455
460 void submit(TargetPosition target) {
461 queued_.emplace_back(std::move(target));
462 }
463
469 void cancel(const OrderRef<BrokerTag>& ref, std::string tag = {}) {
470 queued_.emplace_back(CancelIntent<BrokerTag>{ref, std::move(tag)});
471 }
472
473 // --- What the runner uses ------------------------------------------------------------
474
479 const std::vector<Instruction<BrokerTag>>& queued() const noexcept {
480 return queued_;
481 }
482
487 std::vector<Instruction<BrokerTag>> drain() {
488 std::vector<Instruction<BrokerTag>> taken;
489 taken.swap(queued_);
490 return taken;
491 }
492
497 void set_now(std::chrono::system_clock::time_point when) noexcept {
498 now_ = when;
499 }
500
505 void set_phase(MarketPhase phase) noexcept {
506 phase_ = phase;
507 }
508
514 session_ = std::move(session);
515 }
516
527 calendar_ = std::move(calendar);
528 }
529
535 portfolio_ = std::move(portfolio);
536 ++replacements_.value_;
537 }
538
543 void set_instrument(Instrument reference) {
544 auto key = reference.id_;
545 instruments_.insert_or_assign(std::move(key), std::move(reference));
546 ++reference_changes_;
547 }
548
554 void set_last_price(const InstrumentId& id, Decimal64 price) {
555 prices_.insert_or_assign(id, std::move(price));
556 }
557
558#if defined(ATL_HAS_EIGEN)
566 void record_bar(const BarEvent& event) {
567 require_bar_history();
568 series_for(event).push(event.bar_);
569 }
570#endif
571
572private:
573 friend class context_detail::PortfolioAccess;
574
575 // The two per-instrument tables below are looked up by id and never iterated, so their order is
576 // nobody's to observe.
577 using InstrumentHash = id_detail::InstrumentIdHash;
578
579#if defined(ATL_HAS_EIGEN)
580 // The series a bar of `event`'s instrument and interval goes into, made if it is the first; found by hash,
581 // without building a key, and the instrument copied only for its first bar. A series without bars refuses
582 // a bar not later than a newest bar time a context keeping no history brought in; its first push then sets
583 // a later one.
584 analytics::SeriesBuffer& series_for(const BarEvent& event) {
585 auto& entry = entry_for(event);
586 if (!entry.series_) {
587 entry.series_.emplace(series_capacity_);
588 }
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");
591 }
592 return *entry.series_;
593 }
594
595 // The newest bar time of `event`'s series, for a context keeping no history; made empty if it is the first.
596 std::optional<std::chrono::system_clock::time_point>& bar_time_for(const BarEvent& event) {
597 return entry_for(event).newest_;
598 }
599
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;
604 }
605 return found->second[event.interval_];
606 }
607
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"
613 );
614 }
615 }
616#endif
617
618 std::size_t series_capacity_;
619 std::chrono::system_clock::time_point now_{};
620 MarketPhase phase_{MarketPhase::UNKNOWN};
621 SessionWindow session_{SessionWindow::krx()};
622 TradingCalendar calendar_;
623 Portfolio<BrokerTag> portfolio_;
624 // Counted for `context_detail::PortfolioAccess`: replacements of the portfolio (by `set_portfolio` or by a
625 // move into or out of this context), runners' edits of it in place, and changes of reference data.
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)
632 // Each instrument's cached series by interval, or with no history kept, their newest bar times.
633 context_detail::BarHistory history_;
634#endif
635 std::vector<Instruction<BrokerTag>> queued_;
636 Log log_;
637};
638
639} // namespace runner
640} // namespace algotradelib
An exact signed decimal: an int64 coefficient times 10^-scale.
Definition types.hpp:443
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.
Definition context.hpp:280
std::vector< std::string > take()
Removes and returns the recorded lines.
Definition context.hpp:305
void note(std::string_view message)
Records one line; when 4096 lines are held, the oldest is dropped.
Definition context.hpp:286
const std::vector< std::string > & lines() const noexcept
Returns the lines recorded since the last take.
Definition context.hpp:297
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).
Definition context.hpp:505
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).
Definition context.hpp:402
std::chrono::system_clock::time_point now() const noexcept
Returns the instant the runner is acting at.
Definition context.hpp:330
const TradingCalendar & calendar() const noexcept
Returns the trading calendar the runner last read.
Definition context.hpp:358
std::optional< Instrument > instrument(const InstrumentId &id) const
Returns an instrument's reference data, including its price grid.
Definition context.hpp:375
Log & log() noexcept
Returns the log.
Definition context.hpp:442
void set_session(SessionWindow session)
Sets the session window (for runners).
Definition context.hpp:513
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.
Definition context.hpp:460
const Instrument * find_instrument(const InstrumentId &id) const
Returns an instrument's reference data without copying it.
Definition context.hpp:392
const std::vector< Instruction< BrokerTag > > & queued() const noexcept
Returns the queued requests without removing them (for runners).
Definition context.hpp:479
void set_portfolio(Portfolio< BrokerTag > portfolio)
Replaces the portfolio (for runners).
Definition context.hpp:534
const SessionWindow & session() const noexcept
Returns the session window the runner derives phases from, for strategy::SessionEdges.
Definition context.hpp:350
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.
Definition context.hpp:262
MarketPhase phase() const noexcept
Returns the market phase.
Definition context.hpp:338
void cancel(const OrderRef< BrokerTag > &ref, std::string tag={})
Queues a cancellation of a working order.
Definition context.hpp:469
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).
Definition context.hpp:497
void set_calendar(TradingCalendar calendar)
Replaces the trading calendar (for runners and sources, not strategies).
Definition context.hpp:526
std::vector< Instruction< BrokerTag > > drain()
Removes and returns the queued requests (for runners).
Definition context.hpp:487
BrokerTag Broker
The broker tag of the order references.
Definition context.hpp:260
const Portfolio< BrokerTag > & portfolio() const noexcept
Returns the portfolio: positions, buying power and the orders still working.
Definition context.hpp:366
void submit(OrderIntent intent)
Queues an order; the runner checks and sends it after the handler returns.
Definition context.hpp:452
Context(std::size_t series_capacity=512)
Constructs a context.
Definition context.hpp:322
void set_instrument(Instrument reference)
Adds or replaces an instrument's reference data.
Definition context.hpp:543
void set_last_price(const InstrumentId &id, Decimal64 price)
Records an instrument's latest price, used to value market orders and size notionals.
Definition context.hpp:554
Runs one strategy: feeds it events, reconciles what it asks for, checks the risk limits,...
Definition runner.hpp:305
One order a strategy asks the runner to place.
Definition intent.hpp:253
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.
Definition bootstrap.hpp:16
Runs a strategy: the runner, the polling loop, the order journal, and stopping.
Definition clock.hpp:7
std::variant< OrderIntent, TargetPosition, CancelIntent< Broker > > Instruction
One request a strategy queued: an order, a target position or a cancellation.
Definition context.hpp:49
MarketPhase
Where the clock stands relative to the trading session.
Definition event.hpp:33
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.
Definition types.hpp:85
Reference data for one instrument.
InstrumentId id_
The instrument.
A broker's reference to one order, used to amend or cancel it.
Definition types.hpp:2402
The trading days a broker reported for one market, ascending by date.
Definition calendar.hpp:72
One bar, delivered to on_bar.
Definition event.hpp:313
InstrumentId instrument_
The instrument the bar is for.
Definition event.hpp:315
Identifies one cached bar series: an instrument at one bar interval.
Definition context.hpp:224
InstrumentId instrument_
The instrument.
Definition context.hpp:226
friend bool operator<(const SeriesKey &lhs, const SeriesKey &rhs)
Orders keys by instrument, then interval, so they can key a map.
Definition context.hpp:236
BarInterval interval_
The bar interval; one instrument at two intervals is two series.
Definition context.hpp:228
static SessionWindow krx()
Returns the KRX regular session, 09:00-15:30 KST.
Definition event.hpp:136
One bar, delivered to on_bar.
Definition event.hpp:313
A request to cancel one working order.
Definition intent.hpp:480
What the account holds and which orders are still working, as a strategy sees it.
Definition portfolio.hpp:82
The intraday session of a market, as the operator states it.
Definition event.hpp:122
The position a strategy wants to hold in one instrument.
Definition intent.hpp:451