algotradelib 0.0.0.9000
C++ header-only library for algorithmic trading
Loading...
Searching...
No Matches
run_ledger.hpp
1#pragma once
2
3#include "./journal.hpp"
4
5#include <algotradelib/core>
6
7#include <cstddef>
8#include <optional>
9#include <string>
10#include <unordered_map>
11#include <utility>
12#include <vector>
13
14namespace algotradelib {
15namespace runner {
16
26
40
44 std::string id_;
48 bool withdrawal_{false};
49};
50
60struct RunOpening {
62 bool resume_{false};
66 std::vector<RunTransfer> transfers_;
67};
68
86
90 bool opened_{false};
95 bool closing_{false};
97 bool resumed_{false};
99 std::string id_;
101 std::optional<Money> cash_;
103 std::size_t transfers_applied_{0};
105 bool budget_used_{false};
109 std::string refused_;
110};
111
112template <typename Strategy, typename CapsType, typename BrokerTag, typename Executor>
113class Runner;
114
115namespace run_detail {
116struct Fold;
117} // namespace run_detail
118
129public:
134 explicit RunLedger(Money opening) : cash_(std::move(opening)) {}
135
140 const std::string& id() const noexcept {
141 return id_;
142 }
143
148 const Money& cash() const noexcept {
149 return cash_;
150 }
151
156 const Currency& currency() const noexcept {
157 return cash_.currency_;
158 }
159
165 Decimal64 holding(const InstrumentId& instrument) const {
166 const auto at = find(instrument);
167 return at ? shares_[*at].quantity_ : Decimal64::parse("0");
168 }
169
181 bool book(
182 const InstrumentId& instrument, OrderSide side, const Decimal64& filled, const Money& amount, const Decimal64& fee
183 ) {
184 const auto next = booked(instrument, side, filled, amount, fee);
185 if (!next) {
186 return false;
187 }
188 const auto at = find(instrument);
189 if (at) {
190 shares_[*at].quantity_ = next->second;
191 } else {
192 add(instrument, next->second);
193 }
194 cash_.amount_ = next->first;
195 return true;
196 }
197
198private:
199 // `Runner` alone keeps a journal's run: it opens it, folds it, and moves its placements.
200 template <typename, typename, typename, typename>
201 friend class Runner;
202
203 // Opens a new run recorded in a journal.
204 RunLedger(std::string id, Money opening) : id_(std::move(id)), cash_(std::move(opening)) {}
205
206 // Reads a journal's run: its latest `RunRecordKind::OPEN` record and every line of that run after it.
207 static run_detail::Fold fold(const JournalReplay& replay);
208
209 // Tests whether every placement of the run is booked or still owed: none held or released unbooked.
210 bool settled() const noexcept {
211 return unsettled_ == 0;
212 }
213
214 // Tests whether the run's shares of an instrument are known.
215 bool settled_on(const InstrumentId& instrument) const {
216 if (unsettled_ == 0) {
217 return true;
218 }
219 for (const auto& placement : placements_) {
220 if (placement.state_ != RunPlacementState::BOOKED && placement.instrument_ == instrument) {
221 return false;
222 }
223 }
224 return true;
225 }
226
227 // Lists the placements held for an operator or released without a booking.
228 std::vector<RunPlacement> unsettled() const {
229 std::vector<RunPlacement> found;
230 if (unsettled_ == 0) {
231 return found;
232 }
233 for (const auto& placement : placements_) {
234 if (placement.state_ != RunPlacementState::BOOKED) {
235 found.push_back(placement);
236 }
237 }
238 return found;
239 }
240
241 // Returns a placement of the run.
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];
245 }
246
247 // Returns a transfer the run already holds.
248 const RunTransfer* transfer_of(const std::string& id) const {
249 for (const auto& transfer : transfers_) {
250 if (transfer.id_ == id) {
251 return &transfer;
252 }
253 }
254 return nullptr;
255 }
256
257 // Applies a deposit or a withdrawal; `Runner` refuses a withdrawal past the cash before it is written.
258 bool transfer(const RunTransfer& transfer) {
259 if (
260 transfer.id_.empty() || transfer_of(transfer.id_) != nullptr ||
261 !(transfer.amount_.currency_ == cash_.currency_) || !decimal_less(Decimal64::parse("0"), transfer.amount_.amount_)
262 ) {
263 return false;
264 }
265 const auto cash = transfer.withdrawal_ ?
266 decimal_subtract(cash_.amount_, transfer.amount_.amount_) :
267 decimal_add(cash_.amount_, transfer.amount_.amount_);
268 if (!cash) {
269 return false;
270 }
271 transfers_.push_back(transfer);
272 cash_.amount_ = *cash;
273 return true;
274 }
275
276 // Records a placement held for an operator.
277 bool hold(const RunPlacement& placement) {
278 return settle_state(placement, RunPlacementState::HELD);
279 }
280
281 // Records a placement accounted for without a booking, until `book_released` books it.
282 bool release(const RunPlacement& placement) {
283 return settle_state(placement, RunPlacementState::UNBOOKED);
284 }
285
286 // Tests whether `book_placement` would book a placement.
287 bool can_book_placement(
288 const RunPlacement& placement, const Decimal64& filled, const Money& amount, const Decimal64& fee
289 ) const {
290 const auto* known = this->placement(placement.id_);
291 return (known == nullptr || known->state_ == RunPlacementState::HELD) &&
292 !decimal_less(placement.quantity_, filled) &&
293 booked(placement.instrument_, placement.side_, filled, amount, fee).has_value();
294 }
295
296 // Books a placement's fill as its `CONFIRMED` line does.
297 bool book_placement(
298 const RunPlacement& placement, const Decimal64& filled, const Money& amount, const Decimal64& fee
299 ) {
300 if (!can_book_placement(placement, filled, amount, fee)) {
301 return false;
302 }
303 book(placement.instrument_, placement.side_, filled, amount, fee);
304 settle_state(placement, RunPlacementState::BOOKED);
305 return true;
306 }
307
308 // Tests whether `book_released` would book a placement released without a booking.
309 bool can_book_released(
310 const std::string& id, const Decimal64& filled, const Money& amount, const Decimal64& fee
311 ) const {
312 const auto* known = placement(id);
313 return known != nullptr && known->state_ == RunPlacementState::UNBOOKED &&
314 !decimal_less(known->quantity_, filled) &&
315 booked(known->instrument_, known->side_, filled, amount, fee).has_value();
316 }
317
318 // Books a placement released without a booking, as a `RunRecordKind::FILL` record does.
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)) {
321 return false;
322 }
323 const auto released = *placement(id);
324 book(released.instrument_, released.side_, filled, amount, fee);
325 return settle_state(released, RunPlacementState::BOOKED);
326 }
327
328 // The cash and the instrument's shares after a fill, or nothing if `book` refuses it.
329 std::optional<std::pair<Decimal64, Decimal64>> booked(
330 const InstrumentId& instrument, OrderSide side, const Decimal64& filled, const Money& amount, const Decimal64& fee
331 ) const {
332 const auto zero = Decimal64::parse("0");
333 if (
334 !(amount.currency_ == cash_.currency_) || decimal_less(filled, zero) || decimal_less(amount.amount_, zero) ||
335 decimal_less(fee, zero)
336 ) {
337 return std::nullopt;
338 }
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) {
344 shares = decimal_add(held, filled);
345 const auto spent = decimal_add(amount.amount_, fee);
346 cash = spent ? decimal_subtract(cash_.amount_, *spent) : std::nullopt;
347 } else {
348 if (decimal_less(held, filled)) {
349 return std::nullopt;
350 }
351 shares = decimal_subtract(held, filled);
352 const auto returned = decimal_subtract(amount.amount_, fee);
353 cash = returned ? decimal_add(cash_.amount_, *returned) : std::nullopt;
354 }
355 if (!shares || !cash) {
356 return std::nullopt;
357 }
358 return std::make_pair(*cash, *shares);
359 }
360
361 // Moves a placement to `state`, recording it if new; refused once it is booked (a released one is booked only by
362 // `book_released`).
363 bool settle_state(const RunPlacement& placement, RunPlacementState state) {
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));
370 unsettled_ += state != RunPlacementState::BOOKED ? 1 : 0;
371 return true;
372 }
373 auto& known = placements_[at->second];
374 if (known.state_ == RunPlacementState::BOOKED) {
375 return false;
376 }
377 // Leaving `HELD` or `UNBOOKED` for `BOOKED` settles it.
378 if (state == RunPlacementState::BOOKED) {
379 --unsettled_;
380 }
381 known.state_ = state;
382 return true;
383 }
384
385 // One instrument's shares.
386 struct Shares {
387 InstrumentId instrument_;
388 Decimal64 quantity_;
389 };
390
391 // The instrument at a position of `shares_`, for the table.
392 struct IdOf {
393 const std::vector<Shares>* shares_;
394 const InstrumentId& operator()(std::size_t at) const noexcept {
395 return (*shares_)[at].instrument_;
396 }
397 };
398
399 // Where `instrument` sits in `shares_`: a scan up to `id_detail::scan_limit` rows, the table beyond.
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) {
404 return at;
405 }
406 }
407 return std::nullopt;
408 }
409 return table_.find(instrument, IdOf{&shares_});
410 }
411
412 // Appends a row; if the table cannot take it, the row is removed again and the exception passes on.
413 void add(const InstrumentId& instrument, const Decimal64& quantity) {
414 shares_.push_back(Shares{instrument, quantity});
415 try {
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_});
422 }
423 table_ = std::move(built);
424 }
425 } catch (...) {
426 shares_.pop_back();
427 throw;
428 }
429 }
430
431 std::string id_;
432 Money cash_;
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_;
438 // How many placements are `HELD` or `UNBOOKED`.
439 std::size_t unsettled_{0};
440};
441
442namespace run_detail {
443
444// A journal's run as `RunLedger::fold` read it.
445struct Fold {
446 // The run, or none if the journal holds no opening (or `failure_` is set).
447 std::optional<RunLedger> run_;
448 // Why the run's records do not add up; empty when they do. Recovery then halts.
449 std::string failure_;
450};
451
452} // namespace run_detail
453
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];
459 if (entry.action_ == JournalAction::LEDGER && entry.run_ && entry.run_->kind_ == RunRecordKind::OPEN) {
460 opened = at;
461 }
462 }
463 if (!opened) {
464 return folded;
465 }
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";
469 return folded;
470 }
471 // A line of the run before its latest opening: the opening repeated, which would restart the run at its budget.
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";
475 return folded;
476 }
477 }
478 RunLedger run(open.run_, *open.amount_);
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);
482 };
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_) {
486 continue;
487 }
488 const auto& record = *entry.run_;
489 const RunPlacement placement{entry.id_, entry.instrument_, entry.side_, entry.quantity_, RunPlacementState::HELD};
490 // What the file reader guarantees, checked again for a journal held in memory.
491 const bool whole = entry.action_ == JournalAction::LEDGER ?
492 record.kind_ && record.amount_ && (*record.kind_ != RunRecordKind::FILL || (record.filled_ && record.fee_)) :
493 !record.filled_ || (record.amount_ && record.fee_);
494 if (!whole) {
495 return fail(entry, "is incomplete");
496 }
497 if (entry.action_ == JournalAction::LEDGER) {
498 if (*record.kind_ == RunRecordKind::OPEN) {
499 return fail(entry, "opens its run a second time");
500 }
501 if (*record.kind_ == RunRecordKind::FILL) {
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");
504 }
505 } else if (
506 !run.transfer(RunTransfer{record.given_, *record.amount_, *record.kind_ == RunRecordKind::WITHDRAWAL})
507 ) {
508 return fail(entry, "repeats a transfer id, or is in another currency, or does not fit");
509 }
510 continue;
511 }
512 if (entry.action_ != JournalAction::PLACE) {
513 continue;
514 }
515 if (entry.outcome_ == JournalOutcome::HELD) {
516 if (!run.hold(placement)) {
517 return fail(entry, "holds a placement already booked");
518 }
519 } else if (entry.outcome_ == JournalOutcome::CONFIRMED) {
520 const bool booked = record.filled_.has_value();
521 if (
522 booked ?
523 !run.book_placement(placement, *record.filled_, *record.amount_, *record.fee_) :
524 !run.release(placement)
525 ) {
526 return fail(entry, "accounts for a placement twice, or books a fill the run cannot take");
527 }
528 }
529 }
530 folded.run_ = std::move(run);
531 return folded;
532}
533
534} // namespace runner
535} // 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
static Decimal64 parse(std::string_view input)
Parses a decimal string exactly (no binary floating point).
Definition types.hpp:468
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,...
Definition runner.hpp:305
Runs a strategy: the runner, the polling loop, the order journal, and stopping.
Definition clock.hpp:7
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.
Definition journal.hpp:393
@ FILL
An operator's booking of a placement released without one (runner::Runner::book_run_fill).
Definition journal.hpp:399
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...
Definition journal.hpp:144
@ HELD
Evidence contradicted the placement (holdings moved past what it can explain), so only an operator ma...
Definition journal.hpp:149
@ LEDGER
A record of a run budget's ledger (RunRecord), not an instruction: it sends nothing and names no orde...
Definition journal.hpp:42
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
bool decimal_less(const Decimal64 &lhs, const Decimal64 &rhs)
Compares two decimals numerically, whatever their scales.
Definition types.hpp:926
OrderSide
The side of an order: its economic direction, buy or sell.
Definition types.hpp:1974
Identifies an instrument: its country, venue and symbol.
Definition types.hpp:85
An exact amount of money in one currency.
Definition types.hpp:1168
The contents of a journal, including what could not be read.
Definition journal.hpp:600
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.
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).