algotradelib 0.0.0.9000
C++ header-only library for algorithmic trading
Loading...
Searching...
No Matches
market.hpp
1#pragma once
2
6
7#include "../../core/calendar.hpp"
8#include "../../core/market_data.hpp"
9#include "../../core/types.hpp"
10
11#include <algorithm>
12#include <chrono>
13#include <cstddef>
14#include <cstdint>
15#include <functional>
16#include <optional>
17#include <set>
18#include <stdexcept>
19#include <string>
20#include <string_view>
21#include <utility>
22#include <vector>
23
24namespace algotradelib {
25namespace mock {
26
31struct Broker {
33 static constexpr std::string_view name = "mock";
34};
35
42inline constexpr std::string_view environment = "mock";
43
44class MarketFile;
45
50class MarketFileError : public std::runtime_error {
51public:
53 enum class Kind {
55 NOT_WRITTEN,
57 UNCONFIRMED,
58 };
59
65 : std::runtime_error(
66 kind == Kind::NOT_WRITTEN ?
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"
69 ),
70 kind_(kind) {}
71
76 Kind kind() const noexcept {
77 return kind_;
78 }
79
80private:
81 Kind kind_;
82};
83
87 Money cash_{Decimal64(0, 0), Currency{"KRW"}};
89 std::chrono::system_clock::time_point start_{};
106 std::optional<TradingCalendar> calendar_;
107};
108
143class Market {
144public:
158 Market(std::vector<BarSeries> bars, MarketSettings settings, std::vector<Instrument> instruments = {})
159 : settings_(std::move(settings)),
160 now_(settings_.start_),
161 ledger_(settings_.cash_.amount_, settings_.cash_.currency_, backtest::ExecutionHistory::NONE) {
162 if (decimal_less(settings_.cash_.amount_, Decimal64(0, 0))) {
163 throw std::invalid_argument("the mock market's starting cash is negative");
164 }
165 listings_.reserve(bars.size());
166 for (auto& series : bars) {
167 if (!bar_interval_length(series.interval_) && series.interval_ != BarInterval::ONE_DAY) {
168 throw std::invalid_argument("the mock market takes minute to daily bars only");
169 }
170 if (!series.ascending()) {
171 throw std::invalid_argument("a mock market series is not strictly ascending");
172 }
173 if (find_listing(series.instrument_) != nullptr) {
174 throw std::invalid_argument("the mock market was given two series of one instrument");
175 }
176 Listing listing;
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);
182 listing.reference_.price_rule_ = PriceRule::unconstrained();
183 listing.series_ = std::move(series);
184 while (listing.next_ < listing.series_.bars_.size() && !(now_ < period_end(listing, listing.next_))) {
185 ++listing.next_;
186 }
187 listings_.push_back(std::move(listing));
188 }
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_;
192 });
193 if (found == listings_.end()) {
194 throw std::invalid_argument("the mock market was given reference data for an instrument without bars");
195 }
196 found->reference_ = std::move(reference);
197 }
198 calendar_ = settings_.calendar_ ? *settings_.calendar_ : calendar_of_bars();
199 }
200
205 std::chrono::system_clock::time_point now() const noexcept {
206 return now_;
207 }
208
213 const std::optional<std::string>& halted() const noexcept {
214 return halted_;
215 }
216
226 void advance_to(std::chrono::system_clock::time_point to) {
227 if (to < now_) {
228 throw std::invalid_argument("the mock market's clock does not move backwards");
229 }
230 if (halted_) {
231 throw std::runtime_error(*halted_);
232 }
233 const auto failed = now_ < to ? record(Change{nullptr, nullptr, to}) : std::nullopt;
234 if (failed) {
235 throw MarketFileError(*failed);
236 }
237 for (;;) {
238 Listing* earliest = nullptr;
239 for (auto& listing : listings_) {
240 if (listing.next_ >= listing.series_.bars_.size()) {
241 continue;
242 }
243 if (earliest == nullptr || period_end(listing, listing.next_) < period_end(*earliest, earliest->next_)) {
244 earliest = &listing;
245 }
246 }
247 if (earliest == nullptr || to < period_end(*earliest, earliest->next_)) {
248 break;
249 }
250 now_ = period_end(*earliest, earliest->next_);
251 apply_bar(*earliest);
252 if (halted_) {
253 throw std::runtime_error(*halted_);
254 }
255 ++earliest->next_;
256 }
257 now_ = to;
258 }
259
266 Result<BarSeries> bars(const BarQuery& query) const {
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");
270 }
271 if (query.interval_ != listing->series_.interval_) {
272 return refused<BarSeries>("unsupported_interval", "the mock market has no bars of this interval");
273 }
274 if (query.count_ < 1) {
275 return refused<BarSeries>("bars_count", "a bar request asks for at least one bar");
276 }
277 BarSeries answer;
278 answer.instrument_ = listing->series_.instrument_;
279 answer.interval_ = listing->series_.interval_;
280 answer.stamp_ = listing->series_.stamp_;
281 answer.currency_ = listing->series_.currency_;
282 answer.adjusted_ = listing->series_.adjusted_;
283 answer.received_at_ = now_;
284 const auto& all = listing->series_.bars_;
285 // The bars ended by now and stamped at or before `before_`: a prefix of the series, found by a binary search. A
286 // prefix because the bars are strictly ascending and a bar's period end is its stamp plus a fixed length; a period
287 // end taken from the session would need this search revisited.
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_));
290 };
291 std::size_t end = 0;
292 std::size_t high = all.size();
293 while (end < high) {
294 const std::size_t middle = end + (high - end) / 2;
295 if (readable(middle)) {
296 end = middle + 1;
297 } else {
298 high = middle;
299 }
300 }
301 const auto count = static_cast<std::size_t>(query.count_);
302 const std::size_t begin = end > count ? end - count : 0;
303 answer.bars_.assign(
304 all.begin() + static_cast<std::ptrdiff_t>(begin), all.begin() + static_cast<std::ptrdiff_t>(end)
305 );
306 return Result<BarSeries>(std::move(answer));
307 }
308
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");
319 }
320 const auto last = last_closed(*listing);
321 if (!last) {
322 BrokerError error;
324 error.broker_code_ = "no_price";
325 error.message_ = "no bar of this instrument has ended yet";
326 return Result<QuoteSnapshot>(std::move(error));
327 }
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_;
334 return Result<QuoteSnapshot>(std::move(quote));
335 }
336
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");
347 }
348 return Result<Instrument>(listing->reference_);
349 }
350
358 if (country != calendar_.country_) {
359 return refused<TradingCalendar>("unsupported_market", "the mock market publishes one market's calendar");
360 }
361 auto answer = calendar_;
362 answer.received_at_ = now_;
363 return Result<TradingCalendar>(std::move(answer));
364 }
365
374 HoldingsSnapshot snapshot;
375 snapshot.received_at_ = now_;
379 false,
380 };
381 for (const auto& lot : ledger_.positions()) {
382 if (lot.quantity_.coefficient() == 0) {
383 continue;
384 }
385 auto row = lot;
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)) {
391 BrokerError error;
393 error.broker_code_ = "out_of_range";
394 error.message_ = "a holding's value or the holdings' total does not fit an exact decimal";
395 return Result<HoldingsSnapshot>(std::move(error));
396 }
397 row.purchase_value_ = Money{*cost, currency};
398 row.unrealized_profit_loss_ = Money{*gain, currency};
399 snapshot.positions_.push_back(std::move(row));
400 }
401 return Result<HoldingsSnapshot>(std::move(snapshot));
402 }
403
409 Money cash() const {
410 return Money{ledger_.cash_in(settings_.cash_.currency_).value_or(Decimal64(0, 0)), settings_.cash_.currency_};
411 }
412
424 const auto cash = ledger_.cash_in(currency);
425 if (!cash) {
426 return refused<BuyingPower>("unknown_currency", "the mock market keeps no cash in this currency");
427 }
428 const auto spendable = spendable_in(currency, *cash);
429 if (!spendable) {
430 BrokerError error;
432 error.broker_code_ = "out_of_range";
433 error.message_ = "the buying power does not fit an exact decimal";
434 return Result<BuyingPower>(std::move(error));
435 }
436 BuyingPower power;
437 power.cash_ = Money{*spendable, currency};
438 power.received_at_ = now_;
439 return Result<BuyingPower>(std::move(power));
440 }
441
460 if (halted_) {
461 return refused<PlacedOrder<Broker>>("market_halted", "the mock market halted and takes no orders");
462 }
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");
466 }
467 if (order.type_ != OrderType::MARKET && order.type_ != OrderType::LIMIT) {
468 return refused<PlacedOrder<Broker>>(
469 "unsupported_order_type", "the mock market takes market and limit orders only"
470 );
471 }
472 switch (order.time_in_force_) {
473 case TimeInForce::DAY:
476 break;
477 case TimeInForce::UNKNOWN:
478 return refused<PlacedOrder<Broker>>("unsupported_time_in_force", "the mock market needs a time in force");
479 }
480 const auto quantity = decimal_normalized(order.quantity_);
481 if (quantity.coefficient() <= 0 || quantity.scale() != 0) {
482 return refused<PlacedOrder<Broker>>("invalid_quantity", "an order's quantity is a positive whole number");
483 }
484 const bool limit = order.type_ == OrderType::LIMIT;
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"
488 );
489 }
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_;
495 }
496 }
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");
500 }
501 const auto cash = ledger_.cash_in(currency);
502 const auto spendable = cash ? spendable_in(currency, *cash) : std::nullopt;
503 const auto cost = decimal_multiply(quantity, *reserve_price);
504 if (!spendable || !cost || decimal_less(*spendable, *cost)) {
505 return refused<PlacedOrder<Broker>>("insufficient_cash", "the buy costs more than the buying power");
506 }
507 } else {
508 const auto held = ledger_.quantity_of(order.instrument_).value_or(Decimal64(0, 0));
509 const auto free = decimal_subtract(held, open_sells_of(order.instrument_));
510 if (!free || decimal_less(*free, quantity)) {
511 return refused<PlacedOrder<Broker>>(
512 "insufficient_holdings", "the sell is more than the shares held and not already offered"
513 );
514 }
515 }
516 if (const auto failed = record(Change{&order, nullptr, std::nullopt})) {
517 return not_recorded<PlacedOrder<Broker>>(*failed);
518 }
519 MarketOrder accepted;
520 accepted.snapshot_.order_id_ = std::to_string(++last_id_);
521 accepted.snapshot_.instrument_ = order.instrument_;
522 accepted.snapshot_.side_ = order.side_;
523 accepted.snapshot_.type_ = order.type_;
524 accepted.snapshot_.time_in_force_ = order.time_in_force_;
525 accepted.snapshot_.session_ = order.session_;
526 accepted.snapshot_.venue_ = order.venue_;
527 accepted.snapshot_.status_ = OrderStatus::PENDING;
528 accepted.snapshot_.price_ = order.price_;
529 accepted.snapshot_.quantity_ = quantity;
530 accepted.snapshot_.currency_ = currency;
531 accepted.snapshot_.ordered_at_ = now_;
532 accepted.snapshot_.execution_.filled_quantity_ = Decimal64(0, 0);
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);
537 }
538 orders_.push_back(std::move(accepted));
539 PlacedOrder<Broker> placed;
540 placed.ack_.order_id_ = orders_.back().snapshot_.order_id_;
541 placed.ack_.accepted_at_ = now_;
542 placed.ref_.primary_ = placed.ack_.order_id_;
543 return Result<PlacedOrder<Broker>>(std::move(placed));
544 }
545
553 Result<PlacedOrder<Broker>> cancel(const std::string& order_id) {
554 for (auto& order : orders_) {
555 if (order.snapshot_.order_id_ != order_id) {
556 continue;
557 }
558 if (order.snapshot_.status_ != OrderStatus::PENDING) {
559 break;
560 }
561 if (const auto failed = record(Change{nullptr, &order_id, std::nullopt})) {
562 return not_recorded<PlacedOrder<Broker>>(*failed);
563 }
564 order.snapshot_.status_ = OrderStatus::CANCELED;
565 order.snapshot_.canceled_at_ = now_;
566 PlacedOrder<Broker> placed;
567 placed.ack_.order_id_ = order_id;
568 placed.ack_.accepted_at_ = now_;
569 placed.ref_.primary_ = order_id;
570 return Result<PlacedOrder<Broker>>(std::move(placed));
571 }
572 return refused<PlacedOrder<Broker>>("nothing_to_cancel", "no open order has this id");
573 }
574
581 WorkingOrders<Broker> listing;
582 listing.received_at_ = now_;
583 for (const auto& order : orders_) {
584 if (order.snapshot_.status_ != OrderStatus::PENDING) {
585 continue;
586 }
588 row.order_ = order.snapshot_;
589 row.ref_.primary_ = order.snapshot_.order_id_;
590 row.amendable_quantity_ = order.snapshot_.quantity_;
591 listing.orders_.push_back(std::move(row));
592 }
593 return listing;
594 }
595
603 OrderPage page;
604 page.received_at_ = now_;
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)) {
608 continue;
609 }
610 page.orders_.push_back(order.snapshot_);
611 }
612 return page;
613 }
614
615private:
616 friend class MarketFile;
617
619 struct Change {
621 const OrderRequest* order_{nullptr};
623 const std::string* order_id_{nullptr};
625 std::optional<std::chrono::system_clock::time_point> to_;
626 };
627
632 struct Recorder {
633 Recorder() = default;
634
635 Recorder(const Recorder&) noexcept {}
636
637 Recorder(Recorder&& other) {
638 if (other.record_) {
639 throw std::logic_error("a mock market kept in a file cannot be moved from");
640 }
641 }
642
643 Recorder& operator=(const Recorder&) {
644 if (record_) {
645 throw std::logic_error("a mock market kept in a file cannot be assigned to");
646 }
647 return *this;
648 }
649
650 Recorder& operator=(Recorder&& other) {
651 if (record_ || other.record_) {
652 throw std::logic_error(
653 record_ ?
654 "a mock market kept in a file cannot be assigned to" :
655 "a mock market kept in a file cannot be moved from"
656 );
657 }
658 return *this;
659 }
660
662 std::function<std::optional<MarketFileError::Kind>(const Change&)> record_;
663 };
664
666 struct Listing {
668 BarSeries series_;
670 Instrument reference_;
672 std::size_t next_{0};
673 };
674
676 struct MarketOrder {
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_;
687 };
688
690 template <typename T>
691 static Result<T> refused(const char* code, const char* message) {
692 BrokerError error;
693 error.category_ = ErrorCategory::INVALID_ARGUMENT;
694 error.reached_broker_ = true;
695 error.broker_code_ = code;
696 error.message_ = message;
697 return Result<T>(std::move(error));
698 }
699
701 std::optional<MarketFileError::Kind> record(const Change& change) const {
702 return recorder_.record_ ? recorder_.record_(change) : std::nullopt;
703 }
704
706 template <typename T>
707 static Result<T> not_recorded(MarketFileError::Kind kind) {
708 BrokerError error;
709 error.category_ = ErrorCategory::TRANSPORT;
710 error.reached_broker_ = kind == MarketFileError::Kind::UNCONFIRMED;
711 error.broker_code_ = error.reached_broker_ ? "state_unconfirmed" : "state_not_written";
712 error.message_ = MarketFileError(kind).what();
713 return Result<T>(std::move(error));
714 }
715
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();
722 };
723 TradingCalendar calendar;
724 std::set<std::int64_t> open;
725 for (const auto& listing : listings_) {
726 if (listing.series_.bars_.empty()) {
727 continue;
728 }
729 if (open.empty()) {
730 calendar.country_ = listing.series_.instrument_.country_;
731 }
732 for (const auto& bar : listing.series_.bars_) {
733 open.insert(local_day(bar.timestamp_));
734 }
735 }
736 if (open.empty()) {
737 return calendar;
738 }
739 for (auto day = *open.begin(); day <= *open.rbegin(); ++day) {
740 calendar.days_.push_back(TradingDay{date_from_epoch_days(day), open.count(day) > 0});
741 }
742 return calendar;
743 }
744
746 const Listing* find_listing(const InstrumentId& instrument) const {
747 for (const auto& listing : listings_) {
748 if (listing.series_.instrument_ == instrument) {
749 return &listing;
750 }
751 }
752 return nullptr;
753 }
754
756 static std::chrono::system_clock::time_point period_end(const Listing& listing, std::size_t at) {
757 return strategy::bar_period_end(listing.series_.bars_[at], listing.series_.interval_, listing.series_.stamp_);
758 }
759
761 std::chrono::system_clock::time_point period_start(const Listing& listing, std::size_t at) const {
762 const auto& series = listing.series_;
763 if (series.stamp_ == BarStamp::OPEN) {
764 return series.bars_[at].timestamp_;
765 }
766 if (const auto length = bar_interval_length(series.interval_)) {
767 return period_end(listing, at) - *length;
768 }
769 return settings_.session_.opens_at(period_end(listing, at));
770 }
771
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) {
776 last = at;
777 }
778 return last;
779 }
780
782 Decimal64 open_sells_of(const InstrumentId& instrument) const {
783 Decimal64 total(0, 0);
784 for (const auto& order : orders_) {
785 if (
786 order.snapshot_.status_ == OrderStatus::PENDING && order.snapshot_.side_ == OrderSide::SELL &&
787 order.snapshot_.instrument_ == instrument
788 ) {
789 total = decimal_add(total, order.snapshot_.quantity_).value_or(total);
790 }
791 }
792 return total;
793 }
794
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_) {
799 if (!left) {
800 break;
801 }
802 if (
803 order.snapshot_.status_ != OrderStatus::PENDING || order.snapshot_.side_ != OrderSide::BUY ||
804 !(order.snapshot_.currency_ == currency) || !order.reserve_price_
805 ) {
806 continue;
807 }
808 const auto reserved = decimal_multiply(order.snapshot_.quantity_, *order.reserve_price_);
809 left = reserved ? decimal_subtract(*left, *reserved) : std::nullopt;
810 }
811 return left;
812 }
813
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
818 ) {
819 auto found = std::find_if(totals.begin(), totals.end(), [&](const HoldingsTotals& t) {
820 return t.currency_ == currency;
821 });
822 const auto zero = Decimal64(0, 0);
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) {
827 return false;
828 }
829 if (found == totals.end()) {
830 HoldingsTotals fresh;
831 fresh.currency_ = currency;
832 totals.push_back(fresh);
833 found = totals.end() - 1;
834 }
835 found->purchase_value_ = *purchase;
836 found->market_value_ = *market;
837 found->unrealized_profit_loss_ = *unrealized;
838 return true;
839 }
840
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;
845 }
846
848 void expire_day_orders(
849 const Listing& listing, const Date& date, bool ends, std::chrono::system_clock::time_point at
850 ) {
851 for (auto& order : orders_) {
852 if (
853 order.snapshot_.status_ != OrderStatus::PENDING || !order.session_ ||
854 order.snapshot_.time_in_force_ != TimeInForce::DAY ||
855 !(order.snapshot_.instrument_ == listing.series_.instrument_)
856 ) {
857 continue;
858 }
859 if (*order.session_ < date || (ends && *order.session_ == date)) {
860 cancel_at(order, at);
861 }
862 }
863 }
864
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);
877 const auto date = session.local_date(event.bar_.timestamp_);
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_;
885 if (
886 snapshot.status_ != OrderStatus::PENDING || !(snapshot.instrument_ == series.instrument_) ||
887 start < *snapshot.ordered_at_
888 ) {
889 continue;
890 }
891 if (!order.session_) {
892 order.session_ = date;
893 }
894 strategy::PlannedOrder planned;
895 planned.instrument_ = snapshot.instrument_;
896 planned.side_ = snapshot.side_;
897 planned.type_ = snapshot.type_;
898 planned.time_in_force_ = snapshot.time_in_force_;
899 planned.quantity_ = snapshot.quantity_;
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_
904 );
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_ + ")";
908 return;
909 }
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";
916 return;
917 }
918 record_fill(snapshot, execution, event.period_end_);
919 continue;
920 }
921 if (!decision.still_working_) {
922 cancel_at(order, event.period_end_);
923 }
924 }
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";
929 }
930 }
931
933 static void record_fill(
934 OrderSnapshot& snapshot, const backtest::Execution& execution, std::chrono::system_clock::time_point at
935 ) {
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_;
941 if (const auto amount = decimal_multiply(fill.quantity_, fill.price_)) {
942 done.filled_amount_ = Money{*amount, snapshot.currency_};
943 }
944 auto commission = execution.commission_;
945 if (execution.institution_fee_) {
946 commission = decimal_add(commission, *execution.institution_fee_).value_or(commission);
947 }
948 done.commission_ = Money{commission, snapshot.currency_};
949 done.tax_ = Money{execution.tax_, snapshot.currency_};
950 done.filled_at_ = at;
951 }
952
953 // First, so that assigning to a kept market or moving from it throws before anything changes.
954 Recorder recorder_;
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_;
963};
964
965} // namespace mock
966} // namespace algotradelib
A three-letter currency code, such as KRW or USD (ISO 4217 style).
Definition types.hpp:374
An exact signed decimal: an int64 coefficient times 10^-scale.
Definition types.hpp:443
Decimal64()=default
Constructs zero.
Either a value or a BrokerError.
Definition types.hpp:1058
Result(T value)
Constructs a successful result.
Definition types.hpp:1064
The fill model: market orders at the next bar's open, limit orders when the next bar's range reaches ...
Definition fill.hpp:142
MarketFileError(Kind kind)
Constructs the error.
Definition market.hpp:64
Kind kind() const noexcept
Returns what became of the record.
Definition market.hpp:76
Kind
What became of the record.
Definition market.hpp:53
@ UNCONFIRMED
It was written, and flushing it to disk failed: reopening the file may make the move.
Definition market.hpp:57
A mock market that keeps its account in a file: every placement, cancellation and clock move is writt...
Definition file.hpp:67
Money cash() const
Returns the account's cash, before what open buys reserve.
Definition market.hpp:409
WorkingOrders< Broker > working_orders() const
Answers a working-order request.
Definition market.hpp:580
Market(std::vector< BarSeries > bars, MarketSettings settings, std::vector< Instrument > instruments={})
Builds a market at settings.start_.
Definition market.hpp:158
Result< PlacedOrder< Broker > > cancel(const std::string &order_id)
Cancels the whole remainder of an open order.
Definition market.hpp:553
std::chrono::system_clock::time_point now() const noexcept
Returns the market's clock.
Definition market.hpp:205
Result< PlacedOrder< Broker > > place(const OrderRequest &order)
Places an order.
Definition market.hpp:459
Result< BuyingPower > buying_power(const Currency &currency) const
Answers a buying-power request: cash less what open buys reserve.
Definition market.hpp:423
Result< BarSeries > bars(const BarQuery &query) const
Answers a bar request: bars whose period has ended by now(), never a forming one.
Definition market.hpp:266
Result< Instrument > instrument(const InstrumentId &instrument) const
Answers a reference-data request.
Definition market.hpp:343
Result< HoldingsSnapshot > holdings() const
Answers a holdings request.
Definition market.hpp:373
const std::optional< std::string > & halted() const noexcept
Returns why the market halted, if it did.
Definition market.hpp:213
OrderPage order_history(const OrderHistoryQuery &query) const
Answers an order-history request: every order, oldest first, in one page.
Definition market.hpp:602
Result< TradingCalendar > calendar(Country country) const
Answers a calendar request.
Definition market.hpp:357
Result< QuoteSnapshot > quote(const InstrumentId &instrument) const
Answers a quote: the close of the instrument's last bar that has ended by now().
Definition market.hpp:315
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...
Definition market.hpp:226
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.
Definition bootstrap.hpp:16
The mock broker: an in-memory market over bars the caller gives, bound like any broker.
Definition client.hpp:11
constexpr std::string_view environment
The environment the mock reports: always "mock", never "demo" or "real".
Definition market.hpp:42
void start(S &strategy, Ctx &context)
Calls strategy.on_start(context) if the strategy declares on_start; otherwise does nothing.
Definition concept.hpp:240
void bar(S &strategy, Ctx &context, const BarEvent &event)
Calls strategy.on_bar(context, event) if the strategy declares on_bar; otherwise does nothing.
Definition concept.hpp:282
void fill(S &strategy, Ctx &context, const Fill &event)
Calls strategy.on_fill(context, event) if the strategy declares on_fill; otherwise does nothing.
Definition concept.hpp:352
std::chrono::system_clock::time_point bar_period_end(const Bar &bar, BarInterval interval, BarStamp stamp)
Computes the instant a bar's period ended.
Definition event.hpp:343
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.
Definition types.hpp:760
@ PROTOCOL
The reply could not be read, or the broker declared a failure this client does not classify further: ...
Definition types.hpp:965
@ TRANSPORT
The connection failed (DNS, connect, TLS, write or read).
Definition types.hpp:952
@ INVALID_ARGUMENT
The request was invalid, refused by the client before sending or by the broker.
Definition types.hpp:974
@ LIMIT
지정가: fills at the stated price or better.
Definition types.hpp:2001
@ MARKET
시장가: fills at whatever the book offers.
Definition types.hpp:2003
Country
A country (market) the library supports.
Definition types.hpp:32
Decimal64 decimal_normalized(const Decimal64 &value)
Removes trailing fractional zeros, so equal numbers compare equal with ==.
Definition types.hpp:600
std::optional< Decimal64 > decimal_subtract(const Decimal64 &lhs, const Decimal64 &rhs)
Subtracts two decimals exactly.
Definition types.hpp:783
bool decimal_less(const Decimal64 &lhs, const Decimal64 &rhs)
Compares two decimals numerically, whatever their scales.
Definition types.hpp:926
std::optional< Decimal64 > decimal_multiply(const Decimal64 &lhs, const Decimal64 &rhs)
Multiplies two decimals exactly; the scales add.
Definition types.hpp:826
Date date_from_epoch_days(std::int64_t days)
Converts a day count since 1970-01-01 to a Gregorian date.
Definition types.hpp:1456
@ FILL_OR_KILL
Fills entirely and immediately, or not at all.
Definition types.hpp:2095
@ DAY
Rests until the session ends; an unfilled remainder is cancelled then.
Definition types.hpp:2091
@ IMMEDIATE_OR_CANCEL
Fills what it can immediately and cancels the remainder.
Definition types.hpp:2093
What bars to fetch.
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.
Definition types.hpp:1003
std::string message_
A human-readable description, for logs; do not parse it.
Definition types.hpp:1033
ErrorCategory category_
The kind of failure; the field to branch on.
Definition types.hpp:1005
std::string broker_code_
The broker's own error code, verbatim (for example KIS's EGW00201).
Definition types.hpp:1022
What the broker says may be spent, in one currency.
Definition types.hpp:1396
Money cash_
The amount that may be spent.
Definition types.hpp:1398
std::chrono::system_clock::time_point received_at_
When the figure was received, on this machine's clock (brokers do not timestamp it).
Definition types.hpp:1404
An account's positions and per-currency totals at one point in time.
Definition types.hpp:1345
std::chrono::system_clock::time_point received_at_
When this process received the snapshot (brokers do not timestamp holdings).
Definition types.hpp:1351
std::vector< HoldingsTotals > totals_
One totals row per currency held.
Definition types.hpp:1349
SellableBasis sellable_basis_
What the rows' sellable_quantity_ figures cover (unless a row carries its own).
Definition types.hpp:1358
std::vector< HoldingPosition > positions_
Every position row; one instrument may appear in more than one.
Definition types.hpp:1347
Identifies an instrument: its country, venue and symbol.
Definition types.hpp:85
An exact amount of money in one currency.
Definition types.hpp:1168
Decimal64 amount_
The amount.
Definition types.hpp:1170
std::chrono::system_clock::time_point accepted_at_
When the acknowledgement was received.
Definition types.hpp:2389
std::string order_id_
The order number the broker assigned.
Definition types.hpp:2385
Decimal64 filled_quantity_
The quantity filled so far; zero if nothing has filled. Always present.
Definition types.hpp:2274
The filter for an order-history inquiry.
Definition types.hpp:2617
std::optional< Date > from_
The first date to include; required where BrokerCaps::history_requires_range.
Definition types.hpp:2619
std::optional< Date > to_
The last date to include.
Definition types.hpp:2621
One page of an order listing.
Definition types.hpp:2369
std::vector< OrderSnapshot > orders_
The rows, in the broker's order.
Definition types.hpp:2371
std::chrono::system_clock::time_point received_at_
When the page was received, on this machine's clock.
Definition types.hpp:2375
An order to place, in broker-neutral form.
Definition types.hpp:2216
Decimal64 quantity_
The quantity, in the instrument's units (shares).
Definition types.hpp:2241
OrderType type_
The price basis: limit, market, best-limit, and so on.
Definition types.hpp:2222
InstrumentId instrument_
The instrument; its venue_ is identity, and routing is this struct's venue_.
Definition types.hpp:2218
Venue venue_
Where to route the order, if the broker offers a choice.
Definition types.hpp:2239
std::optional< Decimal64 > price_
The price; required when carries_caller_price(type_), refused otherwise.
Definition types.hpp:2243
OrderSide side_
Buy or sell.
Definition types.hpp:2220
OrderSession session_
The trading session.
Definition types.hpp:2226
TimeInForce time_in_force_
How long the order stays valid.
Definition types.hpp:2224
Venue venue_
Where the broker says the order was routed; UNSPECIFIED if it does not say.
Definition types.hpp:2320
OrderSide side_
Buy or sell.
Definition types.hpp:2307
OrderStatus status_
The status; UNKNOWN where the broker publishes none.
Definition types.hpp:2329
OrderSession session_
The session; UNKNOWN if the broker's code was not recognized.
Definition types.hpp:2313
OrderType type_
The price basis; UNKNOWN if the broker's code was not recognized.
Definition types.hpp:2309
OrderExecution execution_
What has filled and what it cost; see OrderExecution before testing a fill.
Definition types.hpp:2365
Currency currency_
The currency of the row's prices and amounts.
Definition types.hpp:2351
Decimal64 quantity_
The quantity ordered; the remainder is this minus execution_.filled_quantity_.
Definition types.hpp:2341
std::string order_id_
The broker's order number.
Definition types.hpp:2301
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...
Definition types.hpp:2356
InstrumentId instrument_
The instrument (identity venue; the routing venue is venue_).
Definition types.hpp:2303
TimeInForce time_in_force_
The time in force; UNKNOWN if the broker's code was not recognized.
Definition types.hpp:2311
std::optional< Decimal64 > price_
The limit price, if the order has one.
Definition types.hpp:2331
An accepted order: the acknowledgement and the reference to address it with.
Definition types.hpp:2460
OrderRef< Broker > ref_
The reference to amend or cancel the order with.
Definition types.hpp:2464
OrderAck ack_
The acknowledgement.
Definition types.hpp:2462
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.
Definition types.hpp:1143
What a sellable quantity covers, and how RiskGuard must treat resting sells against it.
Definition types.hpp:1191
@ WHOLE_HOLDING
Every share held of the instrument, whatever venue or lot.
Definition types.hpp:1197
@ DEDUCT
Subtract every resting sell from the figure.
Definition types.hpp:1215
An order still open to modification or cancellation.
Definition types.hpp:2582
OrderRef< Broker > ref_
The reference to amend or cancel the order with.
Definition types.hpp:2586
std::optional< Decimal64 > amendable_quantity_
How much the broker says may still be amended. Empty means it stated none, not zero.
Definition types.hpp:2588
OrderSnapshot order_
The order's state.
Definition types.hpp:2584
The orders open to modification or cancellation at one point in time.
Definition types.hpp:2604
std::vector< WorkingOrder< Broker > > orders_
The open orders.
Definition types.hpp:2606
std::chrono::system_clock::time_point received_at_
When the listing was received, on this machine's clock.
Definition types.hpp:2608
The mock broker's tag: its order references are typed by it, so they work with no other broker.
Definition market.hpp:31
static constexpr std::string_view name
The broker's name, "mock".
Definition market.hpp:33
How a Market starts and what it charges.
Definition market.hpp:85
Money cash_
The starting cash, in the one currency the market keeps cash in.
Definition market.hpp:87
backtest::NextBarFillModel fills_
The fill rule and its costs, as a backtest's; no commission, slippage or tax by default.
Definition market.hpp:91
std::optional< TradingCalendar > calendar_
The trading days the market publishes, as a backtest is given them (backtest::ReplayConfig::calendar_...
Definition market.hpp:106
std::chrono::system_clock::time_point start_
The market's first instant; bars that ended by then are history.
Definition market.hpp:89
strategy::SessionWindow session_
The session window local dates and the close are read in, as a backtest's (backtest::ReplayConfig::se...
Definition market.hpp:96
std::chrono::system_clock::time_point period_end_
When the bar's period ended: the earliest moment the bar could be known.
Definition event.hpp:329
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.
Definition event.hpp:122
static SessionWindow krx()
Returns the KRX regular session, 09:00-15:30 KST.
Definition event.hpp:136