4#include "./portfolio.hpp"
7#include <algotradelib/core>
154 return "local_failure";
158 return "order_list_unread";
160 return "portfolio_absent";
162 return "portfolio_stale";
164 return "buying_power_unread";
166 return "poll_failing";
178 "all_halt_reasons must list every HaltReason"
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";
381 static std::optional<Decimal64> charged_on(
const Decimal64& value,
const Decimal64& rate) {
391 const auto scale = exact->scale();
395 std::int64_t unit = 1;
396 for (std::uint8_t step = 0; step < scale; ++step) {
399 const auto coefficient = exact->coefficient();
400 return Decimal64(coefficient / unit + (coefficient % unit != 0 ? 1 : 0), 0);
522 std::chrono::system_clock::time_point
now_{};
557namespace risk_detail {
565inline std::optional<Decimal64> decimal_magnitude(
const Decimal64& value) {
574inline std::optional<Decimal64> run_buy_cost(
const RunFees& fees,
const Decimal64& quantity,
const Decimal64& price) {
576 const auto commission = value ? fees.estimate_commission(*value) : std::nullopt;
577 return commission ?
decimal_add(*value, *commission) : std::nullopt;
618template <
typename Broker>
627 std::vector<InstrumentId> instruments;
628 const auto note = [&instruments](
const InstrumentId& id) {
629 for (
const auto& seen : instruments) {
634 instruments.push_back(
id);
636 for (
const auto& position : portfolio.
positions_) {
639 if (position.quantity_.coefficient() == 0) {
642 note(position.instrument_);
644 for (
const auto& working : portfolio.
working_) {
646 note(working.order_.instrument_);
649 if (candidate !=
nullptr) {
654 for (
const auto&
id : instruments) {
656 for (
const auto& entry : basis) {
657 if (!(entry.instrument_ ==
id)) {
660 if (resolved !=
nullptr) {
667 if (resolved ==
nullptr) {
670 if (!(resolved->
currency_ == currency)) {
681 for (
const auto& position : portfolio.
positions_) {
682 if (!(position.instrument_ ==
id)) {
685 const auto sum =
decimal_add(held, position.quantity_);
693 auto price = resolved->
price_;
694 for (
const auto& working : portfolio.
working_) {
695 if (!(working.order_.instrument_ ==
id) || !
order_is_open(working.order_.status_)) {
698 const auto remaining =
decimal_subtract(working.order_.quantity_, working.order_.execution_.filled_quantity_);
707 const auto sum =
decimal_add(working.order_.side_ == OrderSide::BUY ? buys : sells, *remaining);
711 (working.order_.side_ == OrderSide::BUY ? buys : sells) = *sum;
712 if (working.order_.price_) {
717 price = risk_detail::decimal_max(price, *working.order_.price_);
721 if (candidate !=
nullptr && candidate->
instrument_ ==
id) {
724 const auto stated = candidate->
price_ ? candidate->
price_ : candidate_price;
731 price = risk_detail::decimal_max(price, *stated);
733 bool adds_quantity =
false;
734 switch (contribution) {
736 adds_quantity =
true;
746 (candidate->
side_ == OrderSide::BUY ? buys : sells) = *sum;
752 if (!if_bought || !if_sold) {
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) {
760 const auto projected = risk_detail::decimal_max(*long_side, *short_side);
795template <
typename Broker>
804 const auto held = *net;
806 if (held.coefficient() == 0) {
815 const auto closing =
decimal_less(zero, held) ? OrderSide::SELL : OrderSide::BUY;
816 if (order.
side_ != closing) {
821 for (
const auto& working : portfolio.
working_) {
822 if (!(working.order_.instrument_ == order.
instrument_) || working.order_.side_ != closing) {
828 const auto remaining =
decimal_subtract(working.order_.quantity_, working.order_.execution_.filled_quantity_);
844 const auto magnitude = risk_detail::decimal_magnitude(held);
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()) {}
915 if (
this != &other) {
917 *
this = std::move(copy);
936 if (!limits_.permitted_phases_) {
939 for (
const auto allowed : *limits_.permitted_phases_) {
940 if (allowed == phase) {
970 held_[index_of(reason)] =
true;
971 details_[index_of(reason)] = std::move(detail);
979 halt(reason, std::string());
992 held_[index_of(reason)] =
false;
993 details_[index_of(reason)].clear();
1001 for (
const auto held : held_) {
1015 return held_[index_of(reason)];
1033 const auto reason =
static_cast<HaltReason>(index);
1038 return std::nullopt;
1046 const std::string& hold_detail(
HaltReason reason)
const noexcept {
1047 return details_[index_of(reason)];
1055 std::vector<HaltReason> held;
1058 held.push_back(
static_cast<HaltReason>(index));
1072 void note_sent(std::chrono::system_clock::time_point when) {
1075 if (!sent_.empty() && when < sent_.back()) {
1076 in_time_order_ =
false;
1078 sent_.push_back(when);
1100 const auto in_window = [&](std::chrono::system_clock::time_point when) {
1101 return now - when < limits_.rate_window_;
1103 if (!in_time_order_) {
1104 return static_cast<std::size_t
>(std::count_if(sent_.begin(), sent_.end(), in_window));
1108 std::partition_point(sent_.begin(), sent_.end(), [&](std::chrono::system_clock::time_point when) {
1109 return !in_window(when);
1111 return static_cast<std::size_t
>(sent_.end() - first);
1119 while (!sent_.empty() && sent_.front() < cutoff) {
1134 template <
typename Broker>
1162 template <
typename Broker>
1166 const auto refuse = [&order](
GuardReason reason) {
1171 return GuardDecision{std::optional<GuardRejection>(rejection),
false};
1178 rejection.
limit_ = std::move(limit);
1180 return GuardDecision{std::optional<GuardRejection>(rejection),
false};
1185 bool admitted_outside_phase =
false;
1189 decision.rejection_->halt_reason_ = *holding;
1193 if (limits_.permitted_universe_) {
1194 bool permitted =
false;
1195 for (
const auto& allowed : *limits_.permitted_universe_) {
1206 if (limits_.permitted_phases_) {
1207 bool permitted =
false;
1208 for (
const auto phase : *limits_.permitted_phases_) {
1209 if (phase == inputs.
phase_) {
1220 if (!closing || !*closing) {
1223 admitted_outside_phase =
true;
1227 if (limits_.max_orders_per_window_ &&
recent_orders(inputs.
now_) >= *limits_.max_orders_per_window_) {
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) {
1244 std::optional<Decimal64> value;
1247 if (needs_value && !value) {
1252 if (limits_.max_order_notional_ && value &&
decimal_less(*limits_.max_order_notional_, *value)) {
1256 if (checks_selling_ && order.
side_ == OrderSide::SELL) {
1257 if (limits_.run_budget_) {
1258 if (
auto refused = refuse_run_sell(order, portfolio, inputs)) {
1264 const auto& sellable = reading.
quantity_;
1271 if (!reading.basis_.is_enforceable()) {
1288 if (checks_spending_ && order.
side_ == OrderSide::BUY) {
1289 if (limits_.run_budget_) {
1290 if (
auto refused = refuse_run_buy(order, portfolio, inputs, value)) {
1312 if (limits_.max_position_quantity_) {
1320 const auto held = *net;
1328 const auto signed_quantity =
1329 order.
side_ == OrderSide::BUY ? std::optional<Decimal64>(*committed) :
decimal_subtract(zero, *committed);
1330 if (!signed_quantity) {
1333 const auto resulting =
decimal_add(held, *signed_quantity);
1338 const auto magnitude =
1343 if (
decimal_less(*limits_.max_position_quantity_, *magnitude)) {
1348 if (limits_.max_gross_exposure_) {
1361 if (
decimal_less(*limits_.max_gross_exposure_, *resulting)) {
1384 std::optional<Decimal64> attempted = std::nullopt
1390 rejection.
limit_ = std::move(limit);
1392 return GuardDecision{std::optional<GuardRejection>(std::move(rejection)),
false};
1397 template <
typename Broker>
1398 std::optional<GuardDecision> refuse_run_sell(
1399 const PlannedOrder& order,
const Portfolio<Broker>& portfolio,
const GuardInputs& inputs
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_;
1415 if (!reading.basis_.is_enforceable()) {
1418 resting = portfolio.working_quantity(order.instrument_, OrderSide::SELL);
1419 committed =
decimal_add(*resting, order.quantity_);
1424 if (!inputs.run_holding_) {
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;
1432 bool names_run = !broker_over;
1433 if (broker_over && run_over) {
1436 names_run = room &&
decimal_less(*inputs.run_holding_, *room);
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
1467 std::optional<Decimal64> available;
1468 if (limits_.enforce_buying_power_) {
1469 if (!inputs.order_currency_) {
1472 available = portfolio.buying_power_in(*inputs.order_currency_);
1478 if (!limits_.run_fees_ || !inputs.run_cash_ || !(inputs.run_cash_->currency_ == limits_.run_budget_->currency_)) {
1481 if (!inputs.order_currency_) {
1484 if (!(*inputs.order_currency_ == inputs.run_cash_->currency_)) {
1488 const auto fee = limits_.run_fees_->estimate_commission(*value);
1489 const auto room = fee ?
decimal_subtract(inputs.run_cash_->amount_, *fee) : std::nullopt;
1493 const bool broker_over = available &&
decimal_less(*available, *value);
1495 if (broker_over && (!run_over || !
decimal_less(*room, *available))) {
1501 return std::nullopt;
1505 static constexpr std::size_t index_of(
HaltReason reason)
noexcept {
1506 return static_cast<std::size_t
>(reason);
1511 std::array<bool, halt_reason_count> held_{};
1513 std::array<std::string, halt_reason_count> details_;
1515 std::deque<std::chrono::system_clock::time_point> sent_;
1517 bool in_time_order_{
true};
1519 bool checks_selling_{
true};
1520 bool checks_spending_{
false};
1521 std::size_t total_sent_{0};
A three-letter currency code, such as KRW or USD (ISO 4217 style).
An exact signed decimal: an int64 coefficient times 10^-scale.
std::int64_t coefficient() const noexcept
Returns the coefficient.
Decimal64()=default
Constructs zero.
static Decimal64 parse(std::string_view input)
Parses a decimal string exactly (no binary floating point).
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.
RiskGuard & operator=(const RiskGuard &other)
Replaces this guard with a copy of another, entirely or not at all.
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.
void halt(HaltReason reason)
Takes a hold, with no description.
const RiskLimits & limits() const noexcept
Returns the limits.
bool halted(HaltReason reason) const noexcept
Tests whether one hold is in force.
void resume(HaltReason reason) noexcept
Releases a hold; releasing one that is not held does nothing.
RiskGuard(RiskLimits limits={})
Constructs a guard.
void resume() noexcept
Releases the operator's hold; other holds, if any, still stop trading.
std::size_t total_sent() const noexcept
Returns how many orders have been recorded with note_sent over the guard's life.
RiskGuard(const RiskGuard &other)=default
Copies a guard.
void halt(HaltReason reason, std::string detail)
Takes a hold, with a description.
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.
std::vector< HaltReason > holds() const
Returns every hold in force.
std::optional< GuardRejection > check(const PlannedOrder &order, const Portfolio< Broker > &portfolio, const GuardInputs &inputs) const
Checks one planned order against the limits and holds.
std::optional< HaltReason > blocking_reason_for(InstructionClass klass) const noexcept
Returns the hold that stops an instruction class, the most fundamental first.
void halt() noexcept
Takes the operator's hold (HaltReason::OPERATOR): no order or cancellation is sent until resume().
void forget_before(std::chrono::system_clock::time_point cutoff)
Forgets sends recorded before an instant, to bound memory.
bool halted() const noexcept
Tests whether any hold is in force.
std::optional< HaltReason > blocking_reason() const noexcept
Returns the hold that stops placements, the most fundamental first.
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.
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.
GuardReason
Which check refused an order.
@ SELLABLE_BASIS_UNESTABLISHED
A sellable quantity is present, but what it covers is not established.
@ RUN_LEDGER_UNSETTLED
The run's cash, or its shares of the instrument, is not known.
@ ORDER_NOTIONAL_TOO_LARGE
The order's value exceeds RiskLimits::max_order_notional_.
@ 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...
@ ORDER_RATE_EXCEEDED
RiskLimits::max_orders_per_window_ orders were already sent in the window.
@ QUANTITY_NOT_SELLABLE
The sell exceeds the broker's sellable quantity, or the broker gave none.
@ POSITION_LIMIT_EXCEEDED
The position could exceed RiskLimits::max_position_quantity_.
@ RUN_HOLDING_EXCEEDED
The sell is more than the run's own shares of the instrument less its open sells.
@ VALUE_NOT_KNOWN
A limit needed a value that is not known.
@ INSUFFICIENT_BUYING_POWER
The buy costs more than the broker's buying power, or the broker gave none.
@ INSTRUMENT_NOT_PERMITTED
The instrument is not in RiskLimits::permitted_universe_.
@ PHASE_NOT_PERMITTED
The market phase is not in RiskLimits::permitted_phases_.
@ RUN_BUDGET_EXCEEDED
The buy's value is more than the run's room (RiskLimits::run_budget_).
@ GROSS_EXPOSURE_EXCEEDED
The gross exposure could exceed RiskLimits::max_gross_exposure_.
@ TRADING_HALTED
A hold is in force; GuardRejection::halt_reason_ names it.
MarketPhase
Where the clock stands relative to the trading session.
@ UNKNOWN
Nothing is known about this instant: the calendar does not cover its date, or the filled session hour...
@ OPEN
Inside the session.
constexpr std::size_t halt_reason_count
The number of HaltReason values.
constexpr bool halt_blocks(HaltReason reason, InstructionClass klass) noexcept
Tests whether a hold stops an instruction of a given class.
std::optional< Decimal64 > projected_gross_exposure(const Portfolio< Broker > &portfolio, const std::vector< InstrumentBasis > &basis, const Currency ¤cy, 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.
CandidateContribution
What a candidate order adds to projected_gross_exposure.
@ QUANTITY_AND_PRICE
The candidate's quantity and price: the exposure if the order is sent.
@ PRICE_ONLY
The candidate's price only: the exposure without the order, valued at the same prices.
bool order_is_open(OrderStatus status)
Tests whether an order in a given status may still trade.
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.
InstructionClass
What an instruction can do to a position, which decides which holds stop it.
@ OPENING
A placement, which can open or enlarge a position. Every hold stops it.
@ WITHDRAWAL
A cancellation of an order the caller named.
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.
constexpr std::string_view halt_reason_name(HaltReason reason) noexcept
Returns a lowercase name for a hold, such as "portfolio_stale", for logs.
constexpr std::array< HaltReason, 8 > all_halt_reasons
Every HaltReason, in declaration order.
HaltReason
Who or what is holding trading stopped.
@ BUYING_POWER_UNREAD
A buying-power limit is enforced, but there is no current reading to check it against.
@ LOCAL_FAILURE
Local machinery failed, such as the order journal not being writable; nothing is sent.
@ PORTFOLIO_ABSENT
No holdings snapshot has been read yet, so what the account holds is unknown.
@ ORDER_LIST_UNREAD
The broker's order list has not been read since this process started.
@ OPERATOR
A person stopped trading with RiskGuard::halt(); only RiskGuard::resume() clears it.
@ PORTFOLIO_STALE
The holdings snapshot is older than the configured maximum age.
@ POLL_FAILING
A poll kept failing and the loop gave up, as opposed to STOPPING on request.
@ STOPPING
A stop was requested and the run is shutting down.
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.
@ LIMIT
지정가: fills at the stated price or better.
@ STOP_LIMIT
스톱지정가: a limit released when a trigger price is reached.
std::optional< Decimal64 > decimal_subtract(const Decimal64 &lhs, const Decimal64 &rhs)
Subtracts two decimals exactly.
bool decimal_less(const Decimal64 &lhs, const Decimal64 &rhs)
Compares two decimals numerically, whatever their scales.
std::optional< Decimal64 > decimal_multiply(const Decimal64 &lhs, const Decimal64 &rhs)
Multiplies two decimals exactly; the scales add.
OrderSide
The side of an order: its economic direction, buy or sell.
Reconciliation: turning a strategy's intents and targets into the orders and cancellations to send.
Identifies an instrument: its country, venue and symbol.
What RiskGuard::evaluate concluded about one order.
bool admitted_outside_phase_
Whether the order was permitted only because it closes toward flat in a phase the limits do not permi...
std::optional< GuardRejection > rejection_
Why the order was refused, or std::nullopt if it was permitted.
One order a guard refused, with the limit and the value that exceeded it.
InstrumentId instrument_
The instrument of the refused order.
std::string tag_
The tag of the intent the order came from.
GuardReason reason_
Which check refused the order.
std::optional< Decimal64 > limit_
The limit that was exceeded, where the reason has one.
std::optional< HaltReason > halt_reason_
The hold that stopped the order, when reason_ is TRADING_HALTED; otherwise empty.
std::optional< Decimal64 > attempted_
The value the order would have reached, where the reason has one.
An instrument's currency and the price to value it at, for the exposure ceiling.
InstrumentId instrument_
The instrument.
Decimal64 price_
The mark to value it at.
Currency currency_
The currency it trades in.
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.
std::vector< WorkingOrder< Broker > > working_
Orders still outstanding at the broker.
std::optional< Decimal64 > buying_power_in(const Currency ¤cy) 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.
The limits the operator sets for RiskGuard.
bool enforce_sellable_quantity_
Whether to refuse a sell larger than the broker's sellable quantity.
bool enforce_buying_power_
Whether to refuse a buy that costs more than the broker's buying power.
std::optional< std::vector< InstrumentId > > permitted_universe_
The instruments that may be traded; absent means any.
std::optional< Money > run_budget_
The run's starting cash, in one currency: buys spend it, sells return their proceeds,...
std::optional< Decimal64 > max_gross_exposure_
The largest gross exposure the portfolio may reach, in the order's currency.
std::optional< Decimal64 > max_position_quantity_
The largest absolute position, in shares, any instrument may reach.
std::optional< RunFees > run_fees_
The fees a run budget estimates for each order; required with run_budget_, unread without it.
std::optional< std::size_t > max_orders_per_window_
The most orders that may be sent within rate_window_.
std::optional< Decimal64 > max_order_notional_
The largest value one order may have, in its own currency.
std::chrono::seconds rate_window_
The window max_orders_per_window_ counts over.
std::optional< std::vector< MarketPhase > > permitted_phases_
The market phases in which a position may be opened or increased; absent means any.
The fees a run budget estimates for an order (RiskLimits::run_fees_).
Decimal64 commission_rate_
The fraction of traded value charged on buys and sells (0.00015, not 0.015).
std::optional< Decimal64 > estimate_tax(const Decimal64 &value, OrderSide side) const
Estimates the tax on one order.
std::optional< Decimal64 > sell_tax_rate_
The fraction of a sell's value charged as tax, if any.
std::optional< Decimal64 > estimate_commission(const Decimal64 &value) const
Estimates the commission on one order.
std::optional< Decimal64 > institution_rate_
A fraction of traded value charged on top of the commission (an institution fee), if any.
Decimal64 commission_minimum_
The least commission on one order.