algotradelib 0.0.0.9000
C++ header-only library for algorithmic trading
Loading...
Searching...
No Matches
file_journal.hpp
1#pragma once
2
3#include "./journal.hpp"
4
5#include <algotradelib/core>
6
7#include <boost/crc.hpp>
8#include <boost/json.hpp>
9
10#include <cerrno>
11#include <chrono>
12#include <cstdint>
13#include <cstdio>
14#include <memory>
15#include <optional>
16#include <string>
17#include <string_view>
18#include <utility>
19#include <vector>
20
21#if defined(_WIN32)
22#include <io.h>
23#else
24#include <fcntl.h>
25#include <sys/file.h>
26#include <sys/stat.h>
27#include <unistd.h>
28
29#include <cstring>
30#endif
31
32namespace algotradelib {
33namespace runner {
34
35namespace json = boost::json;
36
37namespace journal_detail {
38
56inline bool sync_to_disk(std::FILE* handle) noexcept {
57#if defined(_WIN32)
58 return ::_commit(::_fileno(handle)) == 0;
59#else
60 return ::fsync(::fileno(handle)) == 0;
61#endif
62}
63
68inline bool flush_to_disk(std::FILE* handle) noexcept {
69 return std::fflush(handle) == 0 && sync_to_disk(handle);
70}
71
110inline bool plausible_instant(std::int64_t micros, bool checksummed) noexcept {
111 constexpr std::int64_t kSecondDay1970 = 86400LL * 1000000LL;
112 constexpr std::int64_t kYear2020 = 1577836800LL * 1000000LL;
113 constexpr std::int64_t kYear2200 = 7258118400LL * 1000000LL;
114 return micros >= (checksummed ? kSecondDay1970 : kYear2020) && micros <= kYear2200;
115}
116
117inline bool has_field(const json::object& row, std::string_view key) {
118 return row.if_contains(key) != nullptr;
119}
120
122inline std::optional<std::string> readable_string(const json::object& row, std::string_view key) {
123 const auto value = row.if_contains(key);
124 if (value == nullptr || !value->is_string() || value->as_string().empty()) {
125 return std::nullopt;
126 }
127 return std::string(value->as_string());
128}
129
130inline std::string string_field(const json::object& row, std::string_view key) {
131 const auto value = row.if_contains(key);
132 if (value == nullptr || !value->is_string()) {
133 return {};
134 }
135 return std::string(value->as_string());
136}
137
145inline constexpr std::string_view country_name(Country country) noexcept {
146 switch (country) {
147 case Country::KR:
148 return "KR";
149 case Country::US:
150 return "US";
151 }
152 return "";
153}
154
155static_assert(
158 [](Country country) {
159 return !country_name(country).empty();
160 }
161 ),
162 "all_countries must list every Country"
163);
164
166inline constexpr std::string_view venue_name(Venue venue) noexcept {
167 switch (venue) {
168 case Venue::UNSPECIFIED:
169 return "UNSPECIFIED";
170 case Venue::KRX:
171 return "KRX";
172 case Venue::NXT:
173 return "NXT";
174 case Venue::COMBINED:
175 return "COMBINED";
176 }
177 return "";
178}
179
190inline std::optional<Venue> known_venue_from(std::string_view text) noexcept {
191 return value_named(all_venues, venue_name, text);
192}
193
195inline constexpr std::string_view side_name(OrderSide side) noexcept {
196 switch (side) {
197 case OrderSide::BUY:
198 return "BUY";
199 case OrderSide::SELL:
200 return "SELL";
201 }
202 return "";
203}
204
205static_assert(
208 [](OrderSide side) {
209 return !side_name(side).empty();
210 }
211 ),
212 "all_order_sides must list every OrderSide"
213);
214
223inline constexpr std::string_view order_type_name(OrderType type) noexcept {
224 switch (type) {
225 case OrderType::LIMIT:
226 return "LIMIT";
228 return "MARKET";
230 return "CONDITIONAL_LIMIT";
232 return "BEST_LIMIT";
234 return "PRIMARY_LIMIT";
236 return "MID_PRICE";
238 return "STOP_LIMIT";
240 return "CLOSING_PRICE";
241 case OrderType::UNKNOWN:
242 return "UNKNOWN";
243 }
244 return "";
245}
246
247static_assert(
250 [](OrderType type) {
251 return !order_type_name(type).empty();
252 }
253 ),
254 "all_order_types must list every OrderType"
255);
256
258inline constexpr std::string_view time_in_force_name(TimeInForce condition) noexcept {
259 switch (condition) {
260 case TimeInForce::DAY:
261 return "DAY";
263 return "IOC";
265 return "FOK";
266 case TimeInForce::UNKNOWN:
267 return "UNKNOWN";
268 }
269 return "";
270}
271
272static_assert(
275 [](TimeInForce condition) {
276 return !time_in_force_name(condition).empty();
277 }
278 ),
279 "all_times_in_force must list every TimeInForce"
280);
281
283inline constexpr std::string_view order_session_name(OrderSession session) noexcept {
284 switch (session) {
286 return "REGULAR";
288 return "OPENING_AUCTION";
290 return "CLOSING_AUCTION";
292 return "PRE_MARKET";
294 return "AFTER_HOURS";
296 return "AFTER_HOURS_AUCTION";
298 return "AFTER_MARKET";
300 return "GTP";
301 case OrderSession::UNKNOWN:
302 return "UNKNOWN";
303 }
304 return "";
305}
306
307static_assert(
310 [](OrderSession session) {
311 return !order_session_name(session).empty();
312 }
313 ),
314 "all_order_sessions must list every OrderSession"
315);
316
349inline std::optional<Decimal64> known_decimal_from(std::string_view text) noexcept {
350 try {
351 return Decimal64::parse(text);
352 } catch (const std::exception&) {
353 return std::nullopt;
354 }
355}
356
358inline std::optional<Currency> known_currency_from(std::string_view text) noexcept {
359 try {
360 return Currency(text);
361 } catch (const std::exception&) {
362 return std::nullopt;
363 }
364}
365
366inline std::optional<Country> known_country_from(std::string_view text) noexcept {
367 return value_named(all_countries, country_name, text);
368}
369
370inline std::optional<OrderSide> known_side_from(std::string_view text) noexcept {
371 return value_named(all_order_sides, side_name, text);
372}
373
374inline std::optional<OrderType> known_order_type_from(std::string_view text) noexcept {
375 return value_named(all_order_types, order_type_name, text);
376}
377
378inline std::optional<TimeInForce> known_time_in_force_from(std::string_view text) noexcept {
379 return value_named(all_times_in_force, time_in_force_name, text);
380}
381
382inline std::optional<OrderSession> known_order_session_from(std::string_view text) noexcept {
383 return value_named(all_order_sessions, order_session_name, text);
384}
385
387inline std::chrono::system_clock::time_point instant_from(std::int64_t micros) noexcept {
388 return std::chrono::system_clock::time_point{} + std::chrono::microseconds(micros);
389}
390
392inline std::int64_t micros_of(std::chrono::system_clock::time_point value) noexcept {
393 return std::chrono::duration_cast<std::chrono::microseconds>(value.time_since_epoch()).count();
394}
395
408inline std::optional<std::string> salvage_string(std::string_view line, std::string_view key) {
409 std::string needle;
410 needle.reserve(key.size() + 4);
411 needle += '"';
412 needle.append(key);
413 needle += "\":\"";
414 const auto at = line.find(needle);
415 if (at == std::string_view::npos) {
416 return std::nullopt;
417 }
418 const auto begin = at + needle.size();
419 // **The closing quote is the first one not escaped**, not the first one. A value holding `\"`
420 // was cut short at the escape, and a symbol cut short is another symbol's key.
421 auto end = begin;
422 while (end < line.size() && line[end] != '"') {
423 end += line[end] == '\\' ? 2 : 1;
424 }
425 if (end >= line.size()) {
426 // The value itself was cut off mid-write. Reporting what is there would invent a symbol.
427 return std::nullopt;
428 }
429 // Decoded as the JSON string it is, so an escape reads as the character it stands for. A value
430 // whose escapes do not decode is not salvaged, for the same reason a cut-off one is not.
431 boost::system::error_code error;
432 const auto quoted = json::parse(line.substr(begin - 1, end - begin + 2), error);
433 if (error || !quoted.is_string()) {
434 return std::nullopt;
435 }
436 return std::string(quoted.as_string());
437}
438
447inline std::uint32_t line_checksum(std::string_view bytes) {
448 boost::crc_32_type crc;
449 crc.process_bytes(bytes.data(), bytes.size());
450 return crc.checksum();
451}
452
454inline std::string checksum_text(std::uint32_t value) {
455 static constexpr char digits[] = "0123456789abcdef";
456 std::string text(8, '0');
457 for (int i = 7; i >= 0; --i) {
458 text[static_cast<std::size_t>(i)] = digits[value & 0xFu];
459 value >>= 4;
460 }
461 return text;
462}
463
465inline constexpr std::string_view kChecksumMember = ",\"crc\":\"";
466
468inline constexpr std::size_t kChecksumSuffixSize = kChecksumMember.size() + 8 + 2;
469
471inline bool ends_in_checksum(std::string_view line) {
472 if (line.size() <= kChecksumSuffixSize) {
473 return false;
474 }
475 const auto suffix = line.substr(line.size() - kChecksumSuffixSize);
476 if (suffix.substr(0, kChecksumMember.size()) != kChecksumMember || suffix.substr(kChecksumSuffixSize - 2) != "\"}") {
477 return false;
478 }
479 for (const char digit : suffix.substr(kChecksumMember.size(), 8)) {
480 if (!((digit >= '0' && digit <= '9') || (digit >= 'a' && digit <= 'f'))) {
481 return false;
482 }
483 }
484 return true;
485}
486
493inline bool checksum_matches(std::string_view line) {
494 std::string body(line.substr(0, line.size() - kChecksumSuffixSize));
495 body += '}';
496 const auto stated = line.substr(line.size() - kChecksumSuffixSize + kChecksumMember.size(), 8);
497 return checksum_text(line_checksum(body)) == stated;
498}
499
509inline bool known_entry_key(std::string_view key) {
510 static constexpr std::string_view known[] = {
511 "id",
512 "action",
513 "outcome",
514 "symbol",
515 "country",
516 "venue",
517 "side",
518 "type",
519 "time_in_force",
520 "session",
521 "route",
522 "quantity",
523 "price",
524 "trigger",
525 "at",
526 "at_text",
527 "order_id",
528 "detail",
529 "requires_operator",
530 "scope",
531 "crc",
532 "baseline",
533 };
534 for (const auto candidate : known) {
535 if (candidate == key) {
536 return true;
537 }
538 }
539 return false;
540}
541
546inline bool run_entry_key(std::string_view key) {
547 static constexpr std::string_view known[] = {
548 "run",
549 "ledger",
550 "amount",
551 "currency",
552 "filled",
553 "fee",
554 "fee_estimated",
555 "given",
556 "of",
557 };
558 for (const auto candidate : known) {
559 if (candidate == key) {
560 return true;
561 }
562 }
563 return false;
564}
565
566#if !defined(_WIN32)
570class DescriptorOwner {
571public:
576 explicit DescriptorOwner(int descriptor) noexcept : descriptor_(descriptor) {}
577
579 ~DescriptorOwner() {
580 if (descriptor_ >= 0) {
581 ::close(descriptor_);
582 }
583 }
584
585 DescriptorOwner(const DescriptorOwner&) = delete;
586 DescriptorOwner& operator=(const DescriptorOwner&) = delete;
587
592 int get() const noexcept {
593 return descriptor_;
594 }
595
600 int release() noexcept {
601 const int descriptor = descriptor_;
602 descriptor_ = -1;
603 return descriptor;
604 }
605
606private:
607 int descriptor_;
608};
609
611struct FileStamp {
613 dev_t device_{};
615 ino_t inode_{};
617 off_t size_{};
619 std::int64_t modified_s_{0};
621 std::int64_t modified_ns_{0};
623 std::int64_t changed_s_{0};
625 std::int64_t changed_ns_{0};
626
632 bool operator==(const FileStamp& other) const noexcept {
633 return device_ == other.device_ && inode_ == other.inode_ && size_ == other.size_ &&
634 modified_s_ == other.modified_s_ && modified_ns_ == other.modified_ns_ && changed_s_ == other.changed_s_ &&
635 changed_ns_ == other.changed_ns_;
636 }
637};
638
644inline FileStamp stamp_of(const struct stat& status) noexcept {
645 FileStamp stamp;
646 stamp.device_ = status.st_dev;
647 stamp.inode_ = status.st_ino;
648 stamp.size_ = status.st_size;
649#if defined(__APPLE__)
650 stamp.modified_s_ = status.st_mtimespec.tv_sec;
651 stamp.modified_ns_ = status.st_mtimespec.tv_nsec;
652 stamp.changed_s_ = status.st_ctimespec.tv_sec;
653 stamp.changed_ns_ = status.st_ctimespec.tv_nsec;
654#else
655 stamp.modified_s_ = status.st_mtim.tv_sec;
656 stamp.modified_ns_ = status.st_mtim.tv_nsec;
657 stamp.changed_s_ = status.st_ctim.tv_sec;
658 stamp.changed_ns_ = status.st_ctim.tv_nsec;
659#endif
660 return stamp;
661}
662#endif
663
664} // namespace journal_detail
665
670inline constexpr std::string_view journal_format_name() noexcept {
671 return "algotradelib-order-journal";
672}
673
679inline std::string journal_header_line(std::string_view scope) {
680 json::object row;
681 row["journal"] = std::string(journal_format_name());
682 row["version"] = 1;
683 row["scope"] = std::string(scope);
684 // Declares that every entry after the header carries a checksum (older readers ignore the key).
685 row["integrity"] = "crc32";
686 return json::serialize(row);
687}
688
694inline bool journal_header_declares_checksums(std::string_view line) {
695 boost::system::error_code error;
696 const auto value = json::parse(line, error);
697 if (error || !value.is_object()) {
698 return false;
699 }
700 const auto* integrity = value.as_object().if_contains("integrity");
701 return integrity != nullptr && integrity->is_string() && std::string_view(integrity->as_string()) == "crc32";
702}
703
709inline std::optional<std::string> journal_header_scope(std::string_view line) {
710 boost::system::error_code error;
711 const auto value = json::parse(line, error);
712 if (error || !value.is_object()) {
713 return std::nullopt;
714 }
715 const auto& row = value.as_object();
716 const auto marker = row.if_contains("journal");
717 if (marker == nullptr || !marker->is_string() || std::string_view(marker->as_string()) != journal_format_name()) {
718 return std::nullopt;
719 }
720 return journal_detail::string_field(row, "scope");
721}
722
732
733namespace journal_detail {
734
736inline void write_order_keys(json::object& row, const JournalEntry& entry) {
737 row["country"] = std::string(journal_detail::country_name(entry.instrument_.country_));
738 row["venue"] = std::string(journal_detail::venue_name(entry.instrument_.venue_));
739 row["symbol"] = entry.instrument_.symbol_;
740 row["side"] = std::string(journal_detail::side_name(entry.side_));
741 row["type"] = std::string(journal_detail::order_type_name(entry.type_));
742 row["time_in_force"] = std::string(journal_detail::time_in_force_name(entry.time_in_force_));
743 row["session"] = std::string(journal_detail::order_session_name(entry.session_));
744 // Distinct from `venue`, which is the instrument's identity venue. This is
745 // where the order actually goes -- the binding resolves a request that named
746 // no venue into the one the broker's default reaches -- and a line that omits
747 // the key entirely is
748 // one written before the field existed -- which is not the same as one that
749 // asked for no particular venue, and recovery treats the two differently.
750 if (entry.venue_) {
751 row["route"] = std::string(journal_detail::venue_name(*entry.venue_));
752 }
753 row["quantity"] = entry.quantity_.str();
754 if (entry.price_) {
755 row["price"] = entry.price_->str();
756 }
757 // Only when present, so a line that is not a stop carries no `trigger` key and every old journal
758 // reads unchanged. (Every new line ends in a `crc` member, added below; the fields before it are
759 // what an earlier writer produced.)
760 if (entry.trigger_price_) {
761 row["trigger"] = entry.trigger_price_->str();
762 }
763 // Only on a serialized runner's lines, so an overlapping runner's journal reads as before.
764 if (entry.baseline_) {
765 row["baseline"] = entry.baseline_->str();
766 }
767}
768
770inline void write_run_keys(json::object& row, const RunRecord& record) {
771 row["run"] = record.run_;
772 if (record.kind_) {
773 row["ledger"] = std::string(run_record_kind_name(*record.kind_));
774 }
775 if (!record.given_.empty()) {
776 row["given"] = record.given_;
777 }
778 if (!record.of_.empty()) {
779 row["of"] = record.of_;
780 }
781 if (record.amount_) {
782 row["amount"] = record.amount_->amount_.str();
783 row["currency"] = record.amount_->currency_.str();
784 }
785 if (record.filled_) {
786 row["filled"] = record.filled_->str();
787 }
788 if (record.fee_) {
789 row["fee"] = record.fee_->str();
790 }
791 if (record.fee_estimated_) {
792 row["fee_estimated"] = true;
793 }
794}
795
796} // namespace journal_detail
797
803inline std::string journal_entry_to_line(const JournalEntry& entry) {
804 json::object row;
805 // Ordered so that the fields a damaged line most needs to yield come first. A truncated write
806 // keeps its prefix, so putting the instrument ahead of the detail text is what makes salvage
807 // work in practice rather than only in principle.
808 row["id"] = entry.id_;
809 row["action"] = std::string(journal_action_name(entry.action_));
810 row["outcome"] = std::string(journal_outcome_name(entry.outcome_));
811 // A ledger record names no order, so it carries none of an order's keys: torn, it salvages to no instrument.
812 const bool order = entry.action_ != JournalAction::LEDGER;
813 if (order) {
814 journal_detail::write_order_keys(row, entry);
815 }
816 // The authoritative instant, exact on every platform. `at_text` beside it is for the operator
817 // reading the file with `tail`, is only second-resolution, and is never read back: one field is
818 // the record and the other is the caption.
819 row["at"] = journal_detail::micros_of(entry.recorded_at_);
820 row["at_text"] = format_iso8601_utc(entry.recorded_at_);
821 if (order && !entry.order_id_.empty()) {
822 row["order_id"] = entry.order_id_;
823 }
824 if (!entry.detail_.empty()) {
825 row["detail"] = entry.detail_;
826 }
827 if (entry.requires_operator_) {
828 row["requires_operator"] = true;
829 }
830 if (!entry.scope_.empty()) {
831 row["scope"] = entry.scope_;
832 }
833 // Only on a budgeted runner's lines, so a journal without a run budget is byte for byte as before.
834 if (entry.run_) {
835 journal_detail::write_run_keys(row, *entry.run_);
836 }
837 // **Last, and over the line as it reads without it** -- the whole object, closing brace included,
838 // which the member then replaces. See `journal_detail::line_checksum` for what it detects
839 // and `journal_entry_from_line` for what a line that fails it becomes.
840 auto line = json::serialize(row);
841 const auto checksum = journal_detail::checksum_text(journal_detail::line_checksum(line));
842 line.pop_back();
843 line.append(journal_detail::kChecksumMember);
844 line += checksum;
845 line += "\"}";
846 return line;
847}
848
857inline JournalEntry unattributable_journal_entry(std::string_view line) {
858 JournalEntry entry;
859 entry.id_ = "unknown~truncated";
861 entry.requires_operator_ = true;
862 entry.detail_ = "a truncated journal line named no instrument; something was in flight: " +
863 std::string(line.substr(0, line.size() < 120 ? line.size() : 120));
864 return entry;
865}
866
867namespace journal_detail {
868
870struct RunKeys {
872 bool present_{false};
874 bool unreadable_{false};
876 RunRecord record_;
877 bool has_run_{false};
878 bool has_amount_{false};
879 bool has_currency_{false};
880 bool has_fee_estimated_{false};
881};
882
884inline RunKeys run_keys_from(const json::object& row) {
885 RunKeys keys;
886 const auto text = [&](std::string_view key, std::string& out) {
887 if (!has_field(row, key)) {
888 return false;
889 }
890 keys.present_ = true;
891 const auto value = readable_string(row, key);
892 if (!value) {
893 keys.unreadable_ = true;
894 return false;
895 }
896 out = *value;
897 return true;
898 };
899 const auto number = [&](std::string_view key, std::optional<Decimal64>& out) {
900 std::string value;
901 if (text(key, value)) {
902 out = known_decimal_from(value);
903 keys.unreadable_ = keys.unreadable_ || !out;
904 }
905 };
906 keys.has_run_ = text("run", keys.record_.run_);
907 std::string kind;
908 if (text("ledger", kind)) {
909 keys.record_.kind_ = run_record_kind_from(kind);
910 keys.unreadable_ = keys.unreadable_ || !keys.record_.kind_;
911 }
912 text("given", keys.record_.given_);
913 text("of", keys.record_.of_);
914 std::optional<Decimal64> amount;
915 number("amount", amount);
916 keys.has_amount_ = amount.has_value();
917 std::string code;
918 std::optional<Currency> currency;
919 if (text("currency", code)) {
920 currency = known_currency_from(code);
921 keys.unreadable_ = keys.unreadable_ || !currency;
922 }
923 keys.has_currency_ = currency.has_value();
924 if (amount && currency) {
925 keys.record_.amount_ = Money{*amount, *currency};
926 }
927 number("filled", keys.record_.filled_);
928 number("fee", keys.record_.fee_);
929 if (const auto estimated = row.if_contains("fee_estimated")) {
930 keys.present_ = true;
931 keys.has_fee_estimated_ = true;
932 if (!estimated->is_bool()) {
933 keys.unreadable_ = true;
934 } else {
935 keys.record_.fee_estimated_ = estimated->as_bool();
936 }
937 }
938 return keys;
939}
940
942inline bool booking_figures_hold(const RunRecord& record) {
943 const auto zero = Decimal64::parse("0");
944 const auto& filled = *record.filled_;
945 const auto& amount = record.amount_->amount_;
946 return !decimal_less(filled, zero) && !decimal_less(amount, zero) && !decimal_less(*record.fee_, zero) &&
947 decimal_less(zero, filled) == decimal_less(zero, amount);
948}
949
955inline bool run_keys_fit_order_line(JournalAction action, JournalOutcome outcome, const RunKeys& keys) {
956 const auto& record = keys.record_;
957 if (
958 outcome == JournalOutcome::RECORDED || (action == JournalAction::CANCEL && keys.present_) || record.kind_ ||
959 !record.given_.empty() || !record.of_.empty()
960 ) {
961 return false;
962 }
963 const bool booking =
964 keys.has_amount_ || keys.has_currency_ || record.filled_ || record.fee_ || keys.has_fee_estimated_;
965 if (!booking) {
966 return true;
967 }
968 return outcome == JournalOutcome::CONFIRMED && keys.has_run_ && record.filled_ && record.amount_ && record.fee_ &&
969 booking_figures_hold(record);
970}
971
976inline std::optional<JournalEntry> ledger_entry_from(
977 const json::object& row, JournalOutcome outcome, bool marked, std::int64_t at, const RunKeys& keys
978) {
979 static constexpr std::string_view order_keys[] = {
980 "country",
981 "venue",
982 "session",
983 "symbol",
984 "side",
985 "type",
986 "time_in_force",
987 "route",
988 "quantity",
989 "price",
990 "trigger",
991 "baseline",
992 "order_id",
993 };
994 for (const auto key : order_keys) {
995 if (has_field(row, key)) {
996 return std::nullopt;
997 }
998 }
999 const auto id = readable_string(row, "id");
1000 const auto& record = keys.record_;
1001 if (
1002 outcome != JournalOutcome::RECORDED || marked || has_field(row, "requires_operator") || !id || !keys.has_run_ ||
1003 !record.kind_ || !record.amount_
1004 ) {
1005 return std::nullopt;
1006 }
1007 // A booking of a released placement names it and carries the booking; any other record is an amount.
1008 const bool holds = *record.kind_ == RunRecordKind::FILL ?
1009 !record.of_.empty() && record.filled_ && record.fee_ && record.given_.empty() && booking_figures_hold(record) :
1010 decimal_less(Decimal64::parse("0"), record.amount_->amount_) && !record.filled_ && !record.fee_ &&
1011 !keys.has_fee_estimated_ && record.of_.empty() && (*record.kind_ != RunRecordKind::OPEN || record.run_ == *id) &&
1012 (*record.kind_ == RunRecordKind::OPEN) == record.given_.empty();
1013 if (!holds) {
1014 return std::nullopt;
1015 }
1016 JournalEntry entry;
1017 entry.id_ = *id;
1018 entry.action_ = JournalAction::LEDGER;
1019 entry.outcome_ = outcome;
1020 entry.venue_.reset();
1021 entry.recorded_at_ = instant_from(at);
1022 entry.detail_ = string_field(row, "detail");
1023 entry.scope_ = string_field(row, "scope");
1024 entry.run_ = std::make_shared<const RunRecord>(record);
1025 return entry;
1026}
1027
1028} // namespace journal_detail
1029
1037inline std::optional<JournalEntry> journal_entry_from_line(std::string_view line) {
1038 boost::system::error_code error;
1039 const auto value = json::parse(line, error);
1040 if (error || !value.is_object()) {
1041 return std::nullopt;
1042 }
1043 const auto& row = value.as_object();
1044
1045 const auto action = journal_action_from(journal_detail::string_field(row, "action"));
1046 const auto outcome = journal_outcome_from(journal_detail::string_field(row, "outcome"));
1047 const auto operator_only = row.if_contains("requires_operator");
1048 const bool marked = operator_only != nullptr && operator_only->is_bool() && operator_only->as_bool();
1049
1050 const auto at = row.if_contains("at");
1051 // An operator-only line may carry the epoch, below the bound, and deliberately: a salvaged fragment records the epoch precisely *because* it has no timestamp, and `requires_operator_` is what stops that epoch window resolving it.
1052 // Repairing such a line writes it back, so rejecting the epoch here would make every repair unreadable on the next open.
1053 // Any other instant keeps the bound, which also keeps it inside what `system_clock` holds.
1054 const bool epoch = marked && at != nullptr && at->is_int64() && at->as_int64() == 0;
1055 if (
1056 !action || !outcome || at == nullptr || !at->is_int64() ||
1057 (!epoch && !journal_detail::plausible_instant(at->as_int64(), journal_detail::has_field(row, "crc")))
1058 ) {
1059 // A well-formed JSON object that is not a journal line. Treated as damage rather than as an
1060 // empty entry, because an entry with a default instrument would be a claim about an order.
1061 return std::nullopt;
1062 }
1063
1064 // **A present value this reader cannot parse is damage, not a default.**
1065 // Each of these has a documented default for an *absent* key -- a line that
1066 // predates the field -- and applying that default to a token the line does
1067 // carry turns damage into evidence: a damaged `"SELL"` reads as a buy, a
1068 // damaged `"IOC"` as a day order, and a damaged `"COMBINED"` moves the entry
1069 // to an instrument the runner is not trading, so the ledger marks the wrong
1070 // key and the right one is never withheld at all.
1071 //
1072 // An unreadable value therefore produces an entry with **no instrument**,
1073 // which `unattributable_journal_entry` documents and recovery already turns
1074 // into a global halt. Marking a guessed instrument would not protect the real
1075 // one, because they are different keys.
1076 // Each field is asked two questions, because they have different answers.
1077 // *Is the key there?* -- if not, the line predates the field and its
1078 // documented default is a fact about such a line. *Is what it holds
1079 // readable?* -- if not, the line says something this release cannot use, and
1080 // guessing turns damage into evidence. `string_field` answers neither: it
1081 // flattens absent, non-string and empty into the same `""`.
1082 const auto read = [&row](std::string_view key) {
1083 return journal_detail::readable_string(row, key);
1084 };
1085 // Present but unusable, for any reason: not a string, an empty string, or a
1086 // token the reader could not parse. The first version of this asked only
1087 // whether the *string* was readable, which let `"IOC"` damaged to `"IO?"`
1088 // through -- that is a perfectly good string, and a perfectly bad condition.
1089 const auto unusable = [&row](std::string_view key, bool parsed) {
1090 return journal_detail::has_field(row, key) && !parsed;
1091 };
1092
1093 // `std::optional::and_then` is C++23 and this library is C++17.
1094 const auto parsed = [&read](std::string_view key, auto reader) {
1095 using Result = decltype(reader(std::string_view{}));
1096 const auto text = read(key);
1097 return text ? reader(*text) : Result{};
1098 };
1099
1100 // A `crc` member anywhere but last, or not eight lowercase hex digits, is not this writer's; one
1101 // that is must match the line without it -- the object with its own closing brace. See
1102 // `journal_detail::line_checksum`.
1103 const bool checksum_holds = !journal_detail::has_field(row, "crc") ||
1104 (journal_detail::ends_in_checksum(line) && journal_detail::checksum_matches(line));
1105 bool unknown_key = false;
1106 bool run_key = false;
1107 for (const auto& member : row) {
1108 if (!journal_detail::known_entry_key(member.key())) {
1109 if (journal_detail::run_entry_key(member.key())) {
1110 run_key = true;
1111 } else {
1112 unknown_key = true;
1113 }
1114 }
1115 }
1116 // **A line whose bytes changed is not read at all**, rather than read as a damaged entry. A damaged
1117 // entry carries its own outcome and an id suffixed `~damaged`, which is right for a line whose
1118 // *value* no longer parses -- but a damaged *terminal* line with an intact pending partner then
1119 // pairs with nothing, is dropped as an orphan, and the pending line stays open as an ordinary one:
1120 // the change was detected and then discarded before recovery decided anything. An unreadable line
1121 // is counted by `parse_journal_bytes` and halts recovery outright, whatever it was.
1122 if (!checksum_holds || unknown_key) {
1123 return std::nullopt;
1124 }
1125
1126 // **A run budget's keys are read strictly**: one that is unparseable, of the wrong type, or inconsistent
1127 // with the line makes the whole line unreadable, so recovery halts. Never a `~damaged` entry, which a
1128 // damaged `CONFIRMED` would become and then be dropped as an orphan, its booking lost. Read only on a line
1129 // that carries one or is a ledger record, so an ordinary line pays nothing for them.
1130 std::optional<journal_detail::RunKeys> run;
1131 if (run_key || *action == JournalAction::LEDGER || *outcome == JournalOutcome::RECORDED) {
1132 run = journal_detail::run_keys_from(row);
1133 if (run->unreadable_) {
1134 return std::nullopt;
1135 }
1136 if (*action == JournalAction::LEDGER) {
1137 return journal_detail::ledger_entry_from(row, *outcome, marked, at->as_int64(), *run);
1138 }
1139 if (!journal_detail::run_keys_fit_order_line(*action, *outcome, *run)) {
1140 return std::nullopt;
1141 }
1142 }
1143
1144 const auto symbol = read("symbol");
1145 const auto country = parsed("country", journal_detail::known_country_from);
1146 const auto venue = parsed("venue", journal_detail::known_venue_from);
1147 const auto side = parsed("side", journal_detail::known_side_from);
1148 const auto type = parsed("type", journal_detail::known_order_type_from);
1149 const auto condition = parsed("time_in_force", journal_detail::known_time_in_force_from);
1150 const auto session = parsed("session", journal_detail::known_order_session_from);
1151 const auto quantity = parsed("quantity", journal_detail::known_decimal_from);
1152 const auto price = parsed("price", journal_detail::known_decimal_from);
1153 const auto trigger = parsed("trigger", journal_detail::known_decimal_from);
1154 const auto baseline = parsed("baseline", journal_detail::known_decimal_from);
1155
1156 const bool damaged =
1157 // Identity and the fields every complete line carries: required outright.
1158 // A line this reader cannot attribute to an instrument must not be
1159 // attributed to a guess, and `quantity` at a silent zero is a claim about
1160 // an order's size.
1161 !symbol || !country || !venue || !side || !type || !quantity ||
1162 // Legacy-defaulted fields: absent is fine, present and unreadable is not.
1163 unusable("time_in_force", condition.has_value()) || unusable("session", session.has_value()) ||
1164 // A price is absent for a market order and required for a basis that
1165 // carries one, so its presence is judged against the basis rather than
1166 // assumed either way.
1167 unusable("price", price.has_value()) ||
1168 // The same rule for a stop's trigger: absent on every other order and on every line written
1169 // before the field existed, and a present value that does not parse is damage.
1170 unusable("trigger", trigger.has_value()) || unusable("baseline", baseline.has_value()) ||
1171 // Checked above, where a changed line becomes unreadable rather than damaged; restated so the
1172 // condition reads whole.
1173 !checksum_holds || unknown_key;
1174 // **A price missing from a priced basis, and a cancellation with no target
1175 // id, are deliberately *not* damage here.** Both are lines this library's own
1176 // writer emits: `JournalingExecutor` appends the pending line *before* the
1177 // executor runs, so an order the binding then refuses locally -- a limit with
1178 // no price, a cancellation of a reservation whose broker id is not known --
1179 // has already been written by the time anyone could object. Rejecting them
1180 // turned an ordinary local refusal into a global halt on the next restart,
1181 // which is worse than the hazard the rejection was meant to close.
1182 //
1183 // The hazard is real and it lives one step later: such a line must not be
1184 // *resolved* on evidence it does not have. `runner::match_against` refuses to
1185 // conclude anything from one, which leaves it withheld for an operator while
1186 // its own terminal line still closes it when the refusal was ordinary.
1187 if (damaged) {
1188 // A run's line whose order cannot be read: its booking or its run would be lost with it.
1189 if (run && run->present_) {
1190 return std::nullopt;
1191 }
1192 auto unattributable = unattributable_journal_entry(line);
1193 const auto id = journal_detail::string_field(row, "id");
1194 unattributable.id_ = (id.empty() ? std::string("unknown") : id) + "~damaged";
1195 unattributable.action_ = *action;
1196 // Its own outcome, not `PENDING`. Both lines of a pair carry the same id, so
1197 // a damaged *terminal* line still closes its damaged pending partner --
1198 // forcing `PENDING` left both open and halted a runner over an instruction
1199 // that had already resolved.
1200 unattributable.outcome_ = *outcome;
1201 unattributable.recorded_at_ = journal_detail::instant_from(at->as_int64());
1202 unattributable.detail_ =
1203 "a journal line carries a value this release cannot read, so the order it describes cannot "
1204 "be identified; nothing may be traded until an operator resolves it: " +
1205 std::string(line.substr(0, line.size() < 160 ? line.size() : 160));
1206 return unattributable;
1207 }
1208
1209 JournalEntry entry;
1210 entry.id_ = journal_detail::string_field(row, "id");
1211 entry.action_ = *action;
1212 entry.outcome_ = *outcome;
1213 entry.instrument_ = InstrumentId{*country, *venue, *symbol};
1214 entry.side_ = *side;
1215 entry.type_ = *type;
1216 // These two keep their documented defaults for an *absent* key only; a
1217 // present value that failed to parse was caught above.
1218 entry.time_in_force_ = condition ? *condition : TimeInForce::DAY;
1219 entry.session_ = session ? *session : OrderSession::REGULAR;
1220 // Absent key -> absent value, which is "this line predates the field" rather
1221 // than "no route was asked for". Recovery will not attribute a row to an
1222 // instruction whose route nobody recorded. The field defaults to a recorded
1223 // `UNSPECIFIED`, so this clears it rather than leaving the default standing.
1224 // An absent key means the line predates the field. An unrecognized value means
1225 // the line says something this reader cannot use. Both are "unknown", and
1226 // neither may become the `UNSPECIFIED` that recovery treats as a recorded
1227 // request for no venue.
1228 entry.venue_ = journal_detail::known_venue_from(journal_detail::string_field(row, "route"));
1229 // Damaged numbers land in the same place as damaged enumerations, for the
1230 // same reason -- and they used to land somewhere far worse, throwing out of
1231 // recovery entirely. See `known_decimal_from`.
1232 entry.quantity_ = *quantity;
1233 if (price) {
1234 entry.price_ = *price;
1235 }
1236 if (trigger) {
1237 entry.trigger_price_ = *trigger;
1238 }
1239 entry.baseline_ = baseline;
1240 entry.recorded_at_ = journal_detail::instant_from(at->as_int64());
1241 entry.order_id_ = journal_detail::string_field(row, "order_id");
1242 entry.detail_ = journal_detail::string_field(row, "detail");
1243 entry.requires_operator_ = marked;
1244 entry.scope_ = journal_detail::string_field(row, "scope");
1245 if (run && run->present_) {
1246 entry.run_ = std::make_shared<const RunRecord>(run->record_);
1247 }
1248 return entry;
1249}
1250
1261inline bool salvage_damaged(std::string_view line, std::string_view key) {
1262 const std::string needle = "\"" + std::string(key) + "\":";
1263 const auto at = line.find(needle);
1264 if (at == std::string_view::npos) {
1265 return false;
1266 }
1267 return line.find(',', at + needle.size()) != std::string_view::npos;
1268}
1269
1281inline std::optional<JournalEntry> salvage_journal_line(std::string_view line) {
1282 const auto symbol = journal_detail::salvage_string(line, "symbol");
1283 if (!symbol || symbol->empty()) {
1284 return std::nullopt;
1285 }
1286 JournalEntry entry;
1287 // The flag that makes the promise in this comment block true. Without it the entry's missing
1288 // timestamp reads as the epoch, every window test passes immediately, no real row falls inside
1289 // the window, and the first sweep resolves it `NOT_PLACED`.
1290 entry.requires_operator_ = true;
1291 const auto id = journal_detail::salvage_string(line, "id");
1292 entry.id_ = (id ? *id : std::string("unknown")) + "~truncated";
1293 entry.action_ =
1294 journal_action_from(journal_detail::salvage_string(line, "action").value_or("place"))
1295 .value_or(JournalAction::PLACE);
1297 // **Absent is a default; present and unreadable is damage** -- the same rule
1298 // the strict reader follows, and for the same reason. A truncated line is
1299 // missing its *tail*, so an absent field is expected and its default is a fact
1300 // about what the line could have said. A field that is there and cannot be
1301 // read is corruption in the middle, and guessing it hands this entry a
1302 // different instrument than the order had: `requires_operator_` would then
1303 // withhold a key the runner is not trading under, while the real one stays
1304 // open. Such a line becomes unattributable instead, carrying no instrument at
1305 // all, which recovery turns into a global halt.
1306 // A key the truncation removed takes its default; a key that is *there* and
1307 // unreadable is damage, and `salvage_string` cannot tell those apart on its
1308 // own -- it recognizes `"key":"value"` and nothing else, so `null` and `7`
1309 // both read as absent.
1310 const auto salvaged = [&line](std::string_view key, const char* fallback) {
1311 const auto text = journal_detail::salvage_string(line, key);
1312 if (text) {
1313 return std::optional<std::string>(*text);
1314 }
1315 return salvage_damaged(line, key) ? std::optional<std::string>() : std::optional<std::string>(fallback);
1316 };
1317 const auto parsed = [&salvaged](std::string_view key, const char* fallback, auto reader) {
1318 using Result = decltype(reader(std::string_view{}));
1319 const auto text = salvaged(key, fallback);
1320 return text ? reader(*text) : Result{};
1321 };
1322
1323 const auto country = parsed("country", "KR", journal_detail::known_country_from);
1324 const auto venue = parsed("venue", "UNSPECIFIED", journal_detail::known_venue_from);
1325 const auto side = parsed("side", "BUY", journal_detail::known_side_from);
1326 const auto type = parsed("type", "UNKNOWN", journal_detail::known_order_type_from);
1327 const auto condition = parsed("time_in_force", "DAY", journal_detail::known_time_in_force_from);
1328 const auto session = parsed("session", "REGULAR", journal_detail::known_order_session_from);
1329 if (!country || !venue || !side || !type || !condition || !session) {
1330 auto unattributable = unattributable_journal_entry(line);
1331 unattributable.id_ = entry.id_;
1332 unattributable.detail_ =
1333 "a truncated journal line carries a value this release cannot read, so the order it "
1334 "describes cannot be identified; nothing may be traded until an operator resolves it: " +
1335 std::string(line.substr(0, line.size() < 160 ? line.size() : 160));
1336 return unattributable;
1337 }
1338 entry.instrument_ = InstrumentId{*country, *venue, *symbol};
1339 entry.side_ = *side;
1340 entry.type_ = *type;
1341 entry.time_in_force_ = *condition;
1342 entry.session_ = *session;
1343 entry.venue_ = journal_detail::known_venue_from(journal_detail::salvage_string(line, "route").value_or(""));
1344 if (const auto quantity = journal_detail::salvage_string(line, "quantity")) {
1345 // A truncated line's last field is routinely half-written, so an unparseable
1346 // number here is expected rather than exceptional -- and it must not throw
1347 // out of a salvage path that exists to survive exactly this.
1348 if (const auto value = journal_detail::known_decimal_from(*quantity)) {
1349 entry.quantity_ = *value;
1350 }
1351 }
1352 if (const auto price = journal_detail::salvage_string(line, "price")) {
1353 if (const auto value = journal_detail::known_decimal_from(*price)) {
1354 entry.price_ = *value;
1355 }
1356 }
1357 if (const auto trigger = journal_detail::salvage_string(line, "trigger")) {
1358 if (const auto value = journal_detail::known_decimal_from(*trigger)) {
1359 entry.trigger_price_ = *value;
1360 }
1361 }
1362 entry.detail_ = "recovered from a truncated journal line; only an operator can resolve it";
1363 return entry;
1364}
1365
1372inline JournalBytes read_journal_bytes(const std::string& path) {
1373 JournalBytes bytes;
1374 errno = 0;
1375 std::unique_ptr<std::FILE, int (*)(std::FILE*)> handle(std::fopen(path.c_str(), "rb"), [](std::FILE* file) {
1376 return file ? std::fclose(file) : 0;
1377 });
1378 if (handle == nullptr) {
1379 if (errno == ENOENT) {
1381 return bytes;
1382 }
1383 // Every other reason -- a permission the process does not have, a directory where a file was
1384 // expected, a device error -- means the file exists and its contents are unknown. Reporting
1385 // that as "no journal" is how a process claims a path holding its predecessor's in-flight
1386 // orders and then trades on an empty ledger.
1388 bytes.detail_ = "the order journal at " + path + " exists and could not be opened for reading";
1389 return bytes;
1390 }
1391
1392 char buffer[4096];
1393 while (const auto read = std::fread(buffer, 1, sizeof(buffer), handle.get())) {
1394 bytes.text_.append(buffer, read);
1395 }
1396 if (std::ferror(handle.get()) != 0) {
1397 // A read that stopped partway looks exactly like an ordinary end of file to the loop above, so
1398 // the truncated tail it produces would be a fiction about where the journal ends.
1400 bytes.detail_ = "the order journal at " + path + " could not be read to the end";
1401 bytes.text_.clear();
1402 return bytes;
1403 }
1405 return bytes;
1406}
1407
1408namespace journal_detail {
1409
1411struct ParseCarry {
1413 bool seen_checksum_{false};
1414};
1415
1427inline std::size_t parse_complete_lines(std::string_view text, JournalReplay& replay, ParseCarry& carry) {
1428 std::size_t begin = 0;
1429 while (begin < text.size()) {
1430 const auto end = text.find('\n', begin);
1431 if (end == std::string_view::npos) {
1432 break;
1433 }
1434 const std::string_view line(text.data() + begin, end - begin);
1435 begin = end + 1;
1436 // **An empty line, or a header anywhere but first, is damage.** This writer produces neither: every
1437 // append is one non-empty line and its newline, and the header is written once, before anything
1438 // else. Skipping them was how an entry overwritten by a bare newline, or by a copy of the header,
1439 // vanished from recovery with nothing counted -- a changed line removed rather than detected.
1440 const auto unreadable = [&replay](const char* why) {
1441 ++replay.unreadable_lines_;
1442 if (replay.detail_.empty()) {
1443 replay.detail_ = why;
1444 }
1445 };
1446 if (line.empty()) {
1447 unreadable("the journal contains an empty line, which this library never writes");
1448 continue;
1449 }
1450 if (auto scope = journal_header_scope(line)) {
1451 if (replay.has_header_ || !replay.entries_.empty() || replay.unreadable_lines_ > 0) {
1452 unreadable(
1453 "the journal contains a header after its first line, which this library never "
1454 "writes"
1455 );
1456 continue;
1457 }
1458 // Not an instruction and not damage. Recorded so an opener can check ownership before it
1459 // writes anything at all.
1460 replay.has_header_ = true;
1461 replay.scope_ = std::move(*scope);
1462 // A header that declares checksums protects every entry after it, the first one included.
1463 carry.seen_checksum_ = carry.seen_checksum_ || journal_header_declares_checksums(line);
1464 continue;
1465 }
1466 const bool checksummed = ends_in_checksum(line);
1467 if (carry.seen_checksum_ && !checksummed) {
1468 // **This writer never puts a checksum-less line after a checksummed one, or after a header that
1469 // declares checksums**, so this is a protected line that lost its checksum -- damage that removed
1470 // the whole member, which the line's own reader cannot tell from a line written before checksums
1471 // existed. Only the first checksummed line of a file begun by an earlier release is left without
1472 // this protection; see `journal_header_line`.
1473 ++replay.unreadable_lines_;
1474 if (replay.detail_.empty()) {
1475 replay.detail_ =
1476 "a journal line without a checksum follows a checksummed one, so it was changed after it "
1477 "was written";
1478 }
1479 continue;
1480 }
1481 carry.seen_checksum_ = carry.seen_checksum_ || checksummed;
1482 if (auto entry = journal_entry_from_line(line)) {
1483 replay.entries_.push_back(std::move(*entry));
1484 } else {
1485 // A complete line that is not a journal entry. Not expected from this writer, so it means
1486 // the file was edited or written by something else, or a repair was interrupted; counted
1487 // rather than ignored, and recovery halts on it.
1488 ++replay.unreadable_lines_;
1489 if (replay.detail_.empty()) {
1490 replay.detail_ = "the journal contains a line this library did not write";
1491 }
1492 }
1493 }
1494 return begin;
1495}
1496
1503inline void parse_torn_tail(std::string_view tail, JournalReplay& replay) {
1504 // Everything after the last newline is a write that never finished. This is the whole reason
1505 // the format is line-oriented, and dropping it silently would defeat the feature.
1506 replay.truncated_tail_ = true;
1507 if (auto salvaged = salvage_journal_line(tail)) {
1508 replay.detail_ = "the final journal line was truncated; it named " + salvaged->instrument_.symbol_ +
1509 " and is treated as unresolved";
1510 replay.entries_.push_back(std::move(*salvaged));
1511 } else {
1512 replay.detail_ = "the final journal line was truncated and named no instrument; something was in flight";
1513 // The same entry a writer's repair appends for this tail, so recovery halts on it whether or
1514 // not the file was repaired, and whatever else is open beside it.
1515 replay.entries_.push_back(unattributable_journal_entry(tail));
1516 }
1517}
1518
1526inline bool parse_bytes_into(const JournalBytes& bytes, JournalReplay& replay, ParseCarry& carry) {
1527 replay.status_ = bytes.status_;
1528 if (bytes.status_ != JournalReadStatus::READ) {
1529 replay.detail_ = bytes.detail_;
1530 return false;
1531 }
1532 const std::string_view text(bytes.text_);
1533 const auto parsed = parse_complete_lines(text, replay, carry);
1534 if (parsed < text.size()) {
1535 parse_torn_tail(text.substr(parsed), replay);
1536 return false;
1537 }
1538 return true;
1539}
1540
1541} // namespace journal_detail
1542
1555 JournalReplay replay;
1556 journal_detail::ParseCarry carry;
1557 journal_detail::parse_bytes_into(bytes, replay, carry);
1558 return replay;
1559}
1560
1566inline JournalReplay read_journal_file(const std::string& path) {
1568}
1569
1600public:
1610 FileJournal(std::string path, std::string scope)
1611 : path_(std::move(path)), scope_(std::move(scope)), handle_(nullptr, &closer) {
1612 if (scope_.empty()) {
1613 // An unnamed journal could not tell another account's file from its own.
1614 rejection_ = "an order journal must name the broker and account it belongs to";
1615 return;
1616 }
1617#if defined(_WIN32)
1618 if (!claim_file()) {
1619 return;
1620 }
1621 repair_torn_tail();
1622 handle_.reset(std::fopen(path_.c_str(), "ab"));
1623#else
1624 // Locked before anything reads or repairs the file, and on the descriptor that becomes the
1625 // write handle: the lock lives exactly as long as `open()` is true, and moving the journal moves
1626 // it with the handle. Every refusal or exception below closes the descriptor (a held lock
1627 // outliving a failed open would refuse this program's own retry), until the handle takes it.
1628 journal_detail::DescriptorOwner descriptor(::open(path_.c_str(), O_WRONLY | O_APPEND | O_CREAT | O_CLOEXEC, 0666));
1629 if (descriptor.get() < 0) {
1630 const int error = errno;
1631 rejection_ = "the journal at " + path_ + " could not be opened (" + std::strerror(error) + ")";
1632 return;
1633 }
1634 if (!lock(descriptor.get())) {
1635 return;
1636 }
1637 if (!claim_file()) {
1638 return;
1639 }
1640 repair_torn_tail();
1641 handle_.reset(::fdopen(descriptor.get(), "ab"));
1642 if (open()) {
1643 descriptor.release();
1644 } else {
1645 const int error = errno;
1646 rejection_ = "the journal at " + path_ + " could not be opened for appending (" + std::strerror(error) + ")";
1647 }
1648#endif
1649 if (!open()) {
1650 return;
1651 }
1652 if (needs_header_ && !write_header()) {
1653 return;
1654 }
1655 if (!pending_repair_.empty()) {
1656 finish_repair();
1657 }
1658 }
1659
1664 bool open() const noexcept {
1665 return handle_ != nullptr;
1666 }
1667
1673 const std::string& repaired() const noexcept {
1674 return repaired_;
1675 }
1676
1681 const std::string& path() const noexcept {
1682 return path_;
1683 }
1684
1689 const std::string& scope() const noexcept {
1690 return scope_;
1691 }
1692
1702 const std::string& rejection() const noexcept {
1703 return rejection_;
1704 }
1705
1714 bool append(const JournalEntry& entry) {
1715 if (!open()) {
1716 return false;
1717 }
1718 auto stamped = entry;
1719 // Overwritten: the journal owns the scope.
1720 stamped.scope_ = scope_;
1721 auto line = journal_entry_to_line(stamped);
1722 line += '\n';
1723 note_write_begins();
1724 const auto written = std::fwrite(line.data(), 1, line.size(), handle_.get());
1725 if (written != line.size() || std::fflush(handle_.get()) != 0) {
1726 forget_kept();
1727 return false;
1728 }
1729 // Stamped before `fsync`, which changes neither the size nor the times, so the stamp spans only
1730 // this journal's own write.
1731 note_write_ended(line.size());
1732 if (!journal_detail::sync_to_disk(handle_.get())) {
1733 forget_kept();
1734 return false;
1735 }
1736 return true;
1737 }
1738
1750 const JournalReplay& replay() const {
1751#if !defined(_WIN32)
1752 if (continuable_ && open() && continue_replay()) {
1753 return kept_;
1754 }
1755#endif
1756 read_whole();
1757 return kept_;
1758 }
1759
1760private:
1761 // Reads and parses the whole file into the kept replay, and on POSIX keeps a stamp of it when a later
1762 // call may continue from it: the file was read whole, ends in a newline, and did not change while it
1763 // was read. The path need not be the file this journal writes to (a rotated journal): the stamp is
1764 // then of another inode, so this journal's next append finds it changed (`note_write_begins`).
1765 //
1766 // The old replay is released before the file is read, so a miss holds no more than one replay and
1767 // the file's bytes at once.
1768 void read_whole() const {
1769#if defined(_WIN32)
1770 kept_ = JournalReplay{};
1771 kept_ = read_journal_file(path_);
1772#else
1773 continuable_ = false;
1774 kept_ = JournalReplay{};
1775 carry_ = journal_detail::ParseCarry{};
1776 struct stat before{};
1777 const bool stated = ::stat(path_.c_str(), &before) == 0;
1778 const auto bytes = read_journal_bytes(path_);
1779 if (!journal_detail::parse_bytes_into(bytes, kept_, carry_) || !stated) {
1780 return;
1781 }
1782 struct stat after{};
1783 const auto stamp = journal_detail::stamp_of(before);
1784 if (
1785 ::stat(path_.c_str(), &after) != 0 || !(stamp == journal_detail::stamp_of(after)) ||
1786 static_cast<std::size_t>(stamp.size_) != bytes.text_.size()
1787 ) {
1788 return;
1789 }
1790 stamp_ = stamp;
1791 parsed_to_ = bytes.text_.size();
1792 continuable_ = true;
1793#endif
1794 }
1795
1796#if !defined(_WIN32)
1797 // Continues the kept replay over what this journal appended since it was read, and returns whether it
1798 // could. It can only when the path's stamp is the one kept: the file read, then only this journal's
1799 // own appends (see `note_write_ended`). Anything else -- another writer, a truncated, replaced or
1800 // deleted file, a read that came back short -- is left to `read_whole`.
1801 bool continue_replay() const {
1802 struct stat now{};
1803 if (::stat(path_.c_str(), &now) != 0 || !(journal_detail::stamp_of(now) == stamp_)) {
1804 return false;
1805 }
1806 const auto size = static_cast<std::size_t>(now.st_size);
1807 if (size == parsed_to_) {
1808 return true;
1809 }
1810 if (size < parsed_to_) {
1811 return false;
1812 }
1813 journal_detail::DescriptorOwner reader(::open(path_.c_str(), O_RDONLY | O_CLOEXEC));
1814 if (reader.get() < 0) {
1815 return false;
1816 }
1817 std::string appended(size - parsed_to_, '\0');
1818 std::size_t got = 0;
1819 while (got < appended.size()) {
1820 const auto read =
1821 ::pread(reader.get(), &appended[got], appended.size() - got, static_cast<off_t>(parsed_to_ + got));
1822 if (read < 0 && errno == EINTR) {
1823 continue;
1824 }
1825 if (read <= 0) {
1826 return false;
1827 }
1828 got += static_cast<std::size_t>(read);
1829 }
1830 struct stat read_status{};
1831 if (
1832 appended.back() != '\n' || ::fstat(reader.get(), &read_status) != 0 ||
1833 !(journal_detail::stamp_of(read_status) == stamp_)
1834 ) {
1835 return false;
1836 }
1837 // Cleared first: a parse that throws leaves the next call reading the whole file.
1838 continuable_ = false;
1839 journal_detail::parse_complete_lines(appended, kept_, carry_);
1840 parsed_to_ = size;
1841 continuable_ = true;
1842 return true;
1843 }
1844#endif
1845
1846 // Before this journal writes: if the file is no longer as the kept replay last saw it, something else
1847 // wrote to it, and the stamp taken after this write must not stand for it.
1848 void note_write_begins() {
1849#if !defined(_WIN32)
1850 struct stat now{};
1851 if (continuable_ && (::fstat(::fileno(handle_.get()), &now) != 0 || !(journal_detail::stamp_of(now) == stamp_))) {
1852 continuable_ = false;
1853 }
1854#endif
1855 }
1856
1857 // After this journal's write of `written` bytes reached the kernel: the bytes past the parsed offset are
1858 // its own, so the stamp now is what the next `replay()` must find. A file that did not grow by at least
1859 // the line (another program truncated it during the write) is left to a whole read.
1860 void note_write_ended([[maybe_unused]] std::size_t written) {
1861#if !defined(_WIN32)
1862 struct stat now{};
1863 if (continuable_) {
1864 if (
1865 ::fstat(::fileno(handle_.get()), &now) == 0 &&
1866 static_cast<std::size_t>(now.st_size) >= static_cast<std::size_t>(stamp_.size_) + written
1867 ) {
1868 stamp_ = journal_detail::stamp_of(now);
1869 } else {
1870 continuable_ = false;
1871 }
1872 }
1873#endif
1874 }
1875
1876 // A write that failed leaves the file in a state no stamp describes.
1877 void forget_kept() noexcept {
1878#if !defined(_WIN32)
1879 continuable_ = false;
1880#endif
1881 }
1882
1883 // Returns whether this journal may write to the file, deciding ownership from the header alone.
1884 //
1885 // **The header, not the records, and that distinction is the fix.** Reading ownership from the
1886 // records leaves a hole exactly where it matters most: the scope is one field among many on a
1887 // record, so a process killed partway through writing the *first* instruction leaves a file whose
1888 // only line is torn and unscoped. Another account could then open the path, repair that line into
1889 // its own journal, and reconcile the first account's instruction against its own rows.
1890 //
1891 // A header is written before any instruction is contemplated, so it is complete or the file is
1892 // empty. Three cases, and the third is the strict one:
1893 //
1894 // - **Empty or absent.** Ours to claim; the header is written before the first append.
1895 // - **Header present.** The scopes must agree.
1896 // - **Non-empty with no header.** Refused. Something else wrote this file, or it predates the
1897 // format, and either way its ownership cannot be established -- which is not a question to
1898 // guess at while holding a file that may name another account's live orders.
1899 bool claim_file() {
1900 const auto replay = read_journal_file(path_);
1901 if (!replay.readable()) {
1902 // Opening for *append* can succeed on a file that cannot be read -- a write-only file is the
1903 // plain case -- so without this the journal would claim a path whose contents it has never
1904 // seen, write a header into it, and report nothing owed.
1905 rejection_ = replay.detail_.empty() ? "the journal at " + path_ + " exists and cannot be read" : replay.detail_;
1906 return false;
1907 }
1908 const bool empty =
1909 !replay.has_header_ && replay.entries_.empty() && replay.unreadable_lines_ == 0 && !replay.truncated_tail_;
1910 if (empty) {
1911 needs_header_ = true;
1912 return true;
1913 }
1914 if (!replay.has_header_) {
1915 rejection_ = "the journal at " + path_ + " has no header, so the account it belongs to cannot be established";
1916 return false;
1917 }
1918 if (replay.scope_ != scope_) {
1919 rejection_ = "the journal at " + path_ + " belongs to " + replay.scope_ + ", not to " + scope_;
1920 return false;
1921 }
1922 return true;
1923 }
1924
1925 // Writes and flushes the header, before any instruction can be recorded.
1926 bool write_header() {
1927 auto line = journal_header_line(scope_);
1928 line += '\n';
1929 const auto written = std::fwrite(line.data(), 1, line.size(), handle_.get());
1930 if (written != line.size() || !journal_detail::flush_to_disk(handle_.get())) {
1931 handle_.reset();
1932 rejection_ = "the journal header at " + path_ + " could not be written";
1933 return false;
1934 }
1935 needs_header_ = false;
1936 return true;
1937 }
1938
1939 // Closes a stream, tolerating the null a failed open leaves behind.
1940 static void closer(std::FILE* handle) noexcept {
1941 if (handle != nullptr) {
1942 std::fclose(handle);
1943 }
1944 }
1945
1946 // Reads the file and works out what a torn final line needs, without writing anything yet.
1947 //
1948 // Split from the writing half because the file must be inspected *before* it is opened for
1949 // appending: once a stream is in append mode, everything written goes to the end, which is
1950 // precisely what must not happen until the fragment is terminated.
1951 void repair_torn_tail() {
1952 const auto replay = read_journal_file(path_);
1953 if (!replay.truncated_tail_) {
1954 return;
1955 }
1956 const auto tail = read_torn_tail(path_);
1957 auto salvaged = salvage_journal_line(tail);
1958 pending_repair_ =
1960 repaired_ = salvaged ?
1961 "a torn final line was terminated and salvaged as " + salvaged->instrument_.symbol_ :
1962 "a torn final line was terminated; it named no instrument";
1963 }
1964
1965 // Terminates the fragment and appends the record that stands for it, durably.
1966 void finish_repair() {
1967 // The newline first and on its own: it is what turns the fragment into a complete -- if
1968 // unreadable -- line, so that the record written next is a line of its own rather than a
1969 // continuation of a half-written one.
1970 std::string repair = "\n";
1971 repair += pending_repair_;
1972 repair += '\n';
1973 const auto written = std::fwrite(repair.data(), 1, repair.size(), handle_.get());
1974 if (written != repair.size() || !journal_detail::flush_to_disk(handle_.get())) {
1975 // The repair itself failed, so the file is still torn. Refusing to be open is the only safe
1976 // answer: a caller that cannot journal must not trade, and `open()` is how it finds out.
1977 handle_.reset();
1978 repaired_ = "a torn final line could not be repaired";
1979 rejection_ = "the journal at " + path_ + " ends in a torn line that could not be repaired";
1980 return;
1981 }
1982 pending_repair_.clear();
1983 }
1984
1985#if !defined(_WIN32)
1986 // Takes the writer's lock on `descriptor`, or says in `rejection_` why it could not.
1987 bool lock(int descriptor) {
1988 if (::flock(descriptor, LOCK_EX | LOCK_NB) == 0) {
1989 return true;
1990 }
1991 const int error = errno;
1992 rejection_ = error == EWOULDBLOCK ?
1993 "the journal at " + path_ +
1994 " is already open for writing, in another process or another "
1995 "FileJournal (one journal, one writer)" :
1996 "the journal at " + path_ + " could not be locked (" + std::strerror(error) +
1997 "), so a second writer could not be refused";
1998 return false;
1999 }
2000#endif
2001
2002 // Returns the text after the file's last newline, which is the fragment a kill left behind.
2003 static std::string read_torn_tail(const std::string& path) {
2004 std::unique_ptr<std::FILE, void (*)(std::FILE*)> reader(std::fopen(path.c_str(), "rb"), &closer);
2005 if (reader == nullptr) {
2006 return {};
2007 }
2008 std::string text;
2009 char buffer[4096];
2010 while (const auto read = std::fread(buffer, 1, sizeof(buffer), reader.get())) {
2011 text.append(buffer, read);
2012 }
2013 const auto last = text.rfind('\n');
2014 return last == std::string::npos ? text : text.substr(last + 1);
2015 }
2016
2017 std::string path_;
2018 std::string scope_;
2019 std::unique_ptr<std::FILE, void (*)(std::FILE*)> handle_;
2020 std::string pending_repair_;
2021 std::string repaired_;
2022 std::string rejection_;
2023 bool needs_header_{false};
2024 // What `replay()` last returned.
2025 mutable JournalReplay kept_;
2026#if !defined(_WIN32)
2027 // The parser's state after the kept replay's last line, how many bytes it covers, the file's stamp
2028 // as this journal last saw it, and whether a later `replay()` may continue from it.
2029 mutable journal_detail::ParseCarry carry_;
2030 mutable std::size_t parsed_to_{0};
2031 mutable journal_detail::FileStamp stamp_;
2032 mutable bool continuable_{false};
2033#endif
2034};
2035
2036} // namespace runner
2037} // namespace algotradelib
Currency()
Constructs Korean won.
Definition types.hpp:377
std::string str() const
Formats the value as a decimal string.
Definition types.hpp:557
static Decimal64 parse(std::string_view input)
Parses a decimal string exactly (no binary floating point).
Definition types.hpp:468
Either a value or a BrokerError.
Definition types.hpp:1058
bool open() const noexcept
Tests whether the journal opened.
const std::string & repaired() const noexcept
Returns what opening had to repair: a torn last line is terminated and a salvaged entry written besid...
bool append(const JournalEntry &entry)
Appends one entry and flushes it to disk.
const std::string & scope() const noexcept
Returns the journal's broker and account.
const JournalReplay & replay() const
Reads the journal back.
FileJournal(std::string path, std::string scope)
Opens a journal file for appending, creating it if absent.
const std::string & path() const noexcept
Returns the file's path.
const std::string & rejection() const noexcept
Returns why the journal refused to open.
Runs a strategy: the runner, the polling loop, the order journal, and stopping.
Definition clock.hpp:7
std::optional< RunRecordKind > run_record_kind_from(std::string_view text) noexcept
Parses a record kind's name.
Definition journal.hpp:444
std::optional< JournalOutcome > journal_outcome_from(std::string_view text) noexcept
Parses an outcome's name.
Definition journal.hpp:208
constexpr std::string_view journal_outcome_name(JournalOutcome outcome) noexcept
Returns an outcome's name as written to the journal ("pending", ...).
Definition journal.hpp:171
JournalBytes read_journal_bytes(const std::string &path)
Reads a journal file's bytes, without opening it for appending.
JournalReadStatus
Whether a journal file could be read.
Definition journal.hpp:569
@ MISSING
No such file: a first start, nothing owed.
Definition journal.hpp:571
@ READ
The file was read in full.
Definition journal.hpp:573
@ UNREADABLE
The file exists and could not be read; its contents are unknown.
Definition journal.hpp:575
std::optional< std::string > journal_header_scope(std::string_view line)
Returns the scope a header line declares.
JournalReplay read_journal_file(const std::string &path)
Reads and parses a journal file.
bool salvage_damaged(std::string_view line, std::string_view key)
Tests whether a journal line has a field that was written completely but cannot be read.
constexpr std::string_view journal_action_name(JournalAction action) noexcept
Returns an action's name as written to the journal ("place", "cancel").
Definition journal.hpp:57
constexpr std::string_view journal_format_name() noexcept
Returns the format name in a journal header's journal field.
RunRecordKind
What a run budget's JournalAction::LEDGER line records (RunRecord::kind_).
Definition journal.hpp:391
@ FILL
An operator's booking of a placement released without one (runner::Runner::book_run_fill).
Definition journal.hpp:399
constexpr std::string_view run_record_kind_name(RunRecordKind kind) noexcept
Returns a record kind's name as written to the journal ("open", ...).
Definition journal.hpp:415
JournalOutcome
What a journal line says about an instruction.
Definition journal.hpp:113
@ CONFIRMED
A serialized runner accounted for the placement: holdings showed what it filled, its history showed i...
Definition journal.hpp:144
@ PENDING
Written before the send; whether the instruction exists is not yet known.
Definition journal.hpp:115
@ RECORDED
A run budget's ledger record (JournalAction::LEDGER); it answers no instruction.
Definition journal.hpp:151
std::string journal_header_line(std::string_view scope)
Renders the header line a journal file starts with, naming its broker and account.
JournalAction
Which kind of instruction a journal line records.
Definition journal.hpp:31
@ CANCEL
A cancellation of a resting order.
Definition journal.hpp:35
@ LEDGER
A record of a run budget's ledger (RunRecord), not an instruction: it sends nothing and names no orde...
Definition journal.hpp:42
std::optional< JournalAction > journal_action_from(std::string_view text) noexcept
Parses an action's name.
Definition journal.hpp:102
std::string journal_entry_to_line(const JournalEntry &entry)
Renders one entry as a journal line: a JSON object ending in a CRC-32 checksum member.
std::optional< JournalEntry > journal_entry_from_line(std::string_view line)
Parses one journal line.
JournalEntry unattributable_journal_entry(std::string_view line)
Makes the entry that stands for a torn line naming no instrument.
bool journal_header_declares_checksums(std::string_view line)
Tests whether a header line declares that every entry after it carries a checksum.
std::optional< JournalEntry > salvage_journal_line(std::string_view line)
Salvages a torn final line into an entry nothing can resolve automatically.
JournalReplay parse_journal_bytes(const JournalBytes &bytes)
Parses a journal's bytes, salvaging a torn final line.
The library: broker-neutral types (core), and the modules below.
constexpr std::array< Venue, 4 > all_venues
Every Venue, in declaration order.
Definition types.hpp:53
constexpr std::optional< Enum > value_named(const std::array< Enum, N > &values, Name name, std::string_view text) noexcept
Returns the value of a list whose name is text, so a parser reads exactly what its writer writes.
constexpr bool lists_every_value(const std::array< Enum, N > &values, IsEnumerator is_enumerator) noexcept
Tests whether a list holds every value of an enum exactly once, in any order.
OrderType
How an order's price is decided (its price basis).
Definition types.hpp:1998
@ LIMIT
지정가: fills at the stated price or better.
Definition types.hpp:2001
@ BEST_LIMIT
최유리지정가: priced at the best quote on the opposite side.
Definition types.hpp:2007
@ PRIMARY_LIMIT
최우선지정가: priced at the best quote on the order's own side.
Definition types.hpp:2009
@ CONDITIONAL_LIMIT
조건부지정가: a limit that becomes a market order at the close.
Definition types.hpp:2005
@ MID_PRICE
중간가: priced at the midpoint of the spread.
Definition types.hpp:2011
@ STOP_LIMIT
스톱지정가: a limit released when a trigger price is reached.
Definition types.hpp:2013
@ CLOSING_PRICE
시간외종가: priced at a session's closing price.
Definition types.hpp:2015
@ MARKET
시장가: fills at whatever the book offers.
Definition types.hpp:2003
constexpr std::array< OrderType, 9 > all_order_types
Every OrderType, in declaration order.
Definition types.hpp:2019
Country
A country (market) the library supports.
Definition types.hpp:32
OrderSession
The trading session an order is submitted into.
Definition types.hpp:2130
@ OPENING_AUCTION
The opening single-price auction (시가단일가; Toss OPG).
Definition types.hpp:2135
@ AFTER_HOURS
After the close, at that session's close (장후 시간외).
Definition types.hpp:2141
@ CLOSING_AUCTION
The closing auction (Toss CLS, a US limit-on-close).
Definition types.hpp:2137
@ REGULAR
The continuous regular session.
Definition types.hpp:2133
@ AFTER_MARKET
KRX's after-market session (애프터마켓).
Definition types.hpp:2145
@ AFTER_HOURS_AUCTION
The after-hours single-price auction (시간외 단일가).
Definition types.hpp:2143
@ PRE_MARKET
Before the open, at the previous session's close (장전 시간외).
Definition types.hpp:2139
@ GTP
NXT's GTP session.
Definition types.hpp:2147
constexpr std::array< OrderSide, 2 > all_order_sides
Every OrderSide, in declaration order.
Definition types.hpp:1980
constexpr std::array< OrderSession, 9 > all_order_sessions
Every OrderSession, in declaration order.
Definition types.hpp:2151
Venue
A trading venue: an exchange, or the combined view across exchanges.
Definition types.hpp:45
constexpr std::array< TimeInForce, 4 > all_times_in_force
Every TimeInForce, in declaration order.
Definition types.hpp:2099
bool decimal_less(const Decimal64 &lhs, const Decimal64 &rhs)
Compares two decimals numerically, whatever their scales.
Definition types.hpp:926
TimeInForce
How long an order stays valid and what happens to an unfilled remainder.
Definition types.hpp:2088
@ FILL_OR_KILL
Fills entirely and immediately, or not at all.
Definition types.hpp:2095
@ DAY
Rests until the session ends; an unfilled remainder is cancelled then.
Definition types.hpp:2091
@ IMMEDIATE_OR_CANCEL
Fills what it can immediately and cancels the remainder.
Definition types.hpp:2093
OrderSide
The side of an order: its economic direction, buy or sell.
Definition types.hpp:1974
std::string format_iso8601_utc(std::chrono::system_clock::time_point value)
Formats an instant as an ISO 8601 timestamp in UTC, such as 2026-10-06T00:30:00Z.
Definition types.hpp:2741
constexpr std::array< Country, 2 > all_countries
Every Country, in declaration order.
Definition types.hpp:38
Identifies an instrument: its country, venue and symbol.
Definition types.hpp:85
Country country_
The listing country, which selects the symbol convention and the price grid.
Definition types.hpp:87
Venue venue_
The venue that is part of the identity (two venues are two instruments).
Definition types.hpp:93
std::string symbol_
The symbol as the venue spells it, such as "005930".
Definition types.hpp:95
A journal file's bytes, and whether they could be read.
JournalReadStatus status_
Whether the file was read.
std::string text_
The contents; empty unless status_ is READ.
std::string detail_
What went wrong, for the operator; empty on success.
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
Decimal64 quantity_
The quantity, which recovery matches against.
Definition journal.hpp:514
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
std::optional< Decimal64 > baseline_
On a serialized runner's placement, the instrument's net holding the order was decided against; on a ...
Definition journal.hpp:525
bool requires_operator_
Whether only an operator may resolve this instruction.
Definition journal.hpp:539
std::string scope_
The broker and account the instruction belongs to, such as "kis:live:12345678-01".
Definition journal.hpp:546
JournalAction action_
Whether the instruction is a placement or a cancellation.
Definition journal.hpp:490
OrderSession session_
The session.
Definition journal.hpp:504
TimeInForce time_in_force_
The time in force.
Definition journal.hpp:502
std::shared_ptr< const RunRecord > run_
What the line says about a run budget's ledger; null on a line of a runner without one,...
Definition journal.hpp:551
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