3#include "./journal.hpp"
5#include <algotradelib/core>
7#include <boost/crc.hpp>
8#include <boost/json.hpp>
35namespace json = boost::json;
37namespace journal_detail {
56inline bool sync_to_disk(std::FILE* handle)
noexcept {
58 return ::_commit(::_fileno(handle)) == 0;
60 return ::fsync(::fileno(handle)) == 0;
68inline bool flush_to_disk(std::FILE* handle)
noexcept {
69 return std::fflush(handle) == 0 && sync_to_disk(handle);
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;
117inline bool has_field(
const json::object& row, std::string_view key) {
118 return row.if_contains(key) !=
nullptr;
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()) {
127 return std::string(value->as_string());
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()) {
135 return std::string(value->as_string());
145inline constexpr std::string_view country_name(
Country country)
noexcept {
159 return !country_name(country).empty();
162 "all_countries must list every Country"
166inline constexpr std::string_view venue_name(
Venue venue)
noexcept {
168 case Venue::UNSPECIFIED:
169 return "UNSPECIFIED";
174 case Venue::COMBINED:
190inline std::optional<Venue> known_venue_from(std::string_view text)
noexcept {
195inline constexpr std::string_view side_name(
OrderSide side)
noexcept {
199 case OrderSide::SELL:
209 return !side_name(side).empty();
212 "all_order_sides must list every OrderSide"
223inline constexpr std::string_view order_type_name(
OrderType type)
noexcept {
230 return "CONDITIONAL_LIMIT";
234 return "PRIMARY_LIMIT";
240 return "CLOSING_PRICE";
241 case OrderType::UNKNOWN:
251 return !order_type_name(type).empty();
254 "all_order_types must list every OrderType"
258inline constexpr std::string_view time_in_force_name(
TimeInForce condition)
noexcept {
266 case TimeInForce::UNKNOWN:
276 return !time_in_force_name(condition).empty();
279 "all_times_in_force must list every TimeInForce"
283inline constexpr std::string_view order_session_name(
OrderSession session)
noexcept {
288 return "OPENING_AUCTION";
290 return "CLOSING_AUCTION";
294 return "AFTER_HOURS";
296 return "AFTER_HOURS_AUCTION";
298 return "AFTER_MARKET";
301 case OrderSession::UNKNOWN:
311 return !order_session_name(session).empty();
314 "all_order_sessions must list every OrderSession"
349inline std::optional<Decimal64> known_decimal_from(std::string_view text)
noexcept {
352 }
catch (
const std::exception&) {
358inline std::optional<Currency> known_currency_from(std::string_view text)
noexcept {
361 }
catch (
const std::exception&) {
366inline std::optional<Country> known_country_from(std::string_view text)
noexcept {
370inline std::optional<OrderSide> known_side_from(std::string_view text)
noexcept {
374inline std::optional<OrderType> known_order_type_from(std::string_view text)
noexcept {
378inline std::optional<TimeInForce> known_time_in_force_from(std::string_view text)
noexcept {
382inline std::optional<OrderSession> known_order_session_from(std::string_view text)
noexcept {
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);
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();
408inline std::optional<std::string> salvage_string(std::string_view line, std::string_view key) {
410 needle.reserve(key.size() + 4);
414 const auto at = line.find(needle);
415 if (at == std::string_view::npos) {
418 const auto begin = at + needle.size();
422 while (end < line.size() && line[end] !=
'"') {
423 end += line[end] ==
'\\' ? 2 : 1;
425 if (end >= line.size()) {
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()) {
436 return std::string(quoted.as_string());
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();
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];
465inline constexpr std::string_view kChecksumMember =
",\"crc\":\"";
468inline constexpr std::size_t kChecksumSuffixSize = kChecksumMember.size() + 8 + 2;
471inline bool ends_in_checksum(std::string_view line) {
472 if (line.size() <= kChecksumSuffixSize) {
475 const auto suffix = line.substr(line.size() - kChecksumSuffixSize);
476 if (suffix.substr(0, kChecksumMember.size()) != kChecksumMember || suffix.substr(kChecksumSuffixSize - 2) !=
"\"}") {
479 for (
const char digit : suffix.substr(kChecksumMember.size(), 8)) {
480 if (!((digit >=
'0' && digit <=
'9') || (digit >=
'a' && digit <=
'f'))) {
493inline bool checksum_matches(std::string_view line) {
494 std::string body(line.substr(0, line.size() - kChecksumSuffixSize));
496 const auto stated = line.substr(line.size() - kChecksumSuffixSize + kChecksumMember.size(), 8);
497 return checksum_text(line_checksum(body)) == stated;
509inline bool known_entry_key(std::string_view key) {
510 static constexpr std::string_view known[] = {
534 for (
const auto candidate : known) {
535 if (candidate == key) {
546inline bool run_entry_key(std::string_view key) {
547 static constexpr std::string_view known[] = {
558 for (
const auto candidate : known) {
559 if (candidate == key) {
570class DescriptorOwner {
576 explicit DescriptorOwner(
int descriptor) noexcept : descriptor_(descriptor) {}
580 if (descriptor_ >= 0) {
581 ::close(descriptor_);
585 DescriptorOwner(
const DescriptorOwner&) =
delete;
586 DescriptorOwner& operator=(
const DescriptorOwner&) =
delete;
592 int get() const noexcept {
600 int release() noexcept {
601 const int descriptor = descriptor_;
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};
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_;
644inline FileStamp stamp_of(
const struct stat& status)
noexcept {
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;
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;
671 return "algotradelib-order-journal";
683 row[
"scope"] = std::string(scope);
685 row[
"integrity"] =
"crc32";
686 return json::serialize(row);
695 boost::system::error_code error;
696 const auto value = json::parse(line, error);
697 if (error || !value.is_object()) {
700 const auto* integrity = value.as_object().if_contains(
"integrity");
701 return integrity !=
nullptr && integrity->is_string() && std::string_view(integrity->as_string()) ==
"crc32";
710 boost::system::error_code error;
711 const auto value = json::parse(line, error);
712 if (error || !value.is_object()) {
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()) {
720 return journal_detail::string_field(row,
"scope");
733namespace journal_detail {
736inline void write_order_keys(json::object& row,
const JournalEntry& entry) {
738 row[
"venue"] = std::string(journal_detail::venue_name(entry.
instrument_.
venue_));
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_));
751 row[
"route"] = std::string(journal_detail::venue_name(*entry.
venue_));
755 row[
"price"] = entry.
price_->str();
765 row[
"baseline"] = entry.
baseline_->str();
770inline void write_run_keys(json::object& row,
const RunRecord& record) {
771 row[
"run"] = record.run_;
775 if (!record.given_.empty()) {
776 row[
"given"] = record.given_;
778 if (!record.of_.empty()) {
779 row[
"of"] = record.of_;
781 if (record.amount_) {
782 row[
"amount"] = record.amount_->amount_.str();
783 row[
"currency"] = record.amount_->currency_.str();
785 if (record.filled_) {
786 row[
"filled"] = record.filled_->str();
789 row[
"fee"] = record.fee_->str();
791 if (record.fee_estimated_) {
792 row[
"fee_estimated"] =
true;
808 row[
"id"] = entry.
id_;
814 journal_detail::write_order_keys(row, entry);
819 row[
"at"] = journal_detail::micros_of(entry.
recorded_at_);
828 row[
"requires_operator"] =
true;
830 if (!entry.
scope_.empty()) {
831 row[
"scope"] = entry.
scope_;
835 journal_detail::write_run_keys(row, *entry.
run_);
840 auto line = json::serialize(row);
841 const auto checksum = journal_detail::checksum_text(journal_detail::line_checksum(line));
843 line.append(journal_detail::kChecksumMember);
859 entry.
id_ =
"unknown~truncated";
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));
867namespace journal_detail {
872 bool present_{
false};
874 bool unreadable_{
false};
877 bool has_run_{
false};
878 bool has_amount_{
false};
879 bool has_currency_{
false};
880 bool has_fee_estimated_{
false};
884inline RunKeys run_keys_from(
const json::object& row) {
886 const auto text = [&](std::string_view key, std::string& out) {
887 if (!has_field(row, key)) {
890 keys.present_ =
true;
891 const auto value = readable_string(row, key);
893 keys.unreadable_ =
true;
899 const auto number = [&](std::string_view key, std::optional<Decimal64>& out) {
901 if (text(key, value)) {
902 out = known_decimal_from(value);
903 keys.unreadable_ = keys.unreadable_ || !out;
906 keys.has_run_ = text(
"run", keys.record_.run_);
908 if (text(
"ledger", kind)) {
910 keys.unreadable_ = keys.unreadable_ || !keys.record_.kind_;
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();
918 std::optional<Currency> currency;
919 if (text(
"currency", code)) {
920 currency = known_currency_from(code);
921 keys.unreadable_ = keys.unreadable_ || !currency;
923 keys.has_currency_ = currency.has_value();
924 if (amount && currency) {
925 keys.record_.amount_ = Money{*amount, *currency};
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;
935 keys.record_.fee_estimated_ = estimated->as_bool();
942inline bool booking_figures_hold(
const RunRecord& record) {
944 const auto& filled = *record.filled_;
945 const auto& amount = record.amount_->amount_;
956 const auto& record = keys.record_;
959 !record.given_.empty() || !record.of_.empty()
964 keys.has_amount_ || keys.has_currency_ || record.filled_ || record.fee_ || keys.has_fee_estimated_;
969 booking_figures_hold(record);
976inline std::optional<JournalEntry> ledger_entry_from(
977 const json::object& row,
JournalOutcome outcome,
bool marked, std::int64_t at,
const RunKeys& keys
979 static constexpr std::string_view order_keys[] = {
994 for (
const auto key : order_keys) {
995 if (has_field(row, key)) {
999 const auto id = readable_string(row,
"id");
1000 const auto& record = keys.record_;
1003 !record.kind_ || !record.amount_
1005 return std::nullopt;
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();
1014 return std::nullopt;
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);
1038 boost::system::error_code error;
1039 const auto value = json::parse(line, error);
1040 if (error || !value.is_object()) {
1041 return std::nullopt;
1043 const auto& row = value.as_object();
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();
1050 const auto at = row.if_contains(
"at");
1054 const bool epoch = marked && at !=
nullptr && at->is_int64() && at->as_int64() == 0;
1056 !action || !outcome || at ==
nullptr || !at->is_int64() ||
1057 (!epoch && !journal_detail::plausible_instant(at->as_int64(), journal_detail::has_field(row,
"crc")))
1061 return std::nullopt;
1082 const auto read = [&row](std::string_view key) {
1083 return journal_detail::readable_string(row, key);
1089 const auto unusable = [&row](std::string_view key,
bool parsed) {
1090 return journal_detail::has_field(row, key) && !parsed;
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{};
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())) {
1122 if (!checksum_holds || unknown_key) {
1123 return std::nullopt;
1130 std::optional<journal_detail::RunKeys> run;
1132 run = journal_detail::run_keys_from(row);
1133 if (run->unreadable_) {
1134 return std::nullopt;
1137 return journal_detail::ledger_entry_from(row, *outcome, marked, at->as_int64(), *run);
1139 if (!journal_detail::run_keys_fit_order_line(*action, *outcome, *run)) {
1140 return std::nullopt;
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);
1156 const bool damaged =
1161 !symbol || !country || !venue || !side || !type || !quantity ||
1163 unusable(
"time_in_force", condition.has_value()) || unusable(
"session", session.has_value()) ||
1167 unusable(
"price", price.has_value()) ||
1170 unusable(
"trigger", trigger.has_value()) || unusable(
"baseline", baseline.has_value()) ||
1173 !checksum_holds || unknown_key;
1189 if (run && run->present_) {
1190 return std::nullopt;
1193 const auto id = journal_detail::string_field(row,
"id");
1194 unattributable.id_ = (
id.empty() ? std::string(
"unknown") :
id) +
"~damaged";
1195 unattributable.action_ = *action;
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;
1210 entry.
id_ = journal_detail::string_field(row,
"id");
1214 entry.
side_ = *side;
1215 entry.
type_ = *type;
1228 entry.
venue_ = journal_detail::known_venue_from(journal_detail::string_field(row,
"route"));
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");
1244 entry.
scope_ = journal_detail::string_field(row,
"scope");
1245 if (run && run->present_) {
1246 entry.
run_ = std::make_shared<const RunRecord>(run->record_);
1262 const std::string needle =
"\"" + std::string(key) +
"\":";
1263 const auto at = line.find(needle);
1264 if (at == std::string_view::npos) {
1267 return line.find(
',', at + needle.size()) != std::string_view::npos;
1282 const auto symbol = journal_detail::salvage_string(line,
"symbol");
1283 if (!symbol || symbol->empty()) {
1284 return std::nullopt;
1291 const auto id = journal_detail::salvage_string(line,
"id");
1292 entry.
id_ = (
id ? *id : std::string(
"unknown")) +
"~truncated";
1310 const auto salvaged = [&line](std::string_view key,
const char* fallback) {
1311 const auto text = journal_detail::salvage_string(line, key);
1313 return std::optional<std::string>(*text);
1315 return salvage_damaged(line, key) ? std::optional<std::string>() : std::optional<std::string>(fallback);
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{};
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) {
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;
1339 entry.
side_ = *side;
1340 entry.
type_ = *type;
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")) {
1348 if (
const auto value = journal_detail::known_decimal_from(*quantity)) {
1352 if (
const auto price = journal_detail::salvage_string(line,
"price")) {
1353 if (
const auto value = journal_detail::known_decimal_from(*price)) {
1357 if (
const auto trigger = journal_detail::salvage_string(line,
"trigger")) {
1358 if (
const auto value = journal_detail::known_decimal_from(*trigger)) {
1362 entry.
detail_ =
"recovered from a truncated journal line; only an operator can resolve it";
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;
1378 if (handle ==
nullptr) {
1379 if (errno == ENOENT) {
1388 bytes.
detail_ =
"the order journal at " + path +
" exists and could not be opened for reading";
1393 while (
const auto read = std::fread(buffer, 1,
sizeof(buffer), handle.get())) {
1394 bytes.
text_.append(buffer, read);
1396 if (std::ferror(handle.get()) != 0) {
1400 bytes.
detail_ =
"the order journal at " + path +
" could not be read to the end";
1401 bytes.
text_.clear();
1408namespace journal_detail {
1413 bool seen_checksum_{
false};
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) {
1434 const std::string_view line(text.data() + begin, end - begin);
1440 const auto unreadable = [&replay](
const char* why) {
1441 ++replay.unreadable_lines_;
1442 if (replay.detail_.empty()) {
1443 replay.detail_ = why;
1447 unreadable(
"the journal contains an empty line, which this library never writes");
1451 if (replay.has_header_ || !replay.entries_.empty() || replay.unreadable_lines_ > 0) {
1453 "the journal contains a header after its first line, which this library never "
1460 replay.has_header_ =
true;
1461 replay.scope_ = std::move(*scope);
1466 const bool checksummed = ends_in_checksum(line);
1467 if (carry.seen_checksum_ && !checksummed) {
1473 ++replay.unreadable_lines_;
1474 if (replay.detail_.empty()) {
1476 "a journal line without a checksum follows a checksummed one, so it was changed after it "
1481 carry.seen_checksum_ = carry.seen_checksum_ || checksummed;
1483 replay.entries_.push_back(std::move(*entry));
1488 ++replay.unreadable_lines_;
1489 if (replay.detail_.empty()) {
1490 replay.detail_ =
"the journal contains a line this library did not write";
1503inline void parse_torn_tail(std::string_view tail, JournalReplay& replay) {
1506 replay.truncated_tail_ =
true;
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));
1512 replay.detail_ =
"the final journal line was truncated and named no instrument; something was in flight";
1526inline bool parse_bytes_into(
const JournalBytes& bytes, JournalReplay& replay, ParseCarry& carry) {
1527 replay.
status_ = bytes.status_;
1529 replay.detail_ = bytes.detail_;
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);
1556 journal_detail::ParseCarry carry;
1557 journal_detail::parse_bytes_into(bytes, replay, carry);
1611 : path_(std::move(
path)), scope_(std::move(
scope)), handle_(nullptr, &closer) {
1612 if (scope_.empty()) {
1614 rejection_ =
"an order journal must name the broker and account it belongs to";
1618 if (!claim_file()) {
1622 handle_.reset(std::fopen(path_.c_str(),
"ab"));
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) +
")";
1634 if (!lock(descriptor.get())) {
1637 if (!claim_file()) {
1641 handle_.reset(::fdopen(descriptor.get(),
"ab"));
1643 descriptor.release();
1645 const int error = errno;
1646 rejection_ =
"the journal at " + path_ +
" could not be opened for appending (" + std::strerror(error) +
")";
1652 if (needs_header_ && !write_header()) {
1655 if (!pending_repair_.empty()) {
1665 return handle_ !=
nullptr;
1681 const std::string&
path() const noexcept {
1689 const std::string&
scope() const noexcept {
1718 auto stamped = entry;
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) {
1731 note_write_ended(line.size());
1732 if (!journal_detail::sync_to_disk(handle_.get())) {
1752 if (continuable_ &&
open() && continue_replay()) {
1768 void read_whole()
const {
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;
1779 if (!journal_detail::parse_bytes_into(bytes, kept_, carry_) || !stated) {
1782 struct stat after{};
1783 const auto stamp = journal_detail::stamp_of(before);
1785 ::stat(path_.c_str(), &after) != 0 || !(stamp == journal_detail::stamp_of(after)) ||
1786 static_cast<std::size_t
>(stamp.size_) != bytes.text_.size()
1791 parsed_to_ = bytes.text_.size();
1792 continuable_ =
true;
1801 bool continue_replay()
const {
1803 if (::stat(path_.c_str(), &now) != 0 || !(journal_detail::stamp_of(now) == stamp_)) {
1806 const auto size =
static_cast<std::size_t
>(now.st_size);
1807 if (size == parsed_to_) {
1810 if (size < parsed_to_) {
1813 journal_detail::DescriptorOwner reader(
::open(path_.c_str(), O_RDONLY | O_CLOEXEC));
1814 if (reader.get() < 0) {
1817 std::string appended(size - parsed_to_,
'\0');
1818 std::size_t got = 0;
1819 while (got < appended.size()) {
1821 ::pread(reader.get(), &appended[got], appended.size() - got,
static_cast<off_t
>(parsed_to_ + got));
1822 if (read < 0 && errno == EINTR) {
1828 got +=
static_cast<std::size_t
>(read);
1830 struct stat read_status{};
1832 appended.back() !=
'\n' || ::fstat(reader.get(), &read_status) != 0 ||
1833 !(journal_detail::stamp_of(read_status) == stamp_)
1838 continuable_ =
false;
1839 journal_detail::parse_complete_lines(appended, kept_, carry_);
1841 continuable_ =
true;
1848 void note_write_begins() {
1851 if (continuable_ && (::fstat(::fileno(handle_.get()), &now) != 0 || !(journal_detail::stamp_of(now) == stamp_))) {
1852 continuable_ =
false;
1860 void note_write_ended([[maybe_unused]] std::size_t written) {
1865 ::fstat(::fileno(handle_.get()), &now) == 0 &&
1866 static_cast<std::size_t
>(now.st_size) >=
static_cast<std::size_t
>(stamp_.size_) + written
1868 stamp_ = journal_detail::stamp_of(now);
1870 continuable_ =
false;
1877 void forget_kept() noexcept {
1879 continuable_ =
false;
1901 if (!
replay.readable()) {
1905 rejection_ =
replay.detail_.empty() ?
"the journal at " + path_ +
" exists and cannot be read" :
replay.detail_;
1911 needs_header_ =
true;
1914 if (!
replay.has_header_) {
1915 rejection_ =
"the journal at " + path_ +
" has no header, so the account it belongs to cannot be established";
1918 if (
replay.scope_ != scope_) {
1919 rejection_ =
"the journal at " + path_ +
" belongs to " +
replay.scope_ +
", not to " + scope_;
1926 bool write_header() {
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())) {
1932 rejection_ =
"the journal header at " + path_ +
" could not be written";
1935 needs_header_ =
false;
1940 static void closer(std::FILE* handle)
noexcept {
1941 if (handle !=
nullptr) {
1942 std::fclose(handle);
1951 void repair_torn_tail() {
1953 if (!
replay.truncated_tail_) {
1956 const auto tail = read_torn_tail(path_);
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";
1966 void finish_repair() {
1970 std::string repair =
"\n";
1971 repair += pending_repair_;
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())) {
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";
1982 pending_repair_.clear();
1987 bool lock(
int descriptor) {
1988 if (::flock(descriptor, LOCK_EX | LOCK_NB) == 0) {
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";
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) {
2010 while (
const auto read = std::fread(buffer, 1,
sizeof(buffer), reader.get())) {
2011 text.append(buffer, read);
2013 const auto last = text.rfind(
'\n');
2014 return last == std::string::npos ? text : text.substr(last + 1);
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};
2025 mutable JournalReplay kept_;
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};
Currency()
Constructs Korean won.
std::string str() const
Formats the value as a decimal string.
static Decimal64 parse(std::string_view input)
Parses a decimal string exactly (no binary floating point).
Either a value or a BrokerError.
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.
std::optional< RunRecordKind > run_record_kind_from(std::string_view text) noexcept
Parses a record kind's name.
std::optional< JournalOutcome > journal_outcome_from(std::string_view text) noexcept
Parses an outcome's name.
constexpr std::string_view journal_outcome_name(JournalOutcome outcome) noexcept
Returns an outcome's name as written to the journal ("pending", ...).
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.
@ MISSING
No such file: a first start, nothing owed.
@ READ
The file was read in full.
@ UNREADABLE
The file exists and could not be read; its contents are unknown.
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").
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_).
@ FILL
An operator's booking of a placement released without one (runner::Runner::book_run_fill).
constexpr std::string_view run_record_kind_name(RunRecordKind kind) noexcept
Returns a record kind's name as written to the journal ("open", ...).
JournalOutcome
What a journal line says about an instruction.
@ CONFIRMED
A serialized runner accounted for the placement: holdings showed what it filled, its history showed i...
@ PENDING
Written before the send; whether the instruction exists is not yet known.
@ RECORDED
A run budget's ledger record (JournalAction::LEDGER); it answers no instruction.
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.
@ CANCEL
A cancellation of a resting order.
@ LEDGER
A record of a run budget's ledger (RunRecord), not an instruction: it sends nothing and names no orde...
std::optional< JournalAction > journal_action_from(std::string_view text) noexcept
Parses an action's name.
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.
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).
@ LIMIT
지정가: fills at the stated price or better.
@ BEST_LIMIT
최유리지정가: priced at the best quote on the opposite side.
@ PRIMARY_LIMIT
최우선지정가: priced at the best quote on the order's own side.
@ CONDITIONAL_LIMIT
조건부지정가: a limit that becomes a market order at the close.
@ MID_PRICE
중간가: priced at the midpoint of the spread.
@ STOP_LIMIT
스톱지정가: a limit released when a trigger price is reached.
@ CLOSING_PRICE
시간외종가: priced at a session's closing price.
@ MARKET
시장가: fills at whatever the book offers.
constexpr std::array< OrderType, 9 > all_order_types
Every OrderType, in declaration order.
Country
A country (market) the library supports.
OrderSession
The trading session an order is submitted into.
@ OPENING_AUCTION
The opening single-price auction (시가단일가; Toss OPG).
@ AFTER_HOURS
After the close, at that session's close (장후 시간외).
@ CLOSING_AUCTION
The closing auction (Toss CLS, a US limit-on-close).
@ REGULAR
The continuous regular session.
@ AFTER_MARKET
KRX's after-market session (애프터마켓).
@ AFTER_HOURS_AUCTION
The after-hours single-price auction (시간외 단일가).
@ PRE_MARKET
Before the open, at the previous session's close (장전 시간외).
constexpr std::array< OrderSide, 2 > all_order_sides
Every OrderSide, in declaration order.
constexpr std::array< OrderSession, 9 > all_order_sessions
Every OrderSession, in declaration order.
Venue
A trading venue: an exchange, or the combined view across exchanges.
constexpr std::array< TimeInForce, 4 > all_times_in_force
Every TimeInForce, in declaration order.
bool decimal_less(const Decimal64 &lhs, const Decimal64 &rhs)
Compares two decimals numerically, whatever their scales.
TimeInForce
How long an order stays valid and what happens to an unfilled remainder.
@ FILL_OR_KILL
Fills entirely and immediately, or not at all.
@ DAY
Rests until the session ends; an unfilled remainder is cancelled then.
@ IMMEDIATE_OR_CANCEL
Fills what it can immediately and cancels the remainder.
OrderSide
The side of an order: its economic direction, buy or sell.
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.
constexpr std::array< Country, 2 > all_countries
Every Country, in declaration order.
Identifies an instrument: its country, venue and symbol.
Country country_
The listing country, which selects the symbol convention and the price grid.
Venue venue_
The venue that is part of the identity (two venues are two instruments).
std::string symbol_
The symbol as the venue spells it, such as "005930".
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.
std::string id_
Links an answering line to its PENDING line.
std::chrono::system_clock::time_point recorded_at_
When the line was written (for PENDING, before the request went out).
OrderType type_
The order type; recovery matches on type, time in force and session together.
Decimal64 quantity_
The quantity, which recovery matches against.
std::optional< Decimal64 > price_
The price, if the order has one.
JournalOutcome outcome_
What the line says about the instruction.
std::string detail_
Why an answering line says what it says, for the operator.
std::optional< Venue > venue_
The venue the order actually goes to, as the binding resolves it.
InstrumentId instrument_
The instrument (identity; the routing venue is venue_).
std::optional< Decimal64 > trigger_price_
The trigger price of a stop-limit order; empty otherwise (and on lines that predate it).
std::optional< Decimal64 > baseline_
On a serialized runner's placement, the instrument's net holding the order was decided against; on a ...
bool requires_operator_
Whether only an operator may resolve this instruction.
std::string scope_
The broker and account the instruction belongs to, such as "kis:live:12345678-01".
JournalAction action_
Whether the instruction is a placement or a cancellation.
OrderSession session_
The session.
TimeInForce time_in_force_
The time in force.
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,...
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...
The contents of a journal, including what could not be read.