5#include "../strategy/portfolio.hpp"
7#include <algotradelib/core>
9#if defined(ATL_HAS_EIGEN)
10#include <algotradelib/analytics>
18#include <unordered_map>
27using strategy::BarEvent;
28using strategy::CancelIntent;
31using strategy::OrderIntent;
32using strategy::Portfolio;
33using strategy::QuoteEvent;
34using strategy::TargetPosition;
44template <
typename Broker>
45using Instruction = std::variant<OrderIntent, TargetPosition, CancelIntent<Broker>>;
80template <
typename BrokerTag,
typename CapsType>
110 void note(std::string_view message) {
111 if (lines_.size() >= capacity_) {
112 lines_.erase(lines_.begin());
114 lines_.emplace_back(message);
121 const std::vector<std::string>&
lines() const noexcept {
return lines_; }
127 std::vector<std::string>
take() {
128 std::vector<std::string> taken;
135 static constexpr std::size_t capacity_ = 4096;
136 std::vector<std::string> lines_;
144 explicit Context(std::size_t series_capacity = 512) : series_capacity_(series_capacity) {}
152 std::chrono::system_clock::time_point
now() const noexcept {
return now_; }
178 const auto found = instruments_.find(
id);
179 if (found == instruments_.end()) {
182 return found->second;
191 const auto found = prices_.find(
id);
192 if (found == prices_.end()) {
195 return found->second;
198#if defined(ATL_HAS_EIGEN)
214 const auto found = series_.find(
SeriesKey{id, interval});
215 if (found == series_.end()) {
218 return &found->second;
257 const std::vector<Instruction<BrokerTag>>&
queued() const noexcept {
return queued_; }
263 std::vector<Instruction<BrokerTag>>
drain() {
264 std::vector<Instruction<BrokerTag>> taken;
273 void set_now(std::chrono::system_clock::time_point when)
noexcept { now_ = when; }
303 auto key = reference.
id_;
304 instruments_.insert_or_assign(std::move(key), std::move(reference));
313 prices_.insert_or_assign(
id, std::move(price));
316#if defined(ATL_HAS_EIGEN)
323 void record_bar(
const BarEvent& event) {
324 const SeriesKey key{
event.instrument_,
event.interval_};
325 auto found = series_.find(key);
326 if (found == series_.end()) {
329 found->second.push(event.
bar_);
336 struct InstrumentHash {
337 std::size_t operator()(
const InstrumentId&
id)
const noexcept {
338 std::size_t seed = std::hash<std::string>{}(
id.symbol_);
339 seed ^=
static_cast<std::size_t
>(
id.country_) + 0x9e3779b97f4a7c15ULL + (seed << 6) + (seed >> 2);
340 seed ^=
static_cast<std::size_t
>(
id.venue_) + 0x9e3779b97f4a7c15ULL + (seed << 6) + (seed >> 2);
345 std::size_t series_capacity_;
346 std::chrono::system_clock::time_point now_{};
348 TradingCalendar calendar_;
349 Portfolio<BrokerTag> portfolio_;
350 std::unordered_map<InstrumentId, Instrument, InstrumentHash> instruments_;
351 std::unordered_map<InstrumentId, Decimal64, InstrumentHash> prices_;
352#if defined(ATL_HAS_EIGEN)
353 std::map<SeriesKey, analytics::SeriesBuffer> series_;
355 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.
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 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).
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.
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...
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.
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.
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.
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 position a strategy wants to hold in one instrument.