Slick Trader 0.11.0
Multi-broker algorithmic trading engine with plugin strategies and a live web dashboard
Loading...
Searching...
No Matches
risk_manager.cpp
Go to the documentation of this file.
2#include <chrono>
3#include <cmath>
4
5namespace slick::trader {
6
7void RiskManager::set_limits(const std::string& strategy_id, const RiskLimits& limits) {
8
9 limits_[strategy_id] = limits;
10 LOG_INFO("RiskManager: Set limits for {}: max_pos={}, max_order_value={}, max_orders/sec={}",
11 strategy_id, from_qty_t(limits.max_position_size),
13}
14
15RiskLimits RiskManager::get_limits(const std::string& strategy_id) const {
16
17 auto it = limits_.find(strategy_id);
18 if (it == limits_.end()) {
19 return RiskLimits{}; // Return default limits
20 }
21 return it->second;
22}
23
24bool RiskManager::validate_order(const std::string& strategy_id, std::string_view instrument,
25 Side side, qty_t quantity, price_t price, std::string* reject_reason) {
26
27 // Check if strategy is halted
28 if (halted_strategies_.find(strategy_id) != halted_strategies_.end()) {
29 if (reject_reason) {
30 *reject_reason = "Strategy halted: " + halted_strategies_[strategy_id];
31 }
32 return false;
33 }
34
35 // Get limits
36 auto limits_it = limits_.find(strategy_id);
37 if (limits_it == limits_.end()) {
38 // No limits configured - allow by default
39 return true;
40 }
41
42 const RiskLimits& limits = limits_it->second;
43
44 // Check position limit
45 if (!check_position_limit(strategy_id, instrument, side == Side::BUY,
46 quantity, reject_reason)) {
47 return false;
48 }
49
50 // Check order value limit
51 if (!check_order_value_limit(instrument, price, quantity, limits, reject_reason)) {
52 return false;
53 }
54
55 // Check rate limit
56 if (!check_rate_limit(strategy_id, limits, reject_reason)) {
57 return false;
58 }
59
60 return true;
61}
62
63bool RiskManager::check_position_limit(const std::string& strategy_id, std::string_view instrument,
64 bool is_buy, qty_t order_qty, std::string* reason) {
65 // Get current position
66 Position pos = position_tracker_.get_position(strategy_id, instrument);
67
68 // Calculate position after order
69 const qty_t signed_order_qty = is_buy ? order_qty : -order_qty;
70 const qty_t new_position = pos.quantity + signed_order_qty;
71
72 // Get limits
73 auto limits_it = limits_.find(strategy_id);
74 if (limits_it == limits_.end()) {
75 return true;
76 }
77
78 // Get instrument-specific limits (or defaults)
79 const auto inst_limits = limits_it->second.get_instrument_limits(instrument);
80 const qty_t max_pos = inst_limits.max_position_size;
81
82 const bool is_reducing = std::abs(from_qty_t(new_position)) < std::abs(from_qty_t(pos.quantity));
83 if (!is_reducing && std::abs(from_qty_t(new_position)) > from_qty_t(max_pos)) {
84 if (reason) {
85 *reason = "Position limit exceeded for " + std::string(instrument) +
86 ": current=" + std::to_string(from_qty_t(pos.quantity)) +
87 " order=" + std::to_string(from_qty_t(order_qty)) +
88 " max=" + std::to_string(from_qty_t(max_pos));
89 }
90 LOG_WARN("RiskManager: Position limit check failed for {}: {}", strategy_id,
91 reason ? *reason : "");
92 return false;
93 }
94
95 return true;
96}
97
98bool RiskManager::check_order_value_limit(std::string_view instrument, price_t price, qty_t quantity,
99 const RiskLimits& limits, std::string* reason) {
100 // Notional: price x quantity x contract multiplier (ES at 5000 is $250,000 a contract, not
101 // $5,000). Absolute, because a spread order's price can be negative.
102 const double order_value = std::abs(from_price_t(price) * from_qty_t(quantity))
103 * position_tracker_.get_contract_multiplier(instrument);
104
105 // Get instrument-specific limits (or defaults)
106 const auto inst_limits = limits.get_instrument_limits(instrument);
107 const double max_value = from_price_t(inst_limits.max_order_value);
108
109 if (order_value > max_value) {
110 if (reason) {
111 *reason = "Order value limit exceeded for " + std::string(instrument) +
112 ": value=" + std::to_string(order_value) +
113 " max=" + std::to_string(max_value);
114 }
115 LOG_WARN("RiskManager: Order value check failed: {}", reason ? *reason : "");
116 return false;
117 }
118
119 return true;
120}
121
122bool RiskManager::check_rate_limit(const std::string& strategy_id, const RiskLimits& limits,
123 std::string* reason) {
124 const uint64_t now_ns = static_cast<uint64_t>(
125 std::chrono::duration_cast<std::chrono::nanoseconds>(
126 std::chrono::steady_clock::now().time_since_epoch()).count());
127 constexpr uint64_t ONE_SECOND_NS = 1'000'000'000;
128
129 auto& rate_limit = rate_limits_[strategy_id];
130
131 // Reset window if more than 1 second has passed
132 if (now_ns - rate_limit.window_start_ns >= ONE_SECOND_NS) {
133 rate_limit.count = 0;
134 rate_limit.window_start_ns = now_ns;
135 }
136
137 // Check if we've exceeded the limit
138 if (rate_limit.count >= limits.max_orders_per_second) {
139 if (reason) {
140 *reason = "Rate limit exceeded: " + std::to_string(rate_limit.count) +
141 " orders in last second (max=" + std::to_string(limits.max_orders_per_second) + ")";
142 }
143 LOG_WARN("RiskManager: Rate limit check failed for {}: {}", strategy_id,
144 reason ? *reason : "");
145 return false;
146 }
147
148 // Increment counter
149 rate_limit.count++;
150 return true;
151}
152
153bool RiskManager::is_halted(const std::string& strategy_id) const {
154
155 return halted_strategies_.find(strategy_id) != halted_strategies_.end();
156}
157
158std::string RiskManager::get_halt_reason(const std::string& strategy_id) const {
159 auto it = halted_strategies_.find(strategy_id);
160 return it != halted_strategies_.end() ? it->second : "";
161}
162
163void RiskManager::halt_strategy(const std::string& strategy_id, const std::string& reason) {
164
165 halted_strategies_[strategy_id] = reason;
166 LOG_ERROR("RiskManager: HALTED strategy {}: {}", strategy_id, reason);
167}
168
169void RiskManager::resume_strategy(const std::string& strategy_id) {
170
171 halted_strategies_.erase(strategy_id);
172 LOG_INFO("RiskManager: RESUMED strategy {}", strategy_id);
173}
174
176
177 limits_.clear();
178 rate_limits_.clear();
179 halted_strategies_.clear();
180 LOG_INFO("RiskManager: Cleared all limits and halt states");
181}
182
183} // namespace slick::trader
Position get_position(const std::string &strategy_id, std::string_view instrument) const
void halt_strategy(const std::string &strategy_id, const std::string &reason)
bool validate_order(const std::string &strategy_id, std::string_view instrument, Side side, qty_t quantity, price_t price, std::string *reject_reason=nullptr)
RiskLimits get_limits(const std::string &strategy_id) const
void set_limits(const std::string &strategy_id, const RiskLimits &limits)
bool is_halted(const std::string &strategy_id) const
void resume_strategy(const std::string &strategy_id)
std::string get_halt_reason(const std::string &strategy_id) const
double from_price_t(price_t value)
Definition types.hpp:36
int64_t qty_t
Definition types.hpp:17
int64_t price_t
Definition types.hpp:16
double from_qty_t(qty_t value)
Definition types.hpp:40