algotradelib 0.0.0.9000
C++ header-only library for algorithmic trading
Loading...
Searching...
No Matches
risk.hpp
1#pragma once
2
3#include "./event.hpp"
4#include "./portfolio.hpp"
5#include "./reconcile.hpp"
6
7#include <algotradelib/core>
8
9#include <algorithm>
10#include <array>
11#include <chrono>
12#include <cstddef>
13#include <deque>
14#include <optional>
15#include <string>
16#include <string_view>
17#include <utility>
18#include <vector>
19
20namespace algotradelib {
21namespace strategy {
22
30enum class HaltReason {
32 OPERATOR,
40 LOCAL_FAILURE,
55 PORTFOLIO_ABSENT,
61 PORTFOLIO_STALE,
74};
75
87
89inline constexpr std::size_t halt_reason_count = all_halt_reasons.size();
90
96enum class InstructionClass {
105 WITHDRAWAL,
106};
107
119inline constexpr bool halt_blocks(HaltReason reason, InstructionClass klass) noexcept {
120 switch (klass) {
122 return true;
124 break;
125 }
126 switch (reason) {
130 return true;
131 // Guards against an opening order duplicating a predecessor's; a named withdrawal duplicates nothing.
133 // None of these says anything about a row the caller already named.
137 // A known resting order is still safe to withdraw when polling is abandoned.
139 return false;
140 }
141 return true;
142}
143
149inline constexpr std::string_view halt_reason_name(HaltReason reason) noexcept {
150 switch (reason) {
152 return "operator";
154 return "local_failure";
156 return "stopping";
158 return "order_list_unread";
160 return "portfolio_absent";
162 return "portfolio_stale";
164 return "buying_power_unread";
166 return "poll_failing";
167 }
168 return "";
169}
170
171static_assert(
174 [](HaltReason reason) {
175 return !halt_reason_name(reason).empty();
176 }
177 ),
178 "all_halt_reasons must list every HaltReason"
179);
180
181/*
182 * Operator limits, checked before anything is sent. A guard refuses an order; it never resizes one.
183 */
184
252
258inline constexpr std::string_view guard_reason_name(GuardReason reason) noexcept {
259 switch (reason) {
261 return "trading_halted";
263 return "instrument_not_permitted";
265 return "phase_not_permitted";
267 return "order_notional_too_large";
269 return "position_limit_exceeded";
271 return "gross_exposure_exceeded";
273 return "order_rate_exceeded";
275 return "value_not_known";
277 return "quantity_not_sellable";
279 return "sellable_basis_unestablished";
281 return "insufficient_buying_power";
283 return "run_budget_exceeded";
285 return "run_buy_needs_limit";
287 return "run_holding_exceeded";
289 return "run_ledger_unsettled";
290 }
291 return "unknown";
292}
293
301 std::string tag_;
303 std::optional<HaltReason> halt_reason_;
305 std::optional<Decimal64> limit_;
307 std::optional<Decimal64> attempted_;
308};
309
320struct RunFees {
326 std::optional<Decimal64> institution_rate_;
328 std::optional<Decimal64> sell_tax_rate_;
329
337 std::optional<Decimal64> estimate_commission(const Decimal64& value) const {
338 // A decimal's sign is its coefficient's.
339 if (
341 (institution_rate_ && institution_rate_->coefficient() < 0)
342 ) {
343 return std::nullopt;
344 }
345 auto commission = charged_on(value, commission_rate_);
346 if (!commission) {
347 return std::nullopt;
348 }
349 if (decimal_less(*commission, commission_minimum_)) {
350 commission = commission_minimum_;
351 }
352 if (!institution_rate_) {
353 return commission;
354 }
355 const auto institution = charged_on(value, *institution_rate_);
356 if (!institution) {
357 return std::nullopt;
358 }
359 return decimal_add(*commission, *institution);
360 }
361
369 std::optional<Decimal64> estimate_tax(const Decimal64& value, OrderSide side) const {
370 if (value.coefficient() < 0 || (sell_tax_rate_ && sell_tax_rate_->coefficient() < 0)) {
371 return std::nullopt;
372 }
373 if (side != OrderSide::SELL || !sell_tax_rate_) {
374 return Decimal64(0, 0);
375 }
376 return charged_on(value, *sell_tax_rate_);
377 }
378
379private:
380 // `value x rate`, rounded up to a whole unit; both are not negative.
381 static std::optional<Decimal64> charged_on(const Decimal64& value, const Decimal64& rate) {
382 if (rate.coefficient() == 0) {
383 return Decimal64(0, 0);
384 }
385 const auto exact = decimal_multiply(value, rate);
386 if (!exact) {
387 return std::nullopt;
388 }
389 // Rounded up on the coefficient: `coefficient / 10^scale`, plus one for any remainder. A scale of 19 or more
390 // has no `int64` power of ten, and gives no estimate.
391 const auto scale = exact->scale();
392 if (scale > 18) {
393 return std::nullopt;
394 }
395 std::int64_t unit = 1;
396 for (std::uint8_t step = 0; step < scale; ++step) {
397 unit *= 10;
398 }
399 const auto coefficient = exact->coefficient();
400 return Decimal64(coefficient / unit + (coefficient % unit != 0 ? 1 : 0), 0);
401 }
402};
403
414 std::optional<Decimal64> max_order_notional_;
421 std::optional<Decimal64> max_position_quantity_;
435 std::optional<Decimal64> max_gross_exposure_;
437 std::optional<std::size_t> max_orders_per_window_;
439 std::chrono::seconds rate_window_{60};
461 std::optional<std::vector<InstrumentId>> permitted_universe_;
475 std::optional<std::vector<MarketPhase>> permitted_phases_{std::vector<MarketPhase>{MarketPhase::OPEN}};
498 std::optional<Money> run_budget_;
500 std::optional<RunFees> run_fees_;
501};
502
518
522 std::chrono::system_clock::time_point now_{};
526 std::optional<Decimal64> reference_price_;
534 std::vector<InstrumentBasis> exposure_basis_;
541 std::optional<Currency> order_currency_;
548 std::optional<Money> run_cash_;
554 std::optional<Decimal64> run_holding_;
555};
556
557namespace risk_detail {
558
560inline Decimal64 decimal_max(const Decimal64& lhs, const Decimal64& rhs) {
561 return decimal_less(lhs, rhs) ? rhs : lhs;
562}
563
565inline std::optional<Decimal64> decimal_magnitude(const Decimal64& value) {
566 const auto zero = Decimal64::parse("0");
567 if (!decimal_less(value, zero)) {
568 return value;
569 }
570 return decimal_subtract(zero, value);
571}
572
574inline std::optional<Decimal64> run_buy_cost(const RunFees& fees, const Decimal64& quantity, const Decimal64& price) {
575 const auto value = decimal_multiply(quantity, price);
576 const auto commission = value ? fees.estimate_commission(*value) : std::nullopt;
577 return commission ? decimal_add(*value, *commission) : std::nullopt;
578}
579
580} // namespace risk_detail
581
594
618template <typename Broker>
619std::optional<Decimal64> projected_gross_exposure(
620 const Portfolio<Broker>& portfolio, const std::vector<InstrumentBasis>& basis, const Currency& currency,
621 const PlannedOrder* candidate, const std::optional<Decimal64>& candidate_price, CandidateContribution contribution
622) {
623 const auto zero = Decimal64::parse("0");
624
625 // Every instrument the answer depends on: held, working, or about to be ordered. Collected first
626 // so each one is valued exactly once however many rows mention it.
627 std::vector<InstrumentId> instruments;
628 const auto note = [&instruments](const InstrumentId& id) {
629 for (const auto& seen : instruments) {
630 if (seen == id) {
631 return;
632 }
633 }
634 instruments.push_back(id);
635 };
636 for (const auto& position : portfolio.positions_) {
637 // A flat row (a closed position a broker or the replay ledger still lists) is not exposure and
638 // needs no basis; if it also has a working order, the loop below collects it.
639 if (position.quantity_.coefficient() == 0) {
640 continue;
641 }
642 note(position.instrument_);
643 }
644 for (const auto& working : portfolio.working_) {
645 if (order_is_open(working.order_.status_)) {
646 note(working.order_.instrument_);
647 }
648 }
649 if (candidate != nullptr) {
650 note(candidate->instrument_);
651 }
652
653 auto total = zero;
654 for (const auto& id : instruments) {
655 const InstrumentBasis* resolved = nullptr;
656 for (const auto& entry : basis) {
657 if (!(entry.instrument_ == id)) {
658 continue;
659 }
660 if (resolved != nullptr) {
661 // Two answers for one instrument. Picking either would be picking one of two currencies or
662 // two marks, and the caller resolved it twice for a reason this cannot see.
663 return std::nullopt;
664 }
665 resolved = &entry;
666 }
667 if (resolved == nullptr) {
668 return std::nullopt;
669 }
670 if (!(resolved->currency_ == currency)) {
671 continue;
672 }
673 // A mark must be positive: zero would omit the position, and a negative one (from bad market
674 // data) would offset real holdings.
675 if (!decimal_less(zero, resolved->price_)) {
676 return std::nullopt;
677 }
678
679 // Summed over every row: a holding can be split across lots.
680 auto held = zero;
681 for (const auto& position : portfolio.positions_) {
682 if (!(position.instrument_ == id)) {
683 continue;
684 }
685 const auto sum = decimal_add(held, position.quantity_);
686 if (!sum) {
687 return std::nullopt;
688 }
689 held = *sum;
690 }
691 auto buys = zero;
692 auto sells = zero;
693 auto price = resolved->price_;
694 for (const auto& working : portfolio.working_) {
695 if (!(working.order_.instrument_ == id) || !order_is_open(working.order_.status_)) {
696 continue;
697 }
698 const auto remaining = decimal_subtract(working.order_.quantity_, working.order_.execution_.filled_quantity_);
699 if (!remaining) {
700 return std::nullopt;
701 }
702 // A row filled beyond its quantity refuses (`working_quantity` skips it): a limit cannot infer
703 // from an inconsistent snapshot that nothing is outstanding.
704 if (decimal_less(*remaining, zero)) {
705 return std::nullopt;
706 }
707 const auto sum = decimal_add(working.order_.side_ == OrderSide::BUY ? buys : sells, *remaining);
708 if (!sum) {
709 return std::nullopt;
710 }
711 (working.order_.side_ == OrderSide::BUY ? buys : sells) = *sum;
712 if (working.order_.price_) {
713 // A non-positive price would silently lose to the mark in `max`; refuse instead.
714 if (!decimal_less(zero, *working.order_.price_)) {
715 return std::nullopt;
716 }
717 price = risk_detail::decimal_max(price, *working.order_.price_);
718 }
719 }
720
721 if (candidate != nullptr && candidate->instrument_ == id) {
722 // The candidate's price applies under both contributions, its quantity only under one, so the
723 // two projections differ only by the quantity.
724 const auto stated = candidate->price_ ? candidate->price_ : candidate_price;
725 if (stated) {
726 // Validated, not just offered to `max`: a negative price would vanish into the mark here and
727 // pass `max_order_notional_` as a negative value. Nothing upstream rules it out.
728 if (!decimal_less(zero, *stated)) {
729 return std::nullopt;
730 }
731 price = risk_detail::decimal_max(price, *stated);
732 }
733 bool adds_quantity = false;
734 switch (contribution) {
736 adds_quantity = true;
737 break;
739 break;
740 }
741 if (adds_quantity) {
742 const auto sum = decimal_add(candidate->side_ == OrderSide::BUY ? buys : sells, candidate->quantity_);
743 if (!sum) {
744 return std::nullopt;
745 }
746 (candidate->side_ == OrderSide::BUY ? buys : sells) = *sum;
747 }
748 }
749
750 const auto if_bought = decimal_add(held, buys);
751 const auto if_sold = decimal_subtract(held, sells);
752 if (!if_bought || !if_sold) {
753 return std::nullopt;
754 }
755 const auto long_side = risk_detail::decimal_magnitude(*if_bought);
756 const auto short_side = risk_detail::decimal_magnitude(*if_sold);
757 if (!long_side || !short_side) {
758 return std::nullopt;
759 }
760 const auto projected = risk_detail::decimal_max(*long_side, *short_side);
761
762 const auto value = decimal_multiply(projected, price);
763 if (!value) {
764 return std::nullopt;
765 }
766 const auto running = decimal_add(total, *value);
767 if (!running) {
768 return std::nullopt;
769 }
770 total = *running;
771 }
772 return total;
773}
774
795template <typename Broker>
796std::optional<bool> closes_toward_flat(const Portfolio<Broker>& portfolio, const PlannedOrder& order) {
797 const auto zero = Decimal64::parse("0");
798
799 // Net across every row; a split holding must not understate `held`.
800 const auto net = portfolio.net_quantity_of(order.instrument_);
801 if (!net) {
802 return std::nullopt;
803 }
804 const auto held = *net;
805 // No row and a row of zero both mean nothing to close.
806 if (held.coefficient() == 0) {
807 return false;
808 }
809
810 // A non-positive quantity closes nothing; a negative one would otherwise satisfy the bound below.
811 if (!decimal_less(zero, order.quantity_)) {
812 return false;
813 }
814
815 const auto closing = decimal_less(zero, held) ? OrderSide::SELL : OrderSide::BUY;
816 if (order.side_ != closing) {
817 return false;
818 }
819
820 auto resting = zero;
821 for (const auto& working : portfolio.working_) {
822 if (!(working.order_.instrument_ == order.instrument_) || working.order_.side_ != closing) {
823 continue;
824 }
825 if (!order_is_open(working.order_.status_)) {
826 continue;
827 }
828 const auto remaining = decimal_subtract(working.order_.quantity_, working.order_.execution_.filled_quantity_);
829 // A row filled beyond its quantity is a contradiction; refuse rather than count zero.
830 if (!remaining || decimal_less(*remaining, zero)) {
831 return std::nullopt;
832 }
833 const auto sum = decimal_add(resting, *remaining);
834 if (!sum) {
835 return std::nullopt;
836 }
837 resting = *sum;
838 }
839
840 const auto committed = decimal_add(resting, order.quantity_);
841 if (!committed) {
842 return std::nullopt;
843 }
844 const auto magnitude = risk_detail::decimal_magnitude(held);
845 if (!magnitude) {
846 return std::nullopt;
847 }
848 // `<=`: an order that reaches flat exactly is a close (the usual liquidation case).
849 return !decimal_less(*magnitude, *committed);
850}
851
861 std::optional<GuardRejection> rejection_;
867};
868
880public:
886 : limits_(std::move(limits)),
887 checks_selling_(limits_.enforce_sellable_quantity_ || limits_.run_budget_.has_value()),
888 checks_spending_(limits_.enforce_buying_power_ || limits_.run_budget_.has_value()) {}
889
894 RiskGuard(const RiskGuard& other) = default;
899 RiskGuard(RiskGuard&& other) = default;
905 RiskGuard& operator=(RiskGuard&& other) = default;
906
914 // Copied whole first: a send list copied in part could be out of time order while still marked in it.
915 if (this != &other) {
916 RiskGuard copy(other);
917 *this = std::move(copy);
918 }
919 return *this;
920 }
921
926 const RiskLimits& limits() const noexcept {
927 return limits_;
928 }
929
935 bool permits_phase(MarketPhase phase) const noexcept {
936 if (!limits_.permitted_phases_) {
937 return true;
938 }
939 for (const auto allowed : *limits_.permitted_phases_) {
940 if (allowed == phase) {
941 return true;
942 }
943 }
944 return false;
945 }
946
956 void halt() noexcept {
957 held_[index_of(HaltReason::OPERATOR)] = true;
958 }
959
969 void halt(HaltReason reason, std::string detail) {
970 held_[index_of(reason)] = true;
971 details_[index_of(reason)] = std::move(detail);
972 }
973
978 void halt(HaltReason reason) {
979 halt(reason, std::string());
980 }
981
983 void resume() noexcept {
985 }
986
991 void resume(HaltReason reason) noexcept {
992 held_[index_of(reason)] = false;
993 details_[index_of(reason)].clear();
994 }
995
1000 bool halted() const noexcept {
1001 for (const auto held : held_) {
1002 if (held) {
1003 return true;
1004 }
1005 }
1006 return false;
1007 }
1008
1014 bool halted(HaltReason reason) const noexcept {
1015 return held_[index_of(reason)];
1016 }
1017
1022 std::optional<HaltReason> blocking_reason() const noexcept {
1024 }
1025
1031 std::optional<HaltReason> blocking_reason_for(InstructionClass klass) const noexcept {
1032 for (std::size_t index = 0; index < halt_reason_count; ++index) {
1033 const auto reason = static_cast<HaltReason>(index);
1034 if (held_[index] && halt_blocks(reason, klass)) {
1035 return reason;
1036 }
1037 }
1038 return std::nullopt;
1039 }
1040
1046 const std::string& hold_detail(HaltReason reason) const noexcept {
1047 return details_[index_of(reason)];
1048 }
1049
1054 std::vector<HaltReason> holds() const {
1055 std::vector<HaltReason> held;
1056 for (std::size_t index = 0; index < halt_reason_count; ++index) {
1057 if (held_[index]) {
1058 held.push_back(static_cast<HaltReason>(index));
1059 }
1060 }
1061 return held;
1062 }
1063
1072 void note_sent(std::chrono::system_clock::time_point when) {
1073 // While every send arrives in time order, `recent_orders` can binary-search; a clock that
1074 // stepped back makes it scan, as it always did.
1075 if (!sent_.empty() && when < sent_.back()) {
1076 in_time_order_ = false;
1077 }
1078 sent_.push_back(when);
1079 ++total_sent_;
1080 }
1081
1090 std::size_t total_sent() const noexcept {
1091 return total_sent_;
1092 }
1093
1099 std::size_t recent_orders(std::chrono::system_clock::time_point now) const {
1100 const auto in_window = [&](std::chrono::system_clock::time_point when) {
1101 return now - when < limits_.rate_window_;
1102 };
1103 if (!in_time_order_) {
1104 return static_cast<std::size_t>(std::count_if(sent_.begin(), sent_.end(), in_window));
1105 }
1106 // In time order, the sends outside the window come first; the same test finds where they end.
1107 const auto first =
1108 std::partition_point(sent_.begin(), sent_.end(), [&](std::chrono::system_clock::time_point when) {
1109 return !in_window(when);
1110 });
1111 return static_cast<std::size_t>(sent_.end() - first);
1112 }
1113
1118 void forget_before(std::chrono::system_clock::time_point cutoff) {
1119 while (!sent_.empty() && sent_.front() < cutoff) {
1120 sent_.pop_front();
1121 }
1122 }
1123
1134 template <typename Broker>
1135 std::optional<GuardRejection> check(
1136 const PlannedOrder& order, const Portfolio<Broker>& portfolio, const GuardInputs& inputs
1137 ) const {
1138 return evaluate(order, portfolio, inputs).rejection_;
1139 }
1140
1162 template <typename Broker>
1164 const PlannedOrder& order, const Portfolio<Broker>& portfolio, const GuardInputs& inputs
1165 ) const {
1166 const auto refuse = [&order](GuardReason reason) {
1167 GuardRejection rejection;
1168 rejection.reason_ = reason;
1169 rejection.instrument_ = order.instrument_;
1170 rejection.tag_ = order.tag_;
1171 return GuardDecision{std::optional<GuardRejection>(rejection), false};
1172 };
1173 const auto refuse_with = [&order](GuardReason reason, Decimal64 limit, Decimal64 attempted) {
1174 GuardRejection rejection;
1175 rejection.reason_ = reason;
1176 rejection.instrument_ = order.instrument_;
1177 rejection.tag_ = order.tag_;
1178 rejection.limit_ = std::move(limit);
1179 rejection.attempted_ = std::move(attempted);
1180 return GuardDecision{std::optional<GuardRejection>(rejection), false};
1181 };
1182 // Set by the phase check and reported only if the order survives every later limit, since
1183 // `refuse` and `refuse_with` both build a decision with it false. An order the exception
1184 // admitted and a ceiling then refused was not admitted.
1185 bool admitted_outside_phase = false;
1186
1187 if (const auto holding = blocking_reason()) {
1188 auto decision = refuse(GuardReason::TRADING_HALTED);
1189 decision.rejection_->halt_reason_ = *holding;
1190 return decision;
1191 }
1192
1193 if (limits_.permitted_universe_) {
1194 bool permitted = false;
1195 for (const auto& allowed : *limits_.permitted_universe_) {
1196 if (allowed == order.instrument_) {
1197 permitted = true;
1198 break;
1199 }
1200 }
1201 if (!permitted) {
1203 }
1204 }
1205
1206 if (limits_.permitted_phases_) {
1207 bool permitted = false;
1208 for (const auto phase : *limits_.permitted_phases_) {
1209 if (phase == inputs.phase_) {
1210 permitted = true;
1211 break;
1212 }
1213 }
1214 if (!permitted) {
1215 // The phase restricts what an order opens, not what it closes: an exit must stay expressible
1216 // after the session. `closes_toward_flat` is narrower than the exposure rule, which would
1217 // admit a sell that opens a short against a resting buy.
1218 const auto closing = closes_toward_flat(portfolio, order);
1219 // Unknown refuses: this branch only relaxes a restriction.
1220 if (!closing || !*closing) {
1221 return refuse(GuardReason::PHASE_NOT_PERMITTED);
1222 }
1223 admitted_outside_phase = true;
1224 }
1225 }
1226
1227 if (limits_.max_orders_per_window_ && recent_orders(inputs.now_) >= *limits_.max_orders_per_window_) {
1228 return refuse_with(
1229 GuardReason::ORDER_RATE_EXCEEDED, Decimal64(static_cast<std::int64_t>(*limits_.max_orders_per_window_), 0),
1230 Decimal64(static_cast<std::int64_t>(recent_orders(inputs.now_) + 1), 0)
1231 );
1232 }
1233
1234 // A market order carries no price, so its value has to come from the runner's last quote.
1235 // Without one, a notional or exposure limit cannot be evaluated, and a limit that cannot be
1236 // evaluated must refuse rather than wave the order through.
1237 const auto price = order.price_ ? order.price_ : inputs.reference_price_;
1238 const bool needs_value = limits_.max_order_notional_.has_value() || limits_.max_gross_exposure_.has_value() ||
1239 (limits_.enforce_buying_power_ && order.side_ == OrderSide::BUY);
1240 if (needs_value && !price) {
1241 return refuse(GuardReason::VALUE_NOT_KNOWN);
1242 }
1243
1244 std::optional<Decimal64> value;
1245 if (price) {
1246 value = decimal_multiply(order.quantity_, *price);
1247 if (needs_value && !value) {
1248 return refuse(GuardReason::VALUE_NOT_KNOWN);
1249 }
1250 }
1251
1252 if (limits_.max_order_notional_ && value && decimal_less(*limits_.max_order_notional_, *value)) {
1253 return refuse_with(GuardReason::ORDER_NOTIONAL_TOO_LARGE, *limits_.max_order_notional_, *value);
1254 }
1255
1256 if (checks_selling_ && order.side_ == OrderSide::SELL) {
1257 if (limits_.run_budget_) {
1258 if (auto refused = refuse_run_sell(order, portfolio, inputs)) {
1259 return *refused;
1260 }
1261 } else {
1262 // One read, so the figure and its basis come from the same row.
1263 const auto reading = portfolio.sellable_reading_for(order.instrument_);
1264 const auto& sellable = reading.quantity_;
1265 if (!sellable) {
1266 // Absent is unknown, and unknown refuses; the held quantity is not substituted.
1268 }
1269 // A figure whose basis is not established refuses even though present; this fails closed for
1270 // an adapter the library has never seen.
1271 if (!reading.basis_.is_enforceable()) {
1273 }
1274 // Every open sell (the broker's rows and this library's reservations) counts against the
1275 // figure. That over-refuses where the broker already deducted them and never under-refuses;
1276 // see `SellableBasis::DEDUCT`.
1277 const auto resting = portfolio.working_quantity(order.instrument_, OrderSide::SELL);
1278 const auto committed = decimal_add(resting, order.quantity_);
1279 if (!committed) {
1281 }
1282 if (decimal_less(*sellable, *committed)) {
1283 return refuse_with(GuardReason::QUANTITY_NOT_SELLABLE, *sellable, *committed);
1284 }
1285 }
1286 }
1287
1288 if (checks_spending_ && order.side_ == OrderSide::BUY) {
1289 if (limits_.run_budget_) {
1290 if (auto refused = refuse_run_buy(order, portfolio, inputs, value)) {
1291 return *refused;
1292 }
1293 } else {
1294 if (!value) {
1295 // A price is present (`needs_value`), so the multiplication itself failed.
1296 return refuse(GuardReason::VALUE_NOT_KNOWN);
1297 }
1298 if (!inputs.order_currency_) {
1300 }
1301 const auto available = portfolio.buying_power_in(*inputs.order_currency_);
1302 if (!available) {
1303 // Absent is unknown, and unknown refuses. (`cash_in` is empty live, so no fallback.)
1305 }
1306 if (decimal_less(*available, *value)) {
1307 return refuse_with(GuardReason::INSUFFICIENT_BUYING_POWER, *available, *value);
1308 }
1309 }
1310 }
1311
1312 if (limits_.max_position_quantity_) {
1313 const auto zero = Decimal64::parse("0");
1314 // Net across every position row, as reconciliation sizes: a split holding read from its first
1315 // row would refuse an exit to flat and pass a buy that both lots together put over the ceiling.
1316 const auto net = portfolio.net_quantity_of(order.instrument_);
1317 if (!net) {
1319 }
1320 const auto held = *net;
1321 // Orders already working on this side count, so two buys that each fit cannot together exceed
1322 // the ceiling. A resting opposite-side order is not counted as relief.
1323 const auto pending = portfolio.working_quantity(order.instrument_, order.side_);
1324 const auto committed = decimal_add(pending, order.quantity_);
1325 if (!committed) {
1327 }
1328 const auto signed_quantity =
1329 order.side_ == OrderSide::BUY ? std::optional<Decimal64>(*committed) : decimal_subtract(zero, *committed);
1330 if (!signed_quantity) {
1332 }
1333 const auto resulting = decimal_add(held, *signed_quantity);
1334 if (!resulting) {
1336 }
1337 // The ceiling is on magnitude, so a short of the same size is limited as a long is.
1338 const auto magnitude =
1339 decimal_less(*resulting, zero) ? decimal_subtract(zero, *resulting) : std::optional<Decimal64>(*resulting);
1340 if (!magnitude) {
1342 }
1343 if (decimal_less(*limits_.max_position_quantity_, *magnitude)) {
1344 return refuse_with(GuardReason::POSITION_LIMIT_EXCEEDED, *limits_.max_position_quantity_, *magnitude);
1345 }
1346 }
1347
1348 if (limits_.max_gross_exposure_) {
1349 // Per currency: an unresolved order currency refuses.
1350 if (!inputs.order_currency_) {
1351 return refuse(GuardReason::VALUE_NOT_KNOWN);
1352 }
1353 const auto resulting = projected_gross_exposure(
1354 portfolio, inputs.exposure_basis_, *inputs.order_currency_, &order, price,
1356 );
1357 if (!resulting) {
1358 // The basis does not describe the portfolio, or the arithmetic did not fit.
1359 return refuse(GuardReason::VALUE_NOT_KNOWN);
1360 }
1361 if (decimal_less(*limits_.max_gross_exposure_, *resulting)) {
1362 // Over the ceiling, refuse only an order that raises the projection, so an account already
1363 // over it can still sell out. Compare against `PRICE_ONLY` (same prices, no quantity), not
1364 // `nullptr`, so the difference is the order's quantity and not its limit price.
1365 const auto without = projected_gross_exposure(
1366 portfolio, inputs.exposure_basis_, *inputs.order_currency_, &order, price, CandidateContribution::PRICE_ONLY
1367 );
1368 if (!without) {
1369 return refuse(GuardReason::VALUE_NOT_KNOWN);
1370 }
1371 if (decimal_less(*without, *resulting)) {
1372 return refuse_with(GuardReason::GROSS_EXPOSURE_EXCEEDED, *limits_.max_gross_exposure_, *resulting);
1373 }
1374 }
1375 }
1376
1377 return GuardDecision{std::nullopt, admitted_outside_phase};
1378 }
1379
1380private:
1381 // A decision refusing `order` for `reason`, with the figures where the reason has them.
1382 static GuardDecision refusal(
1383 const PlannedOrder& order, GuardReason reason, std::optional<Decimal64> limit = std::nullopt,
1384 std::optional<Decimal64> attempted = std::nullopt
1385 ) {
1386 GuardRejection rejection;
1387 rejection.reason_ = reason;
1388 rejection.instrument_ = order.instrument_;
1389 rejection.tag_ = order.tag_;
1390 rejection.limit_ = std::move(limit);
1391 rejection.attempted_ = std::move(attempted);
1392 return GuardDecision{std::optional<GuardRejection>(std::move(rejection)), false};
1393 }
1394
1395 // The selling check with a run budget: the smaller of the broker's sellable room (where enforced) and the run's
1396 // own shares less its open sells, the broker's named on a tie.
1397 template <typename Broker>
1398 std::optional<GuardDecision> refuse_run_sell(
1399 const PlannedOrder& order, const Portfolio<Broker>& portfolio, const GuardInputs& inputs
1400 ) const {
1401 const auto zero = Decimal64(0, 0);
1402 if (!decimal_less(zero, order.quantity_)) {
1403 return refusal(order, GuardReason::VALUE_NOT_KNOWN);
1404 }
1405 // The broker's figures as main's block reads them.
1406 std::optional<Decimal64> sellable;
1407 std::optional<Decimal64> resting;
1408 std::optional<Decimal64> committed;
1409 if (limits_.enforce_sellable_quantity_) {
1410 const auto reading = portfolio.sellable_reading_for(order.instrument_);
1411 sellable = reading.quantity_;
1412 if (!sellable) {
1413 return refusal(order, GuardReason::QUANTITY_NOT_SELLABLE);
1414 }
1415 if (!reading.basis_.is_enforceable()) {
1416 return refusal(order, GuardReason::SELLABLE_BASIS_UNESTABLISHED);
1417 }
1418 resting = portfolio.working_quantity(order.instrument_, OrderSide::SELL);
1419 committed = decimal_add(*resting, order.quantity_);
1420 if (!committed) {
1421 return refusal(order, GuardReason::QUANTITY_NOT_SELLABLE);
1422 }
1423 }
1424 if (!inputs.run_holding_) {
1425 return refusal(order, GuardReason::RUN_LEDGER_UNSETTLED);
1426 }
1427 const bool broker_over = sellable && decimal_less(*sellable, *committed);
1428 const bool run_over = decimal_less(*inputs.run_holding_, order.quantity_);
1429 if (!broker_over && !run_over) {
1430 return std::nullopt;
1431 }
1432 bool names_run = !broker_over;
1433 if (broker_over && run_over) {
1434 // The broker's room is formed only here; a subtraction that fails names the broker.
1435 const auto room = decimal_subtract(*sellable, *resting);
1436 names_run = room && decimal_less(*inputs.run_holding_, *room);
1437 }
1438 if (names_run) {
1439 return refusal(
1440 order, GuardReason::RUN_HOLDING_EXCEEDED, risk_detail::decimal_max(*inputs.run_holding_, zero), order.quantity_
1441 );
1442 }
1443 return refusal(order, GuardReason::QUANTITY_NOT_SELLABLE, *sellable, *committed);
1444 }
1445
1446 // The spending check with a run budget: the smaller of the broker's buying power (where enforced) and the run's
1447 // room, its cash less this buy's estimated fee, the broker's named on a tie. `value` is quantity x limit price.
1448 template <typename Broker>
1449 std::optional<GuardDecision> refuse_run_buy(
1450 const PlannedOrder& order, const Portfolio<Broker>& portfolio, const GuardInputs& inputs,
1451 const std::optional<Decimal64>& value
1452 ) const {
1453 const auto zero = Decimal64(0, 0);
1454 if (!decimal_less(zero, order.quantity_)) {
1455 return refusal(order, GuardReason::VALUE_NOT_KNOWN);
1456 }
1457 // Not a conditional limit, which carries a price but becomes a market order at the close.
1458 if (
1459 (order.type_ != OrderType::LIMIT && order.type_ != OrderType::STOP_LIMIT) || !order.price_ ||
1460 !decimal_less(zero, *order.price_)
1461 ) {
1462 return refusal(order, GuardReason::RUN_BUY_NEEDS_LIMIT);
1463 }
1464 if (!value) {
1465 return refusal(order, GuardReason::VALUE_NOT_KNOWN);
1466 }
1467 std::optional<Decimal64> available;
1468 if (limits_.enforce_buying_power_) {
1469 if (!inputs.order_currency_) {
1470 return refusal(order, GuardReason::INSUFFICIENT_BUYING_POWER);
1471 }
1472 available = portfolio.buying_power_in(*inputs.order_currency_);
1473 if (!available) {
1474 return refusal(order, GuardReason::INSUFFICIENT_BUYING_POWER);
1475 }
1476 }
1477 // A direct caller bypasses the runner's validation, so each run figure is checked before any arithmetic.
1478 if (!limits_.run_fees_ || !inputs.run_cash_ || !(inputs.run_cash_->currency_ == limits_.run_budget_->currency_)) {
1479 return refusal(order, GuardReason::RUN_LEDGER_UNSETTLED);
1480 }
1481 if (!inputs.order_currency_) {
1482 return refusal(order, GuardReason::VALUE_NOT_KNOWN);
1483 }
1484 if (!(*inputs.order_currency_ == inputs.run_cash_->currency_)) {
1485 // Amounts in two currencies are never compared, so there is no attempted figure.
1486 return refusal(order, GuardReason::RUN_BUDGET_EXCEEDED, inputs.run_cash_->amount_);
1487 }
1488 const auto fee = limits_.run_fees_->estimate_commission(*value);
1489 const auto room = fee ? decimal_subtract(inputs.run_cash_->amount_, *fee) : std::nullopt;
1490 if (!room) {
1491 return refusal(order, GuardReason::VALUE_NOT_KNOWN);
1492 }
1493 const bool broker_over = available && decimal_less(*available, *value);
1494 const bool run_over = decimal_less(*room, *value);
1495 if (broker_over && (!run_over || !decimal_less(*room, *available))) {
1496 return refusal(order, GuardReason::INSUFFICIENT_BUYING_POWER, *available, *value);
1497 }
1498 if (run_over) {
1499 return refusal(order, GuardReason::RUN_BUDGET_EXCEEDED, *room, *value);
1500 }
1501 return std::nullopt;
1502 }
1503
1504 // `reason`'s slot in the hold arrays.
1505 static constexpr std::size_t index_of(HaltReason reason) noexcept {
1506 return static_cast<std::size_t>(reason);
1507 }
1508
1509 RiskLimits limits_;
1510 // Which holds are in force, indexed by `HaltReason`; declaration order is priority order.
1511 std::array<bool, halt_reason_count> held_{};
1512 // Each hold's detail, empty where none or not held.
1513 std::array<std::string, halt_reason_count> details_;
1514 // Timestamps of orders sent, oldest first; a sliding window, not a counter reset on a boundary.
1515 std::deque<std::chrono::system_clock::time_point> sent_;
1516 // Whether `sent_` has never had a send earlier than the one before it.
1517 bool in_time_order_{true};
1518 // Whether `evaluate` enters the sellable and the buying-power blocks; fixed with `limits_`.
1519 bool checks_selling_{true};
1520 bool checks_spending_{false};
1521 std::size_t total_sent_{0};
1522};
1523
1524} // namespace strategy
1525} // 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
std::int64_t coefficient() const noexcept
Returns the coefficient.
Definition types.hpp:541
Decimal64()=default
Constructs zero.
static Decimal64 parse(std::string_view input)
Parses a decimal string exactly (no binary floating point).
Definition types.hpp:468
std::size_t recent_orders(std::chrono::system_clock::time_point now) const
Returns how many orders were sent within RiskLimits::rate_window_ before an instant.
Definition risk.hpp:1099
RiskGuard & operator=(const RiskGuard &other)
Replaces this guard with a copy of another, entirely or not at all.
Definition risk.hpp:913
RiskGuard(RiskGuard &&other)=default
Moves a guard.
void note_sent(std::chrono::system_clock::time_point when)
Records that a request was sent, for the rate limit.
Definition risk.hpp:1072
void halt(HaltReason reason)
Takes a hold, with no description.
Definition risk.hpp:978
const RiskLimits & limits() const noexcept
Returns the limits.
Definition risk.hpp:926
bool halted(HaltReason reason) const noexcept
Tests whether one hold is in force.
Definition risk.hpp:1014
void resume(HaltReason reason) noexcept
Releases a hold; releasing one that is not held does nothing.
Definition risk.hpp:991
RiskGuard(RiskLimits limits={})
Constructs a guard.
Definition risk.hpp:885
void resume() noexcept
Releases the operator's hold; other holds, if any, still stop trading.
Definition risk.hpp:983
std::size_t total_sent() const noexcept
Returns how many orders have been recorded with note_sent over the guard's life.
Definition risk.hpp:1090
RiskGuard(const RiskGuard &other)=default
Copies a guard.
void halt(HaltReason reason, std::string detail)
Takes a hold, with a description.
Definition risk.hpp:969
RiskGuard & operator=(RiskGuard &&other)=default
Replaces this guard with a move of another.
bool permits_phase(MarketPhase phase) const noexcept
Tests whether a phase permits opening or increasing a position.
Definition risk.hpp:935
std::vector< HaltReason > holds() const
Returns every hold in force.
Definition risk.hpp:1054
std::optional< GuardRejection > check(const PlannedOrder &order, const Portfolio< Broker > &portfolio, const GuardInputs &inputs) const
Checks one planned order against the limits and holds.
Definition risk.hpp:1135
std::optional< HaltReason > blocking_reason_for(InstructionClass klass) const noexcept
Returns the hold that stops an instruction class, the most fundamental first.
Definition risk.hpp:1031
void halt() noexcept
Takes the operator's hold (HaltReason::OPERATOR): no order or cancellation is sent until resume().
Definition risk.hpp:956
void forget_before(std::chrono::system_clock::time_point cutoff)
Forgets sends recorded before an instant, to bound memory.
Definition risk.hpp:1118
bool halted() const noexcept
Tests whether any hold is in force.
Definition risk.hpp:1000
std::optional< HaltReason > blocking_reason() const noexcept
Returns the hold that stops placements, the most fundamental first.
Definition risk.hpp:1022
GuardDecision evaluate(const PlannedOrder &order, const Portfolio< Broker > &portfolio, const GuardInputs &inputs) const
Checks one planned order, and reports whether only the closing exception admitted it.
Definition risk.hpp:1163
The events a runner delivers to a strategy's handlers, and the market phase.
What a strategy sees and emits: events, intents, the portfolio, reconciliation and risk limits.
Definition concept.hpp:16
GuardReason
Which check refused an order.
Definition risk.hpp:186
@ SELLABLE_BASIS_UNESTABLISHED
A sellable quantity is present, but what it covers is not established.
Definition risk.hpp:216
@ RUN_LEDGER_UNSETTLED
The run's cash, or its shares of the instrument, is not known.
Definition risk.hpp:250
@ ORDER_NOTIONAL_TOO_LARGE
The order's value exceeds RiskLimits::max_order_notional_.
Definition risk.hpp:194
@ RUN_BUY_NEEDS_LIMIT
A budgeted run's buy carries no positive limit price of its own, so there is no cap to reserve agains...
Definition risk.hpp:235
@ ORDER_RATE_EXCEEDED
RiskLimits::max_orders_per_window_ orders were already sent in the window.
Definition risk.hpp:200
@ QUANTITY_NOT_SELLABLE
The sell exceeds the broker's sellable quantity, or the broker gave none.
Definition risk.hpp:209
@ POSITION_LIMIT_EXCEEDED
The position could exceed RiskLimits::max_position_quantity_.
Definition risk.hpp:196
@ RUN_HOLDING_EXCEEDED
The sell is more than the run's own shares of the instrument less its open sells.
Definition risk.hpp:241
@ VALUE_NOT_KNOWN
A limit needed a value that is not known.
Definition risk.hpp:207
@ INSUFFICIENT_BUYING_POWER
The buy costs more than the broker's buying power, or the broker gave none.
Definition risk.hpp:218
@ INSTRUMENT_NOT_PERMITTED
The instrument is not in RiskLimits::permitted_universe_.
Definition risk.hpp:190
@ PHASE_NOT_PERMITTED
The market phase is not in RiskLimits::permitted_phases_.
Definition risk.hpp:192
@ RUN_BUDGET_EXCEEDED
The buy's value is more than the run's room (RiskLimits::run_budget_).
Definition risk.hpp:227
@ GROSS_EXPOSURE_EXCEEDED
The gross exposure could exceed RiskLimits::max_gross_exposure_.
Definition risk.hpp:198
@ TRADING_HALTED
A hold is in force; GuardRejection::halt_reason_ names it.
Definition risk.hpp:188
MarketPhase
Where the clock stands relative to the trading session.
Definition event.hpp:33
@ UNKNOWN
Nothing is known about this instant: the calendar does not cover its date, or the filled session hour...
Definition event.hpp:38
@ OPEN
Inside the session.
Definition event.hpp:46
constexpr std::size_t halt_reason_count
The number of HaltReason values.
Definition risk.hpp:89
constexpr bool halt_blocks(HaltReason reason, InstructionClass klass) noexcept
Tests whether a hold stops an instruction of a given class.
Definition risk.hpp:119
std::optional< Decimal64 > projected_gross_exposure(const Portfolio< Broker > &portfolio, const std::vector< InstrumentBasis > &basis, const Currency &currency, const PlannedOrder *candidate, const std::optional< Decimal64 > &candidate_price, CandidateContribution contribution)
Computes the gross exposure in one currency if every outstanding order (and a candidate) filled.
Definition risk.hpp:619
CandidateContribution
What a candidate order adds to projected_gross_exposure.
Definition risk.hpp:588
@ QUANTITY_AND_PRICE
The candidate's quantity and price: the exposure if the order is sent.
Definition risk.hpp:590
@ PRICE_ONLY
The candidate's price only: the exposure without the order, valued at the same prices.
Definition risk.hpp:592
bool order_is_open(OrderStatus status)
Tests whether an order in a given status may still trade.
Definition portfolio.hpp:22
std::optional< bool > closes_toward_flat(const Portfolio< Broker > &portfolio, const PlannedOrder &order)
Tests whether an order only reduces a held position toward flat, without passing through it.
Definition risk.hpp:796
InstructionClass
What an instruction can do to a position, which decides which holds stop it.
Definition risk.hpp:96
@ OPENING
A placement, which can open or enlarge a position. Every hold stops it.
Definition risk.hpp:98
@ WITHDRAWAL
A cancellation of an order the caller named.
Definition risk.hpp:105
constexpr std::string_view guard_reason_name(GuardReason reason) noexcept
Returns a lowercase name for a refusal reason, such as "order_rate_exceeded", for logs.
Definition risk.hpp:258
constexpr std::string_view halt_reason_name(HaltReason reason) noexcept
Returns a lowercase name for a hold, such as "portfolio_stale", for logs.
Definition risk.hpp:149
constexpr std::array< HaltReason, 8 > all_halt_reasons
Every HaltReason, in declaration order.
Definition risk.hpp:77
HaltReason
Who or what is holding trading stopped.
Definition risk.hpp:30
@ BUYING_POWER_UNREAD
A buying-power limit is enforced, but there is no current reading to check it against.
Definition risk.hpp:71
@ LOCAL_FAILURE
Local machinery failed, such as the order journal not being writable; nothing is sent.
Definition risk.hpp:40
@ PORTFOLIO_ABSENT
No holdings snapshot has been read yet, so what the account holds is unknown.
Definition risk.hpp:55
@ ORDER_LIST_UNREAD
The broker's order list has not been read since this process started.
Definition risk.hpp:49
@ OPERATOR
A person stopped trading with RiskGuard::halt(); only RiskGuard::resume() clears it.
Definition risk.hpp:32
@ PORTFOLIO_STALE
The holdings snapshot is older than the configured maximum age.
Definition risk.hpp:61
@ POLL_FAILING
A poll kept failing and the loop gave up, as opposed to STOPPING on request.
Definition risk.hpp:73
@ STOPPING
A stop was requested and the run is shutting down.
Definition risk.hpp:42
The library: broker-neutral types (core), and the modules below.
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.
std::optional< Decimal64 > decimal_add(const Decimal64 &lhs, const Decimal64 &rhs)
Adds two decimals exactly.
Definition types.hpp:760
@ LIMIT
지정가: fills at the stated price or better.
Definition types.hpp:2001
@ STOP_LIMIT
스톱지정가: a limit released when a trigger price is reached.
Definition types.hpp:2013
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
std::optional< Decimal64 > decimal_multiply(const Decimal64 &lhs, const Decimal64 &rhs)
Multiplies two decimals exactly; the scales add.
Definition types.hpp:826
OrderSide
The side of an order: its economic direction, buy or sell.
Definition types.hpp:1974
Reconciliation: turning a strategy's intents and targets into the orders and cancellations to send.
Identifies an instrument: its country, venue and symbol.
Definition types.hpp:85
What RiskGuard::evaluate concluded about one order.
Definition risk.hpp:859
bool admitted_outside_phase_
Whether the order was permitted only because it closes toward flat in a phase the limits do not permi...
Definition risk.hpp:866
std::optional< GuardRejection > rejection_
Why the order was refused, or std::nullopt if it was permitted.
Definition risk.hpp:861
What RiskGuard::check needs besides the order and the portfolio.
Definition risk.hpp:520
MarketPhase phase_
The market phase the order would be sent in.
Definition risk.hpp:524
std::chrono::system_clock::time_point now_
The current instant; RiskLimits::rate_window_ counts back from it.
Definition risk.hpp:522
std::optional< Currency > order_currency_
The currency the order is priced in, from its reference data.
Definition risk.hpp:541
std::optional< Decimal64 > reference_price_
A price to value a market order, which carries none.
Definition risk.hpp:526
std::vector< InstrumentBasis > exposure_basis_
The currency and mark of every instrument held or working, plus the order's.
Definition risk.hpp:534
std::optional< Decimal64 > run_holding_
The run's own shares of the order's instrument less its open sells, read by a budgeted sell.
Definition risk.hpp:554
std::optional< Money > run_cash_
The run's cash less what its open buys reserve, read by a budgeted buy (RiskLimits::run_budget_).
Definition risk.hpp:548
One order a guard refused, with the limit and the value that exceeded it.
Definition risk.hpp:295
InstrumentId instrument_
The instrument of the refused order.
Definition risk.hpp:299
std::string tag_
The tag of the intent the order came from.
Definition risk.hpp:301
GuardReason reason_
Which check refused the order.
Definition risk.hpp:297
std::optional< Decimal64 > limit_
The limit that was exceeded, where the reason has one.
Definition risk.hpp:305
std::optional< HaltReason > halt_reason_
The hold that stopped the order, when reason_ is TRADING_HALTED; otherwise empty.
Definition risk.hpp:303
std::optional< Decimal64 > attempted_
The value the order would have reached, where the reason has one.
Definition risk.hpp:307
An instrument's currency and the price to value it at, for the exposure ceiling.
Definition risk.hpp:506
InstrumentId instrument_
The instrument.
Definition risk.hpp:508
Decimal64 price_
The mark to value it at.
Definition risk.hpp:516
Currency currency_
The currency it trades in.
Definition risk.hpp:510
One order the runner is to place.
std::string tag_
The tag of the intent or target the order came from.
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.
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.
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.
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
The limits the operator sets for RiskGuard.
Definition risk.hpp:412
bool enforce_sellable_quantity_
Whether to refuse a sell larger than the broker's sellable quantity.
Definition risk.hpp:452
bool enforce_buying_power_
Whether to refuse a buy that costs more than the broker's buying power.
Definition risk.hpp:459
std::optional< std::vector< InstrumentId > > permitted_universe_
The instruments that may be traded; absent means any.
Definition risk.hpp:461
std::optional< Money > run_budget_
The run's starting cash, in one currency: buys spend it, sells return their proceeds,...
Definition risk.hpp:498
std::optional< Decimal64 > max_gross_exposure_
The largest gross exposure the portfolio may reach, in the order's currency.
Definition risk.hpp:435
std::optional< Decimal64 > max_position_quantity_
The largest absolute position, in shares, any instrument may reach.
Definition risk.hpp:421
std::optional< RunFees > run_fees_
The fees a run budget estimates for each order; required with run_budget_, unread without it.
Definition risk.hpp:500
std::optional< std::size_t > max_orders_per_window_
The most orders that may be sent within rate_window_.
Definition risk.hpp:437
std::optional< Decimal64 > max_order_notional_
The largest value one order may have, in its own currency.
Definition risk.hpp:414
std::chrono::seconds rate_window_
The window max_orders_per_window_ counts over.
Definition risk.hpp:439
std::optional< std::vector< MarketPhase > > permitted_phases_
The market phases in which a position may be opened or increased; absent means any.
Definition risk.hpp:475
The fees a run budget estimates for an order (RiskLimits::run_fees_).
Definition risk.hpp:320
Decimal64 commission_rate_
The fraction of traded value charged on buys and sells (0.00015, not 0.015).
Definition risk.hpp:322
std::optional< Decimal64 > estimate_tax(const Decimal64 &value, OrderSide side) const
Estimates the tax on one order.
Definition risk.hpp:369
std::optional< Decimal64 > sell_tax_rate_
The fraction of a sell's value charged as tax, if any.
Definition risk.hpp:328
std::optional< Decimal64 > estimate_commission(const Decimal64 &value) const
Estimates the commission on one order.
Definition risk.hpp:337
std::optional< Decimal64 > institution_rate_
A fraction of traded value charged on top of the commission (an institution fee), if any.
Definition risk.hpp:326
Decimal64 commission_minimum_
The least commission on one order.
Definition risk.hpp:324