3#include "./journal.hpp"
5#include <algotradelib/core>
10#include <unordered_map>
112template <
typename Strategy,
typename CapsType,
typename BrokerTag,
typename Executor>
115namespace run_detail {
140 const std::string&
id() const noexcept {
157 return cash_.currency_;
166 const auto at = find(instrument);
184 const auto next = booked(instrument, side, filled, amount, fee);
188 const auto at = find(instrument);
190 shares_[*at].quantity_ = next->second;
192 add(instrument, next->second);
194 cash_.amount_ = next->first;
200 template <
typename,
typename,
typename,
typename>
204 RunLedger(std::string
id,
Money opening) : id_(std::move(
id)), cash_(std::move(opening)) {}
207 static run_detail::Fold fold(
const JournalReplay& replay);
210 bool settled() const noexcept {
211 return unsettled_ == 0;
215 bool settled_on(
const InstrumentId& instrument)
const {
216 if (unsettled_ == 0) {
219 for (
const auto& placement : placements_) {
228 std::vector<RunPlacement> unsettled()
const {
229 std::vector<RunPlacement> found;
230 if (unsettled_ == 0) {
233 for (
const auto& placement : placements_) {
235 found.push_back(placement);
242 const RunPlacement* placement(
const std::string&
id)
const {
243 const auto at = placement_at_.find(
id);
244 return at == placement_at_.end() ? nullptr : &placements_[at->second];
248 const RunTransfer* transfer_of(
const std::string&
id)
const {
249 for (
const auto& transfer : transfers_) {
250 if (transfer.id_ ==
id) {
258 bool transfer(
const RunTransfer& transfer) {
260 transfer.id_.empty() || transfer_of(transfer.id_) !=
nullptr ||
265 const auto cash = transfer.withdrawal_ ?
267 decimal_add(cash_.amount_, transfer.amount_.amount_);
271 transfers_.push_back(transfer);
272 cash_.amount_ = *
cash;
277 bool hold(
const RunPlacement& placement) {
282 bool release(
const RunPlacement& placement) {
287 bool can_book_placement(
288 const RunPlacement& placement,
const Decimal64& filled,
const Money& amount,
const Decimal64& fee
290 const auto* known = this->placement(placement.id_);
293 booked(placement.instrument_, placement.side_, filled, amount, fee).has_value();
298 const RunPlacement& placement,
const Decimal64& filled,
const Money& amount,
const Decimal64& fee
300 if (!can_book_placement(placement, filled, amount, fee)) {
303 book(placement.instrument_, placement.side_, filled, amount, fee);
309 bool can_book_released(
310 const std::string&
id,
const Decimal64& filled,
const Money& amount,
const Decimal64& fee
312 const auto* known = placement(
id);
315 booked(known->instrument_, known->side_, filled, amount, fee).has_value();
319 bool book_released(
const std::string&
id,
const Decimal64& filled,
const Money& amount,
const Decimal64& fee) {
320 if (!can_book_released(
id, filled, amount, fee)) {
323 const auto released = *placement(
id);
324 book(released.instrument_, released.side_, filled, amount, fee);
329 std::optional<std::pair<Decimal64, Decimal64>> booked(
330 const InstrumentId& instrument,
OrderSide side,
const Decimal64& filled,
const Money& amount,
const Decimal64& fee
339 const auto at = find(instrument);
340 const Decimal64 held = at ? shares_[*at].quantity_ : zero;
341 std::optional<Decimal64> shares;
342 std::optional<Decimal64>
cash;
343 if (side == OrderSide::BUY) {
345 const auto spent =
decimal_add(amount.amount_, fee);
353 cash = returned ?
decimal_add(cash_.amount_, *returned) : std::nullopt;
355 if (!shares || !
cash) {
358 return std::make_pair(*
cash, *shares);
364 const auto at = placement_at_.find(placement.id_);
365 if (at == placement_at_.end()) {
366 auto added = placement;
367 added.state_ = state;
368 placement_at_.emplace(added.id_, placements_.size());
369 placements_.push_back(std::move(added));
373 auto& known = placements_[at->second];
381 known.state_ = state;
387 InstrumentId instrument_;
393 const std::vector<Shares>* shares_;
394 const InstrumentId& operator()(std::size_t at)
const noexcept {
395 return (*shares_)[at].instrument_;
400 std::optional<std::size_t> find(
const InstrumentId& instrument)
const noexcept {
401 if (table_.empty()) {
402 for (std::size_t at = 0; at < shares_.size(); ++at) {
403 if (shares_[at].instrument_ == instrument) {
409 return table_.find(instrument, IdOf{&shares_});
413 void add(
const InstrumentId& instrument,
const Decimal64& quantity) {
414 shares_.push_back(Shares{instrument, quantity});
416 if (!table_.empty()) {
417 table_.insert(instrument, shares_.size() - 1, IdOf{&shares_});
418 }
else if (shares_.size() > id_detail::scan_limit) {
419 id_detail::PositionTable built;
420 for (std::size_t at = 0; at < shares_.size(); ++at) {
421 built.insert(shares_[at].instrument_, at, IdOf{&shares_});
423 table_ = std::move(built);
433 std::vector<Shares> shares_;
434 id_detail::PositionTable table_;
435 std::vector<RunTransfer> transfers_;
436 std::vector<RunPlacement> placements_;
437 std::unordered_map<std::string, std::size_t> placement_at_;
439 std::size_t unsettled_{0};
442namespace run_detail {
447 std::optional<RunLedger> run_;
449 std::string failure_;
454inline run_detail::Fold RunLedger::fold(
const JournalReplay& replay) {
455 run_detail::Fold folded;
456 std::optional<std::size_t> opened;
457 for (std::size_t at = 0; at < replay.entries_.size(); ++at) {
458 const auto& entry = replay.entries_[at];
466 const auto& open = *replay.entries_[*opened].run_;
467 if (!open.amount_ || open.run_ != replay.entries_[*opened].id_) {
468 folded.failure_ =
"the run's opening line " + replay.entries_[*opened].id_ +
" is incomplete";
472 for (std::size_t at = 0; at < *opened; ++at) {
473 if (replay.entries_[at].run_ && replay.entries_[at].run_->run_ == open.run_) {
474 folded.failure_ =
"the run's opening line " + open.run_ +
" is repeated";
479 const auto fail = [&folded](
const JournalEntry& entry,
const char* why) {
480 folded.failure_ =
"the run's journal line " + entry.id_ +
" " + why;
481 return std::move(folded);
483 for (std::size_t at = *opened + 1; at < replay.entries_.size(); ++at) {
484 const auto& entry = replay.entries_[at];
485 if (!entry.run_ || entry.run_->run_ != run.id_) {
488 const auto& record = *entry.run_;
489 const RunPlacement placement{entry.id_, entry.instrument_, entry.side_, entry.quantity_,
RunPlacementState::HELD};
492 record.kind_ && record.amount_ && (*record.kind_ !=
RunRecordKind::FILL || (record.filled_ && record.fee_)) :
493 !record.filled_ || (record.amount_ && record.fee_);
495 return fail(entry,
"is incomplete");
498 if (*record.kind_ == RunRecordKind::OPEN) {
499 return fail(entry,
"opens its run a second time");
502 if (!run.book_released(record.of_, *record.filled_, *record.amount_, *record.fee_)) {
503 return fail(entry,
"books a placement that was not released unbooked, or a fill it cannot take");
506 !run.transfer(RunTransfer{record.given_, *record.amount_, *record.kind_ == RunRecordKind::WITHDRAWAL})
508 return fail(entry,
"repeats a transfer id, or is in another currency, or does not fit");
516 if (!run.hold(placement)) {
517 return fail(entry,
"holds a placement already booked");
520 const bool booked = record.filled_.has_value();
523 !run.book_placement(placement, *record.filled_, *record.amount_, *record.fee_) :
524 !run.release(placement)
526 return fail(entry,
"accounts for a placement twice, or books a fill the run cannot take");
530 folded.run_ = std::move(run);
A three-letter currency code, such as KRW or USD (ISO 4217 style).
An exact signed decimal: an int64 coefficient times 10^-scale.
static Decimal64 parse(std::string_view input)
Parses a decimal string exactly (no binary floating point).
const Money & cash() const noexcept
Returns the run's cash.
RunLedger(Money opening)
Opens a new run.
const std::string & id() const noexcept
Returns the run's id.
const Currency & currency() const noexcept
Returns the run's currency.
Decimal64 holding(const InstrumentId &instrument) const
Returns the run's own shares of an instrument.
bool book(const InstrumentId &instrument, OrderSide side, const Decimal64 &filled, const Money &amount, const Decimal64 &fee)
Books one fill.
Runs one strategy: feeds it events, reconciles what it asks for, checks the risk limits,...
Runs a strategy: the runner, the polling loop, the order journal, and stopping.
RunPlacementState
Where a run's placement stands in its ledger (Runner::run_unsettled).
@ BOOKED
Booked: its fill, if any, moved the run's cash and shares.
@ UNBOOKED
Accounted for without a booking (released by an operator, or confirmed by a runner without a budget).
@ HELD
Held for an operator (JournalOutcome::HELD): what it filled is not known.
@ OPEN
A run begins; its amount is the budget, the run's first deposit, and its line's id is the run's id.
@ FILL
An operator's booking of a placement released without one (runner::Runner::book_run_fill).
RunRefusal
Why recovery opened no run (RunRecoverySummary::refusal_).
@ DAMAGED
The journal was not read whole, or holds a damaged line.
@ CURRENCY
The journal's run is in another currency than strategy::RiskLimits::run_budget_.
@ NONE
None: the run opened, or a new run waits for the old run to close.
@ WRITE
A line of the opening could not be written.
@ NO_RUN
A resume found an intact journal with no run: no halt, buys and sells refused, withdrawals as usual.
@ TRANSFER
A stated transfer was refused (an id reused with another amount, a withdrawal past free cash,...
@ CONFIRMED
A serialized runner accounted for the placement: holdings showed what it filled, its history showed i...
@ HELD
Evidence contradicted the placement (holdings moved past what it can explain), so only an operator ma...
@ LEDGER
A record of a run budget's ledger (RunRecord), not an instruction: it sends nothing and names no orde...
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.
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.
OrderSide
The side of an order: its economic direction, buy or sell.
Identifies an instrument: its country, venue and symbol.
An exact amount of money in one currency.
The contents of a journal, including what could not be read.
How a budgeted runner opens its run when runner::recover_runner reads its journal (Runner::set_run_op...
bool resume_
Resume the journal's latest run instead of opening a new one (none: RunRefusal::NO_RUN).
std::vector< RunTransfer > transfers_
Deposits and withdrawals for a resumed run, each applied once by its id, in order.
bool wait_for_open_orders_
For a new run: wait for the old run's open orders to end, instead of cancelling them.
A placement of a run, as its ledger knows it.
std::string id_
The placement's journal id.
InstrumentId instrument_
The instrument.
RunPlacementState state_
Where it stands.
Decimal64 quantity_
The quantity it was sent for.
How recovery opened a budgeted runner's run, or why it did not (RecoveryReport::run_).
std::size_t transfers_applied_
How many transfers were written now.
std::string id_
The run's id.
bool resumed_
Whether a run found in the journal was resumed; false for a new run.
std::optional< Money > cash_
The run's cash once open.
bool closing_
Whether a new run waits for the old run's open orders to be accounted for: not opened yet (Runner::ru...
std::string refused_
Why the run did not open, for the operator; empty when it did.
bool opened_
Whether the run is open.
RunRefusal refusal_
Why the run did not open; every kind but NO_RUN halts (LOCAL_FAILURE) and stops its writes.
bool budget_used_
Whether strategy::RiskLimits::run_budget_ was used: only a new run opens with it.
Cash an operator adds to a run or takes from it, once (RunOpening::transfers_).
std::string id_
The operator's id for it; a transfer whose id the run already holds is not applied again.
Money amount_
How much, in the run's currency; positive.
bool withdrawal_
Whether it is taken from the run (a withdrawal) rather than added (a deposit).