algotradelib 0.0.0.9000
C++ header-only library for algorithmic trading
Loading...
Searching...
No Matches
example-order-journal.cpp
1// A runner killed with an order in flight, and the restart that finds out what happened.
2//
3// No broker, no credentials, no network, and no signal raised. The "crash" is a scope that ends
4// without the terminal line ever being written, which is exactly what a `SIGKILL` leaves on disk,
5// and the "restart" is a fresh ledger reading the file its predecessor left behind.
6//
7// The point it demonstrates is the one sentence the whole feature rests on: **an empty ledger does
8// not mean nothing is owed -- it means nothing is remembered.**
9//
10// Run it as:
11//
12// example-order-journal
13
14#include <algotradelib/runner>
15
16#include <chrono>
17#include <cstdio>
18#include <iostream>
19#include <string>
20#include <vector>
21
22namespace {
23
26
35using Clock = std::chrono::system_clock;
36
37InstrumentId samsung() {
38 return InstrumentId{Country::KR, Venue::COMBINED, "005930"};
39}
40
42Clock::time_point sent_at() {
43 return Clock::time_point{} + std::chrono::hours(24 * 20000);
44}
45
46strategy::PlannedOrder buy_ten() {
48 order.instrument_ = samsung();
49 order.side_ = OrderSide::BUY;
50 order.type_ = OrderType::LIMIT;
51 order.quantity_ = Decimal64::parse("10");
52 order.price_ = Decimal64::parse("70000");
53 return order;
54}
55
64template <typename Tag>
65class KilledExecutor {
66public:
67 runner::SendOutcome place(const strategy::PlannedOrder&) {
68 throw std::runtime_error("the process died with the request on the wire");
69 }
70 runner::SendOutcome cancel(const algotradelib::WorkingOrder<Tag>&) {
72 }
73};
74
76void show_journal(const std::string& path) {
77 std::FILE* handle = std::fopen(path.c_str(), "rb");
78 if (handle == nullptr) {
79 std::cout << " (no journal)\n";
80 return;
81 }
82 std::string text;
83 char buffer[1024];
84 while (const auto read = std::fread(buffer, 1, sizeof(buffer), handle)) {
85 text.append(buffer, read);
86 }
87 std::fclose(handle);
88
89 std::size_t begin = 0;
90 while (begin < text.size()) {
91 const auto end = text.find('\n', begin);
92 const auto stop = end == std::string::npos ? text.size() : end;
93 std::cout << " " << text.substr(begin, stop - begin);
94 if (end == std::string::npos) {
95 std::cout << " <- no newline: this write never finished";
96 }
97 std::cout << "\n";
98 if (end == std::string::npos) {
99 break;
100 }
101 begin = end + 1;
102 }
103}
104
106OrderSnapshot listed_order() {
107 OrderSnapshot snapshot;
108 snapshot.order_id_ = "KRX-4412";
109 snapshot.instrument_ = samsung();
110 snapshot.side_ = OrderSide::BUY;
111 snapshot.type_ = OrderType::LIMIT;
112 snapshot.status_ = OrderStatus::PENDING;
113 snapshot.quantity_ = Decimal64::parse("10");
114 snapshot.price_ = Decimal64::parse("70000");
115 snapshot.ordered_at_ = sent_at();
116 return snapshot;
117}
118
119} // namespace
120
121int main() {
122 const std::string path = "example-order-journal.jsonl";
123 std::remove(path.c_str());
124
125 std::cout << "1. A runner sends one order, and is killed before it learns the outcome.\n\n";
126 {
127 runner::FileJournal journal(path, "example:demo-account");
128 if (!journal.open()) {
129 std::cout << "could not open " << path << " for appending: " << journal.rejection() << "\n";
130 return 1;
131 }
133 KilledExecutor<runner::DryTag>{}, journal, runner::ManualClock{sent_at()}
134 };
135 executor.set_id_prefix("run-a");
136 try {
137 executor.place(buy_ten());
138 } catch (const std::exception& error) {
139 std::cout << " " << error.what() << "\n\n";
140 }
141 }
142
143 std::cout << " What the file holds:\n";
144 show_journal(path);
145 std::cout
146 << "\n One line, and it says `pending`. The order may be resting on the exchange or may\n"
147 << " never have arrived. Nothing in this process knows which, and the process is gone.\n\n";
148
149 std::cout << "2. A new process starts. Its ledger is empty.\n\n";
151 std::cout
152 << " Before recovery, may it trade " << samsung().symbol_ << "? "
153 << (ledger.requires_reconcile(samsung()) ? "no" : "yes") << " <- and that is the trap\n";
154
155 const auto recovery = runner::recover_into(runner::read_journal_file(path), ledger);
156 std::cout << " After recovery: " << (ledger.requires_reconcile(samsung()) ? "no" : "yes") << "\n";
157 std::cout
158 << " Instruments marked: " << recovery.marked_.size() << ", instructions owed: " << recovery.open_.size()
159 << "\n\n";
160
161 std::cout << "3. The broker's own order list is read, and it is the only thing that resolves.\n\n";
162
163 // Too soon. An accepted write does not appear in a listing instantly, so an absent row this early
164 // is not evidence that the order does not exist.
165 runner::FileJournal journal(path, "example:demo-account");
166 const auto early =
167 runner::reconcile_against(recovery.open_, {}, sent_at() + std::chrono::seconds(5), ledger, journal);
168 std::cout
169 << " Five seconds later, an empty listing: " << runner::match_verdict_name(early.matches_.front().verdict_)
170 << " -- still withheld\n";
171
172 // Later, the row is there. The order existed after all.
173 const auto settled =
174 runner::reconcile_against(recovery.open_, {listed_order()}, sent_at() + std::chrono::minutes(10), ledger, journal);
175 std::cout
176 << " Ten minutes later, the order is listed: " << runner::match_verdict_name(settled.matches_.front().verdict_)
177 << " as " << settled.matches_.front().order_id_ << "\n";
178 std::cout
179 << " May it trade " << samsung().symbol_ << " now? " << (ledger.requires_reconcile(samsung()) ? "no" : "yes")
180 << "\n\n";
181
182 std::cout << "4. The resolution is written back, so a second restart finds nothing owed.\n\n";
183 std::cout << " What the file holds now:\n";
184 show_journal(path);
185
187 const auto again = runner::recover_into(runner::read_journal_file(path), later);
188 std::cout
189 << "\n A third process recovers: instructions owed: " << again.open_.size() << ", may it trade "
190 << samsung().symbol_ << "? " << (later.requires_reconcile(samsung()) ? "no" : "yes") << "\n\n";
191
192 std::cout
193 << "Had the listing stayed empty past the window, the verdict would have been `not_placed`:\n"
194 << "no order found, and the ledger would have cleared just the same. A serialized runner goes\n"
195 << "on owing such an order all the same, since a list can lag an order it accepted. Had two\n"
196 << "rows matched, it would have been `ambiguous`, nothing would clear, and an operator would\n"
197 << "decide. The one thing that never happens is a guess.\n";
198
199 std::remove(path.c_str());
200 return 0;
201}
An exact signed decimal: an int64 coefficient times 10^-scale.
Definition types.hpp:443
The order journal on disk: one JSON object per line, appended and flushed to disk (fsync) before appe...
The instruments with an order of unknown outcome, where nothing may be placed until the broker's orde...
bool requires_reconcile(const InstrumentId &id) const
Tests whether an instrument is waiting for reconciliation.
An executor wrapper that records each instruction in a journal before sending it.
Definition journal.hpp:842
void set_id_prefix(std::string prefix)
Sets the prefix of line ids.
Definition journal.hpp:868
SendOutcome place(const strategy::PlannedOrder &order)
Records and places one order.
Definition journal.hpp:939
A clock for tests: wait_for advances it instead of sleeping.
Definition clock.hpp:102
Runs a strategy: the runner, the polling loop, the order journal, and stopping.
Definition clock.hpp:7
JournalReplay read_journal_file(const std::string &path)
Reads and parses a journal file.
SendOutcome
What became of one instruction (a placement or a cancellation) an executor was asked to send.
Definition execution.hpp:30
@ ACCEPTED
The broker accepted the instruction (for a placement, the order exists).
Definition execution.hpp:32
RecoveryReport recover_into(const JournalReplay &replay, IndeterminacyLedger &ledger)
Marks the ledger for every instrument a journal left an instruction of unknown outcome for.
ReconcileReport reconcile_against(const std::vector< OpenInstruction > &open, const std::vector< OrderSnapshot > &rows, const JournalReplay &replay, std::chrono::system_clock::time_point now, IndeterminacyLedger &ledger, Journal &journal, const MatchWindow &window={}, std::string_view unplaced_note={})
Resolves what a broker listing settles, records it in the journal, and clears the ledger for each ins...
constexpr std::string_view match_verdict_name(MatchVerdict verdict) noexcept
Returns a verdict's lowercase name, such as "not_placed", for logs.
void stop(S &strategy, Ctx &context)
Calls strategy.on_stop(context) if the strategy declares on_stop; otherwise does nothing.
Definition concept.hpp:259
What a strategy sees and emits: events, intents, the portfolio, reconciliation and risk limits.
Definition concept.hpp:16
OrderStatus
Where an order stands in its lifecycle.
Definition types.hpp:2170
OrderType
How an order's price is decided (its price basis).
Definition types.hpp:1998
Country
A country (market) the library supports.
Definition types.hpp:32
Venue
A trading venue: an exchange, or the combined view across exchanges.
Definition types.hpp:45
OrderSide
The side of an order: its economic direction, buy or sell.
Definition types.hpp:1974
Identifies an instrument: its country, venue and symbol.
Definition types.hpp:85
The state of one order, as a broker listing reported it.
Definition types.hpp:2299
One order the runner is to place.
OrderType type_
The order type.
InstrumentId instrument_
The instrument to trade.
std::optional< Decimal64 > price_
The limit price, after clamping and rounding; empty for a market order.
Decimal64 quantity_
The quantity, after rounding onto the lot.