algotradelib 0.0.0.9000
C++ header-only library for algorithmic trading
Loading...
Searching...
No Matches
order_updates.hpp
1#pragma once
2
3#include <algorithm>
4#include <cstddef>
5#include <optional>
6#include <unordered_map>
7#include <utility>
8#include <vector>
9
10#include "../core/types.hpp"
11
12namespace algotradelib {
13namespace runner {
14
15namespace order_update_detail {
16
35inline bool same_number(const Decimal64& lhs, const Decimal64& rhs) {
36 return !decimal_less(lhs, rhs) && !decimal_less(rhs, lhs);
37}
38
40inline bool same_number(const std::optional<Decimal64>& lhs, const std::optional<Decimal64>& rhs) {
41 if (lhs.has_value() != rhs.has_value()) {
42 return false;
43 }
44 return !lhs.has_value() || same_number(*lhs, *rhs);
45}
46
54inline bool same_observable_state(const OrderSnapshot& lhs, const OrderSnapshot& rhs) {
55 return lhs.status_ == rhs.status_ && same_number(lhs.execution_.filled_quantity_, rhs.execution_.filled_quantity_) &&
56 same_number(lhs.price_, rhs.price_) && same_number(lhs.trigger_price_, rhs.trigger_price_) &&
57 same_number(lhs.quantity_, rhs.quantity_) && same_number(lhs.order_amount_, rhs.order_amount_) &&
58 lhs.canceled_at_ == rhs.canceled_at_;
59}
60
61} // namespace order_update_detail
62
91template <typename Broker>
93public:
105 std::vector<OrderSnapshot> changed(const std::vector<WorkingOrder<Broker>>& rows) {
106 return observe(rows, /*report=*/true);
107 }
108
114 void adopt(const std::vector<WorkingOrder<Broker>>& rows) {
115 observe(rows, /*report=*/false);
116 }
117
122 std::size_t untracked_rows() const noexcept {
123 return untracked_;
124 }
125
131 std::size_t tracked_orders() const noexcept {
132 return tracked_.size();
133 }
134
140 std::size_t contradicted_rows() const noexcept {
141 return contradicted_;
142 }
143
144private:
145 // One order's last observed state, against which the next listing is compared.
146 struct Tracked {
147 OrderRef<Broker> ref_;
148 OrderSnapshot last_;
149 // Set when this listing stated the same order twice and the two readings disagreed.
150 bool contradicted_{false};
151 };
152
153 // Runs one observation, reporting differences or silently adopting them.
154 //
155 // Two passes, and the split is what keeps the duplicate rule honest. The first reduces the
156 // listing to one entry per reference; only then does the second decide what changed, so a
157 // contradiction found on the listing's last row still suppresses a report the first row would
158 // otherwise have earned.
159 std::vector<OrderSnapshot> observe(const std::vector<WorkingOrder<Broker>>& rows, bool report) {
160 // The listing's first `same` rows are the first `same` tracked orders again (see `unchanged_prefix`).
161 const std::size_t same = unchanged_prefix(rows);
162 if (same == rows.size() && same == tracked_.size()) {
163 return {};
164 }
165 std::vector<Tracked> next;
166 next.reserve(rows.size());
167 // Where each reference sits, in this listing (`next`) and in the previous one (`tracked_`), so a
168 // long listing is read once and not once per row. Both are looked up and never iterated: the
169 // order of `next`, and so of the updates, is the listing's. Built here from the vectors each
170 // time, so nothing has to be kept in step with `tracked_`; a reference maps to the first entry
171 // that has it, which is the one a scan would find.
172 //
173 // The first `same` rows become `next[0..same)`, each with the reference of `tracked_` at the same
174 // place: they are neither reserved nor without a reference, and tracked references are distinct.
175 // A later row with one of those references is their duplicate in `built`, never a new entry, so
176 // no new entry can match `tracked_[0..same)` and `held_at` leaves them out.
177 std::unordered_map<OrderRef<Broker>, std::size_t> built;
178 built.reserve(rows.size());
179 std::unordered_map<OrderRef<Broker>, std::size_t> held_at;
180 held_at.reserve(tracked_.size() - same);
181 for (std::size_t at = same; at < tracked_.size(); ++at) {
182 held_at.emplace(tracked_[at].ref_, at);
183 }
184
185 for (const auto& row : rows) {
186 // This library's own arithmetic rather than something a broker stated, and the contract is
187 // about what a broker stated. Neither caller passes one today.
188 if (row.reserved_) {
189 continue;
190 }
191 if (row.ref_.primary_.empty() && row.ref_.secondary_.empty()) {
192 ++untracked_;
193 continue;
194 }
195 const auto [at, first] = built.try_emplace(row.ref_, next.size());
196 if (first) {
197 next.push_back(Tracked{row.ref_, row.order_, false});
198 continue;
199 }
200 // One reference, one entry: a duplicated row must not become two events (and two orders).
201 auto& already = next[at->second];
202 if (!order_update_detail::same_observable_state(already.last_, row.order_)) {
203 // Two readings that disagree: report neither, and count it.
204 already.contradicted_ = true;
205 }
206 }
207
208 std::vector<OrderSnapshot> updates;
209 for (std::size_t at = 0; at < next.size(); ++at) {
210 const auto& entry = next[at];
211 if (entry.contradicted_) {
212 ++contradicted_;
213 continue;
214 }
215 if (at < same) {
216 // Tracked at this place, in the same observable state: nothing to report.
217 continue;
218 }
219 const auto found = held_at.find(entry.ref_);
220 const Tracked* held = found == held_at.end() ? nullptr : &tracked_[found->second];
221 const bool differs = held == nullptr || !order_update_detail::same_observable_state(held->last_, entry.last_);
222 if (report && differs) {
223 updates.push_back(entry.last_);
224 }
225 }
226
227 // A contradicted order keeps no baseline, because there is no reading of it this listing could
228 // settle on. The next listing that states it once reports it afresh.
229 next.erase(
230 std::remove_if(
231 next.begin(), next.end(),
232 [](const Tracked& entry) {
233 return entry.contradicted_;
234 }
235 ),
236 next.end()
237 );
238 tracked_ = std::move(next);
239 return updates;
240 }
241
242 // How many leading rows are the tracked orders at the same places again: not reserved, the same reference,
243 // the same observable state. When that is every row and every tracked order, the full pass would report
244 // nothing and count nothing, and `observe` returns at once; the tracked snapshots are then kept rather than
245 // replaced, since they differ only in fields `same_observable_state` ignores and are only ever compared.
246 std::size_t unchanged_prefix(const std::vector<WorkingOrder<Broker>>& rows) const {
247 const std::size_t limit = std::min(rows.size(), tracked_.size());
248 std::size_t at = 0;
249 while (
250 at < limit && !rows[at].reserved_ && rows[at].ref_ == tracked_[at].ref_ &&
251 order_update_detail::same_observable_state(tracked_[at].last_, rows[at].order_)
252 ) {
253 ++at;
254 }
255 return at;
256 }
257
258 std::vector<Tracked> tracked_;
259 std::size_t untracked_{0};
260 std::size_t contradicted_{0};
261};
262
263} // namespace runner
264} // namespace algotradelib
Turns successive working-order listings into order updates: the rows that changed since the previous ...
std::size_t contradicted_rows() const noexcept
Returns how many times a listing stated one order twice with disagreeing readings (and so it was not ...
std::size_t untracked_rows() const noexcept
Returns how many rows had an empty reference, and so were never reported.
void adopt(const std::vector< WorkingOrder< Broker > > &rows)
Takes a listing as the baseline without reporting anything (such as the startup read,...
std::vector< OrderSnapshot > changed(const std::vector< WorkingOrder< Broker > > &rows)
Compares a listing with the previous one and returns the rows that changed.
std::size_t tracked_orders() const noexcept
Returns how many orders the watch is tracking.
Runs a strategy: the runner, the polling loop, the order journal, and stopping.
Definition clock.hpp:7
The library: broker-neutral types (core), and the modules below.
bool decimal_less(const Decimal64 &lhs, const Decimal64 &rhs)
Compares two decimals numerically, whatever their scales.
Definition types.hpp:926
A broker's reference to one order, used to amend or cancel it.
Definition types.hpp:2402
The state of one order, as a broker listing reported it.
Definition types.hpp:2299
An order still open to modification or cancellation.
Definition types.hpp:2582