algotradelib 0.0.0.9000
C++ header-only library for algorithmic trading
Loading...
Searching...
No Matches
portfolio.hpp
1#pragma once
2
3#include <algotradelib/core>
4
5#include <chrono>
6#include <cstddef>
7#include <optional>
8#include <unordered_map>
9#include <vector>
10
11namespace algotradelib {
12namespace strategy {
13
22inline bool order_is_open(OrderStatus status) {
23 switch (status) {
24 case OrderStatus::UNKNOWN:
25 case OrderStatus::PENDING:
26 case OrderStatus::PENDING_CANCEL:
27 case OrderStatus::PENDING_REPLACE:
28 case OrderStatus::PARTIAL_FILLED:
29 return true;
30 case OrderStatus::FILLED:
31 case OrderStatus::CANCELED:
32 case OrderStatus::REJECTED:
33 case OrderStatus::CANCEL_REJECTED:
34 case OrderStatus::REPLACE_REJECTED:
35 case OrderStatus::REPLACED:
36 return false;
37 }
38 return true;
39}
40
41namespace portfolio_detail {
42
43// Adds a position row's quantity to a running net quantity; `false` if the sum does not fit.
44inline bool add_net(Decimal64& total, const HoldingPosition& position) {
45 const auto sum = decimal_add(total, position.quantity_);
46 if (!sum) {
47 return false;
48 }
49 total = *sum;
50 return true;
51}
52
53// Adds what a working row still has to fill, if it is open and on `side`; a row reporting more filled than
54// ordered, or a sum that does not fit, adds nothing.
55template <typename Working>
56void add_working(Decimal64& total, const Working& order, OrderSide side) {
57 if (order.order_.side_ != side || !order_is_open(order.order_.status_)) {
58 return;
59 }
60 const auto remaining = decimal_subtract(order.order_.quantity_, order.order_.execution_.filled_quantity_);
61 if (!remaining || decimal_less(*remaining, Decimal64(0, 0))) {
62 return;
63 }
64 if (const auto sum = decimal_add(total, *remaining)) {
65 total = *sum;
66 }
67}
68
69} // namespace portfolio_detail
70
81template <typename Broker>
82struct Portfolio {
88 std::vector<HoldingPosition> positions_;
96 std::vector<Money> cash_;
103 std::vector<BuyingPower> buying_power_;
109 std::vector<WorkingOrder<Broker>> working_;
116 std::chrono::system_clock::time_point as_of_{};
122 std::chrono::system_clock::time_point working_as_of_{};
123
133 bool listing_newer_than_holdings() const noexcept {
134 const std::chrono::system_clock::time_point epoch{};
135 return as_of_ != epoch && working_as_of_ != epoch && working_as_of_ > as_of_;
136 }
137
145
154 std::optional<Decimal64> quantity_of(const InstrumentId& instrument) const {
155 for (const auto& position : positions_) {
156 if (position.instrument_ == instrument) {
157 return position.quantity_;
158 }
159 }
160 return std::nullopt;
161 }
162
172 std::optional<Decimal64> net_quantity_of(const InstrumentId& instrument) const {
173 auto total = Decimal64(0, 0);
174 for (const auto& position : positions_) {
175 if (position.instrument_ == instrument && !portfolio_detail::add_net(total, position)) {
176 return std::nullopt;
177 }
178 }
179 return total;
180 }
181
192 Decimal64 working_quantity(const InstrumentId& instrument, OrderSide side) const {
193 Decimal64 total = Decimal64(0, 0);
194 for (const auto& order : working_) {
195 if (order.order_.instrument_ == instrument) {
196 portfolio_detail::add_working(total, order, side);
197 }
198 }
199 return total;
200 }
201
202public:
206 std::optional<Decimal64> quantity_;
209 };
210
223 SellableReading reading;
224 bool seen = false;
225 for (const auto& position : positions_) {
226 if (!(position.instrument_ == instrument)) {
227 continue;
228 }
229 const SellableBasis basis = position.sellable_basis_ ? *position.sellable_basis_ : sellable_basis_;
230 if (!seen) {
231 reading.quantity_ = position.sellable_quantity_;
232 reading.basis_ = basis;
233 seen = true;
234 continue;
235 }
236 // A second row of the same instrument. Figures are never summed, and a disagreement makes even
237 // the first row's figure uninterpretable, since nothing says which lot a sale draws from.
238 // First, a basis that disagrees.
239 if (basis.coverage_ != reading.basis_.coverage_ || basis.resting_ != reading.basis_.resting_) {
240 return SellableReading{reading.quantity_, SellableBasis{}};
241 }
242 // Then figures that disagree under one basis: two rows claiming the limit for the same shares
243 // with different numbers contradict each other. (KIS pages can repeat a `pdno`.)
244 // Compared as numbers: `operator==` also compares the scale, and "70" beside "70.0" is one figure.
245 if (
246 reading.quantity_ && position.sellable_quantity_ &&
247 (decimal_less(*position.sellable_quantity_, *reading.quantity_) ||
248 decimal_less(*reading.quantity_, *position.sellable_quantity_))
249 ) {
250 return SellableReading{reading.quantity_, SellableBasis{}};
251 }
252 // A later row's figure where the first had none is the only figure stated.
253 if (!reading.quantity_) {
254 reading.quantity_ = position.sellable_quantity_;
255 }
256 }
257 return reading;
258 }
259
265 std::optional<Decimal64> cash_in(const Currency& currency) const {
266 for (const auto& amount : cash_) {
267 if (amount.currency_ == currency) {
268 return amount.amount_;
269 }
270 }
271 return std::nullopt;
272 }
273
283 std::optional<Decimal64> buying_power_in(const Currency& currency) const {
284 for (const auto& amount : buying_power_) {
285 if (amount.cash_.currency_ == currency) {
286 return amount.cash_.amount_;
287 }
288 }
289 return std::nullopt;
290 }
291
303 std::optional<Decimal64> sellable_quantity_of(const InstrumentId& instrument) const {
304 for (const auto& position : positions_) {
305 if (position.instrument_ == instrument) {
306 return position.sellable_quantity_;
307 }
308 }
309 return std::nullopt;
310 }
311
318 for (const auto& order : working_) {
319 if (order.ref_ == ref) {
320 return &order;
321 }
322 }
323 return nullptr;
324 }
325};
326
335public:
337 struct Rows {
339 std::vector<std::size_t> positions_;
341 std::vector<std::size_t> working_;
342 };
343
349 template <typename Broker>
350 explicit PortfolioRows(const Portfolio<Broker>& portfolio) {
351 for (std::size_t at = 0; at < portfolio.positions_.size(); ++at) {
352 rows_[portfolio.positions_[at].instrument_].positions_.push_back(at);
353 }
354 for (std::size_t at = 0; at < portfolio.working_.size(); ++at) {
355 rows_[portfolio.working_[at].order_.instrument_].working_.push_back(at);
356 }
357 }
358
364 const Rows* of(const InstrumentId& instrument) const {
365 const auto found = rows_.find(instrument);
366 return found == rows_.end() ? nullptr : &found->second;
367 }
368
369private:
370 std::unordered_map<InstrumentId, Rows, id_detail::InstrumentIdHash> rows_;
371};
372
373} // namespace strategy
374} // namespace algotradelib
A three-letter currency code, such as KRW or USD (ISO 4217 style).
Definition types.hpp:374
An exact signed decimal: an int64 coefficient times 10^-scale.
Definition types.hpp:443
Decimal64()=default
Constructs zero.
PortfolioRows(const Portfolio< Broker > &portfolio)
Indexes a portfolio.
const Rows * of(const InstrumentId &instrument) const
Returns where an instrument's rows are.
What a strategy sees and emits: events, intents, the portfolio, reconciliation and risk limits.
Definition concept.hpp:16
bool order_is_open(OrderStatus status)
Tests whether an order in a given status may still trade.
Definition portfolio.hpp:22
The library: broker-neutral types (core), and the modules below.
OrderStatus
Where an order stands in its lifecycle.
Definition types.hpp:2170
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
OrderSide
The side of an order: its economic direction, buy or sell.
Definition types.hpp:1974
One position row in a holdings snapshot.
Definition types.hpp:1288
std::optional< Decimal64 > sellable_quantity_
How much the broker says may be sold now.
Definition types.hpp:1305
Decimal64 quantity_
The quantity in this row.
Definition types.hpp:1298
InstrumentId instrument_
The instrument held (brokers report holdings without a trading venue).
Definition types.hpp:1290
std::optional< SellableBasis > sellable_basis_
What this row's sellable_quantity_ covers, when the figure came from a per-instrument inquiry rather ...
Definition types.hpp:1312
Identifies an instrument: its country, venue and symbol.
Definition types.hpp:85
A broker's reference to one order, used to amend or cancel it.
Definition types.hpp:2402
What a sellable quantity covers, and how RiskGuard must treat resting sells against it.
Definition types.hpp:1191
RestingTreatment resting_
How resting sells are treated; unestablished by default.
Definition types.hpp:1221
Coverage coverage_
What the figure covers; unestablished by default.
Definition types.hpp:1219
An order still open to modification or cancellation.
Definition types.hpp:2582
A sellable quantity together with what it covers, read from the same row.
Where one instrument's rows are.
std::vector< std::size_t > positions_
Places in positions_, ascending.
std::vector< std::size_t > working_
Places in working_, ascending.
A sellable quantity together with what it covers, read from the same row.
SellableBasis basis_
What the figure covers; unestablished if the rows disagree.
std::optional< Decimal64 > quantity_
The figure, or std::nullopt if no row of the instrument reported one.
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.
SellableBasis sellable_basis_
What the sellable_quantity_ figures on positions_ cover.
std::vector< Money > cash_
Cash per currency, in a backtest only.
Definition portfolio.hpp:96
std::optional< Decimal64 > buying_power_in(const Currency &currency) const
Returns the buying power in a currency.
std::optional< Decimal64 > net_quantity_of(const InstrumentId &instrument) const
Returns the net quantity held of an instrument, summed over every row.
Decimal64 working_quantity(const InstrumentId &instrument, OrderSide side) const
Returns the quantity still to fill on open orders for an instrument and side.
std::chrono::system_clock::time_point working_as_of_
When the working-order listing was received, on the same clock as as_of_.
std::optional< Decimal64 > quantity_of(const InstrumentId &instrument) const
Returns the quantity of the first position row for an instrument.
const WorkingOrder< Broker > * find_working(const OrderRef< Broker > &ref) const
Finds a working order by its reference.
std::vector< BuyingPower > buying_power_
What may be spent, per currency.
std::optional< Decimal64 > cash_in(const Currency &currency) const
Returns the cash held in a currency (backtest only; see cash_).
std::chrono::system_clock::time_point as_of_
When the holdings were received, on this machine's clock.
std::optional< Decimal64 > sellable_quantity_of(const InstrumentId &instrument) const
Returns the sellable quantity the broker reported for an instrument (first row).
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
bool listing_newer_than_holdings() const noexcept
Tests whether the working-order listing is newer than the holdings.