algotradelib 0.0.0.9000
C++ header-only library for algorithmic trading
Loading...
Searching...
No Matches
ledger.hpp
Go to the documentation of this file.
1#pragma once
2
4#include "../strategy/portfolio.hpp"
5#include "cost.hpp"
6
7#include <algotradelib/core>
8
9#include <algorithm>
10#include <cstddef>
11#include <cstdint>
12#include <limits>
13#include <optional>
14#include <stdexcept>
15#include <string_view>
16#include <type_traits>
17#include <utility>
18#include <vector>
19
20namespace algotradelib {
21namespace backtest {
22
27
33 static constexpr std::string_view name = "backtest";
34};
35
61
63enum class ExecutionHistory {
72};
73
80public:
88 : history_(history), own_(currency) {
89 cash_.push_back(Money{std::move(cash), std::move(currency)});
90 recount();
91 }
92
97 ReplayLedger(const ReplayLedger& other) = default;
98
103 ReplayLedger(ReplayLedger&& other) noexcept
104 : positions_(std::move(other.positions_)),
105 index_(std::move(other.index_)),
106 cash_(std::move(other.cash_)),
107 realized_(std::move(other.realized_)),
108 executions_(std::move(other.executions_)),
109 history_(other.history_),
110 held_(std::move(other.held_)),
111 lots_(std::move(other.lots_)),
112 changed_(std::move(other.changed_)),
113 changed_count_(other.changed_count_),
114 own_(other.own_),
115 running_(other.running_) {
116 other.forget_tracking();
117 }
118
125 // A self-move must not reach the members: it would empty `positions_` while `index_` kept its entries.
126 if (this != &other) {
127 positions_ = std::move(other.positions_);
128 index_ = std::move(other.index_);
129 cash_ = std::move(other.cash_);
130 realized_ = std::move(other.realized_);
131 executions_ = std::move(other.executions_);
132 history_ = other.history_;
133 held_ = std::move(other.held_);
134 lots_ = std::move(other.lots_);
135 changed_ = std::move(other.changed_);
136 changed_count_ = other.changed_count_;
137 own_ = other.own_;
138 running_ = other.running_;
139 other.forget_tracking();
140 }
141 return *this;
142 }
143
151 if (this != &other) {
152 ReplayLedger copy(other);
153 *this = std::move(copy);
154 }
155 return *this;
156 }
157
163 std::optional<Decimal64> cash_in(const Currency& currency) const {
164 for (const auto& amount : cash_) {
165 if (amount.currency_ == currency) {
166 return amount.amount_;
167 }
168 }
169 return std::nullopt;
170 }
171
177 std::optional<Decimal64> quantity_of(const InstrumentId& instrument) const {
178 if (const auto* lot = find(instrument)) {
179 return lot->quantity_;
180 }
181 return std::nullopt;
182 }
183
189 std::optional<Decimal64> average_price_of(const InstrumentId& instrument) const {
190 if (const auto* lot = find(instrument); lot && lot->quantity_.coefficient() != 0) {
191 return lot->average_purchase_price_;
192 }
193 return std::nullopt;
194 }
195
201 Decimal64 realized_in(const Currency& currency) const {
202 for (const auto& entry : realized_) {
203 if (entry.currency_ == currency) {
204 return entry.amount_;
205 }
206 }
207 return Decimal64::parse("0");
208 }
209
218 const std::vector<HoldingPosition>& positions() const noexcept {
219 return positions_;
220 }
221
226 ExecutionHistory history() const noexcept {
227 return history_;
228 }
229
236 const std::vector<Execution>& executions() const {
237 if (history_ == ExecutionHistory::NONE) {
238 throw std::logic_error(
239 "this ledger keeps no executions (ExecutionHistory::NONE); "
240 "a Backtester's are in ReplayResult::executions_"
241 );
242 }
243 return executions_;
244 }
245
257 std::optional<Decimal64> equity() const {
258 if (!running_.valid_ || !fits_at(running_.bound_, running_.scale_)) {
259 return equity_in(own_);
260 }
261 // With nothing counted, `equity_in` returns the cash as it is stored, without normalizing it.
262 if (running_.counted_ == 0) {
263 return cash_in(own_).value_or(Decimal64(0, 0));
264 }
265 return running_.total_;
266 }
267
282 bool apply(const Execution& execution_in, const Currency& currency_in) {
283 // **Owned copies first.** The execution passed in may be one of `executions()`, which reserving room
284 // below can move, and `currency_in` may be its currency (or a position's, which opening a lot can move);
285 // every read below is of these copies. A ledger that keeps no history copies only the currency: nothing
286 // it changes can hold an execution.
287 std::optional<Execution> recorded;
288 if (history_ == ExecutionHistory::KEEP) {
289 recorded.emplace(execution_in);
290 }
291 const auto currency = currency_in;
292 const auto& execution = recorded ? *recorded : execution_in;
293 const auto& fill = execution.fill_;
294 const auto zero = Decimal64(0, 0);
295
296 // Signed quantity: a sale reduces the position.
297 const auto signed_quantity =
298 fill.side_ == OrderSide::BUY ? std::optional<Decimal64>(fill.quantity_) : decimal_subtract(zero, fill.quantity_);
299 if (!signed_quantity) {
300 return false;
301 }
302
303 const auto gross = decimal_multiply(fill.quantity_, fill.price_);
304 if (!gross) {
305 return false;
306 }
307 // Cash out on a buy, in on a sale, and commission out either way.
308 const auto cash_change =
309 fill.side_ == OrderSide::BUY ? decimal_subtract(zero, *gross) : std::optional<Decimal64>(*gross);
310 if (!cash_change) {
311 return false;
312 }
313 const auto after_commission = decimal_subtract(*cash_change, execution.commission_);
314 if (!after_commission) {
315 return false;
316 }
317 // Both the broker's commission and the institution fee leave cash.
318 const auto after_fees =
319 execution.institution_fee_ ? decimal_subtract(*after_commission, *execution.institution_fee_) : after_commission;
320 if (!after_fees) {
321 return false;
322 }
323 const auto after_tax = decimal_subtract(*after_fees, execution.tax_);
324 if (!after_tax) {
325 return false;
326 }
327
328 // Read, never opened. Opening the lot here is what made an early return leave a trace.
329 const auto* existing = find(fill.instrument_);
330 const auto held = existing != nullptr ? existing->quantity_ : zero;
331 const auto average = existing != nullptr ? existing->average_purchase_price_ : zero;
332
333 // A non-flat position cannot change currency; refuse rather than relabel it.
334 if (existing != nullptr && held.coefficient() != 0 && !(existing->market_value_.currency_ == currency)) {
335 return false;
336 }
337
338 const auto closing = closed_quantity(held, *signed_quantity);
339 if (!closing) {
340 return false;
341 }
342
343 // Realized profit exists only on the part that closed, and only against the old average.
344 std::optional<Decimal64> realized_total;
345 if (closing->coefficient() != 0) {
346 const auto moved = decimal_subtract(fill.price_, average);
347 if (!moved) {
348 return false;
349 }
350 auto banked = decimal_multiply(*closing, *moved);
351 if (!banked) {
352 return false;
353 }
354 // Closing a short banks the opposite sign: it profits when the price fell.
355 if (decimal_less(held, zero)) {
356 banked = decimal_subtract(zero, *banked);
357 if (!banked) {
358 return false;
359 }
360 }
361 realized_total = decimal_add(realized_in(currency), *banked);
362 if (!realized_total) {
363 return false;
364 }
365 }
366
367 const auto resulting = decimal_add(held, *signed_quantity);
368 if (!resulting) {
369 return false;
370 }
371
372 const auto valued = decimal_multiply(*resulting, fill.price_);
373 if (!valued) {
374 return false;
375 }
376
377 // The average price follows only the part that opened or added. A position crossing flat takes the
378 // fill price outright, because nothing of the old basis survives.
379 auto new_average = average;
380 if (resulting->coefficient() == 0) {
381 new_average = zero;
382 } else if (crossed_or_opened(held, *resulting)) {
383 new_average = fill.price_;
384 } else if (adding(held, *signed_quantity)) {
385 const auto blended = weighted_average(held, average, *signed_quantity, fill.price_);
386 if (!blended) {
387 return false;
388 }
389 new_average = *blended;
390 }
391 // Reducing without crossing leaves the average alone: selling half a position does not change
392 // what the remaining half cost.
393
394 const auto cash_total = decimal_add(cash_in(currency).value_or(zero), *after_tax);
395 if (!cash_total) {
396 return false;
397 }
398
399 // Room in `held_` for this lot is made before anything changes, so the insert below cannot allocate,
400 // whatever the list's history (a copy holds no spare room).
401 if (resulting->coefficient() != 0 && held_.size() == held_.capacity()) {
402 held_.reserve(std::max<std::size_t>(8, 2 * held_.capacity()));
403 }
404 // **And every other allocation, so that a failed one leaves the ledger as it was.** A currency seen for
405 // the first time gets its cash and realized entries' room here, and the execution (copied above) is given
406 // room now; after `find_or_open` below (which undoes itself if it fails), nothing allocates.
407 reserve_entry(cash_, currency);
408 if (realized_total) {
409 reserve_entry(realized_, currency);
410 }
411 if (recorded && executions_.size() == executions_.capacity()) {
412 executions_.reserve(std::max<std::size_t>(8, 2 * executions_.capacity()));
413 }
414
415 // --- No arithmetic below can fail, and nothing below returns false -----------------------
416 auto* lot = find_or_open(fill.instrument_);
417 if ((lot->quantity_.coefficient() != 0) != (resulting->coefficient() != 0)) {
418 const auto at = static_cast<std::size_t>(lot - positions_.data());
419 const auto where = std::lower_bound(held_.begin(), held_.end(), at);
420 if (resulting->coefficient() != 0) {
421 held_.insert(where, at);
422 } else {
423 held_.erase(where);
424 }
425 }
426 lot->average_purchase_price_ = new_average;
427 lot->quantity_ = *resulting;
428 lot->last_price_ = fill.price_;
429 // **The currency is recorded here because this is the only place it is known.** `mark` is not
430 // told one and neither is `equity_in`'s caller beyond the currency it is asking about, so a
431 // position that never wrote its own currency down cannot be told apart from one denominated in
432 // whatever the caller happened to ask for. `Currency` default-constructs to KRW
433 // (`Currency`'s default constructor), which makes the untold case silently *answer* rather than be absent --
434 // a USD position would read as Korean won to anything summing per currency.
435 lot->market_value_ = Money{*valued, currency};
436 set_amount(cash_, currency, *cash_total);
437 if (realized_total) {
438 set_amount(realized_, currency, *realized_total);
439 }
440 static_assert(
441 std::is_nothrow_move_constructible<Execution>::value,
442 "the execution is moved into room made for it, which must not throw"
443 );
444 if (recorded) {
445 executions_.push_back(std::move(*recorded));
446 }
447 const auto at = static_cast<std::size_t>(lot - positions_.data());
448 note_changed(at);
449 retrack(at);
450 if (currency == own_) {
451 retrack_cash(*cash_total);
452 }
453 return true;
454 }
455
464 bool mark(const InstrumentId& instrument, const Decimal64& price) {
465 // An instrument has at most one lot: `find_or_open` opens one only when none matches.
466 const auto slot = slot_of(instrument);
467 return slot ? mark_lot(*slot, price) : true;
468 }
469
479 std::optional<std::size_t> lot_of(const InstrumentId& instrument) const {
480 return slot_of(instrument);
481 }
482
489 bool mark_lot(std::size_t lot, const Decimal64& price) {
490 auto& position = positions_[lot];
491 // **Both fields move or neither does, and the caller is told which.** Two earlier versions
492 // each lost one half of that. Advancing the price and leaving the old `market_value_`
493 // handed a strategy reading `positions()` or `snapshot()` a stale number presented as
494 // current, with no error anywhere; skipping the row silently declined to apply a price the
495 // caller asked for. The currency is the one `apply` recorded -- a lot exists only because a
496 // fill opened it -- and it is the half nothing can invalidate.
497 const auto valued = decimal_multiply(position.quantity_, price);
498 if (!valued) {
499 return false;
500 }
501 position.last_price_ = price;
502 position.market_value_ = Money{*valued, position.market_value_.currency_};
503 note_changed(lot);
504 retrack(lot);
505 return true;
506 }
507
519 template <typename BrokerTag>
520 strategy::Portfolio<BrokerTag> snapshot(std::chrono::system_clock::time_point as_of) const {
522 portfolio.positions_ = positions_;
523 // Every held share is sellable: a model consistent with crediting sales on the fill (no
524 // settlement); `ReportCaveats` discloses it.
525 for (auto& position : portfolio.positions_) {
526 position.sellable_quantity_ = position.quantity_;
527 }
528 // The basis a producer of sellable figures must state: whole holding, deduct resting, unverified.
529 portfolio.sellable_basis_ = SellableBasis{
532 false,
533 };
534 portfolio.cash_ = cash_;
535 // Buying power modelled as this ledger's cash, stamped at the snapshot time; the report states
536 // the model.
537 portfolio.buying_power_.reserve(cash_.size());
538 for (const auto& amount : cash_) {
539 portfolio.buying_power_.push_back(BuyingPower{amount, as_of});
540 }
541 portfolio.as_of_ = as_of;
542 return portfolio;
543 }
544
562 template <typename BrokerTag>
563 void update(strategy::Portfolio<BrokerTag>& portfolio, std::chrono::system_clock::time_point as_of) {
564 auto& rows = portfolio.positions_;
565 for (std::size_t k = 0; k < changed_count_; ++k) {
566 const auto at = changed_[k];
567 if (at >= rows.size()) {
568 continue;
569 }
570 // The fields `apply` and `mark` write; a lot's instrument never changes.
571 const auto& lot = positions_[at];
572 auto& row = rows[at];
573 row.quantity_ = lot.quantity_;
574 row.sellable_quantity_ = lot.quantity_;
575 row.average_purchase_price_ = lot.average_purchase_price_;
576 row.last_price_ = lot.last_price_;
577 row.market_value_ = lot.market_value_;
578 }
579 if (rows.size() < positions_.size()) {
580 rows.reserve(positions_.size());
581 while (rows.size() < positions_.size()) {
582 rows.push_back(positions_[rows.size()]);
583 rows.back().sellable_quantity_ = rows.back().quantity_;
584 }
585 }
586 portfolio.sellable_basis_ = SellableBasis{
589 false,
590 };
591 portfolio.cash_ = cash_;
592 portfolio.buying_power_.clear();
593 portfolio.buying_power_.reserve(cash_.size());
594 for (const auto& amount : cash_) {
595 portfolio.buying_power_.push_back(BuyingPower{amount, as_of});
596 }
597 portfolio.as_of_ = as_of;
599 }
600
604 void clear_changed() noexcept {
605 for (std::size_t k = 0; k < changed_count_; ++k) {
606 lots_[changed_[k]].changed_ = false;
607 }
608 changed_count_ = 0;
609 }
610
619 std::optional<Decimal64> equity_in(const Currency& currency) const {
620 auto total = cash_in(currency).value_or(Decimal64(0, 0));
621 // The lots with a non-zero quantity, in the order of `positions_`.
622 for (const auto at : held_) {
623 const auto& lot = positions_[at];
624 // Only positions in `currency` (recorded on `market_value_` by `apply`); no conversion.
625 if (!(lot.market_value_.currency_ == currency)) {
626 continue;
627 }
628 // Computed from the last mark rather than read from `market_value_`.
629 const auto value = decimal_multiply(lot.quantity_, lot.last_price_);
630 if (!value) {
631 return std::nullopt;
632 }
633 const auto sum = decimal_add(total, *value);
634 if (!sum) {
635 return std::nullopt;
636 }
637 total = *sum;
638 }
639 return total;
640 }
641
642private:
643 // Returns the position in `instrument`, or nothing, **without creating one**.
644 const HoldingPosition* find(const InstrumentId& instrument) const {
645 const auto slot = slot_of(instrument);
646 return slot ? &positions_[*slot] : nullptr;
647 }
648
649 // Returns where `instrument`'s lot is in `positions_`: by the index once the ledger holds more than
650 // `id_detail::scan_limit` lots, by a scan before that.
651 std::optional<std::size_t> slot_of(const InstrumentId& instrument) const {
652 if (!index_.empty()) {
653 return index_.find(instrument, lot_ids());
654 }
655 for (std::size_t at = 0; at < positions_.size(); ++at) {
656 if (positions_[at].instrument_ == instrument) {
657 return at;
658 }
659 }
660 return std::nullopt;
661 }
662
663 // The id at a position of `positions_`, for the index.
664 struct LotIds {
665 const std::vector<HoldingPosition>* positions_;
666 const InstrumentId& operator()(std::size_t at) const noexcept {
667 return (*positions_)[at].instrument_;
668 }
669 };
670 LotIds lot_ids() const noexcept {
671 return LotIds{&positions_};
672 }
673
674 HoldingPosition* find_or_open(const InstrumentId& instrument) {
675 if (const auto slot = slot_of(instrument)) {
676 return &positions_[*slot];
677 }
678 HoldingPosition opened;
679 opened.instrument_ = instrument;
680 opened.quantity_ = Decimal64(0, 0);
681 opened.average_purchase_price_ = Decimal64(0, 0);
682 opened.last_price_ = Decimal64(0, 0);
683 // Room in the lists kept beside `positions_` first, so that after the lot is added nothing below can leave
684 // them disagreeing with it.
685 grow_for(lots_, positions_.size() + 1);
686 grow_for(changed_, positions_.size() + 1);
687 positions_.push_back(std::move(opened));
688 lots_.emplace_back();
689 changed_.push_back(0);
690 if (index_.empty() && positions_.size() <= id_detail::scan_limit) {
691 return &positions_.back();
692 }
693 // Past `id_detail::scan_limit` lots the index holds every lot: built whole at the first one past it,
694 // extended after that. If it cannot be, the lot comes out again, so the two never disagree. Lots are never
695 // removed or reordered, so a position stays valid.
696 try {
697 if (index_.empty()) {
698 id_detail::PositionTable built;
699 for (std::size_t at = 0; at < positions_.size(); ++at) {
700 built.insert(positions_[at].instrument_, at, lot_ids());
701 }
702 index_ = std::move(built);
703 } else {
704 index_.insert(instrument, positions_.size() - 1, lot_ids());
705 }
706 } catch (...) {
707 positions_.pop_back();
708 lots_.pop_back();
709 changed_.pop_back();
710 throw;
711 }
712 return &positions_.back();
713 }
714
715 // Returns how much of `held` this trade closes, which is zero when it only adds.
716 static std::optional<Decimal64> closed_quantity(const Decimal64& held, const Decimal64& traded) {
717 const auto zero = Decimal64(0, 0);
718 const bool long_held = decimal_less(zero, held);
719 const bool short_held = decimal_less(held, zero);
720 const bool buying = decimal_less(zero, traded);
721 if ((long_held && buying) || (short_held && !buying) || held.coefficient() == 0) {
722 return zero;
723 }
724 const auto magnitude_held = long_held ? held : decimal_subtract(zero, held);
725 const auto magnitude_traded = buying ? traded : decimal_subtract(zero, traded);
726 if (!magnitude_held || !magnitude_traded) {
727 return std::nullopt;
728 }
729 return decimal_less(*magnitude_held, *magnitude_traded) ? *magnitude_held : *magnitude_traded;
730 }
731
732 // Returns whether the trade opened from flat or crossed through it.
733 static bool crossed_or_opened(const Decimal64& held, const Decimal64& resulting) {
734 const auto zero = Decimal64(0, 0);
735 if (held.coefficient() == 0) {
736 return true;
737 }
738 return decimal_less(zero, held) != decimal_less(zero, resulting);
739 }
740
741 // Returns whether the trade added to a position rather than reducing it.
742 static bool adding(const Decimal64& held, const Decimal64& traded) {
743 const auto zero = Decimal64(0, 0);
744 return decimal_less(zero, held) == decimal_less(zero, traded);
745 }
746
747 // Returns the average of two lots by magnitude, which is what adding to a position produces.
748 static std::optional<Decimal64> weighted_average(
749 const Decimal64& held, const Decimal64& held_price, const Decimal64& traded, const Decimal64& traded_price
750 ) {
751 const auto zero = Decimal64(0, 0);
752 const auto held_magnitude = decimal_less(held, zero) ? decimal_subtract(zero, held) : held;
753 const auto traded_magnitude = decimal_less(traded, zero) ? decimal_subtract(zero, traded) : traded;
754 if (!held_magnitude || !traded_magnitude) {
755 return std::nullopt;
756 }
757 const auto held_cost = decimal_multiply(*held_magnitude, held_price);
758 const auto traded_cost = decimal_multiply(*traded_magnitude, traded_price);
759 if (!held_cost || !traded_cost) {
760 return std::nullopt;
761 }
762 const auto total_cost = decimal_add(*held_cost, *traded_cost);
763 const auto total_quantity = decimal_add(*held_magnitude, *traded_magnitude);
764 if (!total_cost || !total_quantity || total_quantity->coefficient() == 0) {
765 return std::nullopt;
766 }
767 // Four places, which holds a tick on every grid this library knows and more than a price needs.
768 return decimal_divide(*total_cost, *total_quantity, 4);
769 }
770
771 // Writes `total` as the whole amount held in `currency`, appending the entry when there is none.
772 //
773 // Takes the **total** rather than a change, because the addition is the fallible half and `apply`
774 // has already done it before committing anything. What is left cannot fail, which is what lets
775 // `apply` promise the ledger is either wholly updated or untouched.
776 static void set_amount(std::vector<Money>& amounts, const Currency& currency, const Decimal64& total) {
777 for (auto& amount : amounts) {
778 if (amount.currency_ == currency) {
779 amount.amount_ = total;
780 return;
781 }
782 }
783 amounts.push_back(Money{total, currency});
784 }
785
786 std::vector<HoldingPosition> positions_;
787 // Where each instrument's lot is in `positions_`; empty until the ledger holds more than
788 // `id_detail::scan_limit` lots.
789 id_detail::PositionTable index_;
790 std::vector<Money> cash_;
791 std::vector<Money> realized_;
792 std::vector<Execution> executions_;
794 // Where the lots with a non-zero quantity are in `positions_`, ascending; `apply` keeps it.
795 std::vector<std::size_t> held_;
796
797 // What the ledger keeps about each lot, beside `positions_` and in the same order.
798 struct LotTrack {
799 // Listed in `changed_`.
800 bool changed_{false};
801 // The value `running_` counts for this lot: its market value, while it is held in `own_`.
802 std::optional<Decimal64> counted_;
803 };
804 std::vector<LotTrack> lots_;
805 // The lots changed since the last `update` or `clear_changed`, in its first `changed_count_` places. As
806 // long as `positions_`, so that listing a lot never allocates.
807 std::vector<std::size_t> changed_;
808 std::size_t changed_count_{0};
809
810 // The running equity in `own_` that `equity()` returns, and what proves it equal to `equity_in`'s.
811 struct Running {
812 // False when an update did not fit and counting everything again did not either.
813 bool valid_{false};
814 // The cash plus every counted value.
815 Decimal64 total_;
816 // The magnitudes of the cash and of every counted value, added up.
817 Decimal64 bound_;
818 // The largest scale among the cash and the counted values seen since the last `recount`; never lowered between.
819 std::uint8_t scale_{0};
820 // The cash counted in `total_`.
821 Decimal64 cash_;
822 // How many lots are counted: those held (non-zero quantity) in `own_`, whatever their value.
823 std::size_t counted_{0};
824 };
825 // The constructor's currency.
826 Currency own_;
827 Running running_;
828
829 // Makes room for `currency`'s entry in `amounts` if it has none, so `set_amount` will not allocate.
830 static void reserve_entry(std::vector<Money>& amounts, const Currency& currency) {
831 for (const auto& amount : amounts) {
832 if (amount.currency_ == currency) {
833 return;
834 }
835 }
836 amounts.reserve(amounts.size() + 1);
837 }
838
839 // Makes room for `size` entries, doubling, so opening lots one at a time does not copy every list each time.
840 template <typename T>
841 static void grow_for(std::vector<T>& list, std::size_t size) {
842 if (list.capacity() < size) {
843 list.reserve(std::max<std::size_t>(size, 2 * list.capacity()));
844 }
845 }
846
847 // Lists lot `at` as changed; never allocates, since `changed_` has a place for every lot.
848 void note_changed(std::size_t at) noexcept {
849 if (!lots_[at].changed_) {
850 lots_[at].changed_ = true;
851 changed_[changed_count_++] = at;
852 }
853 }
854
855 static std::optional<Decimal64> magnitude(const Decimal64& value) {
856 return value.coefficient() < 0 ? decimal_subtract(Decimal64(0, 0), value) : std::optional<Decimal64>(value);
857 }
858
859 // Returns whether a non-negative `value` still fits when written at `scale`.
860 static bool fits_at(const Decimal64& value, std::uint8_t scale) noexcept {
861 auto coefficient = value.coefficient();
862 for (auto step = value.scale(); step < scale; ++step) {
863 if (coefficient > std::numeric_limits<std::int64_t>::max() / 10) {
864 return false;
865 }
866 coefficient *= 10;
867 }
868 return true;
869 }
870
871 // Replaces `before` with `after` in the running totals, or marks them invalid if that does not fit.
872 void replace_counted(const std::optional<Decimal64>& before, const std::optional<Decimal64>& after) noexcept {
873 std::optional<Decimal64> total = running_.total_;
874 std::optional<Decimal64> bound = running_.bound_;
875 if (before) {
876 const auto size = magnitude(*before);
877 total = decimal_subtract(*total, *before);
878 bound = size ? decimal_subtract(*bound, *size) : std::nullopt;
879 }
880 if (after && total && bound) {
881 const auto size = magnitude(*after);
882 total = decimal_add(*total, *after);
883 bound = size ? decimal_add(*bound, *size) : std::nullopt;
884 running_.scale_ = std::max(running_.scale_, after->scale());
885 }
886 if (!total || !bound) {
887 running_.valid_ = false;
888 return;
889 }
890 running_.total_ = *total;
891 running_.bound_ = *bound;
892 }
893
894 // Brings lot `at`'s counted value up to date.
895 void retrack(std::size_t at) noexcept {
896 const auto& lot = positions_[at];
897 std::optional<Decimal64> value;
898 if (lot.quantity_.coefficient() != 0 && lot.market_value_.currency_ == own_) {
899 value = lot.market_value_.amount_;
900 }
901 auto& counted = lots_[at].counted_;
902 if (counted == value) {
903 return;
904 }
905 if (counted.has_value() != value.has_value()) {
906 running_.counted_ = value ? running_.counted_ + 1 : running_.counted_ - 1;
907 }
908 if (running_.valid_) {
909 replace_counted(counted, value);
910 }
911 counted = value;
912 if (!running_.valid_) {
913 recount();
914 }
915 }
916
917 // Brings the counted cash up to date.
918 void retrack_cash(const Decimal64& cash) noexcept {
919 if (running_.valid_) {
920 replace_counted(running_.cash_, cash);
921 }
922 running_.cash_ = cash;
923 if (!running_.valid_) {
924 recount();
925 }
926 }
927
928 // Leaves a ledger whose contents were moved out consistent with what it now holds (no lots, and whatever
929 // cash a moved-from vector keeps): nothing listed as changed, the running equity counted again.
930 void forget_tracking() noexcept {
931 lots_.clear();
932 changed_.clear();
933 changed_count_ = 0;
934 recount();
935 }
936
937 // Counts everything again: at construction, and after an update that did not fit.
938 void recount() noexcept {
939 Running fresh;
940 fresh.cash_ = cash_in(own_).value_or(Decimal64(0, 0));
941 fresh.total_ = fresh.cash_;
942 fresh.scale_ = fresh.cash_.scale();
943 const auto cash_size = magnitude(fresh.cash_);
944 fresh.valid_ = cash_size.has_value();
945 if (cash_size) {
946 fresh.bound_ = *cash_size;
947 }
948 for (const auto at : held_) {
949 const auto& value = lots_[at].counted_;
950 if (!value) {
951 continue;
952 }
953 ++fresh.counted_;
954 fresh.scale_ = std::max(fresh.scale_, value->scale());
955 if (!fresh.valid_) {
956 continue;
957 }
958 const auto size = magnitude(*value);
959 const auto total = decimal_add(fresh.total_, *value);
960 const auto bound = size ? decimal_add(fresh.bound_, *size) : std::nullopt;
961 if (!total || !bound) {
962 fresh.valid_ = false;
963 continue;
964 }
965 fresh.total_ = *total;
966 fresh.bound_ = *bound;
967 }
968 running_ = fresh;
969 }
970};
971
972} // namespace backtest
973} // 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.
static Decimal64 parse(std::string_view input)
Parses a decimal string exactly (no binary floating point).
Definition types.hpp:468
void clear_changed() noexcept
Forgets which lots changed, after a snapshot that already shows them.
Definition ledger.hpp:604
ReplayLedger(const ReplayLedger &other)=default
Copies a ledger.
bool mark_lot(std::size_t lot, const Decimal64 &price)
Marks the lot at a place lot_of returned to a price, as mark does for its instrument.
Definition ledger.hpp:489
std::optional< Decimal64 > equity() const
Returns total equity in the ledger's own currency (the constructor's), as equity_in would.
Definition ledger.hpp:257
ReplayLedger & operator=(ReplayLedger &&other) noexcept
Replaces this ledger with a move of another; moving a ledger into itself leaves it unchanged.
Definition ledger.hpp:124
ReplayLedger(ReplayLedger &&other) noexcept
Moves a ledger.
Definition ledger.hpp:103
ExecutionHistory history() const noexcept
Returns whether the ledger keeps the executions it applies.
Definition ledger.hpp:226
std::optional< Decimal64 > quantity_of(const InstrumentId &instrument) const
Returns the quantity held of an instrument.
Definition ledger.hpp:177
std::optional< std::size_t > lot_of(const InstrumentId &instrument) const
Returns where an instrument's lot is in positions(), if a fill ever opened one.
Definition ledger.hpp:479
const std::vector< Execution > & executions() const
Returns every execution applied.
Definition ledger.hpp:236
ReplayLedger(Decimal64 cash, Currency currency, ExecutionHistory history=ExecutionHistory::KEEP)
Constructs a ledger holding only cash.
Definition ledger.hpp:87
std::optional< Decimal64 > average_price_of(const InstrumentId &instrument) const
Returns the average price of the position in an instrument.
Definition ledger.hpp:189
const std::vector< HoldingPosition > & positions() const noexcept
Returns every position, including ones that went flat.
Definition ledger.hpp:218
std::optional< Decimal64 > equity_in(const Currency &currency) const
Returns total equity in a currency: cash plus positions at their last marks.
Definition ledger.hpp:619
ReplayLedger & operator=(const ReplayLedger &other)
Replaces this ledger with a copy of another, entirely or not at all.
Definition ledger.hpp:150
void update(strategy::Portfolio< BrokerTag > &portfolio, std::chrono::system_clock::time_point as_of)
Brings a portfolio built by snapshot up to date, changing only what changed since.
Definition ledger.hpp:563
bool mark(const InstrumentId &instrument, const Decimal64 &price)
Marks positions in an instrument to a price, updating their market value.
Definition ledger.hpp:464
Decimal64 realized_in(const Currency &currency) const
Returns the profit realized by closing positions, in a currency (fees excluded).
Definition ledger.hpp:201
strategy::Portfolio< BrokerTag > snapshot(std::chrono::system_clock::time_point as_of) const
Returns the portfolio a strategy sees.
Definition ledger.hpp:520
bool apply(const Execution &execution_in, const Currency &currency_in)
Applies one execution to the position, cash and realized profit.
Definition ledger.hpp:282
std::optional< Decimal64 > cash_in(const Currency &currency) const
Returns the cash held in a currency.
Definition ledger.hpp:163
Trading costs for a backtest: commission (CommissionModel, CommissionPolicy), slippage (SlippageModel...
The events a runner delivers to a strategy's handlers, and the market phase.
Replays a strategy over stored bars: fill and cost models, the replay ledger, and the report.
Definition bootstrap.hpp:16
@ NONE
No points, for a run that does not read the curve; summarize then reports no ratio.
Definition engine.hpp:655
ExecutionHistory
Whether a ReplayLedger keeps the executions it applies.
Definition ledger.hpp:63
@ KEEP
Keep every execution, readable through ReplayLedger::executions().
Definition ledger.hpp:65
@ NONE
Keep none, for an owner that records them itself (a Backtester, in ReplayResult::executions_).
Definition ledger.hpp:71
The library: broker-neutral types (core), and the modules below.
std::optional< Decimal64 > decimal_add(const Decimal64 &lhs, const Decimal64 &rhs)
Adds two decimals exactly.
Definition types.hpp:760
std::optional< Decimal64 > decimal_subtract(const Decimal64 &lhs, const Decimal64 &rhs)
Subtracts two decimals exactly.
Definition types.hpp:783
std::optional< Decimal64 > decimal_divide(const Decimal64 &lhs, const Decimal64 &rhs, std::uint8_t scale)
Divides two decimals, truncating toward zero at a given scale.
Definition types.hpp:860
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
What the broker says may be spent, in one currency.
Definition types.hpp:1396
One position row in a holdings snapshot.
Definition types.hpp:1288
Identifies an instrument: its country, venue and symbol.
Definition types.hpp:85
An exact amount of money in one currency.
Definition types.hpp:1168
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
The commission rate that charged an execution, as the backtest report lists it.
Definition cost.hpp:125
The broker tag of a replay's order references (they reach no broker).
Definition ledger.hpp:31
static constexpr std::string_view name
The name an order reference prints: "backtest".
Definition ledger.hpp:33
One execution a backtest produced, and what it cost.
Definition ledger.hpp:37
std::optional< Decimal64 > institution_fee_
The institution fee (유관기관제비용), if the rate was split; empty is not zero.
Definition ledger.hpp:47
Decimal64 commission_
The broker's commission; includes the institution fee when institution_fee_ is empty.
Definition ledger.hpp:41
AppliedRate applied_
The commission rate that charged this execution.
Definition ledger.hpp:51
Decimal64 slippage_
The price given up to slippage (already included in the fill price).
Definition ledger.hpp:53
strategy::Fill fill_
The fill, as on_fill receives it.
Definition ledger.hpp:39
Decimal64 tax_
The sale tax charged; zero unless a sell tax applies (NextBarFillModel::with_sell_tax).
Definition ledger.hpp:59
Currency currency_
The currency of the cost figures.
Definition ledger.hpp:49
One execution of an order the strategy placed, delivered to on_fill.
Definition event.hpp:886
What the account holds and which orders are still working, as a strategy sees it.
Definition portfolio.hpp:82
SellableBasis sellable_basis_
What the sellable_quantity_ figures on positions_ cover.
std::vector< Money > cash_
Cash per currency, in a backtest only.
Definition portfolio.hpp:96
std::vector< BuyingPower > buying_power_
What may be spent, per currency.
std::chrono::system_clock::time_point as_of_
When the holdings were received, on this machine's clock.
std::vector< HoldingPosition > positions_
Every position row the broker reported.
Definition portfolio.hpp:88