nautilus_risk/engine/
mod.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2025 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16//! Risk management engine implementation.
17
18pub mod config;
19
20#[cfg(test)]
21mod tests;
22
23use std::{cell::RefCell, collections::HashMap, fmt::Debug, rc::Rc};
24
25use config::RiskEngineConfig;
26use nautilus_common::{
27    cache::Cache,
28    clock::Clock,
29    logging::{CMD, EVT, RECV},
30    messages::execution::{ModifyOrder, SubmitOrder, SubmitOrderList, TradingCommand},
31    msgbus,
32    throttler::Throttler,
33};
34use nautilus_core::UUID4;
35use nautilus_model::{
36    accounts::{Account, AccountAny},
37    enums::{InstrumentClass, OrderSide, OrderStatus, TimeInForce, TradingState},
38    events::{OrderDenied, OrderEventAny, OrderModifyRejected},
39    identifiers::InstrumentId,
40    instruments::{Instrument, InstrumentAny},
41    orders::{Order, OrderAny, OrderList},
42    types::{Currency, Money, Price, Quantity},
43};
44use nautilus_portfolio::Portfolio;
45use rust_decimal::{Decimal, prelude::ToPrimitive};
46use ustr::Ustr;
47
48type SubmitOrderFn = Box<dyn Fn(SubmitOrder)>;
49type ModifyOrderFn = Box<dyn Fn(ModifyOrder)>;
50
51/// Central risk management engine that validates and controls trading operations.
52///
53/// The `RiskEngine` provides comprehensive pre-trade risk checks including order validation,
54/// balance verification, position sizing limits, and trading state management. It acts as
55/// a gateway between strategy orders and execution, ensuring all trades comply with
56/// defined risk parameters and regulatory constraints.
57#[allow(dead_code)]
58pub struct RiskEngine {
59    clock: Rc<RefCell<dyn Clock>>,
60    cache: Rc<RefCell<Cache>>,
61    portfolio: Portfolio,
62    pub throttled_submit_order: Throttler<SubmitOrder, SubmitOrderFn>,
63    pub throttled_modify_order: Throttler<ModifyOrder, ModifyOrderFn>,
64    max_notional_per_order: HashMap<InstrumentId, Decimal>,
65    trading_state: TradingState,
66    config: RiskEngineConfig,
67}
68
69impl Debug for RiskEngine {
70    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
71        f.debug_struct(stringify!(RiskEngine)).finish()
72    }
73}
74
75impl RiskEngine {
76    /// Creates a new [`RiskEngine`] instance.
77    pub fn new(
78        config: RiskEngineConfig,
79        portfolio: Portfolio,
80        clock: Rc<RefCell<dyn Clock>>,
81        cache: Rc<RefCell<Cache>>,
82    ) -> Self {
83        let throttled_submit_order =
84            Self::create_submit_order_throttler(&config, clock.clone(), cache.clone());
85
86        let throttled_modify_order =
87            Self::create_modify_order_throttler(&config, clock.clone(), cache.clone());
88
89        Self {
90            clock,
91            cache,
92            portfolio,
93            throttled_submit_order,
94            throttled_modify_order,
95            max_notional_per_order: HashMap::new(),
96            trading_state: TradingState::Active,
97            config,
98        }
99    }
100
101    fn create_submit_order_throttler(
102        config: &RiskEngineConfig,
103        clock: Rc<RefCell<dyn Clock>>,
104        cache: Rc<RefCell<Cache>>,
105    ) -> Throttler<SubmitOrder, SubmitOrderFn> {
106        let success_handler = {
107            Box::new(move |submit_order: SubmitOrder| {
108                msgbus::send_any(
109                    "ExecEngine.execute".into(),
110                    &TradingCommand::SubmitOrder(submit_order),
111                );
112            }) as Box<dyn Fn(SubmitOrder)>
113        };
114
115        let failure_handler = {
116            let cache = cache;
117            let clock = clock.clone();
118            Box::new(move |submit_order: SubmitOrder| {
119                let reason = "REJECTED BY THROTTLER";
120                log::warn!(
121                    "SubmitOrder for {} DENIED: {}",
122                    submit_order.client_order_id,
123                    reason
124                );
125
126                Self::handle_submit_order_cache(&cache, &submit_order);
127
128                let denied = Self::create_order_denied(&submit_order, reason, &clock);
129
130                msgbus::send_any("ExecEngine.process".into(), &denied);
131            }) as Box<dyn Fn(SubmitOrder)>
132        };
133
134        Throttler::new(
135            config.max_order_submit.limit,
136            config.max_order_submit.interval_ns,
137            clock,
138            "ORDER_SUBMIT_THROTTLER".to_string(),
139            success_handler,
140            Some(failure_handler),
141            Ustr::from(&UUID4::new().to_string()),
142        )
143    }
144
145    fn create_modify_order_throttler(
146        config: &RiskEngineConfig,
147        clock: Rc<RefCell<dyn Clock>>,
148        cache: Rc<RefCell<Cache>>,
149    ) -> Throttler<ModifyOrder, ModifyOrderFn> {
150        let success_handler = {
151            Box::new(move |order: ModifyOrder| {
152                msgbus::send_any(
153                    "ExecEngine.execute".into(),
154                    &TradingCommand::ModifyOrder(order),
155                );
156            }) as Box<dyn Fn(ModifyOrder)>
157        };
158
159        let failure_handler = {
160            let cache = cache;
161            let clock = clock.clone();
162            Box::new(move |order: ModifyOrder| {
163                let reason = "Exceeded MAX_ORDER_MODIFY_RATE";
164                log::warn!(
165                    "SubmitOrder for {} DENIED: {}",
166                    order.client_order_id,
167                    reason
168                );
169
170                let order = match Self::get_existing_order(&cache, &order) {
171                    Some(order) => order,
172                    None => return,
173                };
174
175                let rejected = Self::create_modify_rejected(&order, reason, &clock);
176
177                msgbus::send_any("ExecEngine.process".into(), &rejected);
178            }) as Box<dyn Fn(ModifyOrder)>
179        };
180
181        Throttler::new(
182            config.max_order_modify.limit,
183            config.max_order_modify.interval_ns,
184            clock,
185            "ORDER_MODIFY_THROTTLER".to_string(),
186            success_handler,
187            Some(failure_handler),
188            Ustr::from(&UUID4::new().to_string()),
189        )
190    }
191
192    fn handle_submit_order_cache(cache: &Rc<RefCell<Cache>>, submit_order: &SubmitOrder) {
193        let mut cache = cache.borrow_mut();
194        if !cache.order_exists(&submit_order.client_order_id) {
195            cache
196                .add_order(submit_order.order.clone(), None, None, false)
197                .map_err(|e| {
198                    log::error!("Cannot add order to cache: {e}");
199                })
200                .unwrap();
201        }
202    }
203
204    fn get_existing_order(cache: &Rc<RefCell<Cache>>, order: &ModifyOrder) -> Option<OrderAny> {
205        let cache = cache.borrow();
206        if let Some(order) = cache.order(&order.client_order_id) {
207            Some(order.clone())
208        } else {
209            log::error!(
210                "Order with command.client_order_id: {} not found",
211                order.client_order_id
212            );
213            None
214        }
215    }
216
217    fn create_order_denied(
218        submit_order: &SubmitOrder,
219        reason: &str,
220        clock: &Rc<RefCell<dyn Clock>>,
221    ) -> OrderEventAny {
222        let timestamp = clock.borrow().timestamp_ns();
223        OrderEventAny::Denied(OrderDenied::new(
224            submit_order.trader_id,
225            submit_order.strategy_id,
226            submit_order.instrument_id,
227            submit_order.client_order_id,
228            reason.into(),
229            UUID4::new(),
230            timestamp,
231            timestamp,
232        ))
233    }
234
235    fn create_modify_rejected(
236        order: &OrderAny,
237        reason: &str,
238        clock: &Rc<RefCell<dyn Clock>>,
239    ) -> OrderEventAny {
240        let timestamp = clock.borrow().timestamp_ns();
241        OrderEventAny::ModifyRejected(OrderModifyRejected::new(
242            order.trader_id(),
243            order.strategy_id(),
244            order.instrument_id(),
245            order.client_order_id(),
246            reason.into(),
247            UUID4::new(),
248            timestamp,
249            timestamp,
250            false,
251            order.venue_order_id(),
252            None,
253        ))
254    }
255
256    // -- COMMANDS --------------------------------------------------------------------------------
257
258    /// Executes a trading command through the risk management pipeline.
259    pub fn execute(&mut self, command: TradingCommand) {
260        // This will extend to other commands such as `RiskCommand`
261        self.handle_command(command);
262    }
263
264    /// Processes an order event for risk monitoring and state updates.
265    pub fn process(&mut self, event: OrderEventAny) {
266        // This will extend to other events such as `RiskEvent`
267        self.handle_event(event);
268    }
269
270    /// Sets the trading state for risk control enforcement.
271    pub fn set_trading_state(&mut self, state: TradingState) {
272        if state == self.trading_state {
273            log::warn!("No change to trading state: already set to {state:?}");
274            return;
275        }
276
277        self.trading_state = state;
278
279        let _ts_now = self.clock.borrow().timestamp_ns();
280
281        // TODO: Create a new Event "TradingStateChanged" in OrderEventAny enum.
282        // let event = OrderEventAny::TradingStateChanged(TradingStateChanged::new(..,self.trading_state,..));
283
284        msgbus::publish("events.risk".into(), &"message"); // TODO: Send the new Event here
285
286        log::info!("Trading state set to {state:?}");
287    }
288
289    /// Sets the maximum notional value per order for the specified instrument.
290    pub fn set_max_notional_per_order(&mut self, instrument_id: InstrumentId, new_value: Decimal) {
291        self.max_notional_per_order.insert(instrument_id, new_value);
292
293        let new_value_str = new_value.to_string();
294        log::info!("Set MAX_NOTIONAL_PER_ORDER: {instrument_id} {new_value_str}");
295    }
296
297    // -- COMMAND HANDLERS ------------------------------------------------------------------------
298
299    // Renamed from `execute_command`
300    fn handle_command(&mut self, command: TradingCommand) {
301        if self.config.debug {
302            log::debug!("{CMD}{RECV} {command:?}");
303        }
304
305        match command {
306            TradingCommand::SubmitOrder(submit_order) => self.handle_submit_order(submit_order),
307            TradingCommand::SubmitOrderList(submit_order_list) => {
308                self.handle_submit_order_list(submit_order_list);
309            }
310            TradingCommand::ModifyOrder(modify_order) => self.handle_modify_order(modify_order),
311            TradingCommand::QueryAccount(query_account) => {
312                self.send_to_execution(TradingCommand::QueryAccount(query_account));
313            }
314            _ => {
315                log::error!("Cannot handle command: {command}");
316            }
317        }
318    }
319
320    fn handle_submit_order(&mut self, command: SubmitOrder) {
321        if self.config.bypass {
322            self.send_to_execution(TradingCommand::SubmitOrder(command));
323            return;
324        }
325
326        let order = &command.order;
327        if let Some(position_id) = command.position_id
328            && order.is_reduce_only()
329        {
330            let position_exists = {
331                let cache = self.cache.borrow();
332                cache
333                    .position(&position_id)
334                    .map(|pos| (pos.side, pos.quantity))
335            };
336
337            if let Some((pos_side, pos_quantity)) = position_exists {
338                if !order.would_reduce_only(pos_side, pos_quantity) {
339                    self.deny_command(
340                        TradingCommand::SubmitOrder(command),
341                        &format!("Reduce only order would increase position {position_id}"),
342                    );
343                    return; // Denied
344                }
345            } else {
346                self.deny_command(
347                    TradingCommand::SubmitOrder(command),
348                    &format!("Position {position_id} not found for reduce-only order"),
349                );
350                return;
351            }
352        }
353
354        let instrument_exists = {
355            let cache = self.cache.borrow();
356            cache.instrument(&command.instrument_id).cloned()
357        };
358
359        let instrument = if let Some(instrument) = instrument_exists {
360            instrument
361        } else {
362            self.deny_command(
363                TradingCommand::SubmitOrder(command.clone()),
364                &format!("Instrument for {} not found", command.instrument_id),
365            );
366            return; // Denied
367        };
368
369        ////////////////////////////////////////////////////////////////////////////////
370        // PRE-TRADE ORDER(S) CHECKS
371        ////////////////////////////////////////////////////////////////////////////////
372        if !self.check_order(instrument.clone(), order.clone()) {
373            return; // Denied
374        }
375
376        if !self.check_orders_risk(instrument.clone(), Vec::from([order.clone()])) {
377            return; // Denied
378        }
379
380        // Route through execution gateway for TradingState checks & throttling
381        self.execution_gateway(instrument, TradingCommand::SubmitOrder(command));
382    }
383
384    fn handle_submit_order_list(&mut self, command: SubmitOrderList) {
385        if self.config.bypass {
386            self.send_to_execution(TradingCommand::SubmitOrderList(command));
387            return;
388        }
389
390        let instrument_exists = {
391            let cache = self.cache.borrow();
392            cache.instrument(&command.instrument_id).cloned()
393        };
394
395        let instrument = if let Some(instrument) = instrument_exists {
396            instrument
397        } else {
398            self.deny_command(
399                TradingCommand::SubmitOrderList(command.clone()),
400                &format!("no instrument found for {}", command.instrument_id),
401            );
402            return; // Denied
403        };
404
405        ////////////////////////////////////////////////////////////////////////////////
406        // PRE-TRADE ORDER(S) CHECKS
407        ////////////////////////////////////////////////////////////////////////////////
408        for order in command.order_list.orders.clone() {
409            if !self.check_order(instrument.clone(), order) {
410                return; // Denied
411            }
412        }
413
414        if !self.check_orders_risk(instrument.clone(), command.order_list.clone().orders) {
415            self.deny_order_list(
416                command.order_list.clone(),
417                &format!("OrderList {} DENIED", command.order_list.id),
418            );
419            return; // Denied
420        }
421
422        self.execution_gateway(instrument, TradingCommand::SubmitOrderList(command));
423    }
424
425    fn handle_modify_order(&mut self, command: ModifyOrder) {
426        ////////////////////////////////////////////////////////////////////////////////
427        // VALIDATE COMMAND
428        ////////////////////////////////////////////////////////////////////////////////
429        let order_exists = {
430            let cache = self.cache.borrow();
431            cache.order(&command.client_order_id).cloned()
432        };
433
434        let order = if let Some(order) = order_exists {
435            order
436        } else {
437            log::error!(
438                "ModifyOrder DENIED: Order with command.client_order_id: {} not found",
439                command.client_order_id
440            );
441            return;
442        };
443
444        if order.is_closed() {
445            self.reject_modify_order(
446                order,
447                &format!(
448                    "Order with command.client_order_id: {} already closed",
449                    command.client_order_id
450                ),
451            );
452            return;
453        } else if order.status() == OrderStatus::PendingCancel {
454            self.reject_modify_order(
455                order,
456                &format!(
457                    "Order with command.client_order_id: {} is already pending cancel",
458                    command.client_order_id
459                ),
460            );
461            return;
462        }
463
464        let maybe_instrument = {
465            let cache = self.cache.borrow();
466            cache.instrument(&command.instrument_id).cloned()
467        };
468
469        let instrument = if let Some(instrument) = maybe_instrument {
470            instrument
471        } else {
472            self.reject_modify_order(
473                order,
474                &format!("no instrument found for {:?}", command.instrument_id),
475            );
476            return; // Denied
477        };
478
479        // Check Price
480        let mut risk_msg = self.check_price(&instrument, command.price);
481        if let Some(risk_msg) = risk_msg {
482            self.reject_modify_order(order, &risk_msg);
483            return; // Denied
484        }
485
486        // Check Trigger
487        risk_msg = self.check_price(&instrument, command.trigger_price);
488        if let Some(risk_msg) = risk_msg {
489            self.reject_modify_order(order, &risk_msg);
490            return; // Denied
491        }
492
493        // Check Quantity
494        risk_msg = self.check_quantity(&instrument, command.quantity);
495        if let Some(risk_msg) = risk_msg {
496            self.reject_modify_order(order, &risk_msg);
497            return; // Denied
498        }
499
500        // Check TradingState
501        match self.trading_state {
502            TradingState::Halted => {
503                self.reject_modify_order(order, "TradingState is HALTED: Cannot modify order");
504            }
505            TradingState::Reducing => {
506                if let Some(quantity) = command.quantity
507                    && quantity > order.quantity()
508                    && ((order.is_buy() && self.portfolio.is_net_long(&instrument.id()))
509                        || (order.is_sell() && self.portfolio.is_net_short(&instrument.id())))
510                {
511                    self.reject_modify_order(
512                        order,
513                        &format!(
514                            "TradingState is REDUCING and update will increase exposure {}",
515                            instrument.id()
516                        ),
517                    );
518                }
519            }
520            _ => {}
521        }
522
523        self.throttled_modify_order.send(command);
524    }
525
526    // -- PRE-TRADE CHECKS ------------------------------------------------------------------------
527
528    fn check_order(&self, instrument: InstrumentAny, order: OrderAny) -> bool {
529        ////////////////////////////////////////////////////////////////////////////////
530        // VALIDATION CHECKS
531        ////////////////////////////////////////////////////////////////////////////////
532        if order.time_in_force() == TimeInForce::Gtd {
533            // SAFETY: GTD guarantees an expire time
534            let expire_time = order.expire_time().unwrap();
535            if expire_time <= self.clock.borrow().timestamp_ns() {
536                self.deny_order(
537                    order,
538                    &format!("GTD {} already past", expire_time.to_rfc3339()),
539                );
540                return false; // Denied
541            }
542        }
543
544        if !self.check_order_price(instrument.clone(), order.clone())
545            || !self.check_order_quantity(instrument, order)
546        {
547            return false; // Denied
548        }
549
550        true
551    }
552
553    fn check_order_price(&self, instrument: InstrumentAny, order: OrderAny) -> bool {
554        ////////////////////////////////////////////////////////////////////////////////
555        // CHECK PRICE
556        ////////////////////////////////////////////////////////////////////////////////
557        if order.price().is_some() {
558            let risk_msg = self.check_price(&instrument, order.price());
559            if let Some(risk_msg) = risk_msg {
560                self.deny_order(order, &risk_msg);
561                return false; // Denied
562            }
563        }
564
565        ////////////////////////////////////////////////////////////////////////////////
566        // CHECK TRIGGER
567        ////////////////////////////////////////////////////////////////////////////////
568        if order.trigger_price().is_some() {
569            let risk_msg = self.check_price(&instrument, order.trigger_price());
570            if let Some(risk_msg) = risk_msg {
571                self.deny_order(order, &risk_msg);
572                return false; // Denied
573            }
574        }
575
576        true
577    }
578
579    fn check_order_quantity(&self, instrument: InstrumentAny, order: OrderAny) -> bool {
580        let risk_msg = self.check_quantity(&instrument, Some(order.quantity()));
581        if let Some(risk_msg) = risk_msg {
582            self.deny_order(order, &risk_msg);
583            return false; // Denied
584        }
585
586        true
587    }
588
589    fn check_orders_risk(&self, instrument: InstrumentAny, orders: Vec<OrderAny>) -> bool {
590        ////////////////////////////////////////////////////////////////////////////////
591        // CHECK TRIGGER
592        ////////////////////////////////////////////////////////////////////////////////
593        let mut last_px: Option<Price> = None;
594        let mut max_notional: Option<Money> = None;
595
596        // Determine max notional
597        let max_notional_setting = self.max_notional_per_order.get(&instrument.id());
598        if let Some(max_notional_setting_val) = max_notional_setting.copied() {
599            max_notional = Some(Money::new(
600                max_notional_setting_val
601                    .to_f64()
602                    .expect("Invalid decimal conversion"),
603                instrument.quote_currency(),
604            ));
605        }
606
607        // Get account for risk checks
608        let account_exists = {
609            let cache = self.cache.borrow();
610            cache.account_for_venue(&instrument.id().venue).cloned()
611        };
612
613        let account = if let Some(account) = account_exists {
614            account
615        } else {
616            log::debug!("Cannot find account for venue {}", instrument.id().venue);
617            return true; // TODO: Temporary early return until handling routing/multiple venues
618        };
619        let cash_account = match account {
620            AccountAny::Cash(cash_account) => cash_account,
621            AccountAny::Margin(_) => return true, // TODO: Determine risk controls for margin
622        };
623        let free = cash_account.balance_free(Some(instrument.quote_currency()));
624        if self.config.debug {
625            log::debug!("Free cash: {free:?}");
626        }
627
628        let mut cum_notional_buy: Option<Money> = None;
629        let mut cum_notional_sell: Option<Money> = None;
630        let mut base_currency: Option<Currency> = None;
631        for order in &orders {
632            // Determine last price based on order type
633            last_px = match order {
634                OrderAny::Market(_) | OrderAny::MarketToLimit(_) => {
635                    if last_px.is_none() {
636                        let cache = self.cache.borrow();
637                        if let Some(last_quote) = cache.quote(&instrument.id()) {
638                            match order.order_side() {
639                                OrderSide::Buy => Some(last_quote.ask_price),
640                                OrderSide::Sell => Some(last_quote.bid_price),
641                                _ => panic!("Invalid order side"),
642                            }
643                        } else {
644                            let cache = self.cache.borrow();
645                            let last_trade = cache.trade(&instrument.id());
646
647                            if let Some(last_trade) = last_trade {
648                                Some(last_trade.price)
649                            } else {
650                                log::warn!(
651                                    "Cannot check MARKET order risk: no prices for {}",
652                                    instrument.id()
653                                );
654                                continue;
655                            }
656                        }
657                    } else {
658                        last_px
659                    }
660                }
661                OrderAny::StopMarket(_) | OrderAny::MarketIfTouched(_) => order.trigger_price(),
662                OrderAny::TrailingStopMarket(_) | OrderAny::TrailingStopLimit(_) => {
663                    if let Some(trigger_price) = order.trigger_price() {
664                        Some(trigger_price)
665                    } else {
666                        log::warn!(
667                            "Cannot check {} order risk: no trigger price was set", // TODO: Use last_trade += offset
668                            order.order_type()
669                        );
670                        continue;
671                    }
672                }
673                _ => order.price(),
674            };
675
676            let last_px = if let Some(px) = last_px {
677                px
678            } else {
679                log::error!("Cannot check order risk: no price available");
680                continue;
681            };
682
683            let effective_quantity = if order.is_quote_quantity() && !instrument.is_inverse() {
684                instrument.calculate_base_quantity(order.quantity(), last_px)
685            } else {
686                order.quantity()
687            };
688
689            let notional =
690                instrument.calculate_notional_value(effective_quantity, last_px, Some(true));
691
692            if self.config.debug {
693                log::debug!("Notional: {notional:?}");
694            }
695
696            // Check MAX notional per order limit
697            if let Some(max_notional_value) = max_notional
698                && notional > max_notional_value
699            {
700                self.deny_order(
701                        order.clone(),
702                        &format!(
703                            "NOTIONAL_EXCEEDS_MAX_PER_ORDER: max_notional={max_notional_value:?}, notional={notional:?}"
704                        ),
705                    );
706                return false; // Denied
707            }
708
709            // Check MIN notional instrument limit
710            if let Some(min_notional) = instrument.min_notional()
711                && notional.currency == min_notional.currency
712                && notional < min_notional
713            {
714                self.deny_order(
715                        order.clone(),
716                        &format!(
717                            "NOTIONAL_LESS_THAN_MIN_FOR_INSTRUMENT: min_notional={min_notional:?}, notional={notional:?}"
718                        ),
719                    );
720                return false; // Denied
721            }
722
723            // // Check MAX notional instrument limit
724            if let Some(max_notional) = instrument.max_notional()
725                && notional.currency == max_notional.currency
726                && notional > max_notional
727            {
728                self.deny_order(
729                        order.clone(),
730                        &format!(
731                            "NOTIONAL_GREATER_THAN_MAX_FOR_INSTRUMENT: max_notional={max_notional:?}, notional={notional:?}"
732                        ),
733                    );
734                return false; // Denied
735            }
736
737            // Calculate OrderBalanceImpact (valid for CashAccount only)
738            let notional = instrument.calculate_notional_value(effective_quantity, last_px, None);
739            let order_balance_impact = match order.order_side() {
740                OrderSide::Buy => Money::from_raw(-notional.raw, notional.currency),
741                OrderSide::Sell => Money::from_raw(notional.raw, notional.currency),
742                OrderSide::NoOrderSide => {
743                    panic!("invalid `OrderSide`, was {}", order.order_side());
744                }
745            };
746
747            if self.config.debug {
748                log::debug!("Balance impact: {order_balance_impact}");
749            }
750
751            if let Some(free_val) = free
752                && (free_val.as_decimal() + order_balance_impact.as_decimal()) < Decimal::ZERO
753            {
754                self.deny_order(
755                    order.clone(),
756                    &format!(
757                        "NOTIONAL_EXCEEDS_FREE_BALANCE: free={free_val:?}, notional={notional:?}"
758                    ),
759                );
760                return false;
761            }
762
763            if base_currency.is_none() {
764                base_currency = instrument.base_currency();
765            }
766            if order.is_buy() {
767                match cum_notional_buy.as_mut() {
768                    Some(cum_notional_buy_val) => {
769                        cum_notional_buy_val.raw += -order_balance_impact.raw;
770                    }
771                    None => {
772                        cum_notional_buy = Some(Money::from_raw(
773                            -order_balance_impact.raw,
774                            order_balance_impact.currency,
775                        ));
776                    }
777                }
778
779                if self.config.debug {
780                    log::debug!("Cumulative notional BUY: {cum_notional_buy:?}");
781                }
782
783                if let (Some(free), Some(cum_notional_buy)) = (free, cum_notional_buy)
784                    && cum_notional_buy > free
785                {
786                    self.deny_order(order.clone(), &format!("CUM_NOTIONAL_EXCEEDS_FREE_BALANCE: free={free}, cum_notional={cum_notional_buy}"));
787                    return false; // Denied
788                }
789            } else if order.is_sell() {
790                if cash_account.base_currency.is_some() {
791                    if order.is_reduce_only() {
792                        if self.config.debug {
793                            log::debug!(
794                                "Reduce-only SELL skips cumulative notional free-balance check"
795                            );
796                        }
797                    } else {
798                        match cum_notional_sell.as_mut() {
799                            Some(cum_notional_buy_val) => {
800                                cum_notional_buy_val.raw += order_balance_impact.raw;
801                            }
802                            None => {
803                                cum_notional_sell = Some(Money::from_raw(
804                                    order_balance_impact.raw,
805                                    order_balance_impact.currency,
806                                ));
807                            }
808                        }
809                        if self.config.debug {
810                            log::debug!("Cumulative notional SELL: {cum_notional_sell:?}");
811                        }
812
813                        if let (Some(free), Some(cum_notional_sell)) = (free, cum_notional_sell)
814                            && cum_notional_sell > free
815                        {
816                            self.deny_order(order.clone(), &format!("CUM_NOTIONAL_EXCEEDS_FREE_BALANCE: free={free}, cum_notional={cum_notional_sell}"));
817                            return false; // Denied
818                        }
819                    }
820                }
821                // Account is already of type Cash, so no check
822                else if let Some(base_currency) = base_currency {
823                    if order.is_reduce_only() {
824                        if self.config.debug {
825                            log::debug!(
826                                "Reduce-only SELL skips base-currency cumulative free check"
827                            );
828                        }
829                        continue;
830                    }
831
832                    let cash_value = Money::from_raw(
833                        effective_quantity
834                            .raw
835                            .try_into()
836                            .map_err(|e| log::error!("Unable to convert Quantity to f64: {e}"))
837                            .unwrap(),
838                        base_currency,
839                    );
840
841                    if self.config.debug {
842                        log::debug!("Cash value: {cash_value:?}");
843                        log::debug!(
844                            "Total: {:?}",
845                            cash_account.balance_total(Some(base_currency))
846                        );
847                        log::debug!(
848                            "Locked: {:?}",
849                            cash_account.balance_locked(Some(base_currency))
850                        );
851                        log::debug!("Free: {:?}", cash_account.balance_free(Some(base_currency)));
852                    }
853
854                    match cum_notional_sell {
855                        Some(mut cum_notional_sell) => {
856                            cum_notional_sell.raw += cash_value.raw;
857                        }
858                        None => cum_notional_sell = Some(cash_value),
859                    }
860
861                    if self.config.debug {
862                        log::debug!("Cumulative notional SELL: {cum_notional_sell:?}");
863                    }
864                    if let (Some(free), Some(cum_notional_sell)) = (free, cum_notional_sell)
865                        && cum_notional_sell.raw > free.raw
866                    {
867                        self.deny_order(order.clone(), &format!("CUM_NOTIONAL_EXCEEDS_FREE_BALANCE: free={free}, cum_notional={cum_notional_sell}"));
868                        return false; // Denied
869                    }
870                }
871            }
872        }
873
874        // Finally
875        true // Passed
876    }
877
878    fn check_price(&self, instrument: &InstrumentAny, price: Option<Price>) -> Option<String> {
879        let price_val = price?;
880
881        if price_val.precision > instrument.price_precision() {
882            return Some(format!(
883                "price {} invalid (precision {} > {})",
884                price_val,
885                price_val.precision,
886                instrument.price_precision()
887            ));
888        }
889
890        if instrument.instrument_class() != InstrumentClass::Option && price_val.raw <= 0 {
891            return Some(format!("price {price_val} invalid (<= 0)"));
892        }
893
894        None
895    }
896
897    fn check_quantity(
898        &self,
899        instrument: &InstrumentAny,
900        quantity: Option<Quantity>,
901    ) -> Option<String> {
902        let quantity_val = quantity?;
903
904        // Check precision
905        if quantity_val.precision > instrument.size_precision() {
906            return Some(format!(
907                "quantity {} invalid (precision {} > {})",
908                quantity_val,
909                quantity_val.precision,
910                instrument.size_precision()
911            ));
912        }
913
914        // Check maximum quantity
915        if let Some(max_quantity) = instrument.max_quantity()
916            && quantity_val > max_quantity
917        {
918            return Some(format!(
919                "quantity {quantity_val} invalid (> maximum trade size of {max_quantity})"
920            ));
921        }
922
923        // // Check minimum quantity
924        if let Some(min_quantity) = instrument.min_quantity()
925            && quantity_val < min_quantity
926        {
927            return Some(format!(
928                "quantity {quantity_val} invalid (< minimum trade size of {min_quantity})"
929            ));
930        }
931
932        None
933    }
934
935    // -- DENIALS ---------------------------------------------------------------------------------
936
937    fn deny_command(&self, command: TradingCommand, reason: &str) {
938        match command {
939            TradingCommand::SubmitOrder(command) => {
940                self.deny_order(command.order, reason);
941            }
942            TradingCommand::SubmitOrderList(command) => {
943                self.deny_order_list(command.order_list, reason);
944            }
945            _ => {
946                panic!("Cannot deny command {command}");
947            }
948        }
949    }
950
951    fn deny_order(&self, order: OrderAny, reason: &str) {
952        log::warn!(
953            "SubmitOrder for {} DENIED: {}",
954            order.client_order_id(),
955            reason
956        );
957
958        if order.status() != OrderStatus::Initialized {
959            return;
960        }
961
962        let mut cache = self.cache.borrow_mut();
963        if !cache.order_exists(&order.client_order_id()) {
964            cache
965                .add_order(order.clone(), None, None, false)
966                .map_err(|e| {
967                    log::error!("Cannot add order to cache: {e}");
968                })
969                .unwrap();
970        }
971
972        let denied = OrderEventAny::Denied(OrderDenied::new(
973            order.trader_id(),
974            order.strategy_id(),
975            order.instrument_id(),
976            order.client_order_id(),
977            reason.into(),
978            UUID4::new(),
979            self.clock.borrow().timestamp_ns(),
980            self.clock.borrow().timestamp_ns(),
981        ));
982
983        msgbus::send_any("ExecEngine.process".into(), &denied);
984    }
985
986    fn deny_order_list(&self, order_list: OrderList, reason: &str) {
987        for order in order_list.orders {
988            if !order.is_closed() {
989                self.deny_order(order, reason);
990            }
991        }
992    }
993
994    fn reject_modify_order(&self, order: OrderAny, reason: &str) {
995        let ts_event = self.clock.borrow().timestamp_ns();
996        let denied = OrderEventAny::ModifyRejected(OrderModifyRejected::new(
997            order.trader_id(),
998            order.strategy_id(),
999            order.instrument_id(),
1000            order.client_order_id(),
1001            reason.into(),
1002            UUID4::new(),
1003            ts_event,
1004            ts_event,
1005            false,
1006            order.venue_order_id(),
1007            order.account_id(),
1008        ));
1009
1010        msgbus::send_any("ExecEngine.process".into(), &denied);
1011    }
1012
1013    // -- EGRESS ----------------------------------------------------------------------------------
1014
1015    fn execution_gateway(&mut self, instrument: InstrumentAny, command: TradingCommand) {
1016        match self.trading_state {
1017            TradingState::Halted => match command {
1018                TradingCommand::SubmitOrder(submit_order) => {
1019                    self.deny_order(submit_order.order, "TradingState::HALTED");
1020                }
1021                TradingCommand::SubmitOrderList(submit_order_list) => {
1022                    self.deny_order_list(submit_order_list.order_list, "TradingState::HALTED");
1023                }
1024                _ => {}
1025            },
1026            TradingState::Reducing => match command {
1027                TradingCommand::SubmitOrder(submit_order) => {
1028                    let order = submit_order.order;
1029                    if order.is_buy() && self.portfolio.is_net_long(&instrument.id()) {
1030                        self.deny_order(
1031                            order,
1032                            &format!(
1033                                "BUY when TradingState::REDUCING and LONG {}",
1034                                instrument.id()
1035                            ),
1036                        );
1037                    } else if order.is_sell() && self.portfolio.is_net_short(&instrument.id()) {
1038                        self.deny_order(
1039                            order,
1040                            &format!(
1041                                "SELL when TradingState::REDUCING and SHORT {}",
1042                                instrument.id()
1043                            ),
1044                        );
1045                    }
1046                }
1047                TradingCommand::SubmitOrderList(submit_order_list) => {
1048                    let order_list = submit_order_list.order_list;
1049                    for order in &order_list.orders {
1050                        if order.is_buy() && self.portfolio.is_net_long(&instrument.id()) {
1051                            self.deny_order_list(
1052                                order_list,
1053                                &format!(
1054                                    "BUY when TradingState::REDUCING and LONG {}",
1055                                    instrument.id()
1056                                ),
1057                            );
1058                            return;
1059                        } else if order.is_sell() && self.portfolio.is_net_short(&instrument.id()) {
1060                            self.deny_order_list(
1061                                order_list,
1062                                &format!(
1063                                    "SELL when TradingState::REDUCING and SHORT {}",
1064                                    instrument.id()
1065                                ),
1066                            );
1067                            return;
1068                        }
1069                    }
1070                }
1071                _ => {}
1072            },
1073            TradingState::Active => match command {
1074                TradingCommand::SubmitOrder(submit_order) => {
1075                    self.throttled_submit_order.send(submit_order);
1076                }
1077                TradingCommand::SubmitOrderList(submit_order_list) => {
1078                    // TODO: implement throttler for order lists
1079                    self.send_to_execution(TradingCommand::SubmitOrderList(submit_order_list));
1080                }
1081                _ => {}
1082            },
1083        }
1084    }
1085
1086    fn send_to_execution(&self, command: TradingCommand) {
1087        msgbus::send_any("ExecEngine.execute".into(), &command);
1088    }
1089
1090    fn handle_event(&mut self, event: OrderEventAny) {
1091        // We intend to extend the risk engine to be able to handle additional events.
1092        // For now we just log.
1093        if self.config.debug {
1094            log::debug!("{RECV}{EVT} {event:?}");
1095        }
1096    }
1097}