algotradelib 0.0.0.9000
C++ header-only library for algorithmic trading
Loading...
Searching...
No Matches
reconcile_orders.hpp
1#pragma once
2
3#include "./execution.hpp"
4#include "./journal.hpp"
5#include "./run_ledger.hpp"
6
7#include <algotradelib/core>
8
9#include <algorithm>
10#include <chrono>
11#include <cstddef>
12#include <ctime>
13#include <iterator>
14#include <optional>
15#include <string>
16#include <string_view>
17#include <unordered_map>
18#include <utility>
19#include <vector>
20
21namespace algotradelib {
22namespace runner {
23
59
65inline constexpr std::string_view match_verdict_name(MatchVerdict verdict) noexcept {
66 switch (verdict) {
68 return "matched";
70 return "not_placed";
72 return "ambiguous";
74 return "undecided";
76 return "needs_operator";
77 }
78 return "unknown";
79}
80
86inline constexpr bool match_verdict_resolves(MatchVerdict verdict) noexcept {
87 return verdict == MatchVerdict::MATCHED || verdict == MatchVerdict::NOT_PLACED;
88}
89
98 std::chrono::seconds clock_skew_{30};
100 std::chrono::seconds maximum_request_{60};
102 std::chrono::seconds listing_delay_{30};
103};
104
120
121namespace reconcile_detail {
122
130inline bool same_value(const Decimal64& lhs, const Decimal64& rhs) {
131 return !decimal_less(lhs, rhs) && !decimal_less(rhs, lhs);
132}
133
135inline bool same_value(const std::optional<Decimal64>& lhs, const std::optional<Decimal64>& rhs) {
136 if (!lhs.has_value() || !rhs.has_value()) {
137 return lhs.has_value() == rhs.has_value();
138 }
139 return same_value(*lhs, *rhs);
140}
141
142} // namespace reconcile_detail
143
150inline std::chrono::system_clock::time_point instruction_sent_by(
151 const OpenInstruction& instruction, const MatchWindow& window
152) {
153 return instruction.closed_at_ ? *instruction.closed_at_ : instruction.opened_at_ + window.maximum_request_;
154}
155
164 const OpenInstruction& instruction, std::chrono::system_clock::time_point now, const MatchWindow& window
165) {
166 return now >= instruction_sent_by(instruction, window) + window.clock_skew_ + window.listing_delay_;
167}
168
169namespace shape_detail {
170
172template <typename Enum>
173inline constexpr bool both_known(Enum left, Enum right) noexcept {
174 return left != Enum::UNKNOWN && right != Enum::UNKNOWN;
175}
176
177} // namespace shape_detail
178
192
198inline constexpr bool evidence_confirms(Evidence evidence) noexcept {
199 switch (evidence) {
201 return true;
203 case Evidence::ABSENT:
204 return false;
205 }
206 return false;
207}
208
214inline constexpr bool evidence_contradicts(Evidence evidence) noexcept {
215 switch (evidence) {
217 return true;
219 case Evidence::ABSENT:
220 return false;
221 }
222 return false;
223}
224
231inline constexpr bool evidence_leaves_open(Evidence evidence) noexcept {
232 switch (evidence) {
233 case Evidence::ABSENT:
234 return true;
237 return false;
238 }
239 return true;
240}
241
244
252template <typename Enum>
253inline Evidence attribute_evidence(Enum row_value, Enum entry_value) noexcept {
254 if (row_value == Enum::UNKNOWN || entry_value == Enum::UNKNOWN) {
255 return Evidence::ABSENT;
256 }
257 return row_value == entry_value ? Evidence::CONFIRMS : Evidence::CONTRADICTS;
258}
259
276 const std::optional<Decimal64>& row_trigger, const std::optional<Decimal64>& entry_trigger
277) {
278 if (!row_trigger) {
279 return entry_trigger ? Evidence::ABSENT : Evidence::CONFIRMS;
280 }
281 if (!entry_trigger) {
282 return Evidence::ABSENT;
283 }
284 return reconcile_detail::same_value(*row_trigger, *entry_trigger) ? Evidence::CONFIRMS : Evidence::CONTRADICTS;
285}
286
303inline Evidence time_evidence(const OpenInstruction& instruction, const OrderSnapshot& row, const MatchWindow& window) {
304 if (row.ordered_date_assumed_) {
305 return Evidence::ABSENT;
306 }
307 if (!row.ordered_at_) {
308 return Evidence::CONFIRMS;
309 }
310 const auto begin = instruction.opened_at_ - window.clock_skew_;
311 const auto end = instruction_sent_by(instruction, window) + window.clock_skew_;
312 return (*row.ordered_at_ >= begin && *row.ordered_at_ <= end) ? Evidence::CONFIRMS : Evidence::CONTRADICTS;
313}
314
325inline RouteEvidence route_evidence(const OpenInstruction& instruction, const OrderSnapshot& row) {
326 const auto& asked = instruction.entry_.venue_;
327 if (!asked) {
328 // The line predates the field, so what it asked for is unknowable.
330 }
331 if (*asked == Venue::UNSPECIFIED) {
332 // It asked for nothing, so nothing about the row's venue can contradict it.
334 }
335 if (row.venue_ == Venue::UNSPECIFIED) {
336 // It asked for a venue and the broker did not say where the order went.
338 }
340}
341
354inline bool row_corresponds(const OpenInstruction& instruction, const OrderSnapshot& row, const MatchWindow& window) {
355 const auto& entry = instruction.entry_;
356 if (!(row.instrument_ == entry.instrument_)) {
357 return false;
358 }
359 if (row.side_ != entry.side_) {
360 return false;
361 }
362 // A known basis on both sides must agree. An `UNKNOWN` on either side is not
363 // a disagreement and is not a correspondence either: it is a row this
364 // library could not classify, and `row_might_correspond` below is what stops
365 // it being read as absence.
366 if (!shape_detail::both_known(row.type_, entry.type_)) {
367 return false;
368 }
369 if (row.type_ != entry.type_) {
370 return false;
371 }
372 if (!reconcile_detail::same_value(row.quantity_, entry.quantity_)) {
373 return false;
374 }
375 if (!reconcile_detail::same_value(row.price_, entry.price_)) {
376 return false;
377 }
378 // A match needs every attribute established, not merely not contradicted.
379 for (
380 const auto evidence : {
381 attribute_evidence(row.time_in_force_, entry.time_in_force_),
382 attribute_evidence(row.session_, entry.session_),
383 trigger_evidence(row.trigger_price_, entry.trigger_price_),
384 route_evidence(instruction, row),
385 time_evidence(instruction, row, window),
386 }
387 ) {
388 if (!evidence_confirms(evidence)) {
389 return false;
390 }
391 }
392 return true;
393}
394
410 const OpenInstruction& instruction, const OrderSnapshot& row, const MatchWindow& window
411) {
412 const auto& entry = instruction.entry_;
413 // Anything that positively disagrees rules the row out however much else is
414 // silent -- an unknown-code row at a venue the instruction did not use is not
415 // this order, and letting it force an ambiguity would stall recovery for
416 // nothing.
417 for (
418 const auto evidence : {
419 attribute_evidence(row.type_, entry.type_),
420 attribute_evidence(row.time_in_force_, entry.time_in_force_),
421 attribute_evidence(row.session_, entry.session_),
422 trigger_evidence(row.trigger_price_, entry.trigger_price_),
423 route_evidence(instruction, row),
424 time_evidence(instruction, row, window),
425 }
426 ) {
427 if (evidence_contradicts(evidence)) {
428 return false;
429 }
430 }
431
432 const bool anything_silent = evidence_leaves_open(attribute_evidence(row.type_, entry.type_)) ||
433 evidence_leaves_open(attribute_evidence(row.time_in_force_, entry.time_in_force_)) ||
434 evidence_leaves_open(attribute_evidence(row.session_, entry.session_)) ||
435 evidence_leaves_open(trigger_evidence(row.trigger_price_, entry.trigger_price_)) ||
436 evidence_leaves_open(route_evidence(instruction, row)) ||
437 evidence_leaves_open(time_evidence(instruction, row, window));
438 if (!anything_silent) {
439 // Everything comparable was compared, so `row_corresponds` has already
440 // given the definitive answer and this predicate has nothing to add.
441 return false;
442 }
443
444 if (!(row.instrument_ == entry.instrument_) || row.side_ != entry.side_) {
445 return false;
446 }
447 if (!reconcile_detail::same_value(row.quantity_, entry.quantity_)) {
448 return false;
449 }
450 // Compare what survived. A row whose *basis* is unreadable has no price
451 // either, because the parser discards it -- but one whose only silence is a
452 // route or a timestamp still has both, and a row differing there is plainly
453 // another order rather than an ambiguity worth withholding an instrument for.
454 if (!evidence_leaves_open(attribute_evidence(row.type_, entry.type_))) {
455 if (!reconcile_detail::same_value(row.price_, entry.price_)) {
456 return false;
457 }
458 }
459 return true;
460}
461
472inline std::string unresolvable_reason(const JournalEntry& entry) {
473 const bool by_order_id = journal_action_matches_by_order_id(entry.action_);
474 if (by_order_id && entry.order_id_.empty()) {
475 return "a cancellation was journalled without the order id it names, so no row can be identified as its target; an operator must say what became of it";
476 }
477 // **Placements only.** A cancellation is matched on the broker id alone --
478 // `row.order_id_ == entry.order_id_` and nothing else -- so its copy of the
479 // order's shape is never compared and an inconsistency in it cannot mislead
480 // anything. Applying the check to every action withheld an instrument whose
481 // identity the journal *had* recorded, for a cancellation that resolves
482 // without trouble: the shape is copied from the working order, so a
483 // reservation carrying an unpriced `LIMIT` or a reported `MARKET` price puts
484 // it there without the cancellation caring.
485 if (!by_order_id && entry.type_ != OrderType::UNKNOWN) {
486 const bool priced = carries_caller_price(entry.type_);
487 if (priced && !entry.price_) {
488 return "a price-bearing order was journalled without its price, so no row can be matched on it; an operator must say what became of it";
489 }
490 if (!priced && entry.price_) {
491 return "an order whose price the market sets was journalled carrying one, so no row can be matched on it; an operator must say what became of it";
492 }
493 // The trigger's twin of the price rule, for the same reason: a line the writer emits before
494 // the binding could refuse it, which no row can be matched against.
495 const bool triggered = carries_trigger_price(entry.type_);
496 if (triggered && !entry.trigger_price_) {
497 return "a stop-limit order was journalled without its trigger price, so no row can be matched on it; an operator must say what became of it";
498 }
499 if (!triggered && entry.trigger_price_) {
500 return "an order that takes no trigger price was journalled carrying one, so no row can be matched on it; an operator must say what became of it";
501 }
502 }
503 return {};
504}
505
517inline std::vector<OpenInstruction> recorded_placements(const JournalReplay& replay) {
518 std::vector<OpenInstruction> found;
519 std::unordered_map<std::string, std::size_t> found_at;
520 std::vector<std::string> refused;
521 for (const auto& entry : replay.entries_) {
522 if (entry.action_ != JournalAction::PLACE || entry.requires_operator_) {
523 continue;
524 }
525 auto known = found_at.find(entry.id_);
526 if (known == found_at.end()) {
527 OpenInstruction placement;
528 placement.entry_ = entry;
529 placement.entry_.order_id_.clear();
530 placement.opened_at_ = entry.recorded_at_;
531 known = found_at.emplace(entry.id_, found.size()).first;
532 found.push_back(std::move(placement));
533 }
534 auto& placement = found[known->second];
535 if (journal_outcome_refuses(entry.outcome_)) {
536 refused.push_back(entry.id_);
537 }
538 if (journal_outcome_answers_send(entry.outcome_) && !placement.closed_at_) {
539 placement.closed_at_ = entry.recorded_at_;
540 }
541 if (journal_outcome_names_order(entry.outcome_) && !entry.order_id_.empty() && placement.entry_.order_id_.empty()) {
542 placement.entry_.order_id_ = entry.order_id_;
543 }
544 }
545 found.erase(
546 std::remove_if(
547 found.begin(), found.end(),
548 [&](const OpenInstruction& placement) {
549 return placement.entry_.order_id_.empty() ||
550 std::find(refused.begin(), refused.end(), placement.entry_.id_) != refused.end();
551 }
552 ),
553 found.end()
554 );
555 return found;
556}
557
571 const OpenInstruction& instruction, const OrderSnapshot& row, const std::vector<OpenInstruction>& recorded,
572 const MatchWindow& window
573) {
574 if (row.order_id_.empty()) {
575 return nullptr;
576 }
577 for (const auto& other : recorded) {
578 if (other.entry_.id_ == instruction.entry_.id_ || other.entry_.order_id_ != row.order_id_) {
579 continue;
580 }
581 if (row_corresponds(other, row, window) || row_might_correspond(other, row, window)) {
582 return &other;
583 }
584 }
585 return nullptr;
586}
587
607 const OpenInstruction& instruction, const std::vector<OrderSnapshot>& rows,
608 const std::vector<OpenInstruction>& recorded, std::chrono::system_clock::time_point now,
609 const MatchWindow& window = {}
610) {
611 OrderMatch match;
612 match.instrument_ = instruction.entry_.instrument_;
613 match.entry_id_ = instruction.entry_.id_;
614
615 // **An instruction whose own line cannot support a conclusion.** These are
616 // written by this library -- `JournalingExecutor` appends the pending line
617 // before the binding runs, so a locally refused order is on disk before
618 // anything could object -- which is why the *reader* accepts them. What must
619 // not happen is resolving one: each lacks precisely the field the matcher
620 // would decide on, so a sweep would conclude from silence.
621 //
622 // An ordinary local refusal is unaffected: its own terminal line closes the
623 // pending one before any of this is reached. Only an instruction still open
624 // at recovery arrives here, and for those the honest answer is an operator.
625 if (const auto reason = unresolvable_reason(instruction.entry_); !reason.empty()) {
626 match.verdict_ = MatchVerdict::NEEDS_OPERATOR;
627 match.detail_ = reason;
628 return match;
629 }
630 if (instruction.entry_.requires_operator_) {
631 // Checked before anything else, so no window arithmetic runs on a timestamp that was never
632 // recorded. This is the entry the file-journal documentation calls "something nothing can ever
633 // resolve", and this check is what makes that true rather than aspirational.
634 match.verdict_ = MatchVerdict::NEEDS_OPERATOR;
635 match.detail_ = instruction.entry_.detail_.empty() ?
636 "recovered from a damaged journal line; only an operator can resolve it" :
637 instruction.entry_.detail_;
638 return match;
639 }
640
641 const OrderSnapshot* found = nullptr;
642 std::size_t unreadable = 0;
643 std::size_t claimed = 0;
644 const OrderSnapshot* claimed_row = nullptr;
645 const OpenInstruction* claimant = nullptr;
646 const bool by_order_id = journal_action_matches_by_order_id(instruction.entry_.action_);
647 if (by_order_id) {
648 for (const auto& row : rows) {
649 if (!instruction.entry_.order_id_.empty() && row.order_id_ == instruction.entry_.order_id_) {
650 ++match.candidates_;
651 found = &row;
652 }
653 }
654 } else {
655 for (const auto& row : rows) {
656 const bool fits = row_corresponds(instruction, row, window);
657 // Counted separately, because these are not candidates for a *match* -- the
658 // library could not read their shape, so it cannot claim one is this order.
659 // They are candidates against concluding the order does not exist.
660 const bool might_fit = row_might_correspond(instruction, row, window);
661 if (!fits && !might_fit) {
662 continue;
663 }
664 // Another placement's order by the journal's own record: neither this order nor evidence
665 // that this order is missing.
666 if (const auto* owner = recorded_owner(instruction, row, recorded, window)) {
667 ++claimed;
668 claimed_row = &row;
669 claimant = owner;
670 continue;
671 }
672 if (fits) {
673 ++match.candidates_;
674 found = &row;
675 }
676 if (might_fit) {
677 ++unreadable;
678 }
679 }
680 }
681
682 if (claimed > 0) {
683 // Not `MATCHED`: the row is another placement's. Not `NOT_PLACED` either, even when nothing else
684 // fits, and not `MATCHED` on another row that fits: the record may be a sweep's mistaken name,
685 // and then the claimed row is this order and the other row is the claimant's.
686 match.verdict_ = MatchVerdict::AMBIGUOUS;
687 const auto others = match.candidates_ + unreadable;
688 match.candidates_ = others + claimed;
689 match.detail_ = "order " + claimed_row->order_id_ +
690 " in the broker's listing fits this instruction, and the "
691 "journal records it for another placement (" +
692 claimant->entry_.id_ + ")" +
693 (claimed > 1 ? ", as it does " + std::to_string(claimed - 1) + " more such row(s)" : std::string()) +
694 (others > 0 ? "; " + std::to_string(others) + " other row(s) fit as well" : std::string()) +
695 "; nothing was resolved";
696 return match;
697 }
698 if (match.candidates_ > 1) {
699 match.verdict_ = MatchVerdict::AMBIGUOUS;
700 match.detail_ = std::to_string(match.candidates_) +
701 " orders in the broker's listing could be this instruction; nothing was resolved";
702 return match;
703 }
704 if (unreadable > 0) {
705 // Report, never guess -- and **whether or not a readable row also matched**.
706 // A row whose order code this release does not publish is not evidence that
707 // the order is missing, so `NOT_PLACED` would clear the hold and send it
708 // again beside the one already resting. But it is equally not evidence that
709 // some *other* row is the order: with one readable row matching every
710 // attribute and one unreadable row matching every attribute that survives
711 // an unreadable shape, the unreadable one may be the instruction and the
712 // readable one another order on the same account. Resolving to the readable
713 // one would attribute the wrong order and clear the hold on it, which is
714 // the same harm by a different route.
715 match.verdict_ = MatchVerdict::AMBIGUOUS;
716 match.candidates_ += unreadable;
717 match.order_id_.clear();
718 // Says which it is. An operator reading "unrecognized order code" about a
719 // row whose code was perfectly readable, and whose *route* was the unknown,
720 // is being sent to look at the wrong field.
721 match.detail_ = std::to_string(unreadable) +
722 " order(s) in the broker's listing match this instruction on instrument, side, quantity "
723 "and time, but this library cannot confirm which order they are: an order code it does "
724 "not recognize, a route nobody recorded, or both" +
725 (found != nullptr ? ", and another row matches it fully" : "") +
726 "; nothing was resolved. Each row carries the broker's own code as shape_code_ and its "
727 "venue as venue_";
728 return match;
729 }
730 if (match.candidates_ == 1) {
731 match.verdict_ = MatchVerdict::MATCHED;
732 match.order_id_ = found->order_id_;
733 match.detail_ = by_order_id ?
734 "the order named by the cancellation is still in the broker's listing" :
735 "the broker's listing carries this order";
736 return match;
737 }
738 if (!match_window_closed(instruction, now, window)) {
739 match.verdict_ = MatchVerdict::UNDECIDED;
740 match.detail_ = "no matching order yet, and not enough time has passed for the listing to show one";
741 return match;
742 }
743 match.verdict_ = MatchVerdict::NOT_PLACED;
744 match.detail_ = by_order_id ?
745 "the order named by the cancellation is no longer in the broker's listing" :
746 "no matching order was found among the rows read, within the matching window";
747 return match;
748}
749
764 const OpenInstruction& instruction, const std::vector<OrderSnapshot>& rows, std::chrono::system_clock::time_point now,
765 const MatchWindow& window = {}
766) {
767 return match_against(instruction, rows, {}, now, window);
768}
769
793 std::vector<OrderSnapshot>& rows, const JournalReplay& replay, const std::vector<OpenInstruction>& matching,
794 const MatchWindow& window = {}
795) {
796 // The other placements on the instruments being matched, each with the span of its send.
797 std::vector<OpenInstruction> others;
798 std::unordered_map<std::string, std::size_t> other_of;
799 std::vector<std::string> refused;
800 for (const auto& entry : replay.entries_) {
801 if (entry.action_ != JournalAction::PLACE) {
802 continue;
803 }
804 const bool on_an_instrument_matched =
805 std::any_of(matching.begin(), matching.end(), [&](const OpenInstruction& instruction) {
806 return instruction.entry_.instrument_ == entry.instrument_;
807 });
808 const bool being_matched = std::any_of(matching.begin(), matching.end(), [&](const OpenInstruction& instruction) {
809 return instruction.entry_.id_ == entry.id_;
810 });
811 if (!on_an_instrument_matched || being_matched) {
812 continue;
813 }
814 if (journal_outcome_refuses(entry.outcome_)) {
815 refused.push_back(entry.id_);
816 }
817 auto known = other_of.find(entry.id_);
818 if (known == other_of.end()) {
819 OpenInstruction other;
820 other.entry_ = entry;
821 other.opened_at_ = entry.recorded_at_;
822 known = other_of.emplace(entry.id_, others.size()).first;
823 others.push_back(std::move(other));
824 }
825 auto& other = others[known->second];
826 if (journal_outcome_answers_send(entry.outcome_) && !other.closed_at_) {
827 other.closed_at_ = entry.recorded_at_;
828 }
829 }
830 rows.erase(
831 std::remove_if(
832 rows.begin(), rows.end(),
833 [&](const OrderSnapshot& row) {
834 return std::any_of(others.begin(), others.end(), [&](const OpenInstruction& other) {
835 return std::find(refused.begin(), refused.end(), other.entry_.id_) == refused.end() &&
836 (row_corresponds(other, row, window) || row_might_correspond(other, row, window));
837 });
838 }
839 ),
840 rows.end()
841 );
842}
843
847 std::vector<OrderMatch> matches_;
849 std::vector<InstrumentId> resolved_;
851 std::vector<InstrumentId> withheld_;
853 bool ambiguous_{false};
855 std::size_t recorded_{0};
860 bool unrecorded_{false};
861
866 bool settled() const noexcept {
867 return withheld_.empty();
868 }
869};
870
879 const OpenInstruction& instruction, const OrderMatch& match, std::chrono::system_clock::time_point now
880) {
881 auto entry = instruction.entry_;
882 // RESOLVED records what the listing showed, not the broker's answer to the instruction.
884 entry.recorded_at_ = now;
885 entry.requires_operator_ = false;
886 entry.order_id_ = match.order_id_;
887 entry.detail_ = "resolved by reading the broker's order list: " + match.detail_;
888 return entry;
889}
890
914template <typename Journal>
916 const std::vector<OpenInstruction>& open, const std::vector<OrderSnapshot>& rows, const JournalReplay& replay,
917 std::chrono::system_clock::time_point now, IndeterminacyLedger& ledger, Journal& journal,
918 const MatchWindow& window = {}, std::string_view unplaced_note = {}
919) {
920 ReconcileReport report;
921 report.matches_.reserve(open.size());
922 const auto recorded = recorded_placements(replay);
923
924 std::vector<InstrumentId> undecided;
925 std::vector<InstrumentId> seen;
926 for (const auto& instruction : open) {
927 auto match = match_against(instruction, rows, recorded, now, window);
928 const auto instrument = match.instrument_;
929 if (match.verdict_ == MatchVerdict::AMBIGUOUS) {
930 report.ambiguous_ = true;
931 }
932 if (match.verdict_ == MatchVerdict::NOT_PLACED && instruction.entry_.action_ == JournalAction::PLACE) {
933 match.detail_ += unplaced_note;
934 }
935 if (match_verdict_resolves(match.verdict_)) {
936 // Written before the ledger is cleared, for the same reason a placement is written before it
937 // is sent: the durable record has to be the conservative one. A sweep that cleared memory and
938 // failed to record why would leave the instruction owed on disk, and the next restart would
939 // withhold the instrument again for a question that had already been answered.
940 if (journal.append(resolution_entry(instruction, match, now))) {
941 ++report.recorded_;
942 } else {
943 report.unrecorded_ = true;
944 undecided.push_back(instrument);
945 match.detail_ += " (not recorded: the journal could not be written, so the hold stands)";
946 }
947 } else {
948 undecided.push_back(instrument);
949 }
950 report.matches_.push_back(std::move(match));
951
952 bool known = false;
953 for (const auto& id : seen) {
954 if (id == instrument) {
955 known = true;
956 break;
957 }
958 }
959 if (!known) {
960 seen.push_back(instrument);
961 }
962 }
963
964 for (const auto& instrument : seen) {
965 bool blocked = false;
966 for (const auto& id : undecided) {
967 if (id == instrument) {
968 blocked = true;
969 break;
970 }
971 }
972 if (blocked) {
973 report.withheld_.push_back(instrument);
974 continue;
975 }
976 ledger.resolve_after_reading_orders(instrument);
977 report.resolved_.push_back(instrument);
978 }
979 return report;
980}
981
995template <typename Journal>
997 const std::vector<OpenInstruction>& open, const std::vector<OrderSnapshot>& rows,
998 std::chrono::system_clock::time_point now, IndeterminacyLedger& ledger, Journal& journal,
999 const MatchWindow& window = {}, std::string_view unplaced_note = {}
1000) {
1001 return reconcile_against(open, rows, journal.replay(), now, ledger, journal, window, unplaced_note);
1002}
1003
1013inline ReconcileReport decide_nothing(const std::vector<OpenInstruction>& open, std::string detail) {
1014 ReconcileReport report;
1015 report.matches_.reserve(open.size());
1016 for (const auto& instruction : open) {
1017 OrderMatch match;
1019 match.instrument_ = instruction.entry_.instrument_;
1020 match.entry_id_ = instruction.entry_.id_;
1021 match.detail_ = detail;
1022 report.matches_.push_back(std::move(match));
1023
1024 bool known = false;
1025 for (const auto& id : report.withheld_) {
1026 if (id == instruction.entry_.instrument_) {
1027 known = true;
1028 break;
1029 }
1030 }
1031 if (!known) {
1032 report.withheld_.push_back(instruction.entry_.instrument_);
1033 }
1034 }
1035 return report;
1036}
1037
1044inline bool any_placement(const std::vector<OpenInstruction>& open) {
1045 for (const auto& instruction : open) {
1046 // Operator-only entries are excluded, because no listing can decide them: `match_against`
1047 // returns `NEEDS_OPERATOR` before it looks at a single row. Including them bought pointless
1048 // pagination on Toss and a guaranteed rejected inquiry on KIS, on every sweep, forever.
1049 if (instruction.entry_.action_ == JournalAction::PLACE && !instruction.entry_.requires_operator_) {
1050 return true;
1051 }
1052 }
1053 return false;
1054}
1055
1063inline bool exact_copy(const OrderSnapshot& a, const OrderSnapshot& b) {
1064 return !a.order_id_.empty() && a.order_id_ == b.order_id_ && a.instrument_ == b.instrument_ && a.ordered_at_ &&
1065 b.ordered_at_ && *a.ordered_at_ == *b.ordered_at_;
1066}
1067
1077inline bool dates_listed_order(const OrderSnapshot& assumed, const OrderSnapshot& row) {
1078 if (
1079 row.ordered_date_assumed_ || !row.ordered_at_ || !assumed.ordered_at_ || assumed.order_id_.empty() ||
1080 row.order_id_ != assumed.order_id_ || !(row.instrument_ == assumed.instrument_)
1081 ) {
1082 return false;
1083 }
1084 // Both stamped from a date and the same `HHmmss` in one zone, so one order's two rows differ by whole days.
1085 if ((*assumed.ordered_at_ - *row.ordered_at_) % std::chrono::hours(24) != std::chrono::hours(0)) {
1086 return false;
1087 }
1088 // A number reused on another day can belong to a different order at the same time of day.
1089 const bool venues_differ =
1090 row.venue_ != Venue::UNSPECIFIED && assumed.venue_ != Venue::UNSPECIFIED && row.venue_ != assumed.venue_;
1091 return row.side_ == assumed.side_ && reconcile_detail::same_value(row.quantity_, assumed.quantity_) &&
1092 reconcile_detail::same_value(row.price_, assumed.price_) &&
1096 !evidence_contradicts(trigger_evidence(row.trigger_price_, assumed.trigger_price_)) && !venues_differ;
1097}
1098
1112inline void merge_dated_history(std::vector<OrderSnapshot>& into, const std::vector<OrderSnapshot>& rows) {
1113 std::vector<OrderSnapshot> listing;
1114 listing.reserve(into.size() + rows.size());
1115 for (auto& listed : into) {
1116 const bool dated_by_history =
1117 listed.ordered_date_assumed_ && std::any_of(rows.begin(), rows.end(), [&](const OrderSnapshot& row) {
1118 return dates_listed_order(listed, row);
1119 });
1120 if (!dated_by_history) {
1121 listing.push_back(std::move(listed));
1122 }
1123 }
1124 into = std::move(listing);
1125 const auto listed = into.size();
1126 for (const auto& row : rows) {
1127 bool known = false;
1128 for (std::size_t at = 0; at < listed; ++at) {
1129 // A listing row still assumed is no copy of anything: the dated row is the evidence, and both stay.
1130 if (!into[at].ordered_date_assumed_ && exact_copy(into[at], row)) {
1131 known = true;
1132 break;
1133 }
1134 }
1135 if (!known) {
1136 into.push_back(row);
1137 }
1138 }
1139}
1140
1146inline void merge_rows(std::vector<OrderSnapshot>& into, const std::vector<OrderSnapshot>& rows) {
1147 for (const auto& row : rows) {
1148 bool known = false;
1149 for (const auto& held : into) {
1150 // Deduplicated by the broker's own id, because an order that is still open appears in *both*
1151 // listings. Two copies of one row would read as two candidates, and the matcher would report
1152 // `AMBIGUOUS` for an instruction that is not ambiguous at all.
1153 if (!row.order_id_.empty() && held.order_id_ == row.order_id_) {
1154 known = true;
1155 break;
1156 }
1157 }
1158 if (!known) {
1159 into.push_back(row);
1160 }
1161 }
1162}
1163
1169inline Date date_of(std::chrono::system_clock::time_point at) {
1170 const auto seconds = std::chrono::time_point_cast<std::chrono::seconds>(at);
1171 const std::time_t raw = std::chrono::system_clock::to_time_t(seconds);
1172 std::tm utc{};
1173#ifdef _WIN32
1174 gmtime_s(&utc, &raw);
1175#else
1176 gmtime_r(&raw, &utc);
1177#endif
1178 Date date;
1179 date.year_ = utc.tm_year + 1900;
1180 date.month_ = static_cast<unsigned>(utc.tm_mon + 1);
1181 date.day_ = static_cast<unsigned>(utc.tm_mday);
1182 return date;
1183}
1184
1195inline std::pair<Date, Date> history_range_for(const std::vector<OpenInstruction>& open, const MatchWindow& window) {
1196 auto earliest = open.front().opened_at_;
1197 auto latest = instruction_sent_by(open.front(), window);
1198 for (const auto& instruction : open) {
1199 if (instruction.opened_at_ < earliest) {
1200 earliest = instruction.opened_at_;
1201 }
1202 const auto sent_by = instruction_sent_by(instruction, window);
1203 if (sent_by > latest) {
1204 latest = sent_by;
1205 }
1206 }
1207 return {
1208 date_of(earliest - std::chrono::hours(24)),
1209 date_of(latest + std::chrono::hours(24)),
1210 };
1211}
1212
1216 std::vector<InstrumentId> marked_;
1218 std::vector<OpenInstruction> open_;
1220 bool truncated_{false};
1225 bool unattributable_{false};
1227 std::size_t unreadable_lines_{0};
1229 bool unreadable_file_{false};
1231 std::string detail_;
1236 std::optional<RunRecoverySummary> run_;
1237
1242 bool clean() const noexcept {
1243 return marked_.empty() && !truncated_ && !unattributable_ && unreadable_lines_ == 0 && !unreadable_file_;
1244 }
1245};
1246
1259 RecoveryReport report;
1260 report.truncated_ = replay.truncated_tail_;
1261 report.unreadable_lines_ = replay.unreadable_lines_;
1262 report.unreadable_file_ = !replay.readable();
1263 report.detail_ = replay.detail_;
1264 report.open_ = unresolved_instructions(replay);
1265
1266 for (const auto& instruction : report.open_) {
1267 const auto& instrument = instruction.entry_.instrument_;
1268 if (instrument.symbol_.empty()) {
1269 report.unattributable_ = true;
1270 continue;
1271 }
1272 const auto marked = ledger.requires_reconcile(instrument);
1273 ledger.mark(
1274 instrument,
1275 instruction.detail_.empty() ?
1276 "a previous process left this instruction unresolved in the order journal" :
1277 instruction.detail_
1278 );
1279 if (!marked) {
1280 report.marked_.push_back(instrument);
1281 }
1282 }
1283 if (report.truncated_ && report.open_.empty()) {
1284 report.unattributable_ = true;
1285 }
1286 return report;
1287}
1288
1296template <typename Journal>
1297RecoveryReport recover_into(const Journal& journal, IndeterminacyLedger& ledger) {
1298 return recover_into(journal.replay(), ledger);
1299}
1300
1316template <typename Runner, typename Journal>
1317RecoveryReport recover_runner(Runner& runner_instance, const Journal& journal) {
1318 const auto& replay = journal.replay();
1319 auto report = recover_into(replay, runner_instance.ledger());
1320 // A serialized runner also gets back every order it may still owe (`Runner::restore_obligations`),
1321 // and places nothing until this has run; a budgeted one opens its run there.
1322 runner_instance.restore_obligations(replay);
1323 report.run_ = runner_instance.run_recovery();
1324 if (report.unattributable_) {
1325 runner_instance.halt_locally(
1326 report.detail_.empty() ? "the order journal was damaged in a way that names no instrument" : report.detail_
1327 );
1328 }
1329 if (report.unreadable_lines_ > 0) {
1330 runner_instance.halt_locally(
1331 "the order journal holds " + std::to_string(report.unreadable_lines_) +
1332 " line(s) this library did not write, so it cannot account for what was in flight"
1333 );
1334 }
1335 if (report.unreadable_file_) {
1336 // Nothing about the file's contents is known, and unlike a missing journal this one may hold
1337 // every order a predecessor left in flight. There is nothing to withhold specifically.
1338 runner_instance.halt_locally(
1339 report.detail_.empty() ? "the order journal exists and could not be read" : report.detail_
1340 );
1341 }
1342 return report;
1343}
1344
1345} // namespace runner
1346} // namespace algotradelib
An exact signed decimal: an int64 coefficient times 10^-scale.
Definition types.hpp:443
The instruments with an order of unknown outcome, where nothing may be placed until the broker's orde...
bool requires_reconcile(const InstrumentId &id) const
Tests whether an instrument is waiting for reconciliation.
void mark(const InstrumentId &id, std::string detail)
Records an instrument's order of unknown outcome; an existing entry keeps its first detail.
void resolve_after_reading_orders(const InstrumentId &id)
Clears an instrument; call it only after reading the broker's order list for it.
Runs one strategy: feeds it events, reconciles what it asks for, checks the risk limits,...
Definition runner.hpp:305
const std::optional< RunRecoverySummary > & run_recovery() const noexcept
Returns how runner::recover_runner opened the run, or why it did not, or that a new run waits for the...
Definition runner.hpp:816
void halt_locally(std::string detail)
Stops this runner sending, with the LOCAL_FAILURE hold, until resume_after_local_failure.
Definition runner.hpp:519
void restore_obligations(const JournalReplay &replay)
Restores the orders a previous process left unaccounted for; runner::recover_runner calls it,...
Definition runner.hpp:1285
const IndeterminacyLedger & ledger() const noexcept
Returns the ledger of instruments withheld pending reconciliation or an operator: an order of unknown...
Definition runner.hpp:415
Runs a strategy: the runner, the polling loop, the order journal, and stopping.
Definition clock.hpp:7
MatchVerdict
What the broker's order list says about one instruction of unknown outcome.
@ AMBIGUOUS
Several rows could correspond, a row that fits is another placement's, or a row that fits cannot be c...
@ NOT_PLACED
No row corresponds and the window has closed: no order was found.
@ UNDECIDED
No row yet, and the window is still open; wait for the next sweep.
@ MATCHED
Exactly one row corresponds; the order exists.
@ NEEDS_OPERATOR
The instruction came from a damaged journal line, or its line cannot be matched (unresolvable_reason)...
void merge_rows(std::vector< OrderSnapshot > &into, const std::vector< OrderSnapshot > &rows)
Adds rows to a listing, skipping any whose order id is already there.
Date date_of(std::chrono::system_clock::time_point at)
Returns the UTC calendar date of an instant.
constexpr bool journal_outcome_answers_send(JournalOutcome outcome) noexcept
Tests whether a line with this outcome answers the send itself (the broker's reply,...
Definition journal.hpp:265
bool any_placement(const std::vector< OpenInstruction > &open)
Tests whether any instruction is a placement a listing could decide (which needs history,...
void merge_dated_history(std::vector< OrderSnapshot > &into, const std::vector< OrderSnapshot > &rows)
Adds history rows to a working-order listing, dropping established copies (exact_copy) and listing ro...
bool row_might_correspond(const OpenInstruction &instruction, const OrderSnapshot &row, const MatchWindow &window)
Tests whether a row might be an instruction's order although some attributes could not be read (such ...
ReconcileReport decide_nothing(const std::vector< OpenInstruction > &open, std::string detail)
Makes a report that decides nothing, for a sweep that could not see a complete listing.
std::pair< Date, Date > history_range_for(const std::vector< OpenInstruction > &open, const MatchWindow &window)
Returns the date range an order-history inquiry must cover for some instructions.
std::chrono::system_clock::time_point instruction_sent_by(const OpenInstruction &instruction, const MatchWindow &window)
Returns the last instant an instruction could have reached the broker.
Evidence time_evidence(const OpenInstruction &instruction, const OrderSnapshot &row, const MatchWindow &window)
Compares a row's order time with the window in which the instruction was sent.
std::vector< OpenInstruction > recorded_placements(const JournalReplay &replay)
Returns the placements a journal records an order id for, each with the span of its send.
const OpenInstruction * recorded_owner(const OpenInstruction &instruction, const OrderSnapshot &row, const std::vector< OpenInstruction > &recorded, const MatchWindow &window)
Returns the recorded placement whose order a row is: the row carries the order id the journal records...
bool match_window_closed(const OpenInstruction &instruction, std::chrono::system_clock::time_point now, const MatchWindow &window)
Tests whether a missing row may now be read as "not placed".
constexpr bool journal_action_matches_by_order_id(JournalAction action) noexcept
Tests whether recovery matches an instruction of this action by the broker's order id it names,...
Definition journal.hpp:86
constexpr bool journal_outcome_refuses(JournalOutcome outcome) noexcept
Tests whether a line with this outcome says the instruction was refused, so it does not exist.
Definition journal.hpp:307
RecoveryReport recover_into(const JournalReplay &replay, IndeterminacyLedger &ledger)
Marks the ledger for every instrument a journal left an instruction of unknown outcome for.
bool dates_listed_order(const OrderSnapshot &assumed, const OrderSnapshot &row)
Tests whether a dated history row is the order a listing row whose date was assumed shows: the same o...
RecoveryReport recover_runner(Runner &runner_instance, const Journal &journal)
Recovers a journal into a runner at startup: marks each instrument left owed, restores a serialized r...
constexpr bool match_verdict_resolves(MatchVerdict verdict) noexcept
Tests whether a verdict settles the question.
@ RESOLVED
A recovery sweep read the broker's order list and closed the question.
Definition journal.hpp:136
Evidence trigger_evidence(const std::optional< Decimal64 > &row_trigger, const std::optional< Decimal64 > &entry_trigger)
Compares a row's trigger price with the instruction's.
void drop_rows_fitting_another_placement(std::vector< OrderSnapshot > &rows, const JournalReplay &replay, const std::vector< OpenInstruction > &matching, const MatchWindow &window={})
Removes the rows that could be another placement's order as well.
OrderMatch match_against(const OpenInstruction &instruction, const std::vector< OrderSnapshot > &rows, const std::vector< OpenInstruction > &recorded, std::chrono::system_clock::time_point now, const MatchWindow &window={})
Decides what a broker listing says about one instruction of unknown outcome.
std::string unresolvable_reason(const JournalEntry &entry)
Returns why an instruction cannot be resolved from a broker listing.
ReconcileReport reconcile_against(const std::vector< OpenInstruction > &open, const std::vector< OrderSnapshot > &rows, const JournalReplay &replay, std::chrono::system_clock::time_point now, IndeterminacyLedger &ledger, Journal &journal, const MatchWindow &window={}, std::string_view unplaced_note={})
Resolves what a broker listing settles, records it in the journal, and clears the ledger for each ins...
constexpr std::string_view match_verdict_name(MatchVerdict verdict) noexcept
Returns a verdict's lowercase name, such as "not_placed", for logs.
constexpr bool evidence_contradicts(Evidence evidence) noexcept
Tests whether a piece of evidence rules the row out.
Evidence RouteEvidence
Evidence, under the name used for the route comparison.
JournalEntry resolution_entry(const OpenInstruction &instruction, const OrderMatch &match, std::chrono::system_clock::time_point now)
Makes the RESOLVED journal line that records a sweep's verdict.
std::vector< OpenInstruction > unresolved_instructions(const JournalReplay &replay)
Lists the instructions whose outcome is unknown, in the order they were opened.
Definition journal.hpp:673
constexpr bool evidence_leaves_open(Evidence evidence) noexcept
Tests whether a piece of evidence leaves the question open, so the row might still be the order and c...
bool exact_copy(const OrderSnapshot &a, const OrderSnapshot &b)
Tests whether two rows are established copies of one order: the same order id and instrument,...
Evidence
What one attribute of a broker row says about an instruction.
@ CONTRADICTS
The row disagrees; it is not this order.
@ ABSENT
Not enough was recorded to say.
constexpr bool evidence_confirms(Evidence evidence) noexcept
Tests whether a piece of evidence confirms the row is the instruction's order.
constexpr bool journal_outcome_names_order(JournalOutcome outcome) noexcept
Tests whether a line with this outcome may carry the broker's id for the order.
Definition journal.hpp:286
Evidence attribute_evidence(Enum row_value, Enum entry_value) noexcept
Compares an enumerated attribute of a row with the instruction's.
bool row_corresponds(const OpenInstruction &instruction, const OrderSnapshot &row, const MatchWindow &window)
Tests whether a row is established to be an instruction's order.
RouteEvidence route_evidence(const OpenInstruction &instruction, const OrderSnapshot &row)
Compares a row's venue with the route the instruction recorded.
The library: broker-neutral types (core), and the modules below.
constexpr bool carries_trigger_price(OrderType type) noexcept
Tests whether an order type takes a trigger price.
Definition types.hpp:2065
constexpr bool carries_caller_price(OrderType type) noexcept
Tests whether an order type takes a price from the caller.
Definition types.hpp:2039
bool decimal_less(const Decimal64 &lhs, const Decimal64 &rhs)
Compares two decimals numerically, whatever their scales.
Definition types.hpp:926
A calendar date with no time of day or time zone.
Definition types.hpp:1412
unsigned month_
The month, 1-12; zero means unset.
Definition types.hpp:1416
int year_
The year.
Definition types.hpp:1414
unsigned day_
The day of the month, 1-31; zero means unset.
Definition types.hpp:1418
Identifies an instrument: its country, venue and symbol.
Definition types.hpp:85
The state of one order, as a broker listing reported it.
Definition types.hpp:2299
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
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
std::optional< Decimal64 > trigger_price_
The trigger price, whenever the broker reports a positive one.
Definition types.hpp:2339
bool ordered_date_assumed_
Whether the broker stated only the time of day, and the date in ordered_at_ is the day the adapter re...
Definition types.hpp:2361
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
One journal line: an instruction and what was known about it when the line was written.
Definition journal.hpp:482
std::string id_
Links an answering line to its PENDING line.
Definition journal.hpp:488
std::chrono::system_clock::time_point recorded_at_
When the line was written (for PENDING, before the request went out).
Definition journal.hpp:494
OrderType type_
The order type; recovery matches on type, time in force and session together.
Definition journal.hpp:500
std::optional< Decimal64 > price_
The price, if the order has one.
Definition journal.hpp:516
JournalOutcome outcome_
What the line says about the instruction.
Definition journal.hpp:492
std::string detail_
Why an answering line says what it says, for the operator.
Definition journal.hpp:532
std::optional< Venue > venue_
The venue the order actually goes to, as the binding resolves it.
Definition journal.hpp:512
InstrumentId instrument_
The instrument (identity; the routing venue is venue_).
Definition journal.hpp:496
std::optional< Decimal64 > trigger_price_
The trigger price of a stop-limit order; empty otherwise (and on lines that predate it).
Definition journal.hpp:518
bool requires_operator_
Whether only an operator may resolve this instruction.
Definition journal.hpp:539
JournalAction action_
Whether the instruction is a placement or a cancellation.
Definition journal.hpp:490
std::string order_id_
The broker's order id, if known: from the start on a CANCEL line, and only on an answering line for a...
Definition journal.hpp:530
The contents of a journal, including what could not be read.
Definition journal.hpp:600
bool readable() const noexcept
Tests whether the file could be read.
Definition journal.hpp:620
std::size_t unreadable_lines_
How many lines did not parse (on an append-only file, writes that did not finish).
Definition journal.hpp:604
std::vector< JournalEntry > entries_
Every line that parsed, in file order.
Definition journal.hpp:602
std::string detail_
What was wrong, for the operator.
Definition journal.hpp:608
bool truncated_tail_
Whether the last line was incomplete, as after a kill during a write.
Definition journal.hpp:606
The time allowances used when matching journalled instructions against a broker listing.
std::chrono::seconds clock_skew_
How far the broker's clock may differ from this machine's, either way.
std::chrono::seconds listing_delay_
How long the broker's listing may lag an order it accepted.
std::chrono::seconds maximum_request_
How long a request could have been in flight when no answering line records its end.
One instruction of unknown outcome, and the span in which it may have reached the broker.
Definition journal.hpp:646
JournalEntry entry_
The instruction, as its first line recorded it (its order_id_ may come from a later line).
Definition journal.hpp:648
std::string detail_
What the journal says went wrong.
Definition journal.hpp:659
std::optional< std::chrono::system_clock::time_point > closed_at_
When the send was answered: by an INDETERMINATE line in unresolved_instructions, by any answer in rec...
Definition journal.hpp:655
std::chrono::system_clock::time_point opened_at_
When the send began.
Definition journal.hpp:650
One instruction's verdict, with context for the operator.
InstrumentId instrument_
The instruction's instrument.
std::string entry_id_
The journal line id.
std::string detail_
What was decided and why, for the operator.
std::string order_id_
The broker's order id, on MATCHED.
MatchVerdict verdict_
The verdict.
std::size_t candidates_
How many rows could correspond (one or more on AMBIGUOUS).
What one sweep of the broker's order list settled, and what is still withheld.
std::vector< OrderMatch > matches_
One verdict per instruction, in journal order.
bool settled() const noexcept
Tests whether the sweep settled everything.
bool unrecorded_
Whether a resolution could not be written to the journal; its instrument then stays withheld.
std::size_t recorded_
How many resolutions were written to the journal.
std::vector< InstrumentId > resolved_
Instruments cleared; they may trade again.
bool ambiguous_
Whether any instruction was AMBIGUOUS.
std::vector< InstrumentId > withheld_
Instruments still withheld (their reasons are in matches_).
What a journal showed was left owed by the process that wrote it.
bool unattributable_
Whether something was in flight that names no instrument (a torn line too short to name one); recover...
std::vector< InstrumentId > marked_
Instruments marked in the ledger, withheld until the order list resolves them.
std::optional< RunRecoverySummary > run_
How a budgeted runner that keeps its run in the journal opened it, or why it did not (Runner::run_rec...
bool truncated_
Whether the last line was torn.
std::string detail_
What was found, for the operator.
std::vector< OpenInstruction > open_
The instructions of unknown outcome.
std::size_t unreadable_lines_
Complete lines that did not parse.
bool clean() const noexcept
Tests whether nothing was owed or damaged.
bool unreadable_file_
Whether the journal exists and could not be read; it may hold orders left in flight.