algotradelib 0.0.0.9000
C++ header-only library for algorithmic trading
Loading...
Searching...
No Matches
sellable_convention.hpp
1#pragma once
2
3#include "./portfolio.hpp"
4
5#include <algotradelib/core>
6
7#include <cstddef>
8#include <string_view>
9#include <utility>
10#include <vector>
11
12namespace algotradelib {
13namespace strategy {
14
31
37inline constexpr std::string_view sellable_convention_name(SellableConvention convention) noexcept {
38 switch (convention) {
40 return "undetermined";
42 return "net_of_resting";
44 return "gross_of_resting";
46 return "inconsistent";
47 }
48 return "undetermined";
49}
50
59 std::size_t net_{0};
61 std::size_t gross_{0};
62
68 SellableConvention verdict() const noexcept {
69 if (net_ > 0 && gross_ > 0) {
71 }
72 if (net_ > 0) {
74 }
75 if (gross_ > 0) {
77 }
79 }
80
85 std::size_t total() const noexcept {
86 return net_ + gross_;
87 }
88};
89
105template <typename Broker>
107public:
112 void observe(const Portfolio<Broker>& portfolio) {
113 // **A figure of unknown coverage teaches nothing about resting orders, and would teach something
114 // false.** This probe reads the *distance* between what is held and what is sellable and watches
115 // how that distance moves. Both numbers have to describe the same shares for the distance to mean
116 // anything: if `rmnd_qty` is account-wide while `trde_able_qty` covers one venue -- exactly what
117 // `SellableBasis::Coverage::UNESTABLISHED` means at Kiwoom -- the distance is a venue split, and a
118 // position moving between venues would read as a resting convention. So an unenforceable basis is
119 // skipped whole rather than judged, and the verdict stays `UNDETERMINED`, which is true.
120 for (const auto& position : portfolio.positions_) {
121 const auto reading = portfolio.sellable_reading_for(position.instrument_);
122 if (!reading.basis_.is_enforceable()) {
123 // **Skipped, and the baseline is dropped with it.** Merely ignoring the reading would leave the
124 // previous one pending, so the *next* enforceable reading would be compared against a
125 // baseline from before the gap -- and the distance would appear to move by whatever happened
126 // in between. A declared 100/100/0, an undeclared 100/70/0, then a declared 100/70/30 would
127 // record a confident NET_OF_RESTING across a window the probe never observed.
128 //
129 // Resolved per instrument rather than per portfolio, because a per-instrument inquiry's basis
130 // lands on its own row: checking only the snapshot's would discard every Toss reading.
131 forget(position.instrument_);
132 continue;
133 }
134 if (!position.sellable_quantity_) {
135 // The broker did not publish it, so there is nothing to learn from this position.
136 continue;
137 }
138 const auto resting = reported_resting(portfolio, position.instrument_);
139 const Reading now{position.quantity_, *position.sellable_quantity_, resting};
140 if (auto* previous = find(last_, position.instrument_)) {
141 judge(position.instrument_, *previous, now);
142 *previous = now;
143 continue;
144 }
145 last_.push_back({position.instrument_, now});
146 }
147 }
148
154 void forget(const InstrumentId& instrument) {
155 for (auto it = last_.begin(); it != last_.end(); ++it) {
156 if (it->first == instrument) {
157 last_.erase(it);
158 return;
159 }
160 }
161 }
162
168 SellableEvidence evidence(const InstrumentId& instrument) const {
169 if (const auto* found = find(evidence_, instrument)) {
170 return *found;
171 }
172 return SellableEvidence{};
173 }
174
180 SellableEvidence total;
181 for (const auto& entry : evidence_) {
182 total.net_ += entry.second.net_;
183 total.gross_ += entry.second.gross_;
184 }
185 return total;
186 }
187
193 return overall().verdict();
194 }
195
200 const std::vector<std::pair<InstrumentId, SellableEvidence>>& per_instrument() const noexcept {
201 return evidence_;
202 }
203
204private:
205 // Returns the sell quantity **the broker reported** resting, ignoring the runner's reservations.
206 //
207 // A runner adds a row of its own for an order it has just sent, so that the next order in the
208 // pass cannot re-sell the same shares. Those rows are this library's arithmetic, and counting
209 // them here would be circular: the resting quantity would rise with no change in the broker's
210 // sellable figure, and the probe would record `GROSS_OF_RESTING` on evidence it manufactured
211 // itself -- every time, for any broker, whenever the sellable check happened to be enabled.
212 static Decimal64 reported_resting(const Portfolio<Broker>& portfolio, const InstrumentId& instrument) {
213 Decimal64 total = Decimal64::parse("0");
214 for (const auto& order : portfolio.working_) {
215 if (order.reserved_ || !(order.order_.instrument_ == instrument) || order.order_.side_ != OrderSide::SELL) {
216 continue;
217 }
218 if (!order_is_open(order.order_.status_)) {
219 continue;
220 }
221 const auto remaining = decimal_subtract(order.order_.quantity_, order.order_.execution_.filled_quantity_);
222 if (!remaining || decimal_less(*remaining, Decimal64::parse("0"))) {
223 continue;
224 }
225 if (const auto sum = decimal_add(total, *remaining)) {
226 total = *sum;
227 }
228 }
229 return total;
230 }
231
232 // One position as a poll reported it.
233 struct Reading {
234 Decimal64 held_;
235 Decimal64 sellable_;
236 Decimal64 resting_;
237 };
238
239 // Returns whether two decimals are numerically equal, across differing scales.
240 static bool same(const Decimal64& lhs, const Decimal64& rhs) {
241 // `operator==` compares the coefficient and the scale, so "70" and "70.0" are not equal by it.
242 // A broker is free to change the scale it reports between two polls, and a probe that read that
243 // as a change would conclude from noise.
244 return !decimal_less(lhs, rhs) && !decimal_less(rhs, lhs);
245 }
246
247 // Records what the move from `before` to `now` says, if it says anything.
248 void judge(const InstrumentId& instrument, const Reading& before, const Reading& now) {
249 if (!same(before.held_, now.held_)) {
250 return;
251 }
252 const auto grew = decimal_subtract(now.resting_, before.resting_);
253 if (!grew || !decimal_less(Decimal64::parse("0"), *grew)) {
254 return;
255 }
256 const auto gap_before = decimal_subtract(before.held_, before.sellable_);
257 const auto gap_now = decimal_subtract(now.held_, now.sellable_);
258 if (!gap_before || !gap_now) {
259 return;
260 }
261 const auto moved = decimal_subtract(*gap_now, *gap_before);
262 if (!moved) {
263 return;
264 }
265
266 auto* entry = find(evidence_, instrument);
267 if (entry == nullptr) {
268 evidence_.push_back({instrument, SellableEvidence{}});
269 entry = &evidence_.back().second;
270 }
271 if (same(*moved, *grew)) {
272 ++entry->net_;
273 } else if (same(*moved, Decimal64::parse("0"))) {
274 ++entry->gross_;
275 }
276 // Anything else moved by an amount neither rule predicts -- a settlement in the same window,
277 // most likely -- and is discarded rather than forced into one of the two answers.
278 }
279
280 // Returns the entry for `instrument`, or null.
281 template <typename Entries>
282 static auto find(Entries& entries, const InstrumentId& instrument) -> decltype(&entries.front().second) {
283 for (auto& entry : entries) {
284 if (entry.first == instrument) {
285 return &entry.second;
286 }
287 }
288 return nullptr;
289 }
290
291 std::vector<std::pair<InstrumentId, Reading>> last_;
292 std::vector<std::pair<InstrumentId, SellableEvidence>> evidence_;
293};
294
295} // namespace strategy
296} // namespace algotradelib
An exact signed decimal: an int64 coefficient times 10^-scale.
Definition types.hpp:443
static Decimal64 parse(std::string_view input)
Parses a decimal string exactly (no binary floating point).
Definition types.hpp:468
Infers a broker's SellableConvention from successive portfolios.
SellableEvidence evidence(const InstrumentId &instrument) const
Returns the evidence for one instrument.
SellableConvention verdict() const
Returns the broker's convention as observed so far.
SellableEvidence overall() const
Returns the evidence summed over every instrument.
const std::vector< std::pair< InstrumentId, SellableEvidence > > & per_instrument() const noexcept
Returns the evidence per instrument.
void observe(const Portfolio< Broker > &portfolio)
Records one polled portfolio, comparing it with the previous one.
void forget(const InstrumentId &instrument)
Discards the last recorded reading for an instrument, so the next one is not compared across a gap.
What a strategy sees and emits: events, intents, the portfolio, reconciliation and risk limits.
Definition concept.hpp:16
SellableConvention
Whether a broker's sellable quantity already excludes sell orders resting at the broker.
@ INCONSISTENT
Both behaviours were observed; no single rule fits.
@ GROSS_OF_RESTING
The figure did not move when a sell began resting: the broker includes them.
@ NET_OF_RESTING
The figure fell when a sell began resting: the broker excludes resting sells.
@ UNDETERMINED
Nothing conclusive has been observed yet.
bool order_is_open(OrderStatus status)
Tests whether an order in a given status may still trade.
Definition portfolio.hpp:22
constexpr std::string_view sellable_convention_name(SellableConvention convention) noexcept
Returns a lowercase name for a convention, such as "net_of_resting", for logs.
The library: broker-neutral types (core), and the modules below.
std::optional< Decimal64 > decimal_add(const Decimal64 &lhs, const Decimal64 &rhs)
Adds two decimals exactly.
Definition types.hpp:760
std::optional< Decimal64 > decimal_subtract(const Decimal64 &lhs, const Decimal64 &rhs)
Subtracts two decimals exactly.
Definition types.hpp:783
bool decimal_less(const Decimal64 &lhs, const Decimal64 &rhs)
Compares two decimals numerically, whatever their scales.
Definition types.hpp:926
Identifies an instrument: its country, venue and symbol.
Definition types.hpp:85
What the account holds and which orders are still working, as a strategy sees it.
Definition portfolio.hpp:82
std::vector< WorkingOrder< Broker > > working_
Orders still outstanding at the broker.
SellableReading sellable_reading_for(const InstrumentId &instrument) const
Returns an instrument's sellable quantity and its basis, taken from the same row.
std::vector< HoldingPosition > positions_
Every position row the broker reported.
Definition portfolio.hpp:88
How many observations supported each answer.
std::size_t total() const noexcept
Returns the number of observations.
std::size_t gross_
Observations where the figure did not move when a sell began resting.
SellableConvention verdict() const noexcept
Returns the convention the counts support.
std::size_t net_
Observations where the figure fell by the quantity that began resting.