5#include "./portfolio.hpp"
61namespace strategy_detail {
76#define ATL_DETECT_DECLARED(NAME) \
77 struct NAME##_fallback { \
80 template <typename S> \
81 struct NAME##_probe : S, NAME##_fallback {}; \
82 template <typename S, typename = void> \
83 struct NAME##_is_ambiguous : std::true_type {}; \
84 template <typename S> \
85 struct NAME##_is_ambiguous<S, std::void_t<decltype(&NAME##_probe<S>::NAME)>> : std::false_type {}; \
86 template <typename S> \
87 constexpr bool declares_##NAME = \
88 std::conjunction_v<std::is_class<S>, std::negation<std::is_final<S>>, NAME##_is_ambiguous<S>>
101#undef ATL_DETECT_DECLARED
105template <
typename S,
typename =
void>
106struct names_static_bool_reads_bar_history : std::false_type {};
108struct names_static_bool_reads_bar_history<
109 S, std::void_t<decltype(S::reads_bar_history), decltype(&S::reads_bar_history)>
112 std::is_same_v<decltype(S::reads_bar_history), const bool> &&
113 std::is_same_v<decltype(&S::reads_bar_history), const bool*>
116template <
typename S,
bool Declared = declares_reads_bar_history<S>>
117struct bar_history_policy {
118 static constexpr bool value =
true;
122struct bar_history_policy<S, true> {
124 names_static_bool_reads_bar_history<S>::value,
125 "reads_bar_history must be a public `static constexpr bool`; a declaration of any other kind is "
126 "refused rather than read as absent, which would keep the history it asked to drop, or the reverse"
128 static constexpr bool value = S::reads_bar_history;
136constexpr bool reads_bar_history = bar_history_policy<S>::value;
139template <
typename S,
typename =
void>
140struct names_data_type : std::false_type {};
142struct names_data_type<S, std::void_t<typename S::data_type>> : std::true_type {};
146 NoDataRecord() =
delete;
149template <typename S, bool Names = names_data_type<S>::value>
150struct named_data_type {
151 using type = NoDataRecord;
155struct named_data_type<S, true> {
156 using type =
typename S::data_type;
159template <
typename S,
bool Declared = declares_on_data<S>>
162 !names_data_type<S>::value,
163 "`data_type` names the record type on_data takes, but this strategy declares no on_data, so no record "
164 "would reach it: declare on_data, or remove data_type"
166 using type = NoDataRecord;
170struct data_policy<S, true> {
172 names_data_type<S>::value,
173 "a strategy declaring on_data names the record type it takes: `using data_type = ...;` (a std::variant "
174 "for several kinds of record)"
176 using type =
typename named_data_type<S>::type;
184using data_record_t =
typename data_policy<S>::type;
188constexpr bool declares_any_handler =
189 declares_on_start<S> || declares_on_stop<S> || declares_on_bar<S> || declares_on_bars<S> || declares_on_quote<S> ||
190 declares_on_fill<S> || declares_on_order_update<S> || declares_on_phase<S> || declares_on_data<S>;
194constexpr bool names_can_be_read = std::is_class_v<S> && !std::is_final_v<S>;
198void require_readable_names() {
200 names_can_be_read<S>,
201 "a final strategy cannot be checked for a handler the runner would skip, because its member names "
202 "cannot be looked up; remove `final` from the strategy class"
211void require_one_bar_handler() {
213 !(declares_on_bar<S> && declares_on_bars<S>),
214 "a strategy declares on_bar or on_bars, not both: on_bar receives each bar, on_bars every "
215 "instrument's bar of a period at once; keep the one this strategy decides with"
239template <
typename S,
typename Ctx>
241 strategy_detail::require_readable_names<S>();
242 if constexpr (strategy_detail::declares_on_start<S>) {
246 static_cast<void>(context);
258template <
typename S,
typename Ctx>
260 strategy_detail::require_readable_names<S>();
261 if constexpr (strategy_detail::declares_on_stop<S>) {
265 static_cast<void>(context);
281template <
typename S,
typename Ctx>
283 strategy_detail::require_readable_names<S>();
284 strategy_detail::require_one_bar_handler<S>();
286 strategy_detail::declares_on_bar<S> || !strategy_detail::declares_on_bars<S>,
287 "this strategy declares on_bars, so its bars are delivered in slices: feed it through "
288 "Runner::record and Runner::feed(const BarSlice&), not one BarEvent at a time"
290 if constexpr (strategy_detail::declares_on_bar<S>) {
294 static_cast<void>(context);
295 static_cast<void>(event);
308template <
typename S,
typename Ctx>
310 strategy_detail::require_readable_names<S>();
311 strategy_detail::require_one_bar_handler<S>();
312 if constexpr (strategy_detail::declares_on_bars<S>) {
316 static_cast<void>(context);
317 static_cast<void>(slice);
330template <
typename S,
typename Ctx>
332 strategy_detail::require_readable_names<S>();
333 if constexpr (strategy_detail::declares_on_quote<S>) {
337 static_cast<void>(context);
338 static_cast<void>(event);
351template <
typename S,
typename Ctx>
353 strategy_detail::require_readable_names<S>();
354 if constexpr (strategy_detail::declares_on_fill<S>) {
358 static_cast<void>(context);
359 static_cast<void>(event);
372template <
typename S,
typename Ctx>
374 strategy_detail::require_readable_names<S>();
375 if constexpr (strategy_detail::declares_on_order_update<S>) {
376 strategy.on_order_update(context, event);
379 static_cast<void>(context);
380 static_cast<void>(event);
394template <
typename S,
typename Ctx>
396 strategy_detail::require_readable_names<S>();
397 if constexpr (strategy_detail::declares_on_phase<S>) {
401 static_cast<void>(context);
402 static_cast<void>(event);
415template <
typename S,
typename Ctx>
417 strategy_detail::require_readable_names<S>();
418 if constexpr (strategy_detail::declares_on_data<S>) {
422 static_cast<void>(context);
423 static_cast<void>(event);
429namespace strategy_detail {
432template <
typename S,
typename Ctx>
433void call_every_handler(
434 S&
strategy, Ctx& context,
const BarEvent& bar,
const BarSlice& slice,
const QuoteEvent& quote,
const Fill& fill,
440 if constexpr (declares_on_bars<S>) {
441 static_cast<void>(bar);
444 static_cast<void>(slice);
458template <
typename S,
typename Ctx>
459constexpr bool compiles_every_handler_call() {
460 if constexpr (names_can_be_read<S>) {
461 static_cast<void>(&call_every_handler<S, Ctx>);
609 static constexpr std::string_view
name =
"probe";
625template <
typename CapsType>
657 void note(std::string_view message) {
658 lines_.emplace_back(message);
664 const std::vector<std::string>&
lines() const noexcept {
669 std::vector<std::string> lines_;
676 std::chrono::system_clock::time_point
now() const noexcept {
720 if (known.id_ ==
id) {
732 submitted_.push_back(std::move(intent));
740 targets_.push_back(std::move(target));
763 const std::vector<OrderIntent>&
submitted() const noexcept {
770 const std::vector<TargetPosition>&
targets() const noexcept {
777 const std::vector<CancelIntent<ProbeBroker>>&
canceled() const noexcept {
782 std::chrono::system_clock::time_point
now_{};
795 std::vector<OrderIntent> submitted_;
796 std::vector<TargetPosition> targets_;
797 std::vector<CancelIntent<ProbeBroker>> canceled_;
813template <
typename S,
typename Ctx>
818 strategy_detail::names_can_be_read<S>,
819 "a final strategy cannot be checked for a handler the runner would skip, because its member names "
820 "cannot be looked up; remove `final` from the strategy class"
826 !std::is_copy_constructible_v<Ctx> && !std::is_constructible_v<Ctx, Ctx&>,
827 "a strategy context must not be copyable, so that a handler taking it by value does not compile "
828 "(what it submitted would go to the copy and be lost); delete the context's copy constructor"
831 strategy_detail::declares_any_handler<S>,
832 "This type declares no strategy handler. Expected at least one of on_start, on_bar, on_bars, "
833 "on_quote, on_fill, on_order_update, on_phase, on_data, or on_stop"
836 !(strategy_detail::declares_on_bar<S> && strategy_detail::declares_on_bars<S>),
837 "a strategy declares on_bar or on_bars, not both: on_bar receives each bar, on_bars every "
838 "instrument's bar of a period at once; keep the one this strategy decides with"
842 static_assert(strategy_detail::reads_bar_history<S> || !strategy_detail::reads_bar_history<S>);
845 static constexpr bool value = strategy_detail::compiles_every_handler_call<S, Ctx>();
866#define ATL_ASSERT_STRATEGY(S, Ctx) \
868 ::algotradelib::strategy::StrategyConformance<S, Ctx>::value, \
869 "Strategy does not satisfy the algotradelib strategy surface; see the messages above" \
One order a strategy asks the runner to place.
A log that keeps each line in memory for a test to read.
void note(std::string_view message)
Records one line.
const std::vector< std::string > & lines() const noexcept
Returns the recorded lines.
A context for testing a strategy without a runner: it records what the strategy asks for.
ProbeContextT & operator=(const ProbeContextT &)=delete
Deleted: a probe cannot be copied.
std::chrono::system_clock::time_point now() const noexcept
Returns the current instant.
const std::vector< CancelIntent< ProbeBroker > > & canceled() const noexcept
Returns the cancellations requested.
void cancel(const OrderRef< ProbeBroker > &ref)
Records a cancellation.
TradingCalendar calendar_
const std::vector< TargetPosition > & targets() const noexcept
Returns the target positions submitted.
const Portfolio< ProbeBroker > & portfolio() const noexcept
Returns the portfolio.
CapsType caps
The broker capabilities the strategy sees.
ProbeContextT & operator=(ProbeContextT &&)=default
Move assignment: takes the other probe's state.
ProbeBroker Broker
The broker tag; see ProbeBroker.
Log & log() noexcept
Returns the log.
ProbeContextT(ProbeContextT &&)=default
Move constructor: takes the other probe's state.
const TradingCalendar & calendar() const noexcept
Returns the trading calendar.
void submit(TargetPosition target)
Records a target position.
std::vector< Instrument > instruments_
Portfolio< ProbeBroker > portfolio_
std::chrono::system_clock::time_point now_
const SessionWindow & session() const noexcept
Returns the session window.
void submit(OrderIntent intent)
Records an order intent.
MarketPhase phase() const noexcept
Returns the market phase.
const std::vector< OrderIntent > & submitted() const noexcept
Returns the order intents submitted.
ProbeContextT()=default
Constructs an empty probe.
std::optional< Instrument > instrument(const InstrumentId &id) const
Looks up an instrument's reference data in instruments_.
ProbeContextT(const ProbeContextT &)=delete
Deleted: like a runner's context, a probe cannot be copied.
#define ATL_DETECT_DECLARED(NAME)
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...
Calls a strategy's handlers, skipping the ones it does not declare.
void phase(S &strategy, Ctx &context, const MarketPhase &event)
Calls strategy.on_phase(context, event) if the strategy declares on_phase; otherwise does nothing.
void quote(S &strategy, Ctx &context, const QuoteEvent &event)
Calls strategy.on_quote(context, event) if the strategy declares on_quote; otherwise does nothing.
void start(S &strategy, Ctx &context)
Calls strategy.on_start(context) if the strategy declares on_start; otherwise does nothing.
void stop(S &strategy, Ctx &context)
Calls strategy.on_stop(context) if the strategy declares on_stop; otherwise does nothing.
void bar(S &strategy, Ctx &context, const BarEvent &event)
Calls strategy.on_bar(context, event) if the strategy declares on_bar; otherwise does nothing.
void fill(S &strategy, Ctx &context, const Fill &event)
Calls strategy.on_fill(context, event) if the strategy declares on_fill; otherwise does nothing.
void order_update(S &strategy, Ctx &context, const OrderSnapshot &event)
Calls strategy.on_order_update(context, event) if the strategy declares on_order_update; otherwise do...
void data(S &strategy, Ctx &context, const DataEvent< strategy_detail::data_record_t< S > > &event)
Calls strategy.on_data(context, event) if the strategy declares on_data; otherwise does nothing.
void bars(S &strategy, Ctx &context, const BarSlice &slice)
Calls strategy.on_bars(context, slice) if the strategy declares on_bars; otherwise does nothing.
What a strategy sees and emits: events, intents, the portfolio, reconciliation and risk limits.
MarketPhase
Where the clock stands relative to the trading session.
@ OPEN
Inside the session.
ProbeContextT< NoCaps > MinimalContext
A probe context whose broker implements nothing optional.
ProbeContextT< AllCaps > FullContext
A probe context whose broker implements everything optional.
The library: broker-neutral types (core), and the modules below.
SellableSource
Where the library gets a broker's sellable quantity.
@ INQUIRY
From a per-instrument inquiry, made only where the snapshot has no figure.
@ NONE
No per-instrument inquiry: any figure comes on the holdings rows (Kiwoom), or there is none.
BarInterval
The period one bar covers.
Identifies an instrument: its country, venue and symbol.
A broker's reference to one order, used to amend or cancel it.
The state of one order, as a broker listing reported it.
What a sellable quantity covers, and how RiskGuard must treat resting sells against it.
@ WHOLE_HOLDING
Every share held of the instrument, whatever venue or lot.
@ DEDUCT
Subtract every resting sell from the figure.
The trading days a broker reported for one market, ascending by date.
A capability set in which the broker implements everything optional.
static constexpr bool has_batch_reference_data
Whether one reference-data request can cover several instruments.
static constexpr bool has_calendar_sessions
Whether the adapter fills each open day's session hours (TradingDay::regular_, extended_); a live loo...
static constexpr bool has_client_order_id
Whether the broker accepts an idempotency key (OrderRequest::client_order_id_).
static constexpr bool has_trigger_price
Whether the adapter sends trigger prices (stop-limit orders).
static constexpr bool supports_interval(BarInterval)
Tests whether the broker serves bars of an interval (the unnamed argument).
static constexpr bool has_trade_prints
Whether the broker publishes recent trades.
static constexpr bool has_history_limit
Whether an order-history inquiry accepts a row limit (OrderHistoryQuery::limit_).
static constexpr bool working_orders_state_terminal
Whether the working-order listing can show a terminal status (filled, cancelled, ....
static constexpr SellableBasis sellable_inquiry_basis
The whole holding, with resting sells deducted (the basis the library assumes for Toss,...
static constexpr bool has_batch_prices
Whether the broker quotes several instruments in one request.
static constexpr bool has_working_orders
Whether the broker lists the orders still open to amendment. A listing shows only what the broker's A...
static constexpr bool has_price_limits
Whether the broker publishes the day's price limits.
static constexpr bool has_amendable_quantity
Whether the broker reports the quantity still amendable on an open order.
static constexpr bool has_partial_cancel
Whether the broker can cancel part of an order.
static constexpr bool has_calendar_range
Whether one calendar request covers a span of dates.
static constexpr bool has_depth
Whether the broker publishes the order book (depth).
static constexpr bool history_requires_range
Whether an order-history inquiry needs a date range (OrderHistoryQuery::from_).
static constexpr bool has_buying_power
Whether the broker reports buying power.
static constexpr bool has_account_discovery
Whether the broker lists the selectable accounts.
static constexpr bool has_calendar
Whether the broker publishes the trading calendar.
static constexpr SellableSource sellable_source
The sellable quantity comes from an inquiry.
static constexpr bool has_order_by_id
Whether the broker can look up one order by its id.
static constexpr bool has_commission_schedule
Whether the broker publishes the account's commission rates.
static constexpr bool has_reference_data
Whether the broker publishes instrument reference data.
static constexpr bool data_only
false: this broker takes orders.
static constexpr bool has_buying_power_quantity
Whether the broker can also say how many shares are affordable.
static constexpr bool has_history_symbol_filter
Whether an order-history inquiry can filter by symbol.
static constexpr bool has_history_cursor
Whether an order-history answer can carry a cursor to the next page.
One bar, delivered to on_bar.
Every instrument's bar of one interval for one period end, delivered to on_bars.
A request to cancel one working order.
A record of data from outside the broker, delivered to on_data.
One execution of an order the strategy placed, delivered to on_fill.
A capability set in which the broker implements nothing optional.
static constexpr bool history_requires_range
Whether an order-history inquiry needs a date range (OrderHistoryQuery::from_).
static constexpr bool has_reference_data
Whether the broker publishes instrument reference data.
static constexpr bool has_buying_power
Whether the broker reports buying power.
static constexpr bool has_client_order_id
Whether the broker accepts an idempotency key (OrderRequest::client_order_id_).
static constexpr bool has_calendar_sessions
Whether the adapter fills each open day's session hours (TradingDay::regular_, extended_); a live loo...
static constexpr bool has_order_by_id
Whether the broker can look up one order by its id.
static constexpr bool data_only
Whether the client is a market-data source that takes no orders (built on DataOnlyTraits).
static constexpr bool has_batch_reference_data
Whether one reference-data request can cover several instruments.
static constexpr bool has_account_discovery
Whether the broker lists the selectable accounts.
static constexpr bool has_batch_prices
Whether the broker quotes several instruments in one request.
static constexpr bool has_history_limit
Whether an order-history inquiry accepts a row limit (OrderHistoryQuery::limit_).
static constexpr bool has_buying_power_quantity
Whether the broker can also say how many shares are affordable.
static constexpr bool has_commission_schedule
Whether the broker publishes the account's commission rates.
static constexpr bool supports_interval(BarInterval)
Tests whether the broker serves bars of an interval (the unnamed argument).
static constexpr bool working_orders_state_terminal
Whether the working-order listing can show a terminal status (filled, cancelled, ....
static constexpr SellableBasis sellable_inquiry_basis
Unestablished, since there is no inquiry.
static constexpr bool has_trigger_price
Whether the adapter sends trigger prices (stop-limit orders).
static constexpr bool has_calendar_range
Whether one calendar request covers a span of dates.
static constexpr bool has_history_cursor
Whether an order-history answer can carry a cursor to the next page.
static constexpr bool has_trade_prints
Whether the broker publishes recent trades.
static constexpr bool has_amendable_quantity
Whether the broker reports the quantity still amendable on an open order.
static constexpr bool has_working_orders
Whether the broker lists the orders still open to amendment. A listing shows only what the broker's A...
static constexpr bool has_price_limits
Whether the broker publishes the day's price limits.
static constexpr bool has_calendar
Whether the broker publishes the trading calendar.
static constexpr bool has_partial_cancel
Whether the broker can cancel part of an order.
static constexpr bool has_depth
Whether the broker publishes the order book (depth).
static constexpr bool has_history_symbol_filter
Whether an order-history inquiry can filter by symbol.
static constexpr SellableSource sellable_source
No sellable-quantity figure is available.
What the account holds and which orders are still working, as a strategy sees it.
The broker tag of a probe context; nothing it issues reaches a market.
static constexpr std::string_view name
The broker name an order reference prints.
A quote the runner has just read, delivered to on_quote.
The intraday session of a market, as the operator states it.
static SessionWindow krx()
Returns the KRX regular session, 09:00-15:30 KST.
The position a strategy wants to hold in one instrument.