7#include "../../core/calendar.hpp"
8#include "../../core/market_data.hpp"
9#include "../../core/types.hpp"
33 static constexpr std::string_view
name =
"mock";
67 "the mock market's state file did not record this change, which was not made" :
68 "the mock market's state file may hold this change, which was not made here"
89 std::chrono::system_clock::time_point
start_{};
159 : settings_(std::move(settings)),
160 now_(settings_.start_),
161 ledger_(settings_.cash_.amount_, settings_.cash_.currency_,
backtest::ExecutionHistory::NONE) {
163 throw std::invalid_argument(
"the mock market's starting cash is negative");
165 listings_.reserve(
bars.size());
166 for (
auto& series :
bars) {
168 throw std::invalid_argument(
"the mock market takes minute to daily bars only");
170 if (!series.ascending()) {
171 throw std::invalid_argument(
"a mock market series is not strictly ascending");
173 if (find_listing(series.instrument_) !=
nullptr) {
174 throw std::invalid_argument(
"the mock market was given two series of one instrument");
177 listing.reference_.id_ = series.instrument_;
178 listing.reference_.type_ = SecurityType::STOCK;
179 listing.reference_.status_ = InstrumentStatus::ACTIVE;
180 listing.reference_.currency_ = series.currency_;
181 listing.reference_.lot_size_ =
Decimal64(1, 0);
183 listing.series_ = std::move(series);
184 while (listing.next_ < listing.series_.bars_.size() && !(now_ < period_end(listing, listing.next_))) {
187 listings_.push_back(std::move(listing));
189 for (
auto& reference : instruments) {
190 auto found = std::find_if(listings_.begin(), listings_.end(), [&](
const Listing& listing) {
191 return listing.series_.instrument_ == reference.id_;
193 if (found == listings_.end()) {
194 throw std::invalid_argument(
"the mock market was given reference data for an instrument without bars");
196 found->reference_ = std::move(reference);
198 calendar_ = settings_.calendar_ ? *settings_.calendar_ : calendar_of_bars();
205 std::chrono::system_clock::time_point
now() const noexcept {
213 const std::optional<std::string>&
halted() const noexcept {
228 throw std::invalid_argument(
"the mock market's clock does not move backwards");
231 throw std::runtime_error(*halted_);
233 const auto failed = now_ < to ? record(Change{
nullptr,
nullptr, to}) : std::nullopt;
238 Listing* earliest =
nullptr;
239 for (
auto& listing : listings_) {
240 if (listing.next_ >= listing.series_.bars_.size()) {
243 if (earliest ==
nullptr || period_end(listing, listing.next_) < period_end(*earliest, earliest->next_)) {
247 if (earliest ==
nullptr || to < period_end(*earliest, earliest->next_)) {
250 now_ = period_end(*earliest, earliest->next_);
251 apply_bar(*earliest);
253 throw std::runtime_error(*halted_);
267 const auto* listing = find_listing(query.
instrument_);
268 if (listing ==
nullptr) {
269 return refused<BarSeries>(
"unknown_instrument",
"the mock market has no bars of this instrument");
271 if (query.
interval_ != listing->series_.interval_) {
272 return refused<BarSeries>(
"unsupported_interval",
"the mock market has no bars of this interval");
275 return refused<BarSeries>(
"bars_count",
"a bar request asks for at least one bar");
279 answer.
interval_ = listing->series_.interval_;
280 answer.
stamp_ = listing->series_.stamp_;
281 answer.
currency_ = listing->series_.currency_;
282 answer.
adjusted_ = listing->series_.adjusted_;
284 const auto& all = listing->series_.bars_;
288 const auto readable = [
this, listing, &query, &all](std::size_t k) {
289 return !(now_ < period_end(*listing, k)) && (!query.
before_ || !(*query.
before_ < all[k].timestamp_));
292 std::size_t high = all.size();
294 const std::size_t middle = end + (high - end) / 2;
295 if (readable(middle)) {
301 const auto count =
static_cast<std::size_t
>(query.
count_);
302 const std::size_t begin = end > count ? end - count : 0;
304 all.begin() +
static_cast<std::ptrdiff_t
>(begin), all.begin() +
static_cast<std::ptrdiff_t
>(end)
316 const auto* listing = find_listing(
instrument);
317 if (listing ==
nullptr) {
318 return refused<QuoteSnapshot>(
"unknown_instrument",
"the mock market has no bars of this instrument");
320 const auto last = last_closed(*listing);
325 error.
message_ =
"no bar of this instrument has ended yet";
329 quote.instrument_ = listing->series_.instrument_;
330 quote.last_price_ = listing->series_.bars_[*last].close_;
331 quote.currency_ = listing->series_.currency_;
332 quote.exchange_time_ = period_end(*listing, *last);
333 quote.received_at_ = now_;
344 const auto* listing = find_listing(
instrument);
345 if (listing ==
nullptr) {
346 return refused<Instrument>(
"unknown_instrument",
"the mock market has no bars of this instrument");
358 if (country != calendar_.country_) {
359 return refused<TradingCalendar>(
"unsupported_market",
"the mock market publishes one market's calendar");
361 auto answer = calendar_;
362 answer.received_at_ = now_;
381 for (
const auto& lot : ledger_.positions()) {
382 if (lot.quantity_.coefficient() == 0) {
386 row.sellable_quantity_ = row.quantity_;
387 const auto currency = lot.market_value_.currency_;
388 const auto cost =
decimal_multiply(row.quantity_, row.average_purchase_price_);
389 const auto gain = cost ?
decimal_subtract(row.market_value_.amount_, *cost) : std::nullopt;
390 if (!gain || !add_to_totals(snapshot.
totals_, row.market_value_.amount_, *cost, *gain, currency)) {
394 error.
message_ =
"a holding's value or the holdings' total does not fit an exact decimal";
397 row.purchase_value_ =
Money{*cost, currency};
398 row.unrealized_profit_loss_ =
Money{*gain, currency};
399 snapshot.
positions_.push_back(std::move(row));
410 return Money{ledger_.cash_in(settings_.cash_.currency_).value_or(
Decimal64(0, 0)), settings_.cash_.currency_};
424 const auto cash = ledger_.cash_in(currency);
426 return refused<BuyingPower>(
"unknown_currency",
"the mock market keeps no cash in this currency");
428 const auto spendable = spendable_in(currency, *
cash);
433 error.
message_ =
"the buying power does not fit an exact decimal";
461 return refused<PlacedOrder<Broker>>(
"market_halted",
"the mock market halted and takes no orders");
463 const auto* listing = find_listing(order.
instrument_);
464 if (listing ==
nullptr) {
465 return refused<PlacedOrder<Broker>>(
"unknown_instrument",
"the mock market has no bars of this instrument");
468 return refused<PlacedOrder<Broker>>(
469 "unsupported_order_type",
"the mock market takes market and limit orders only"
477 case TimeInForce::UNKNOWN:
478 return refused<PlacedOrder<Broker>>(
"unsupported_time_in_force",
"the mock market needs a time in force");
481 if (quantity.coefficient() <= 0 || quantity.scale() != 0) {
482 return refused<PlacedOrder<Broker>>(
"invalid_quantity",
"an order's quantity is a positive whole number");
485 if (limit != order.
price_.has_value() || (order.
price_ && order.
price_->coefficient() <= 0)) {
486 return refused<PlacedOrder<Broker>>(
487 "invalid_price",
"a limit order has a positive price and a market order none"
490 const auto currency = listing->series_.currency_;
491 std::optional<Decimal64> reserve_price = order.
price_;
492 if (!reserve_price) {
493 if (
const auto last = last_closed(*listing)) {
494 reserve_price = listing->series_.bars_[*last].close_;
497 if (order.
side_ == OrderSide::BUY) {
498 if (!reserve_price) {
499 return refused<PlacedOrder<Broker>>(
"no_price",
"no bar of this instrument has ended to price a market buy at");
501 const auto cash = ledger_.cash_in(currency);
502 const auto spendable =
cash ? spendable_in(currency, *
cash) : std::nullopt;
504 if (!spendable || !cost ||
decimal_less(*spendable, *cost)) {
505 return refused<PlacedOrder<Broker>>(
"insufficient_cash",
"the buy costs more than the buying power");
511 return refused<PlacedOrder<Broker>>(
512 "insufficient_holdings",
"the sell is more than the shares held and not already offered"
516 if (
const auto failed = record(Change{&order,
nullptr, std::nullopt})) {
517 return not_recorded<PlacedOrder<Broker>>(*failed);
519 MarketOrder accepted;
520 accepted.snapshot_.
order_id_ = std::to_string(++last_id_);
527 accepted.snapshot_.
status_ = OrderStatus::PENDING;
533 accepted.reserve_price_ = reserve_price;
534 if (
const auto last = last_closed(*listing)) {
535 accepted.decision_price_ = listing->series_.bars_[*last].close_;
536 accepted.decision_price_at_ = period_end(*listing, *last);
538 orders_.push_back(std::move(accepted));
554 for (
auto& order : orders_) {
555 if (order.snapshot_.order_id_ != order_id) {
558 if (order.snapshot_.status_ != OrderStatus::PENDING) {
561 if (
const auto failed = record(Change{
nullptr, &order_id, std::nullopt})) {
562 return not_recorded<PlacedOrder<Broker>>(*failed);
564 order.snapshot_.status_ = OrderStatus::CANCELED;
565 order.snapshot_.canceled_at_ = now_;
569 placed.
ref_.primary_ = order_id;
572 return refused<PlacedOrder<Broker>>(
"nothing_to_cancel",
"no open order has this id");
583 for (
const auto& order : orders_) {
584 if (order.snapshot_.status_ != OrderStatus::PENDING) {
588 row.
order_ = order.snapshot_;
589 row.
ref_.primary_ = order.snapshot_.order_id_;
591 listing.
orders_.push_back(std::move(row));
605 for (
const auto& order : orders_) {
606 const auto date = settings_.session_.local_date(*order.snapshot_.ordered_at_);
607 if ((query.
from_ && date < *query.
from_) || (query.
to_ && *query.
to_ < date)) {
610 page.
orders_.push_back(order.snapshot_);
623 const std::string* order_id_{
nullptr};
625 std::optional<std::chrono::system_clock::time_point> to_;
633 Recorder() =
default;
635 Recorder(
const Recorder&)
noexcept {}
637 Recorder(Recorder&& other) {
639 throw std::logic_error(
"a mock market kept in a file cannot be moved from");
643 Recorder& operator=(
const Recorder&) {
645 throw std::logic_error(
"a mock market kept in a file cannot be assigned to");
650 Recorder& operator=(Recorder&& other) {
651 if (record_ || other.record_) {
652 throw std::logic_error(
654 "a mock market kept in a file cannot be assigned to" :
655 "a mock market kept in a file cannot be moved from"
662 std::function<std::optional<MarketFileError::Kind>(
const Change&)> record_;
670 Instrument reference_;
672 std::size_t next_{0};
678 OrderSnapshot snapshot_;
680 std::optional<Decimal64> reserve_price_;
682 std::optional<Decimal64> decision_price_;
684 std::optional<std::chrono::system_clock::time_point> decision_price_at_;
686 std::optional<Date> session_;
690 template <
typename T>
691 static Result<T> refused(
const char* code,
const char* message) {
694 error.reached_broker_ =
true;
695 error.broker_code_ = code;
696 error.message_ = message;
701 std::optional<MarketFileError::Kind> record(
const Change& change)
const {
702 return recorder_.record_ ? recorder_.record_(change) : std::nullopt;
706 template <
typename T>
711 error.broker_code_ = error.reached_broker_ ?
"state_unconfirmed" :
"state_not_written";
717 TradingCalendar calendar_of_bars()
const {
718 using Days = std::chrono::duration<std::int64_t, std::ratio<86400>>;
719 const auto& session = settings_.session_;
720 const auto local_day = [&](std::chrono::system_clock::time_point at) {
721 return std::chrono::floor<Days>(at + session.utc_offset_).time_since_epoch().count();
724 std::set<std::int64_t> open;
725 for (
const auto& listing : listings_) {
726 if (listing.series_.bars_.empty()) {
730 calendar.country_ = listing.series_.instrument_.country_;
732 for (
const auto& bar : listing.series_.bars_) {
733 open.insert(local_day(
bar.timestamp_));
739 for (
auto day = *open.begin(); day <= *open.rbegin(); ++day) {
746 const Listing* find_listing(
const InstrumentId&
instrument)
const {
747 for (
const auto& listing : listings_) {
748 if (listing.series_.instrument_ ==
instrument) {
756 static std::chrono::system_clock::time_point period_end(
const Listing& listing, std::size_t at) {
761 std::chrono::system_clock::time_point period_start(
const Listing& listing, std::size_t at)
const {
762 const auto& series = listing.series_;
764 return series.bars_[at].timestamp_;
767 return period_end(listing, at) - *length;
769 return settings_.session_.opens_at(period_end(listing, at));
773 std::optional<std::size_t> last_closed(
const Listing& listing)
const {
774 std::optional<std::size_t> last;
775 for (std::size_t at = 0; at < listing.series_.bars_.size() && !(now_ < period_end(listing, at)); ++at) {
782 Decimal64 open_sells_of(
const InstrumentId&
instrument)
const {
783 Decimal64 total(0, 0);
784 for (
const auto& order : orders_) {
786 order.snapshot_.status_ == OrderStatus::PENDING && order.snapshot_.side_ == OrderSide::SELL &&
789 total =
decimal_add(total, order.snapshot_.quantity_).value_or(total);
796 std::optional<Decimal64> spendable_in(
const Currency& currency,
const Decimal64&
cash)
const {
797 std::optional<Decimal64> left =
cash;
798 for (
const auto& order : orders_) {
803 order.snapshot_.status_ != OrderStatus::PENDING || order.snapshot_.side_ != OrderSide::BUY ||
804 !(order.snapshot_.currency_ == currency) || !order.reserve_price_
808 const auto reserved =
decimal_multiply(order.snapshot_.quantity_, *order.reserve_price_);
815 static bool add_to_totals(
816 std::vector<HoldingsTotals>& totals,
const Decimal64& market_value,
const Decimal64& cost,
const Decimal64& gain,
817 const Currency& currency
819 auto found = std::find_if(totals.begin(), totals.end(), [&](
const HoldingsTotals& t) {
820 return t.currency_ == currency;
823 const auto purchase =
decimal_add(found == totals.end() ? zero : found->purchase_value_, cost);
824 const auto market =
decimal_add(found == totals.end() ? zero : found->market_value_, market_value);
825 const auto unrealized =
decimal_add(found == totals.end() ? zero : found->unrealized_profit_loss_, gain);
826 if (!purchase || !market || !unrealized) {
829 if (found == totals.end()) {
830 HoldingsTotals fresh;
831 fresh.currency_ = currency;
832 totals.push_back(fresh);
833 found = totals.end() - 1;
835 found->purchase_value_ = *purchase;
836 found->market_value_ = *market;
837 found->unrealized_profit_loss_ = *unrealized;
842 static void cancel_at(MarketOrder& order, std::chrono::system_clock::time_point at) {
843 order.snapshot_.status_ = OrderStatus::CANCELED;
844 order.snapshot_.canceled_at_ = at;
848 void expire_day_orders(
849 const Listing& listing,
const Date& date,
bool ends, std::chrono::system_clock::time_point at
851 for (
auto& order : orders_) {
853 order.snapshot_.status_ != OrderStatus::PENDING || !order.session_ ||
855 !(order.snapshot_.instrument_ == listing.series_.instrument_)
859 if (*order.session_ < date || (ends && *order.session_ == date)) {
860 cancel_at(order, at);
866 void apply_bar(Listing& listing) {
867 const auto at = listing.next_;
868 const auto& series = listing.series_;
869 const auto& session = settings_.session_;
870 strategy::BarEvent event;
871 event.instrument_ = series.instrument_;
872 event.interval_ = series.interval_;
873 event.stamp_ = series.stamp_;
874 event.bar_ = series.bars_[at];
875 event.period_end_ = period_end(listing, at);
876 const auto start = period_start(listing, at);
878 const auto fill_date = session.local_date(event.
period_end_);
879 const auto open_date = series.stamp_ ==
BarStamp::OPEN ? std::optional<Date>(date) : std::nullopt;
880 const auto closes = session.opens_at(event.
bar_.
timestamp_) - session.open_ + session.close_;
881 const bool ends_session = !
bar_interval_length(series.interval_) || !(
event.period_end_ < closes);
882 expire_day_orders(listing, date,
false, event.
period_end_);
883 for (
auto& order : orders_) {
884 auto& snapshot = order.snapshot_;
886 snapshot.status_ != OrderStatus::PENDING || !(snapshot.instrument_ == series.instrument_) ||
887 start < *snapshot.ordered_at_
891 if (!order.session_) {
892 order.session_ = date;
894 strategy::PlannedOrder planned;
896 planned.
side_ = snapshot.side_;
897 planned.
type_ = snapshot.type_;
900 planned.
price_ = snapshot.price_;
901 const auto decision = settings_.fills_.decide(
902 planned, event, listing.reference_.price_rule_, fill_date, open_date,
false, order.decision_price_,
903 order.decision_price_at_, snapshot.ordered_at_
905 if (decision.costing_error_) {
906 halted_ =
"the mock market halted: order " + snapshot.order_id_ +
"'s fill could not be costed (" +
907 decision.costing_error_->message_ +
")";
910 if (decision.execution_) {
911 auto execution = *decision.execution_;
912 execution.fill_.order_id_ = snapshot.order_id_;
913 execution.currency_ = snapshot.currency_;
914 if (!ledger_.apply(execution, snapshot.currency_)) {
915 halted_ =
"the mock market halted: order " + snapshot.order_id_ +
"'s fill does not fit an exact decimal";
918 record_fill(snapshot, execution, event.
period_end_);
921 if (!decision.still_working_) {
925 expire_day_orders(listing, date, ends_session, event.
period_end_);
926 if (!ledger_.mark(series.instrument_, event.
bar_.
close_)) {
927 halted_ =
"the mock market halted: a position's value at the close of " + series.instrument_.symbol_ +
928 " does not fit an exact decimal";
933 static void record_fill(
934 OrderSnapshot& snapshot,
const backtest::Execution& execution, std::chrono::system_clock::time_point at
936 const auto&
fill = execution.fill_;
937 snapshot.status_ = OrderStatus::FILLED;
938 auto& done = snapshot.execution_;
939 done.filled_quantity_ =
fill.quantity_;
940 done.average_filled_price_ =
fill.price_;
942 done.filled_amount_ = Money{*amount, snapshot.currency_};
944 auto commission = execution.commission_;
945 if (execution.institution_fee_) {
946 commission =
decimal_add(commission, *execution.institution_fee_).value_or(commission);
948 done.commission_ = Money{commission, snapshot.currency_};
949 done.tax_ = Money{execution.tax_, snapshot.currency_};
950 done.filled_at_ = at;
955 MarketSettings settings_;
956 std::chrono::system_clock::time_point now_;
957 backtest::ReplayLedger ledger_;
958 std::vector<Listing> listings_;
959 std::vector<MarketOrder> orders_;
960 TradingCalendar calendar_;
961 std::uint64_t last_id_{0};
962 std::optional<std::string> halted_;
A three-letter currency code, such as KRW or USD (ISO 4217 style).
An exact signed decimal: an int64 coefficient times 10^-scale.
Decimal64()=default
Constructs zero.
Either a value or a BrokerError.
Result(T value)
Constructs a successful result.
The fill model: market orders at the next bar's open, limit orders when the next bar's range reaches ...
MarketFileError(Kind kind)
Constructs the error.
Kind kind() const noexcept
Returns what became of the record.
Kind
What became of the record.
@ UNCONFIRMED
It was written, and flushing it to disk failed: reopening the file may make the move.
A mock market that keeps its account in a file: every placement, cancellation and clock move is writt...
Money cash() const
Returns the account's cash, before what open buys reserve.
WorkingOrders< Broker > working_orders() const
Answers a working-order request.
Market(std::vector< BarSeries > bars, MarketSettings settings, std::vector< Instrument > instruments={})
Builds a market at settings.start_.
Result< PlacedOrder< Broker > > cancel(const std::string &order_id)
Cancels the whole remainder of an open order.
std::chrono::system_clock::time_point now() const noexcept
Returns the market's clock.
Result< PlacedOrder< Broker > > place(const OrderRequest &order)
Places an order.
Result< BuyingPower > buying_power(const Currency ¤cy) const
Answers a buying-power request: cash less what open buys reserve.
Result< BarSeries > bars(const BarQuery &query) const
Answers a bar request: bars whose period has ended by now(), never a forming one.
Result< Instrument > instrument(const InstrumentId &instrument) const
Answers a reference-data request.
Result< HoldingsSnapshot > holdings() const
Answers a holdings request.
const std::optional< std::string > & halted() const noexcept
Returns why the market halted, if it did.
OrderPage order_history(const OrderHistoryQuery &query) const
Answers an order-history request: every order, oldest first, in one page.
Result< TradingCalendar > calendar(Country country) const
Answers a calendar request.
Result< QuoteSnapshot > quote(const InstrumentId &instrument) const
Answers a quote: the close of the instrument's last bar that has ended by now().
void advance_to(std::chrono::system_clock::time_point to)
Moves the clock to an instant, applying every bar whose period end it reaches, in order of period end...
The events a runner delivers to a strategy's handlers, and the market phase.
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.
The mock broker: an in-memory market over bars the caller gives, bound like any broker.
constexpr std::string_view environment
The environment the mock reports: always "mock", never "demo" or "real".
void start(S &strategy, Ctx &context)
Calls strategy.on_start(context) if the strategy declares on_start; 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.
std::chrono::system_clock::time_point bar_period_end(const Bar &bar, BarInterval interval, BarStamp stamp)
Computes the instant a bar's period ended.
The library: broker-neutral types (core), and the modules below.
@ 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.
@ PROTOCOL
The reply could not be read, or the broker declared a failure this client does not classify further: ...
@ TRANSPORT
The connection failed (DNS, connect, TLS, write or read).
@ INVALID_ARGUMENT
The request was invalid, refused by the client before sending or by the broker.
@ LIMIT
지정가: fills at the stated price or better.
@ MARKET
시장가: fills at whatever the book offers.
Country
A country (market) the library supports.
Decimal64 decimal_normalized(const Decimal64 &value)
Removes trailing fractional zeros, so equal numbers compare equal with ==.
std::optional< Decimal64 > decimal_subtract(const Decimal64 &lhs, const Decimal64 &rhs)
Subtracts two decimals exactly.
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.
Date date_from_epoch_days(std::int64_t days)
Converts a day count since 1970-01-01 to a Gregorian date.
@ 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.
InstrumentId instrument_
The instrument.
BarInterval interval_
The period of each bar; an interval the broker does not publish is refused.
int count_
How many bars to return in total, across pages.
std::optional< std::chrono::system_clock::time_point > before_
The newest bar time to return, inclusive; pass the oldest timestamp seen to page backwards.
The bars of one instrument and interval, oldest first.
std::chrono::system_clock::time_point received_at_
When the series was received, on this machine's clock.
BarInterval interval_
The period each bar covers.
Currency currency_
The currency of the prices.
bool adjusted_
Whether the prices are adjusted for corporate actions.
BarStamp stamp_
Which edge of its period each bar's timestamp marks.
InstrumentId instrument_
The instrument.
std::vector< Bar > bars_
The bars, oldest first.
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).
What the broker says may be spent, in one currency.
Money cash_
The amount that may be spent.
std::chrono::system_clock::time_point received_at_
When the figure was received, on this machine's clock (brokers do not timestamp it).
An account's positions and per-currency totals at one point in time.
std::chrono::system_clock::time_point received_at_
When this process received the snapshot (brokers do not timestamp holdings).
std::vector< HoldingsTotals > totals_
One totals row per currency held.
SellableBasis sellable_basis_
What the rows' sellable_quantity_ figures cover (unless a row carries its own).
std::vector< HoldingPosition > positions_
Every position row; one instrument may appear in more than one.
Identifies an instrument: its country, venue and symbol.
An exact amount of money in one currency.
Decimal64 amount_
The amount.
std::chrono::system_clock::time_point accepted_at_
When the acknowledgement was received.
std::string order_id_
The order number the broker assigned.
Decimal64 filled_quantity_
The quantity filled so far; zero if nothing has filled. Always present.
The filter for an order-history inquiry.
std::optional< Date > from_
The first date to include; required where BrokerCaps::history_requires_range.
std::optional< Date > to_
The last date to include.
One page of an order listing.
std::vector< OrderSnapshot > orders_
The rows, in the broker's order.
std::chrono::system_clock::time_point received_at_
When the page was received, on this machine's clock.
An order to place, in broker-neutral form.
Decimal64 quantity_
The quantity, in the instrument's units (shares).
OrderType type_
The price basis: limit, market, best-limit, and so on.
InstrumentId instrument_
The instrument; its venue_ is identity, and routing is this struct's venue_.
Venue venue_
Where to route the order, if the broker offers a choice.
std::optional< Decimal64 > price_
The price; required when carries_caller_price(type_), refused otherwise.
OrderSide side_
Buy or sell.
OrderSession session_
The trading session.
TimeInForce time_in_force_
How long the order stays valid.
Venue venue_
Where the broker says the order was routed; UNSPECIFIED if it does not say.
OrderSide side_
Buy or sell.
OrderStatus status_
The status; UNKNOWN where the broker publishes none.
OrderSession session_
The session; UNKNOWN if the broker's code was not recognized.
OrderType type_
The price basis; UNKNOWN if the broker's code was not recognized.
OrderExecution execution_
What has filled and what it cost; see OrderExecution before testing a fill.
Currency currency_
The currency of the row's prices and amounts.
Decimal64 quantity_
The quantity ordered; the remainder is this minus execution_.filled_quantity_.
std::string order_id_
The broker's order number.
std::optional< std::chrono::system_clock::time_point > ordered_at_
When the broker recorded the order, if it gives a time. KIS's real-server working orders have none; o...
InstrumentId instrument_
The instrument (identity venue; the routing venue is venue_).
TimeInForce time_in_force_
The time in force; UNKNOWN if the broker's code was not recognized.
std::optional< Decimal64 > price_
The limit price, if the order has one.
An accepted order: the acknowledgement and the reference to address it with.
OrderRef< Broker > ref_
The reference to amend or cancel the order with.
OrderAck ack_
The acknowledgement.
static PriceRule unconstrained()
Returns a rule with no grid, for a market quoted in free decimals.
A quote: the last traded price of an instrument at a point in time.
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.
An order still open to modification or cancellation.
OrderRef< Broker > ref_
The reference to amend or cancel the order with.
std::optional< Decimal64 > amendable_quantity_
How much the broker says may still be amended. Empty means it stated none, not zero.
OrderSnapshot order_
The order's state.
The orders open to modification or cancellation at one point in time.
std::vector< WorkingOrder< Broker > > orders_
The open orders.
std::chrono::system_clock::time_point received_at_
When the listing was received, on this machine's clock.
The mock broker's tag: its order references are typed by it, so they work with no other broker.
static constexpr std::string_view name
The broker's name, "mock".
How a Market starts and what it charges.
Money cash_
The starting cash, in the one currency the market keeps cash in.
backtest::NextBarFillModel fills_
The fill rule and its costs, as a backtest's; no commission, slippage or tax by default.
std::optional< TradingCalendar > calendar_
The trading days the market publishes, as a backtest is given them (backtest::ReplayConfig::calendar_...
std::chrono::system_clock::time_point start_
The market's first instant; bars that ended by then are history.
strategy::SessionWindow session_
The session window local dates and the close are read in, as a backtest's (backtest::ReplayConfig::se...
std::chrono::system_clock::time_point period_end_
When the bar's period ended: the earliest moment the bar could be known.
TimeInForce time_in_force_
How long the order stays valid.
OrderType type_
The order type.
InstrumentId instrument_
The instrument to trade.
std::optional< Decimal64 > price_
The limit price, after clamping and rounding; empty for a market order.
Decimal64 quantity_
The quantity, after rounding onto the lot.
The intraday session of a market, as the operator states it.
static SessionWindow krx()
Returns the KRX regular session, 09:00-15:30 KST.