1pub mod config;
19
20use std::{cell::RefCell, fmt::Debug, rc::Rc};
21
22use ahash::AHashMap;
23use config::RiskEngineConfig;
24use indexmap::IndexMap;
25use nautilus_common::{
26 cache::Cache,
27 clock::Clock,
28 logging::{CMD, EVT, RECV},
29 messages::{
30 execution::{
31 BatchModifyOrders, ModifyOrder, PARAMS_CLOSE_POSITION, SubmitOrder, SubmitOrderList,
32 TradingCommand,
33 },
34 system::trading::TradingStateChanged,
35 },
36 msgbus,
37 msgbus::{MessagingSwitchboard, TypedHandler, TypedIntoHandler, get_message_bus},
38 runner::{TradingCommandMessage, try_get_trading_cmd_sender},
39 throttler::Throttler,
40};
41use nautilus_core::{UUID4, WeakCell};
42use nautilus_execution::trailing::{
43 trailing_stop_calculate_with_bid_ask, trailing_stop_calculate_with_last,
44};
45use nautilus_model::{
46 accounts::{Account, AccountAny},
47 enums::{
48 AggregationSource, ContingencyType, OrderSide, OrderStatus, OrderType, PositionSide,
49 PriceType, TimeInForce, TradingState, TrailingOffsetType, TriggerType,
50 },
51 events::{
52 OrderDenied, OrderDeniedReason, OrderEventAny, OrderModifyDenied, OrderPriceField,
53 OrderUpdated, PositionEvent,
54 },
55 identifiers::{AccountId, ClientId, ClientOrderId, InstrumentId, Venue},
56 instruments::{Instrument, InstrumentAny},
57 orders::{LIMIT_ORDER_TYPES, Order, OrderAny, STOP_ORDER_TYPES},
58 types::{Currency, Money, Price, Quantity, quantity::QuantityRaw},
59};
60use nautilus_portfolio::Portfolio;
61use rust_decimal::Decimal;
62use ustr::Ustr;
63
64type SubmitCommandFn = Box<dyn Fn(TradingCommand)>;
65type ModifyOrderFn = Box<dyn Fn(ModifyOrder)>;
66
67#[allow(dead_code)]
74pub struct RiskEngine {
75 clock: Rc<RefCell<dyn Clock>>,
76 cache: Rc<RefCell<Cache>>,
77 portfolio: Portfolio,
78 trading_state: TradingState,
79 config: RiskEngineConfig,
80 max_notional_per_order: AHashMap<InstrumentId, Decimal>,
81 throttler_submit: Throttler<TradingCommand, SubmitCommandFn>,
82 throttler_modify: Throttler<ModifyOrder, ModifyOrderFn>,
83 reservations: Vec<Reservation>,
84 command_count: u64,
85 event_count: u64,
86}
87
88impl Debug for RiskEngine {
89 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
90 f.debug_struct(stringify!(RiskEngine))
91 .field("trading_state", &self.trading_state)
92 .field("config", &self.config)
93 .field("max_notional_per_order", &self.max_notional_per_order)
94 .field("throttler_submit", &self.throttler_submit)
95 .field("throttler_modify", &self.throttler_modify)
96 .field("command_count", &self.command_count)
97 .field("event_count", &self.event_count)
98 .finish_non_exhaustive()
99 }
100}
101
102impl RiskEngine {
103 pub fn new(
105 config: RiskEngineConfig,
106 portfolio: Portfolio,
107 clock: Rc<RefCell<dyn Clock>>,
108 cache: Rc<RefCell<Cache>>,
109 ) -> Self {
110 let throttler_submit =
111 Self::create_submit_throttler(&config, Rc::clone(&clock), Rc::clone(&cache));
112 let throttler_modify =
113 Self::create_modify_throttler(&config, Rc::clone(&clock), Rc::clone(&cache));
114 let max_notional_per_order = config.max_notional_per_order.clone();
115
116 Self {
117 clock,
118 cache,
119 portfolio,
120 trading_state: TradingState::Active,
121 config,
122 max_notional_per_order,
123 throttler_submit,
124 throttler_modify,
125 reservations: Vec::new(),
126 command_count: 0,
127 event_count: 0,
128 }
129 }
130
131 pub fn register_msgbus_handlers(engine: &Rc<RefCell<Self>>) {
133 let weak = WeakCell::from(Rc::downgrade(engine));
134
135 let weak_execute = weak.clone();
136 msgbus::register_trading_command_endpoint(
137 MessagingSwitchboard::risk_engine_execute(),
138 TypedIntoHandler::from(move |cmd: TradingCommand| {
139 if let Some(rc) = weak_execute.upgrade() {
140 rc.borrow_mut().execute(cmd);
141 }
142 }),
143 );
144
145 msgbus::register_trading_command_endpoint(
154 MessagingSwitchboard::risk_engine_queue_execute(),
155 TypedIntoHandler::from(move |cmd: TradingCommand| {
156 if let Some(sender) = try_get_trading_cmd_sender() {
157 sender.execute(TradingCommandMessage::new(
158 MessagingSwitchboard::risk_engine_execute(),
159 cmd,
160 ));
161 } else {
162 let endpoint = MessagingSwitchboard::risk_engine_execute();
163 msgbus::send_trading_command(endpoint, cmd);
164 }
165 }),
166 );
167
168 let weak_process = weak.clone();
169 msgbus::register_order_event_endpoint(
170 MessagingSwitchboard::risk_engine_process(),
171 TypedIntoHandler::from(move |event: OrderEventAny| {
172 if let Some(rc) = weak_process.upgrade() {
173 rc.borrow_mut().process(event);
174 }
175 }),
176 );
177
178 let weak_order_events = weak.clone();
179 msgbus::subscribe_order_events(
180 "events.order.*".into(),
181 TypedHandler::from(move |event: &OrderEventAny| {
182 if let Some(rc) = weak_order_events.upgrade()
186 && let Ok(mut engine) = rc.try_borrow_mut()
187 {
188 engine.process(event.clone());
189 }
190 }),
191 Some(10),
192 );
193
194 let weak_position_events = weak;
195 msgbus::subscribe_position_events(
196 "events.position.*".into(),
197 TypedHandler::from(move |event: &PositionEvent| {
198 if let Some(rc) = weak_position_events.upgrade() {
199 rc.borrow_mut().process_position_event(event);
200 }
201 }),
202 Some(10),
203 );
204 }
205
206 fn create_submit_throttler(
207 config: &RiskEngineConfig,
208 clock: Rc<RefCell<dyn Clock>>,
209 cache: Rc<RefCell<Cache>>,
210 ) -> Throttler<TradingCommand, SubmitCommandFn> {
211 let success_handler = {
212 Box::new(move |command: TradingCommand| {
213 let endpoint = MessagingSwitchboard::exec_engine_queue_execute();
214 msgbus::send_trading_command(endpoint, command);
215 }) as Box<dyn Fn(TradingCommand)>
216 };
217
218 let failure_handler = {
219 let cache = cache;
220 let clock = Rc::clone(&clock);
221 Box::new(move |command: TradingCommand| {
222 let reason = OrderDeniedReason::RateLimitExceeded.to_string();
223
224 match command {
225 TradingCommand::SubmitOrder(submit_order) => {
226 log::warn!(
227 "SubmitOrder for {} DENIED: {reason}",
228 submit_order.client_order_id,
229 );
230
231 Self::handle_submit_order_cache(&cache, &submit_order);
232
233 let denied = Self::create_order_denied(&submit_order, &reason, &clock);
234
235 let endpoint = MessagingSwitchboard::exec_engine_process();
236 msgbus::send_order_event(endpoint, denied);
237 }
238 TradingCommand::SubmitOrderList(submit_order_list) => {
239 log::warn!(
240 "SubmitOrderList for {} DENIED: {reason}",
241 submit_order_list.order_list.id,
242 );
243
244 let orders: Vec<OrderAny> = cache.borrow().orders_for_ids(
245 &submit_order_list.order_list.client_order_ids,
246 &submit_order_list,
247 );
248
249 let timestamp = clock.borrow().timestamp_ns();
250
251 for order in &orders {
252 if order.status() == OrderStatus::Initialized {
253 let denied = OrderEventAny::Denied(OrderDenied::new(
254 order.trader_id(),
255 order.strategy_id(),
256 order.instrument_id(),
257 order.client_order_id(),
258 reason.as_str().into(),
259 UUID4::new(),
260 timestamp,
261 timestamp,
262 ));
263 let endpoint = MessagingSwitchboard::exec_engine_process();
264 msgbus::send_order_event(endpoint, denied);
265 }
266 }
267 }
268 _ => {
269 log::error!("Unexpected command type in submit throttler: {command}");
270 }
271 }
272 }) as Box<dyn Fn(TradingCommand)>
273 };
274
275 Throttler::new(
276 config.max_order_submit,
277 clock,
278 "ORDER_SUBMIT_THROTTLER",
279 success_handler,
280 Some(failure_handler),
281 Ustr::from(UUID4::new().as_str()),
282 )
283 }
284
285 fn create_modify_throttler(
286 config: &RiskEngineConfig,
287 clock: Rc<RefCell<dyn Clock>>,
288 cache: Rc<RefCell<Cache>>,
289 ) -> Throttler<ModifyOrder, ModifyOrderFn> {
290 let success_handler = {
291 Box::new(move |order: ModifyOrder| {
292 let endpoint = MessagingSwitchboard::exec_engine_queue_execute();
293 msgbus::send_trading_command(endpoint, TradingCommand::ModifyOrder(order));
294 }) as Box<dyn Fn(ModifyOrder)>
295 };
296
297 let failure_handler = {
298 let cache = cache;
299 let clock = Rc::clone(&clock);
300 Box::new(move |command: ModifyOrder| {
301 let reason = "Exceeded MAX_ORDER_MODIFY_RATE";
302 log::warn!(
303 "ModifyOrder for {} DENIED: {reason}",
304 command.client_order_id
305 );
306 let order = Self::get_existing_order(&cache, &command);
307 let denied = Self::create_modify_denied(order.as_ref(), &command, reason, &clock);
308 let endpoint = MessagingSwitchboard::exec_engine_process();
309 msgbus::send_order_event(endpoint, denied);
310 }) as Box<dyn Fn(ModifyOrder)>
311 };
312
313 Throttler::new(
314 config.max_order_modify,
315 clock,
316 "ORDER_MODIFY_THROTTLER",
317 success_handler,
318 Some(failure_handler),
319 Ustr::from(UUID4::new().as_str()),
320 )
321 }
322
323 fn handle_submit_order_cache(cache: &Rc<RefCell<Cache>>, submit_order: &SubmitOrder) {
324 let cache = cache.borrow();
325 if !cache.order_exists(&submit_order.client_order_id) {
326 log::error!(
327 "Order not found in cache for client_order_id: {}",
328 submit_order.client_order_id
329 );
330 }
331 }
332
333 fn get_existing_order(cache: &Rc<RefCell<Cache>>, order: &ModifyOrder) -> Option<OrderAny> {
334 let cache = cache.borrow();
335 if let Some(order) = cache.order(&order.client_order_id) {
336 Some(order.clone())
337 } else {
338 log::error!(
339 "Order with command.client_order_id: {} not found",
340 order.client_order_id
341 );
342 None
343 }
344 }
345
346 fn create_order_denied(
347 submit_order: &SubmitOrder,
348 reason: &str,
349 clock: &Rc<RefCell<dyn Clock>>,
350 ) -> OrderEventAny {
351 let timestamp = clock.borrow().timestamp_ns();
352 OrderEventAny::Denied(OrderDenied::new(
353 submit_order.trader_id,
354 submit_order.strategy_id,
355 submit_order.instrument_id,
356 submit_order.client_order_id,
357 reason.into(),
358 UUID4::new(),
359 timestamp,
360 timestamp,
361 ))
362 }
363
364 fn create_modify_denied(
365 order: Option<&OrderAny>,
366 command: &ModifyOrder,
367 reason: &str,
368 clock: &Rc<RefCell<dyn Clock>>,
369 ) -> OrderEventAny {
370 let timestamp = clock.borrow().timestamp_ns();
371
372 let mut event = OrderModifyDenied::new(
373 order.map_or(command.trader_id, Order::trader_id),
374 order.map_or(command.strategy_id, Order::strategy_id),
375 order.map_or(command.instrument_id, Order::instrument_id),
376 order.map_or(command.client_order_id, Order::client_order_id),
377 reason.into(),
378 UUID4::new(),
379 timestamp,
380 timestamp,
381 order.and_then(Order::venue_order_id),
382 order.and_then(Order::account_id),
383 );
384 event.causation_id = Some(command.command_id);
385 OrderEventAny::ModifyDenied(event)
386 }
387
388 pub fn execute(&mut self, command: TradingCommand) {
391 self.command_count += 1;
392
393 self.handle_command(command);
395 }
396
397 #[expect(
399 clippy::needless_pass_by_value,
400 reason = "message bus dispatch passes owned order events"
401 )]
402 pub fn process(&mut self, event: OrderEventAny) {
403 self.event_count += 1;
404
405 self.handle_event(&event);
407 }
408
409 fn process_position_event(&mut self, event: &PositionEvent) {
410 self.event_count += 1;
411
412 self.handle_position_event(event);
413 }
414
415 pub fn set_trading_state(&mut self, state: TradingState) {
419 if state == self.trading_state {
420 log::warn!("No change to trading state: already set to {state:?}");
421 return;
422 }
423
424 self.trading_state = state;
425
426 let ts_now = self.clock.borrow().timestamp_ns();
427 let trader_id = get_message_bus().borrow().trader_id;
428
429 let config = self.config_as_map();
430 let event =
431 TradingStateChanged::new(trader_id, state, config, UUID4::new(), ts_now, ts_now);
432
433 msgbus::publish_any(MessagingSwitchboard::risk_events_topic(), &event);
434
435 log::info!("Trading state set to {state:?}");
436 }
437
438 pub fn set_max_notional_per_order(&mut self, instrument_id: InstrumentId, new_value: Decimal) {
440 self.max_notional_per_order.insert(instrument_id, new_value);
441
442 let new_value_str = new_value.to_string();
443 log::info!("Set MAX_NOTIONAL_PER_ORDER: {instrument_id} {new_value_str}");
444 }
445
446 pub fn start(&mut self) {
448 log::info!("Started");
449 }
450
451 pub fn stop(&mut self) {
453 log::info!("Stopped");
454 }
455
456 pub fn reset(&mut self) {
458 self.throttler_submit.reset();
459 self.throttler_modify.reset();
460 self.max_notional_per_order = self.config.max_notional_per_order.clone();
461 self.reservations.clear();
462 self.command_count = 0;
463 self.event_count = 0;
464
465 if self.trading_state != TradingState::Active {
466 self.set_trading_state(TradingState::Active);
467 }
468
469 log::info!("Reset");
470 }
471
472 pub fn dispose(&mut self) {
474 log::info!("Disposed");
475 }
476
477 #[must_use]
479 pub fn clock(&self) -> &Rc<RefCell<dyn Clock>> {
480 &self.clock
481 }
482
483 #[must_use]
485 pub fn cache(&self) -> &Rc<RefCell<Cache>> {
486 &self.cache
487 }
488
489 pub fn portfolio_mut(&mut self) -> &mut Portfolio {
491 &mut self.portfolio
492 }
493
494 #[must_use]
496 pub const fn config(&self) -> &RiskEngineConfig {
497 &self.config
498 }
499
500 #[must_use]
502 pub const fn command_count(&self) -> u64 {
503 self.command_count
504 }
505
506 #[must_use]
508 pub const fn event_count(&self) -> u64 {
509 self.event_count
510 }
511
512 #[must_use]
514 pub const fn trading_state(&self) -> TradingState {
515 self.trading_state
516 }
517
518 #[must_use]
520 pub const fn max_notional_per_order(&self) -> &AHashMap<InstrumentId, Decimal> {
521 &self.max_notional_per_order
522 }
523
524 fn config_as_map(&self) -> IndexMap<String, String> {
525 let mut map = IndexMap::new();
526 map.insert("bypass".to_string(), self.config.bypass.to_string());
527 map.insert(
528 "max_order_submit_rate".to_string(),
529 self.config.max_order_submit.to_string(),
530 );
531 map.insert(
532 "max_order_modify_rate".to_string(),
533 self.config.max_order_modify.to_string(),
534 );
535
536 for (instrument_id, value) in &self.max_notional_per_order {
537 map.insert(
538 format!("max_notional_per_order.{instrument_id}"),
539 value.to_string(),
540 );
541 }
542
543 let mut full_position_exit_venues = self
544 .config
545 .full_position_exit_venues
546 .iter()
547 .map(ToString::to_string)
548 .collect::<Vec<_>>();
549 full_position_exit_venues.sort_unstable();
550 map.insert(
551 "full_position_exit_venues".to_string(),
552 full_position_exit_venues.join(","),
553 );
554
555 map.insert("debug".to_string(), self.config.debug.to_string());
556 map
557 }
558
559 fn handle_command(&mut self, command: TradingCommand) {
560 if self.config.debug {
561 log::debug!("{CMD}{RECV} {command}");
562 }
563
564 self.release_reservations();
565
566 match command {
567 TradingCommand::SubmitOrder(submit_order) => self.handle_submit_order(submit_order),
568 TradingCommand::SubmitOrderList(submit_order_list) => {
569 self.handle_submit_order_list(submit_order_list);
570 }
571 TradingCommand::ModifyOrder(modify_order) => self.handle_modify_order(modify_order),
572 TradingCommand::ModifyOrders(modify_orders) => {
573 self.handle_batch_modify_orders(modify_orders);
574 }
575 TradingCommand::QueryAccount(query_account) => {
576 Self::send_to_execution(TradingCommand::QueryAccount(query_account));
577 }
578 _ => {
579 log::error!("Cannot handle command: {command}");
580 }
581 }
582 }
583
584 fn handle_submit_order(&mut self, command: SubmitOrder) {
585 if self.config.bypass {
586 Self::send_to_execution(TradingCommand::SubmitOrder(command));
587 return;
588 }
589
590 let order = {
591 let cache = self.cache.borrow();
592 let Some(order) = cache.order(&command.client_order_id) else {
593 log::error!(
594 "Cannot handle submit order: order not found in cache for {}",
595 command.client_order_id
596 );
597 return;
598 };
599 order.clone()
600 };
601
602 if let Some(position_id) = command.position_id
603 && order.is_reduce_only()
604 {
605 let position_exists = {
606 let cache = self.cache.borrow();
607 cache
608 .position(&position_id)
609 .map(|pos| (pos.side, pos.quantity))
610 };
611
612 if let Some((pos_side, pos_quantity)) = position_exists {
613 if !order.would_reduce_only(pos_side, pos_quantity) {
614 self.deny_command(
615 TradingCommand::SubmitOrder(command),
616 &OrderDeniedReason::ReduceOnlyWouldIncreasePosition { position_id }
617 .to_string(),
618 );
619 return; }
621 } else {
622 self.deny_command(
623 TradingCommand::SubmitOrder(command),
624 &OrderDeniedReason::PositionNotFound { position_id }.to_string(),
625 );
626 return;
627 }
628 }
629
630 let instrument_exists = {
631 let cache = self.cache.borrow();
632 cache.instrument(&command.instrument_id).cloned()
633 };
634
635 let Some(instrument) = instrument_exists else {
636 self.deny_command(
637 TradingCommand::SubmitOrder(command.clone()),
638 &OrderDeniedReason::InstrumentNotFound {
639 instrument_id: command.instrument_id,
640 }
641 .to_string(),
642 );
643 return; };
645
646 let full_position_exit = self.is_full_position_exit(&command, &instrument, &order);
647 if !self.check_order(&instrument, &order, full_position_exit) {
648 return; }
650
651 let Some(reservations) = self.check_orders_risk(
652 &instrument,
653 &[order],
654 full_position_exit,
655 RiskCheck::Submit,
656 command.client_id,
657 ) else {
658 return; };
660
661 self.execution_gateway(TradingCommand::SubmitOrder(command), reservations);
662 }
663
664 fn is_full_position_exit(
665 &self,
666 command: &SubmitOrder,
667 instrument: &InstrumentAny,
668 order: &OrderAny,
669 ) -> bool {
670 if !self
671 .config
672 .full_position_exit_venues
673 .contains(&instrument.id().venue)
674 {
675 return false;
676 }
677
678 if !Self::has_full_position_exit_intent(command) {
679 return false;
680 }
681
682 if command.instrument_id != order.instrument_id() {
683 return false;
684 }
685
686 if !Self::is_full_position_exit_instrument(instrument)
687 || !Self::is_full_position_exit_order(order)
688 {
689 return false;
690 }
691
692 self.reduces_identified_open_position(command, order)
693 }
694
695 fn has_full_position_exit_intent(command: &SubmitOrder) -> bool {
696 command
697 .params
698 .as_ref()
699 .and_then(|params| params.get_bool(PARAMS_CLOSE_POSITION))
700 .unwrap_or(false)
701 }
702
703 fn is_full_position_exit_instrument(instrument: &InstrumentAny) -> bool {
704 match instrument {
705 InstrumentAny::CryptoFuture(_) | InstrumentAny::CryptoPerpetual(_) => true,
706 InstrumentAny::PerpetualContract(_) => !instrument.is_inverse(),
707 _ => false,
708 }
709 }
710
711 fn is_full_position_exit_order(order: &OrderAny) -> bool {
712 matches!(
713 order.order_type(),
714 OrderType::StopMarket | OrderType::MarketIfTouched
715 ) && order.trigger_price().is_some()
716 && order.is_reduce_only()
717 && order.quantity().is_positive()
718 }
719
720 fn is_reducing_submission(&self, command: &SubmitOrder, order: &OrderAny) -> bool {
721 order.is_reduce_only()
722 && order.quantity().is_positive()
723 && command.instrument_id == order.instrument_id()
724 && self
725 .identified_open_position(command, order)
726 .is_some_and(|(side, quantity)| {
727 order.would_reduce_only(side, quantity) && order.quantity() <= quantity
728 })
729 }
730
731 fn reduces_identified_open_position(&self, command: &SubmitOrder, order: &OrderAny) -> bool {
732 self.identified_open_position(command, order)
733 .is_some_and(|(side, quantity)| order.would_reduce_only(side, quantity))
734 }
735
736 fn identified_open_position(
737 &self,
738 command: &SubmitOrder,
739 order: &OrderAny,
740 ) -> Option<(PositionSide, Quantity)> {
741 let position_id = command.position_id?;
742 let account_id =
743 self.order_account_id(order, command.client_id, command.instrument_id.venue);
744
745 let position = {
746 let cache = self.cache.borrow();
747 if cache.position_id(&order.client_order_id()).copied() != Some(position_id) {
748 return None;
749 }
750
751 cache
752 .position(&position_id)
753 .filter(|position| account_id == Some(position.account_id))
754 .map(|position| {
755 (
756 position.is_open(),
757 position.instrument_id,
758 position.side,
759 position.quantity,
760 )
761 })
762 };
763 let (is_open, position_instrument_id, position_side, position_quantity) = position?;
764
765 (is_open
766 && position_instrument_id == order.instrument_id()
767 && matches!(
768 (order.order_side(), position_side),
769 (OrderSide::Buy, PositionSide::Short) | (OrderSide::Sell, PositionSide::Long)
770 ))
771 .then_some((position_side, position_quantity))
772 }
773
774 fn handle_submit_order_list(&mut self, command: SubmitOrderList) {
775 if self.config.bypass {
776 Self::send_to_execution(TradingCommand::SubmitOrderList(command));
777 return;
778 }
779
780 let orders: Vec<OrderAny> = self
781 .cache
782 .borrow()
783 .orders_for_ids(&command.order_list.client_order_ids, &command);
784
785 if orders.len() != command.order_list.client_order_ids.len() {
786 self.deny_order_list(
787 &orders,
788 &OrderDeniedReason::OrderListIncomplete {
789 order_list_id: command.order_list.id,
790 }
791 .to_string(),
792 );
793 return; }
795
796 let mut instruments: AHashMap<InstrumentId, InstrumentAny> = AHashMap::new();
800
801 for order in &orders {
802 let instrument_id = order.instrument_id();
803 if instruments.contains_key(&instrument_id) {
804 continue;
805 }
806 let resolved = self.cache.borrow().instrument(&instrument_id).cloned();
807 let Some(instrument) = resolved else {
808 self.deny_command(
809 TradingCommand::SubmitOrderList(command),
810 &OrderDeniedReason::InstrumentNotFound { instrument_id }.to_string(),
811 );
812 return; };
814 instruments.insert(instrument_id, instrument);
815 }
816
817 for (index, order) in orders.iter().enumerate() {
818 let Some(instrument) = instruments.get(&order.instrument_id()) else {
819 self.deny_order(
820 order,
821 &OrderDeniedReason::InstrumentNotFound {
822 instrument_id: order.instrument_id(),
823 }
824 .to_string(),
825 );
826 return; };
828
829 if !self.check_order(instrument, order, false) {
830 let reason = OrderDeniedReason::OrderListDenied {
831 order_list_id: command.order_list.id,
832 }
833 .to_string();
834
835 self.deny_order_list(&orders[..index], &reason);
836 self.deny_order_list(&orders[index + 1..], &reason);
837 return; }
839 }
840
841 let representative = if let Some(instrument) = instruments.get(&command.instrument_id) {
842 instrument.clone()
843 } else {
844 self.deny_order_list(
845 &orders,
846 &OrderDeniedReason::InstrumentNotFound {
847 instrument_id: command.instrument_id,
848 }
849 .to_string(),
850 );
851 return; };
853
854 let Some(reservations) = self.check_orders_risk(
855 &representative,
856 &orders,
857 false,
858 RiskCheck::Submit,
859 command.client_id,
860 ) else {
861 self.deny_order_list(
862 &orders,
863 &OrderDeniedReason::OrderListDenied {
864 order_list_id: command.order_list.id,
865 }
866 .to_string(),
867 );
868 return; };
870
871 self.execution_gateway(TradingCommand::SubmitOrderList(command), reservations);
872 }
873
874 fn handle_modify_order(&mut self, command: ModifyOrder) {
875 if self.config.bypass {
876 Self::send_to_execution(TradingCommand::ModifyOrder(command));
877 return;
878 }
879
880 if !self.validate_modify_order(&command)
881 || !self.check_modify_orders_risk(std::slice::from_ref(&command), command.client_id)
882 {
883 return;
884 }
885
886 self.throttler_modify.send(command);
887 }
888
889 fn handle_batch_modify_orders(&mut self, command: BatchModifyOrders) {
890 if self.config.bypass {
891 Self::send_to_execution(TradingCommand::ModifyOrders(command));
892 return;
893 }
894
895 if command.modifies.is_empty() {
896 log::warn!("Cannot handle BatchModifyOrders: no modify commands");
897 return;
898 }
899
900 if !self.validate_batch_modify_orders(&command) {
901 return;
902 }
903
904 if !self.check_modify_orders_risk(&command.modifies, command.client_id) {
905 return;
906 }
907
908 if !self.throttler_modify.try_reserve(command.modifies.len()) {
909 let reason = "Exceeded MAX_ORDER_MODIFY_RATE";
910
911 for modify in &command.modifies {
912 let Some(order) = Self::get_existing_order(&self.cache, modify) else {
913 continue;
914 };
915
916 self.deny_modify_order(Some(&order), modify, reason);
917 }
918
919 return;
920 }
921
922 Self::send_to_execution(TradingCommand::ModifyOrders(command));
923 }
924
925 fn validate_batch_modify_orders(&self, command: &BatchModifyOrders) -> bool {
926 let mut denied_command_ids = Vec::new();
927 let mut valid = true;
928
929 for modify in &command.modifies {
930 if !self.validate_batch_modify_order(command, modify) {
931 denied_command_ids.push(modify.command_id);
932 valid = false;
933 }
934 }
935
936 if !valid {
937 let reason = "BatchModifyOrders rejected because one or more child modifications failed validation";
938
939 for modify in &command.modifies {
940 if denied_command_ids.contains(&modify.command_id) {
941 continue;
942 }
943
944 let Some(order) = Self::get_existing_order(&self.cache, modify) else {
945 continue;
946 };
947
948 self.deny_modify_order(Some(&order), modify, reason);
949 }
950
951 return false;
952 }
953
954 true
955 }
956
957 fn validate_batch_modify_order(
958 &self,
959 command: &BatchModifyOrders,
960 modify: &ModifyOrder,
961 ) -> bool {
962 if modify.instrument_id != command.instrument_id {
963 let order = self
964 .cache
965 .borrow()
966 .order(&modify.client_order_id)
967 .map(|order| order.clone());
968
969 if let Some(order) = order {
970 self.deny_modify_order(
971 Some(&order),
972 modify,
973 &format!(
974 "BatchModifyOrders instrument {} does not match child instrument {}",
975 command.instrument_id, modify.instrument_id
976 ),
977 );
978 }
979
980 return false;
981 }
982
983 self.validate_modify_order(modify)
984 }
985
986 fn validate_modify_order(&self, command: &ModifyOrder) -> bool {
987 let order_exists = {
988 let cache = self.cache.borrow();
989 cache.order(&command.client_order_id).map(|o| o.clone())
990 };
991
992 let Some(order) = order_exists else {
993 log::error!(
994 "ModifyOrder DENIED: Order with command.client_order_id: {} not found",
995 command.client_order_id
996 );
997 self.deny_modify_order(None, command, "Order not found in cache");
998 return false;
999 };
1000
1001 if order.is_closed() {
1002 self.deny_modify_order(
1003 Some(&order),
1004 command,
1005 &format!(
1006 "Order with command.client_order_id: {} already closed",
1007 command.client_order_id
1008 ),
1009 );
1010 return false;
1011 } else if order.status() == OrderStatus::PendingCancel {
1012 self.deny_modify_order(
1013 Some(&order),
1014 command,
1015 &format!(
1016 "Order with command.client_order_id: {} is already pending cancel",
1017 command.client_order_id
1018 ),
1019 );
1020 return false;
1021 }
1022
1023 let maybe_instrument = {
1024 let cache = self.cache.borrow();
1025 cache.instrument(&command.instrument_id).cloned()
1026 };
1027
1028 let Some(instrument) = maybe_instrument else {
1029 self.deny_modify_order(
1030 Some(&order),
1031 command,
1032 &format!("no instrument found for {:?}", command.instrument_id),
1033 );
1034 return false;
1035 };
1036
1037 let mut reason = Self::check_price(&instrument, command.price, OrderPriceField::Price);
1039 if let Some(reason) = reason {
1040 self.deny_modify_order(Some(&order), command, &reason.to_string());
1041 return false;
1042 }
1043
1044 reason = Self::check_price(
1046 &instrument,
1047 command.trigger_price,
1048 OrderPriceField::TriggerPrice,
1049 );
1050
1051 if let Some(reason) = reason {
1052 self.deny_modify_order(Some(&order), command, &reason.to_string());
1053 return false;
1054 }
1055
1056 reason = Self::check_quantity(
1058 &instrument,
1059 command.quantity,
1060 order.is_quote_quantity(),
1061 false,
1062 );
1063
1064 if let Some(reason) = reason {
1065 self.deny_modify_order(Some(&order), command, &reason.to_string());
1066 return false;
1067 }
1068
1069 let state_reason = match self.trading_state {
1070 TradingState::Halted => Some(OrderDeniedReason::TradingHalted.to_string()),
1071 TradingState::Reducing => Some(
1072 OrderDeniedReason::TradingStateReducing {
1073 order_side: order.order_side(),
1074 instrument_id: instrument.id(),
1075 }
1076 .to_string(),
1077 ),
1078 TradingState::Active => None,
1079 };
1080
1081 if let Some(reason) = state_reason {
1082 self.deny_modify_order(Some(&order), command, &reason);
1083 return false;
1084 }
1085
1086 true
1087 }
1088
1089 fn check_modify_orders_risk(
1090 &self,
1091 commands: &[ModifyOrder],
1092 client_id: Option<ClientId>,
1093 ) -> bool {
1094 let mut originals = Vec::with_capacity(commands.len());
1095 let mut orders = Vec::with_capacity(commands.len());
1096 let cache = self.cache.borrow();
1097 for command in commands {
1098 let Some(order) = cache.order(&command.client_order_id) else {
1099 return false;
1100 };
1101
1102 originals.push(order.clone());
1103 let mut projected = order.clone();
1104
1105 projected.update(&OrderUpdated::new(
1107 order.trader_id(),
1108 order.strategy_id(),
1109 order.instrument_id(),
1110 order.client_order_id(),
1111 command.quantity.unwrap_or(order.quantity()),
1112 command.command_id,
1113 command.ts_init,
1114 command.ts_init,
1115 false,
1116 order.venue_order_id(),
1117 order.account_id(),
1118 command.price.filter(|_| {
1119 LIMIT_ORDER_TYPES.contains(&order.order_type())
1120 || order.order_type() == OrderType::MarketToLimit
1121 }),
1122 command.trigger_price.filter(|_| {
1123 STOP_ORDER_TYPES.contains(&order.order_type())
1124 || matches!(
1125 order.order_type(),
1126 OrderType::TrailingStopMarket | OrderType::TrailingStopLimit
1127 )
1128 }),
1129 None,
1130 order.is_quote_quantity(),
1131 ));
1132
1133 orders.push(projected);
1134 }
1135
1136 let instrument = cache.instrument(&commands[0].instrument_id).cloned();
1137 drop(cache);
1138 let check = RiskCheck::Modify(&originals, commands);
1139
1140 let Some(instrument) = instrument else {
1141 return false;
1142 };
1143
1144 self.check_orders_risk(&instrument, &orders, false, check, client_id)
1145 .is_some()
1146 }
1147
1148 fn check_order(
1149 &self,
1150 instrument: &InstrumentAny,
1151 order: &OrderAny,
1152 full_position_exit: bool,
1153 ) -> bool {
1154 if !self.check_order_price(instrument, order)
1155 || !self.check_order_quantity(instrument, order, full_position_exit)
1156 {
1157 return false; }
1159
1160 if order.time_in_force() == TimeInForce::Gtd {
1161 let Some(expire_time) = order.expire_time() else {
1162 self.deny_order(order, &OrderDeniedReason::MissingExpireTime.to_string());
1163 return false; };
1165
1166 if expire_time <= self.clock.borrow().timestamp_ns() {
1167 self.deny_order(
1168 order,
1169 &OrderDeniedReason::ExpireTimeInPast {
1170 expire_time: expire_time.to_rfc3339(),
1171 }
1172 .to_string(),
1173 );
1174 return false; }
1176 }
1177
1178 true
1179 }
1180
1181 fn check_order_price(&self, instrument: &InstrumentAny, order: &OrderAny) -> bool {
1182 if order.price().is_some() {
1183 let reason = Self::check_price(instrument, order.price(), OrderPriceField::Price);
1184 if let Some(reason) = reason {
1185 self.deny_order(order, &reason.to_string());
1186 return false; }
1188 }
1189
1190 if order.trigger_price().is_some() {
1191 let reason = Self::check_price(
1192 instrument,
1193 order.trigger_price(),
1194 OrderPriceField::TriggerPrice,
1195 );
1196
1197 if let Some(reason) = reason {
1198 self.deny_order(order, &reason.to_string());
1199 return false; }
1201 }
1202
1203 true
1204 }
1205
1206 fn check_order_quantity(
1207 &self,
1208 instrument: &InstrumentAny,
1209 order: &OrderAny,
1210 full_position_exit: bool,
1211 ) -> bool {
1212 let reason = Self::check_quantity(
1213 instrument,
1214 Some(order.quantity()),
1215 order.is_quote_quantity(),
1216 full_position_exit,
1217 );
1218
1219 if let Some(reason) = reason {
1220 self.deny_order(order, &reason.to_string());
1221 return false; }
1223
1224 true
1225 }
1226
1227 fn check_orders_risk(
1228 &self,
1229 instrument: &InstrumentAny,
1230 orders: &[OrderAny],
1231 full_position_exit: bool,
1232 check: RiskCheck<'_>,
1233 client_id: Option<ClientId>,
1234 ) -> Option<Vec<Reservation>> {
1235 let venue = instrument.id().venue;
1236 let mut orders_by_account: AHashMap<Option<AccountId>, Vec<&OrderAny>> = AHashMap::new();
1237 for order in orders {
1238 orders_by_account
1239 .entry(self.order_account_id(order, client_id, venue))
1240 .or_default()
1241 .push(order);
1242 }
1243
1244 let mut reservations = Vec::new();
1245
1246 for (account_id, account_orders) in &orders_by_account {
1247 reservations.extend(self.check_orders_risk_for_account(
1248 instrument,
1249 account_orders,
1250 *account_id,
1251 client_id,
1252 full_position_exit,
1253 check,
1254 )?);
1255 }
1256
1257 Some(reservations)
1258 }
1259
1260 fn record_reservations(&mut self, reservations: Vec<Reservation>) {
1263 self.reservations.retain(|held| {
1264 reservations
1265 .iter()
1266 .all(|reservation| reservation.client_order_id != held.client_order_id)
1267 });
1268 self.reservations.extend(reservations);
1269 }
1270
1271 fn release_reservations(&mut self) {
1272 if self.reservations.is_empty() {
1273 return;
1274 }
1275
1276 let cache = self.cache.borrow();
1277 let mut previous_id = None;
1278 let mut previous_order = None;
1279 self.reservations.retain(|reservation| {
1280 if previous_id != Some(reservation.client_order_id) {
1281 previous_id = Some(reservation.client_order_id);
1282 previous_order = cache.order_ref(&reservation.client_order_id);
1283 }
1284
1285 previous_order
1286 .as_ref()
1287 .is_some_and(|order| !reservation.is_released(order))
1288 });
1289 }
1290
1291 fn unreflected_reservations<'a>(
1293 &'a self,
1294 account_id: AccountId,
1295 orders: &'a [&OrderAny],
1296 ) -> impl Iterator<Item = Money> + 'a {
1297 self.reservations
1298 .iter()
1299 .filter(move |reservation| {
1300 reservation.account_id == account_id
1301 && orders
1302 .iter()
1303 .all(|order| order.client_order_id() != reservation.client_order_id)
1304 })
1305 .filter_map(|reservation| match reservation.exposure {
1306 ReservedExposure::Balance(amount) => Some(amount),
1307 ReservedExposure::Position { .. } => None,
1308 })
1309 }
1310
1311 fn order_account_id(
1316 &self,
1317 order: &OrderAny,
1318 client_id: Option<ClientId>,
1319 venue: Venue,
1320 ) -> Option<AccountId> {
1321 if let Some(account_id) = order.account_id() {
1322 return Some(account_id);
1323 }
1324
1325 let cache = self.cache.borrow();
1326
1327 let routed_account_id = || {
1328 cache
1329 .client_id_for_venue(&venue)
1330 .and_then(|client_id| cache.account_id_for_client(client_id))
1331 };
1332
1333 let account_id = match client_id {
1334 Some(client_id) if cache.is_external_exec_client(&client_id) => None,
1335 Some(client_id) => cache
1336 .account_id_for_client(&client_id)
1337 .or_else(routed_account_id),
1338 None => routed_account_id(),
1339 };
1340
1341 account_id.or_else(|| cache.account_id(&venue)).copied()
1342 }
1343
1344 #[allow(
1345 clippy::too_many_lines,
1346 reason = "risk checks keep related denial branches together for auditability"
1347 )]
1348 fn check_orders_risk_for_account(
1349 &self,
1350 instrument: &InstrumentAny,
1351 orders: &[&OrderAny],
1352 account_id: Option<AccountId>,
1353 client_id: Option<ClientId>,
1354 full_position_exit: bool,
1355 check: RiskCheck<'_>,
1356 ) -> Option<Vec<Reservation>> {
1357 let max_notional = match self.order_notional_limit(instrument) {
1358 Ok(limit) => limit,
1359 Err(reason) => {
1360 check.reject_orders(self, orders, &reason.to_string());
1361 return None;
1362 }
1363 };
1364
1365 let mut market_prices = Vec::with_capacity(orders.len());
1366
1367 for order in orders {
1368 let price = match order {
1369 OrderAny::Market(_) | OrderAny::MarketToLimit(_) => {
1370 self.market_order_price(instrument.id(), order.order_side())
1371 }
1372 _ => None,
1373 };
1374
1375 market_prices.push(price);
1376 }
1377
1378 let resolved_account = account_id.and_then(|account_id| {
1379 self.cache
1380 .borrow()
1381 .account(&account_id)
1382 .map(|account| account.clone_without_events())
1383 });
1384
1385 let Some(account) = resolved_account else {
1386 check.reject_orders(
1387 self,
1388 orders,
1389 &OrderDeniedReason::ValidationFailed {
1390 detail: format!(
1391 "No account available for risk checks: instrument_id={}, client_id={client_id:?}, account_id={account_id:?}",
1392 instrument.id()
1393 ),
1394 }
1395 .to_string(),
1396 );
1397
1398 return None;
1399 };
1400
1401 let allow_borrowing = match &account {
1402 AccountAny::Cash(cash) => cash.allow_borrowing,
1403 AccountAny::Margin(_) | AccountAny::Betting(_) | AccountAny::Wallet(_) => false,
1404 };
1405
1406 let available_long_qty_raw = self.available_position_quantity(
1407 instrument.id(),
1408 account.id(),
1409 PositionSide::Long,
1410 OrderSide::Sell,
1411 check,
1412 orders,
1413 );
1414
1415 let available_short_qty_raw =
1416 if matches!(account, AccountAny::Margin(_) | AccountAny::Betting(_)) {
1417 self.available_position_quantity(
1418 instrument.id(),
1419 account.id(),
1420 PositionSide::Short,
1421 OrderSide::Buy,
1422 check,
1423 orders,
1424 )
1425 } else {
1426 0
1427 };
1428
1429 let mut risk = AccountRisk {
1430 engine: self,
1431 instrument,
1432 account,
1433 check,
1434 orders,
1435 full_position_exit,
1436 max_notional,
1437 allow_borrowing,
1438 available_long_qty_raw,
1439 available_short_qty_raw,
1440 cum_sell_qty_raw: 0,
1441 cum_buy_qty_raw: 0,
1442 cum_original_sell_qty_raw: 0,
1443 cum_original_buy_qty_raw: 0,
1444 cum_notional_buy: None,
1445 cum_notional_sell: None,
1446 cum_margin_required: None,
1447 balances_free: RefCell::new(Vec::new()),
1448 xrates: RefCell::new(None),
1449 reservations: Vec::new(),
1450 };
1451
1452 for (&order, market_price) in orders.iter().zip(market_prices) {
1453 if !risk.check_order(order, market_price) {
1454 return None;
1455 }
1456 }
1457
1458 Some(risk.reservations)
1459 }
1460
1461 fn order_notional_limit(
1462 &self,
1463 instrument: &InstrumentAny,
1464 ) -> Result<Option<Money>, OrderDeniedReason> {
1465 let Some(value) = self.max_notional_per_order.get(&instrument.id()).copied() else {
1466 return Ok(None);
1467 };
1468
1469 Money::from_decimal(value, instrument.quote_currency())
1470 .map(Some)
1471 .map_err(|_| OrderDeniedReason::InvalidMaxNotionalPerOrder {
1472 instrument_id: instrument.id(),
1473 value,
1474 })
1475 }
1476
1477 fn available_position_quantity(
1478 &self,
1479 instrument_id: InstrumentId,
1480 account_id: AccountId,
1481 position_side: PositionSide,
1482 order_side: OrderSide,
1483 check: RiskCheck<'_>,
1484 orders: &[&OrderAny],
1485 ) -> QuantityRaw {
1486 let cache = self.cache.borrow();
1487 let position_quantity: QuantityRaw = cache
1488 .positions_open(
1489 None,
1490 Some(&instrument_id),
1491 None,
1492 Some(&account_id),
1493 Some(position_side),
1494 )
1495 .iter()
1496 .map(|position| position.quantity.raw())
1497 .sum();
1498
1499 if position_quantity == 0 {
1500 return 0;
1501 }
1502
1503 let pending_quantity: QuantityRaw = cache
1504 .orders_open(
1505 None,
1506 Some(&instrument_id),
1507 None,
1508 Some(&account_id),
1509 Some(order_side),
1510 )
1511 .iter()
1512 .filter(|order| check.original(order).is_none())
1513 .map(|order| order.leaves_qty().raw())
1514 .sum();
1515
1516 let reserved_quantity = self
1517 .reservations
1518 .iter()
1519 .filter(|reservation| {
1520 reservation.account_id == account_id
1521 && orders
1522 .iter()
1523 .all(|order| order.client_order_id() != reservation.client_order_id)
1524 })
1525 .filter_map(|reservation| match reservation.exposure {
1526 ReservedExposure::Position {
1527 instrument_id: held_instrument,
1528 side,
1529 quantity,
1530 } if held_instrument == instrument_id && side == order_side => Some(quantity.raw()),
1531 _ => None,
1532 })
1533 .fold(0, QuantityRaw::saturating_add);
1534
1535 let available = position_quantity
1536 .saturating_sub(pending_quantity)
1537 .saturating_sub(reserved_quantity);
1538
1539 if self.config.debug && position_quantity > 0 {
1540 log::debug!(
1541 "Net {position_side} qty (raw): {position_quantity}, pending {order_side}: {pending_quantity}, available: {available}"
1542 );
1543 }
1544
1545 available
1546 }
1547
1548 fn order_risk_quantity(
1549 &self,
1550 check: RiskCheck<'_>,
1551 instrument: &InstrumentAny,
1552 order: &OrderAny,
1553 quantity: Quantity,
1554 price: Price,
1555 ) -> Result<Quantity, ()> {
1556 if !order.is_quote_quantity() || instrument.is_inverse() {
1557 return Ok(quantity);
1558 }
1559
1560 let effective_price = if matches!(order, OrderAny::Limit(_) | OrderAny::StopLimit(_)) {
1561 self.cache
1562 .borrow()
1563 .quote(&instrument.id())
1564 .map_or(price, |quote| match order.order_side() {
1565 OrderSide::Buy => price.min(quote.ask_price),
1566 OrderSide::Sell => price.max(quote.bid_price),
1567 })
1568 } else {
1569 price
1570 };
1571
1572 instrument
1573 .try_calculate_base_quantity(quantity, effective_price)
1574 .map_err(|e| {
1575 check.reject(
1576 self,
1577 order,
1578 &OrderDeniedReason::QuantityConversionFailed {
1579 detail: e.to_string(),
1580 }
1581 .to_string(),
1582 );
1583 })
1584 }
1585
1586 fn check_risk_increase(
1587 &self,
1588 check: RiskCheck<'_>,
1589 order: &OrderAny,
1590 current: Money,
1591 previous: Money,
1592 ) -> Option<Money> {
1593 let increase = if current.currency == previous.currency {
1595 Money::from_decimal_native(
1596 (current.as_decimal().max(Decimal::ZERO)
1597 - previous.as_decimal().max(Decimal::ZERO))
1598 .max(Decimal::ZERO),
1599 current.currency,
1600 )
1601 .ok()
1602 } else {
1603 None
1604 };
1605
1606 if increase.is_none() {
1607 check.reject(
1608 self,
1609 order,
1610 &OrderDeniedReason::NotionalCalculationFailed {
1611 detail:
1612 "amendment risk increase exceeds Money bounds or has incompatible currency"
1613 .to_string(),
1614 }
1615 .to_string(),
1616 );
1617 }
1618
1619 increase
1620 }
1621
1622 fn market_order_price(
1623 &self,
1624 instrument_id: InstrumentId,
1625 order_side: OrderSide,
1626 ) -> Option<Price> {
1627 let price_type = match order_side {
1628 OrderSide::Buy => PriceType::Ask,
1629 OrderSide::Sell => PriceType::Bid,
1630 };
1631
1632 let cache = self.cache.borrow();
1633
1634 if let Some(price) = cache.price(&instrument_id, price_type) {
1635 return Some(price);
1636 }
1637
1638 if let Some(price) = cache.price(&instrument_id, PriceType::Last) {
1639 return Some(price);
1640 }
1641
1642 let bar_price = |price_type| {
1643 cache
1644 .bar_types(
1645 Some(&instrument_id),
1646 Some(&price_type),
1647 AggregationSource::External,
1648 )
1649 .into_iter()
1650 .filter_map(|bar_type| {
1651 cache
1652 .bar(bar_type)
1653 .map(|bar| (bar.ts_init, *bar_type, bar.close))
1654 })
1655 .max_by_key(|(ts_init, bar_type, _)| (*ts_init, *bar_type))
1656 .map(|(_, _, price)| price)
1657 };
1658
1659 bar_price(price_type).or_else(|| bar_price(PriceType::Last))
1660 }
1661
1662 #[allow(
1663 clippy::too_many_arguments,
1664 reason = "cash sell validation shares the account, cumulative exposure, and rejection context"
1665 )]
1666 fn check_cash_sell_balance(
1667 &self,
1668 check: RiskCheck<'_>,
1669 account: &dyn Account,
1670 allow_borrowing: bool,
1671 order: &OrderAny,
1672 quantity: Quantity,
1673 base_free: Money,
1674 cum_notional_sell: &mut Option<Money>,
1675 ) -> Result<Money, ()> {
1676 let base_currency = base_free.currency;
1677 let cash_value = match Money::from_quantity(quantity, base_currency) {
1678 Ok(value) => value,
1679 Err(e) => {
1680 check.reject(
1681 self,
1682 order,
1683 &OrderDeniedReason::QuantityConversionFailed {
1684 detail: e.to_string(),
1685 }
1686 .to_string(),
1687 );
1688
1689 return Err(());
1690 }
1691 };
1692
1693 if self.config.debug {
1694 log::debug!("Cash value: {cash_value:?}");
1695 log::debug!("Total: {:?}", account.balance_total(Some(base_currency)));
1696 log::debug!("Locked: {:?}", account.balance_locked(Some(base_currency)));
1697 log::debug!("Free: {base_free:?}");
1698 }
1699
1700 if !self.accumulate_notional(check, order, cum_notional_sell, cash_value) {
1701 return Err(());
1702 }
1703
1704 if self.config.debug {
1705 log::debug!("Cumulative notional SELL: {cum_notional_sell:?}");
1706 }
1707
1708 if !allow_borrowing
1709 && let Some(cum_notional_sell) = *cum_notional_sell
1710 && cum_notional_sell > base_free
1711 {
1712 check.reject(
1713 self,
1714 order,
1715 &OrderDeniedReason::CumulativeNotionalExceedsFreeBalance {
1716 free_balance: base_free,
1717 cumulative_notional: cum_notional_sell,
1718 }
1719 .to_string(),
1720 );
1721 return Err(());
1722 }
1723
1724 Ok(cash_value)
1725 }
1726
1727 fn accumulate_notional(
1728 &self,
1729 check: RiskCheck<'_>,
1730 order: &OrderAny,
1731 total: &mut Option<Money>,
1732 value: Money,
1733 ) -> bool {
1734 let next = match *total {
1735 Some(current) if current.currency == value.currency => current.checked_add(value),
1736 Some(_) => None,
1737 None => Some(value),
1738 };
1739
1740 let Some(next) = next else {
1741 check.reject(self,
1742 order,
1743 &OrderDeniedReason::NotionalCalculationFailed {
1744 detail: "cumulative notional exceeds Money bounds or has incompatible currency or scale".to_string(),
1745 }
1746 .to_string(),
1747 );
1748
1749 return false;
1750 };
1751
1752 *total = Some(next);
1753 true
1754 }
1755
1756 fn deny_no_market_price(
1757 &self,
1758 instrument_id: InstrumentId,
1759 order: &OrderAny,
1760 check: RiskCheck<'_>,
1761 ) {
1762 check.reject(
1763 self,
1764 order,
1765 &OrderDeniedReason::MarketPriceUnavailable {
1766 order_type: order.order_type(),
1767 instrument_id,
1768 }
1769 .to_string(),
1770 );
1771 }
1772
1773 fn check_price(
1774 instrument: &InstrumentAny,
1775 price: Option<Price>,
1776 field: OrderPriceField,
1777 ) -> Option<OrderDeniedReason> {
1778 let price_val = price?;
1779
1780 if price_val.precision > instrument.price_precision() {
1781 return Some(OrderDeniedReason::PricePrecisionExceedsMaximum {
1782 field,
1783 price: price_val,
1784 price_precision: price_val.precision,
1785 max_precision: instrument.price_precision(),
1786 });
1787 }
1788
1789 if !instrument.allows_negative_price() && (price_val.is_zero() || price_val.is_negative()) {
1790 return Some(OrderDeniedReason::PriceNotPositive {
1791 field,
1792 price: price_val,
1793 });
1794 }
1795
1796 None
1797 }
1798
1799 fn check_quantity(
1800 instrument: &InstrumentAny,
1801 quantity: Option<Quantity>,
1802 is_quote_quantity: bool,
1803 full_position_exit: bool,
1804 ) -> Option<OrderDeniedReason> {
1805 let quantity_val = quantity?;
1806
1807 if quantity_val.precision > instrument.size_precision() {
1809 return Some(OrderDeniedReason::QuantityPrecisionExceedsMaximum {
1810 quantity: quantity_val,
1811 quantity_precision: quantity_val.precision,
1812 max_precision: instrument.size_precision(),
1813 });
1814 }
1815
1816 if is_quote_quantity || full_position_exit {
1819 return None;
1820 }
1821
1822 if let Some(max_quantity) = instrument.max_quantity()
1824 && quantity_val > max_quantity
1825 {
1826 return Some(OrderDeniedReason::QuantityExceedsMaximum {
1827 effective_quantity: quantity_val,
1828 max_quantity,
1829 });
1830 }
1831
1832 if let Some(min_quantity) = instrument.min_quantity()
1834 && quantity_val < min_quantity
1835 {
1836 return Some(OrderDeniedReason::QuantityBelowMinimum {
1837 effective_quantity: quantity_val,
1838 min_quantity,
1839 });
1840 }
1841
1842 None
1843 }
1844
1845 fn deny_command(&self, command: TradingCommand, reason: &str) {
1846 match command {
1847 TradingCommand::SubmitOrder(command) => {
1848 let order = {
1849 let cache = self.cache.borrow();
1850 cache.order(&command.client_order_id).map(|o| o.clone())
1851 };
1852
1853 if let Some(ref order) = order {
1854 self.deny_order(order, reason);
1855 } else {
1856 log::error!(
1857 "Cannot deny order: not found in cache for {}",
1858 command.client_order_id
1859 );
1860 }
1861 }
1862 TradingCommand::SubmitOrderList(command) => {
1863 let orders: Vec<OrderAny> = self
1864 .cache
1865 .borrow()
1866 .orders_for_ids(&command.order_list.client_order_ids, &command);
1867 self.deny_order_list(&orders, reason);
1868 }
1869 _ => {
1870 log::error!("Cannot deny command {command}");
1871 }
1872 }
1873 }
1874
1875 fn deny_order(&self, order: &OrderAny, reason: &str) {
1876 log::warn!(
1877 "SubmitOrder for {} DENIED: {}",
1878 order.client_order_id(),
1879 reason
1880 );
1881
1882 if !matches!(
1883 order.status(),
1884 OrderStatus::Initialized | OrderStatus::Released
1885 ) {
1886 return;
1887 }
1888
1889 {
1891 let mut cache = self.cache.borrow_mut();
1892 if cache.is_order_dispatched(&order.client_order_id()) {
1893 return;
1894 }
1895
1896 if !cache.order_exists(&order.client_order_id())
1897 && let Err(e) = cache.add_order(order.clone(), None, None, false)
1898 {
1899 log::error!("Cannot add order to cache: {e}");
1900 return;
1901 }
1902 }
1903
1904 let denied = OrderEventAny::Denied(OrderDenied::new(
1905 order.trader_id(),
1906 order.strategy_id(),
1907 order.instrument_id(),
1908 order.client_order_id(),
1909 reason.into(),
1910 UUID4::new(),
1911 self.clock.borrow().timestamp_ns(),
1912 self.clock.borrow().timestamp_ns(),
1913 ));
1914
1915 let endpoint = MessagingSwitchboard::exec_engine_process();
1916 msgbus::send_order_event(endpoint, denied);
1917 }
1918
1919 fn deny_order_list(&self, orders: &[OrderAny], reason: &str) {
1920 for order in orders {
1921 if !order.is_closed() {
1922 self.deny_order(order, reason);
1923 }
1924 }
1925 }
1926
1927 fn deny_modify_order(&self, order: Option<&OrderAny>, command: &ModifyOrder, reason: &str) {
1928 let denied = Self::create_modify_denied(order, command, reason, &self.clock);
1929 let endpoint = MessagingSwitchboard::exec_engine_process();
1930 msgbus::send_order_event(endpoint, denied);
1931 }
1932
1933 fn execution_gateway(&mut self, command: TradingCommand, reservations: Vec<Reservation>) {
1934 match self.trading_state {
1935 TradingState::Halted => match command {
1936 TradingCommand::SubmitOrder(submit_order) => {
1937 let order = {
1938 let cache = self.cache.borrow();
1939 cache
1940 .order(&submit_order.client_order_id)
1941 .map(|order| order.clone())
1942 };
1943
1944 if let Some(order) = order {
1945 self.deny_order(&order, &OrderDeniedReason::TradingHalted.to_string());
1946 }
1947 }
1948 TradingCommand::SubmitOrderList(submit_order_list) => {
1949 let orders: Vec<OrderAny> = self.cache.borrow().orders_for_ids(
1950 &submit_order_list.order_list.client_order_ids,
1951 &submit_order_list,
1952 );
1953 self.deny_order_list(&orders, &OrderDeniedReason::TradingHalted.to_string());
1954 }
1955 _ => {}
1956 },
1957 TradingState::Reducing => match command {
1958 TradingCommand::SubmitOrder(submit_order) => {
1959 let order = {
1960 let cache = self.cache.borrow();
1961 cache
1962 .order(&submit_order.client_order_id)
1963 .map(|order| order.clone())
1964 };
1965 let Some(order) = order else {
1966 return;
1967 };
1968
1969 if self.is_reducing_submission(&submit_order, &order) {
1970 self.record_reservations(reservations);
1971 self.throttler_submit
1972 .send(TradingCommand::SubmitOrder(submit_order));
1973 } else {
1974 self.deny_order(
1975 &order,
1976 &OrderDeniedReason::TradingStateReducing {
1977 order_side: order.order_side(),
1978 instrument_id: order.instrument_id(),
1979 }
1980 .to_string(),
1981 );
1982 }
1983 }
1984 TradingCommand::SubmitOrderList(submit_order_list) => {
1985 let orders: Vec<OrderAny> = self.cache.borrow().orders_for_ids(
1986 &submit_order_list.order_list.client_order_ids,
1987 &submit_order_list,
1988 );
1989
1990 for order in &orders {
1991 self.deny_order(
1992 order,
1993 &OrderDeniedReason::TradingStateReducing {
1994 order_side: order.order_side(),
1995 instrument_id: order.instrument_id(),
1996 }
1997 .to_string(),
1998 );
1999 }
2000 }
2001 _ => {}
2002 },
2003 TradingState::Active => match command {
2004 TradingCommand::SubmitOrder(_) | TradingCommand::SubmitOrderList(_) => {
2005 self.record_reservations(reservations);
2006 self.throttler_submit.send(command);
2007 }
2008 _ => {}
2009 },
2010 }
2011 }
2012
2013 fn send_to_execution(command: TradingCommand) {
2014 let endpoint = MessagingSwitchboard::exec_engine_queue_execute();
2015 msgbus::send_trading_command(endpoint, command);
2016 }
2017
2018 fn handle_event(&self, event: &OrderEventAny) {
2019 if self.config.debug {
2022 log::debug!("{RECV}{EVT} {event}");
2023 }
2024 }
2025
2026 fn handle_position_event(&self, event: &PositionEvent) {
2027 if self.config.debug {
2028 log::debug!("{RECV}{EVT} {event:?}");
2029 }
2030 }
2031}
2032
2033struct Reservation {
2035 client_order_id: ClientOrderId,
2036 account_id: AccountId,
2037 exposure: ReservedExposure,
2038 wallet: bool,
2039}
2040
2041enum ReservedExposure {
2042 Balance(Money),
2043 Position {
2044 instrument_id: InstrumentId,
2045 side: OrderSide,
2046 quantity: Quantity,
2047 },
2048}
2049
2050impl Reservation {
2051 fn is_released(&self, order: &OrderAny) -> bool {
2054 order.is_open() || order.is_closed() || (self.wallet && order.is_inflight())
2055 }
2056}
2057
2058#[derive(Clone, Copy)]
2059enum RiskCheck<'a> {
2060 Submit,
2061 Modify(&'a [OrderAny], &'a [ModifyOrder]),
2062}
2063
2064impl<'a> RiskCheck<'a> {
2065 fn reject_orders(self, engine: &RiskEngine, orders: &[&OrderAny], reason: &str) {
2066 for order in orders {
2067 self.reject(engine, order, reason);
2068
2069 if matches!(self, Self::Modify(_, _)) {
2070 break;
2071 }
2072 }
2073 }
2074
2075 fn reject(self, engine: &RiskEngine, order: &OrderAny, reason: &str) {
2076 match self {
2077 Self::Submit => engine.deny_order(order, reason),
2078 Self::Modify(originals, commands) => {
2079 for (index, command) in commands.iter().enumerate() {
2080 if commands[..index]
2081 .iter()
2082 .any(|previous| previous.command_id == command.command_id)
2083 {
2084 continue;
2085 }
2086
2087 let original = originals
2088 .iter()
2089 .find(|order| order.client_order_id() == command.client_order_id);
2090 engine.deny_modify_order(original, command, reason);
2091 }
2092 }
2093 }
2094 }
2095
2096 fn original(self, order: &OrderAny) -> Option<&'a OrderAny> {
2097 match self {
2098 Self::Submit => None,
2099 Self::Modify(originals, _) => originals
2100 .iter()
2101 .find(|original| original.client_order_id() == order.client_order_id()),
2102 }
2103 }
2104}
2105
2106struct AccountRisk<'a> {
2109 engine: &'a RiskEngine,
2110 instrument: &'a InstrumentAny,
2111 account: AccountAny,
2112 check: RiskCheck<'a>,
2113 orders: &'a [&'a OrderAny],
2114 full_position_exit: bool,
2115 max_notional: Option<Money>,
2116 allow_borrowing: bool,
2117 available_long_qty_raw: QuantityRaw,
2118 available_short_qty_raw: QuantityRaw,
2119 cum_sell_qty_raw: QuantityRaw,
2120 cum_buy_qty_raw: QuantityRaw,
2121 cum_original_sell_qty_raw: QuantityRaw,
2122 cum_original_buy_qty_raw: QuantityRaw,
2123 cum_notional_buy: Option<Money>,
2124 cum_notional_sell: Option<Money>,
2125 cum_margin_required: Option<Money>,
2126 balances_free: RefCell<Vec<(Currency, Money)>>,
2127 xrates: RefCell<Option<AHashMap<(Currency, OrderSide), Decimal>>>,
2128 reservations: Vec<Reservation>,
2129}
2130
2131impl AccountRisk<'_> {
2132 fn balance_free(&self, order: &OrderAny, currency: Currency) -> Result<Money, ()> {
2134 let cached = self
2135 .balances_free
2136 .borrow()
2137 .iter()
2138 .find(|(cached, _)| *cached == currency && cached.precision == currency.precision)
2139 .map(|(_, free)| *free);
2140
2141 if let Some(free) = cached {
2142 return Ok(free);
2143 }
2144
2145 let free = self
2146 .account
2147 .balance_free(Some(currency))
2148 .unwrap_or_else(|| Money::zero(currency));
2149
2150 if matches!(self.check, RiskCheck::Modify(_, _)) || self.engine.reservations.is_empty() {
2152 return Ok(free);
2153 }
2154
2155 let free = self
2156 .engine
2157 .unreflected_reservations(self.account.id(), self.orders)
2158 .try_fold(free, |free, amount| {
2159 let amount = if self.account.base_currency() == Some(currency) {
2160 self.account_currency_amount(order, amount, OrderSide::Sell)?
2161 } else {
2162 amount
2163 };
2164
2165 if amount.currency == currency {
2166 self.deduct_reservation(order, free, amount)
2167 } else {
2168 Ok(free)
2169 }
2170 })?;
2171
2172 self.balances_free.borrow_mut().push((currency, free));
2173 Ok(free)
2174 }
2175
2176 fn deduct_reservation(
2179 &self,
2180 order: &OrderAny,
2181 free: Money,
2182 amount: Money,
2183 ) -> Result<Money, ()> {
2184 let remaining = if matches!(self.account, AccountAny::Wallet(_))
2185 && amount.currency.precision != free.currency.precision
2186 {
2187 Err(format!(
2188 "reserved balance precision {} differed from balance precision {} for {}",
2189 amount.currency.precision, free.currency.precision, free.currency
2190 ))
2191 } else {
2192 free.checked_sub(amount).ok_or_else(|| {
2193 "reserved balance exceeds Money bounds or has incompatible scale".to_string()
2194 })
2195 };
2196
2197 remaining.map_err(|detail| {
2198 self.check.reject(
2199 self.engine,
2200 order,
2201 &OrderDeniedReason::NotionalCalculationFailed { detail }.to_string(),
2202 );
2203 })
2204 }
2205
2206 fn reserve_balance(&mut self, order: &OrderAny, amount: Money) {
2207 if amount.is_positive() {
2208 self.reservations.push(Reservation {
2209 client_order_id: order.client_order_id(),
2210 account_id: self.account.id(),
2211 exposure: ReservedExposure::Balance(amount),
2212 wallet: matches!(self.account, AccountAny::Wallet(_)),
2213 });
2214 }
2215 }
2216
2217 fn check_order(&mut self, order: &OrderAny, market_price: Option<Price>) -> bool {
2218 let Ok(last_px) = self.order_price(order, market_price) else {
2219 return false;
2220 };
2221
2222 let Some(last_px) = last_px else {
2223 self.engine
2224 .deny_no_market_price(self.instrument.id(), order, self.check);
2225 return false;
2226 };
2227
2228 let Ok(effective_quantity) = self.engine.order_risk_quantity(
2229 self.check,
2230 self.instrument,
2231 order,
2232 order.quantity(),
2233 last_px,
2234 ) else {
2235 return false;
2236 };
2237
2238 if !self.check_order_limits(order, effective_quantity, last_px) {
2239 return false;
2240 }
2241
2242 let effective_quantity = if matches!(self.check, RiskCheck::Modify(_, _)) {
2244 let Ok(quantity) = self.engine.order_risk_quantity(
2245 self.check,
2246 self.instrument,
2247 order,
2248 order.leaves_qty(),
2249 last_px,
2250 ) else {
2251 return false;
2252 };
2253
2254 quantity
2255 } else {
2256 effective_quantity
2257 };
2258
2259 let Ok(original) = self.original_exposure(order, market_price) else {
2260 return false;
2261 };
2262
2263 let reserved_quantity = original.map_or(effective_quantity.raw(), |(_, quantity, _)| {
2265 quantity.raw().max(effective_quantity.raw())
2266 });
2267
2268 if matches!(self.account, AccountAny::Margin(_)) {
2269 return self.check_margin(
2270 order,
2271 effective_quantity,
2272 last_px,
2273 original,
2274 reserved_quantity,
2275 );
2276 }
2277
2278 self.check_balance(
2279 order,
2280 effective_quantity,
2281 last_px,
2282 original,
2283 reserved_quantity,
2284 )
2285 }
2286
2287 fn original_exposure(
2288 &mut self,
2289 order: &OrderAny,
2290 market_price: Option<Price>,
2291 ) -> Result<Option<(Price, Quantity, bool)>, ()> {
2292 let Some(original) = self.check.original(order).filter(|original| {
2293 original.is_open()
2294 || (matches!(self.account, AccountAny::Wallet(_)) && original.is_inflight())
2295 }) else {
2296 return Ok(None);
2297 };
2298
2299 let original_price = match self.order_price(original, market_price) {
2300 Ok(Some(price)) => price,
2301 Ok(None) => {
2302 self.engine
2303 .deny_no_market_price(self.instrument.id(), order, self.check);
2304 return Err(());
2305 }
2306 Err(()) => return Err(()),
2307 };
2308
2309 let quantity = self.engine.order_risk_quantity(
2310 self.check,
2311 self.instrument,
2312 original,
2313 original.leaves_qty(),
2314 original_price,
2315 )?;
2316 let is_reducing = !self.is_cash_disposal(original, original_price)
2317 && !matches!(self.account, AccountAny::Wallet(_))
2318 && ((original.is_reduce_only()
2319 && (matches!(self.account, AccountAny::Margin(_)) || original.is_sell()))
2320 || (original.is_sell()
2321 && self.cum_original_sell_qty_raw + quantity.raw()
2322 <= self.available_long_qty_raw)
2323 || (original.is_buy()
2324 && self.cum_original_buy_qty_raw + quantity.raw()
2325 <= self.available_short_qty_raw));
2326
2327 if original.is_sell() {
2328 self.cum_original_sell_qty_raw += quantity.raw();
2329 } else {
2330 self.cum_original_buy_qty_raw += quantity.raw();
2331 }
2332
2333 Ok(Some((original_price, quantity, is_reducing)))
2334 }
2335
2336 fn order_price(
2337 &mut self,
2338 order: &OrderAny,
2339 market_price: Option<Price>,
2340 ) -> Result<Option<Price>, ()> {
2341 match order {
2342 OrderAny::MarketToLimit(_) if order.price().is_some() => Ok(order.price()),
2343 OrderAny::Market(_) | OrderAny::MarketToLimit(_) => {
2344 let Some(price) = market_price else {
2345 let is_reducing = !matches!(self.account, AccountAny::Wallet(_))
2346 && (order.is_reduce_only()
2347 || (order.is_sell()
2348 && (self.cum_sell_qty_raw + order.quantity().raw())
2349 <= self.available_long_qty_raw));
2350
2351 if !order.is_quote_quantity()
2352 && order.is_sell()
2353 && !is_reducing
2354 && let Some(unleveraged) = cash_or_wallet_account(&self.account)
2355 && unleveraged.base_currency().is_none()
2356 && let Some(base_currency) = self.instrument.base_currency()
2357 {
2358 let base_free = self.balance_free(order, base_currency)?;
2359 self.engine.check_cash_sell_balance(
2360 self.check,
2361 unleveraged,
2362 self.allow_borrowing,
2363 order,
2364 order.quantity(),
2365 base_free,
2366 &mut self.cum_notional_sell,
2367 )?;
2368 }
2369
2370 self.engine
2371 .deny_no_market_price(self.instrument.id(), order, self.check);
2372 return Err(());
2373 };
2374
2375 Ok(Some(price))
2376 }
2377 OrderAny::StopMarket(_) | OrderAny::MarketIfTouched(_) => Ok(order.trigger_price()),
2378 OrderAny::TrailingStopMarket(_) | OrderAny::TrailingStopLimit(_) => {
2379 self.trailing_order_price(order)
2380 }
2381 _ => Ok(order.price()),
2382 }
2383 }
2384
2385 fn trailing_order_price(&self, order: &OrderAny) -> Result<Option<Price>, ()> {
2386 if let Some(price) = order.trigger_price() {
2387 return Ok(order.price().or(Some(price)));
2388 }
2389
2390 let Some(offset_type) = order.trailing_offset_type() else {
2392 self.check.reject(
2393 self.engine,
2394 order,
2395 &OrderDeniedReason::MissingTrailingOffsetType.to_string(),
2396 );
2397 return Err(()); };
2399
2400 if !matches!(
2401 offset_type,
2402 TrailingOffsetType::Price | TrailingOffsetType::BasisPoints | TrailingOffsetType::Ticks
2403 ) {
2404 self.check.reject(
2405 self.engine,
2406 order,
2407 &OrderDeniedReason::UnsupportedTrailingOffsetType { offset_type }.to_string(),
2408 );
2409 return Err(());
2410 }
2411
2412 let Some(trigger_type) = order.trigger_type() else {
2413 self.check.reject(
2414 self.engine,
2415 order,
2416 &OrderDeniedReason::MissingTriggerType.to_string(),
2417 );
2418 return Err(()); };
2420
2421 let Some(trailing_offset) = order.trailing_offset() else {
2422 self.check.reject(
2423 self.engine,
2424 order,
2425 &OrderDeniedReason::MissingTrailingOffset.to_string(),
2426 );
2427 return Err(()); };
2429
2430 if let Some(price) = order.price() {
2431 return Ok(Some(price));
2432 }
2433
2434 self.calculate_trailing_price(order, offset_type, trigger_type, trailing_offset)
2436 .map_err(|detail| {
2437 self.check.reject(
2438 self.engine,
2439 order,
2440 &OrderDeniedReason::TrailingStopCalculationFailed { detail }.to_string(),
2441 );
2442 })
2443 }
2444
2445 fn calculate_trailing_price(
2446 &self,
2447 order: &OrderAny,
2448 offset_type: TrailingOffsetType,
2449 trigger_type: TriggerType,
2450 trailing_offset: Decimal,
2451 ) -> Result<Option<Price>, String> {
2452 let cache = self.engine.cache.borrow();
2453 if trigger_type != TriggerType::BidAsk
2454 && let Some(trade) = cache.trade(&self.instrument.id())
2455 {
2456 return trailing_stop_calculate_with_last(
2457 self.instrument.price_increment(),
2458 offset_type,
2459 order.order_side(),
2460 trailing_offset,
2461 trade.price,
2462 )
2463 .map(Some)
2464 .map_err(|e| e.to_string());
2465 }
2466
2467 if matches!(
2468 trigger_type,
2469 TriggerType::BidAsk | TriggerType::LastOrBidAsk
2470 ) && let Some(quote) = cache.quote(&self.instrument.id())
2471 {
2472 return trailing_stop_calculate_with_bid_ask(
2473 self.instrument.price_increment(),
2474 offset_type,
2475 order.order_side(),
2476 trailing_offset,
2477 quote.bid_price,
2478 quote.ask_price,
2479 )
2480 .map(Some)
2481 .map_err(|e| e.to_string());
2482 }
2483
2484 if trigger_type == TriggerType::BidAsk {
2485 log::warn!(
2486 "Cannot check {} order risk: no trigger price set and no bid/ask quotes available for {}",
2487 order.order_type(),
2488 self.instrument.id()
2489 );
2490 } else {
2491 log::warn!(
2492 "Cannot check {} order risk: no trigger price set and no market data available for {}",
2493 order.order_type(),
2494 self.instrument.id()
2495 );
2496 }
2497
2498 Ok(None)
2499 }
2500
2501 fn check_order_limits(
2502 &self,
2503 order: &OrderAny,
2504 effective_quantity: Quantity,
2505 last_px: Price,
2506 ) -> bool {
2507 if !order.is_quote_quantity() && !self.full_position_exit {
2513 if let Some(max_quantity) = self.instrument.max_quantity()
2514 && effective_quantity > max_quantity
2515 {
2516 self.check.reject(
2517 self.engine,
2518 order,
2519 &OrderDeniedReason::QuantityExceedsMaximum {
2520 effective_quantity,
2521 max_quantity,
2522 }
2523 .to_string(),
2524 );
2525
2526 return false; }
2528
2529 if let Some(min_quantity) = self.instrument.min_quantity()
2530 && effective_quantity < min_quantity
2531 {
2532 self.check.reject(
2533 self.engine,
2534 order,
2535 &OrderDeniedReason::QuantityBelowMinimum {
2536 effective_quantity,
2537 min_quantity,
2538 }
2539 .to_string(),
2540 );
2541
2542 return false; }
2544 }
2545
2546 let notional = match self.instrument.try_calculate_notional_value(
2548 effective_quantity,
2549 last_px,
2550 Some(true),
2551 ) {
2552 Ok(notional) => notional.abs(),
2553 Err(e) => {
2554 self.check.reject(
2555 self.engine,
2556 order,
2557 &OrderDeniedReason::NotionalCalculationFailed {
2558 detail: e.to_string(),
2559 }
2560 .to_string(),
2561 );
2562
2563 return false;
2564 }
2565 };
2566
2567 if self.engine.config.debug {
2568 log::debug!("Notional: {notional:?}");
2569 }
2570
2571 if !self.full_position_exit
2573 && let Some(max_notional_value) = self.max_notional
2574 && notional > max_notional_value
2575 {
2576 self.check.reject(
2577 self.engine,
2578 order,
2579 &OrderDeniedReason::NotionalExceedsMaxPerOrder {
2580 max_notional: max_notional_value,
2581 notional,
2582 }
2583 .to_string(),
2584 );
2585
2586 return false; }
2588
2589 if !order.is_reduce_only()
2592 && !self.full_position_exit
2593 && let Some(min_notional) = self.instrument.min_notional()
2594 && notional.currency == min_notional.currency
2595 && notional < min_notional
2596 {
2597 self.check.reject(
2598 self.engine,
2599 order,
2600 &OrderDeniedReason::NotionalBelowMinimum {
2601 min_notional,
2602 notional,
2603 }
2604 .to_string(),
2605 );
2606
2607 return false; }
2609
2610 if !self.full_position_exit
2612 && let Some(max_notional) = self.instrument.max_notional()
2613 && notional.currency == max_notional.currency
2614 && notional > max_notional
2615 {
2616 self.check.reject(
2617 self.engine,
2618 order,
2619 &OrderDeniedReason::NotionalExceedsMaximum {
2620 max_notional,
2621 notional,
2622 }
2623 .to_string(),
2624 );
2625
2626 return false; }
2628
2629 true
2630 }
2631
2632 fn check_margin(
2633 &mut self,
2634 order: &OrderAny,
2635 quantity: Quantity,
2636 price: Price,
2637 original: Option<(Price, Quantity, bool)>,
2638 reserved_quantity: QuantityRaw,
2639 ) -> bool {
2640 let Ok(required) = self.initial_margin(order, quantity, price) else {
2641 return false;
2642 };
2643
2644 if self.engine.config.debug {
2645 log::debug!("Initial margin required: {required}");
2646 }
2647
2648 if self.reserve_position(order, quantity, reserved_quantity) {
2649 if self.engine.config.debug {
2650 log::debug!("Position-reducing order skips margin check");
2651 }
2652
2653 return true;
2654 }
2655
2656 let Ok(required) = self.margin_increase(order, required, original) else {
2657 return false;
2658 };
2659
2660 self.check_margin_balance(order, required)
2661 }
2662
2663 fn margin_increase(
2664 &mut self,
2665 order: &OrderAny,
2666 required: Money,
2667 original: Option<(Price, Quantity, bool)>,
2668 ) -> Result<Money, ()> {
2669 let Some((price, quantity, was_reducing)) = original else {
2670 return Ok(required);
2671 };
2672
2673 let previous = if was_reducing {
2674 Money::zero(required.currency)
2675 } else {
2676 self.initial_margin(order, quantity, price)?
2677 };
2678
2679 self.engine
2680 .check_risk_increase(self.check, order, required, previous)
2681 .ok_or(())
2682 }
2683
2684 fn initial_margin(
2685 &mut self,
2686 order: &OrderAny,
2687 quantity: Quantity,
2688 price: Price,
2689 ) -> Result<Money, ()> {
2690 let AccountAny::Margin(margin) = &mut self.account else {
2691 unreachable!()
2692 };
2693
2694 margin
2695 .calculate_initial_margin(self.instrument, quantity, price, None)
2696 .map_err(|e| {
2697 self.check.reject(
2698 self.engine,
2699 order,
2700 &OrderDeniedReason::InitialMarginCalculationFailed {
2701 detail: e.to_string(),
2702 }
2703 .to_string(),
2704 );
2705 })
2706 }
2707
2708 fn check_margin_balance(&mut self, order: &OrderAny, required: Money) -> bool {
2709 if matches!(self.check, RiskCheck::Modify(_, _)) && required.is_zero() {
2710 return true;
2711 }
2712
2713 let Ok(required) = self.account_currency_amount(order, required, order.order_side()) else {
2714 return false;
2715 };
2716
2717 let Ok(free) = self.balance_free(order, required.currency) else {
2719 return false;
2720 };
2721
2722 if required > free {
2723 self.check.reject(
2724 self.engine,
2725 order,
2726 &OrderDeniedReason::InitialMarginExceedsFreeBalance {
2727 free_balance: free,
2728 initial_margin: required,
2729 }
2730 .to_string(),
2731 );
2732
2733 return false;
2734 }
2735
2736 let total = match self.cum_margin_required {
2737 Some(total) => total.checked_add(required),
2738 None => Some(required),
2739 };
2740
2741 let Some(total) = total else {
2742 self.check.reject(
2743 self.engine,
2744 order,
2745 &OrderDeniedReason::CumulativeInitialMarginCalculationFailed {
2746 detail: "total exceeds Money bounds".to_string(),
2747 }
2748 .to_string(),
2749 );
2750
2751 return false;
2752 };
2753
2754 self.cum_margin_required = Some(total);
2755
2756 if self.engine.config.debug {
2757 log::debug!("Cumulative margin required: {:?}", self.cum_margin_required);
2758 }
2759
2760 if total > free {
2761 self.check.reject(
2762 self.engine,
2763 order,
2764 &OrderDeniedReason::CumulativeInitialMarginExceedsFreeBalance {
2765 free_balance: free,
2766 cumulative_initial_margin: total,
2767 }
2768 .to_string(),
2769 );
2770
2771 return false;
2772 }
2773
2774 self.reserve_balance(order, required);
2775 true
2776 }
2777
2778 fn check_balance(
2779 &mut self,
2780 order: &OrderAny,
2781 quantity: Quantity,
2782 price: Price,
2783 original: Option<(Price, Quantity, bool)>,
2784 reserved_quantity: QuantityRaw,
2785 ) -> bool {
2786 let Ok((notional, impact)) = self.balance_impact(order, quantity, price) else {
2787 return false;
2788 };
2789
2790 if self.engine.config.debug {
2791 log::debug!("Balance impact: {impact}");
2792 }
2793
2794 let reducing = self.reserve_position(order, quantity, reserved_quantity);
2795 let cash_disposal = self.is_cash_disposal(order, price);
2796 if reducing && !cash_disposal {
2797 if self.engine.config.debug {
2798 log::debug!("Position-reducing order skips balance check");
2799 }
2800
2801 return self.check_balance_inventory(
2802 order,
2803 quantity,
2804 original,
2805 reducing,
2806 cash_disposal,
2807 );
2808 }
2809
2810 let Ok(impact) = self.balance_increase(order, impact, original) else {
2811 return false;
2812 };
2813
2814 let is_debit =
2815 order.is_buy() || matches!(self.account, AccountAny::Betting(_)) || cash_disposal;
2816
2817 if !self.check_balance_funding(order, notional, impact, is_debit) {
2818 return false;
2819 }
2820
2821 self.check_balance_inventory(order, quantity, original, reducing, cash_disposal)
2822 }
2823
2824 fn check_balance_inventory(
2825 &mut self,
2826 order: &OrderAny,
2827 quantity: Quantity,
2828 original: Option<(Price, Quantity, bool)>,
2829 reducing: bool,
2830 cash_disposal: bool,
2831 ) -> bool {
2832 if order.is_buy()
2833 || matches!(self.account, AccountAny::Betting(_))
2834 || (order.is_reduce_only() && !matches!(self.account, AccountAny::Wallet(_)))
2835 || (reducing && matches!(self.check, RiskCheck::Modify(_, _)))
2836 {
2837 return true;
2838 }
2839
2840 if self.account.base_currency().is_some()
2841 && !reducing
2842 && !cash_disposal
2843 && !original.is_some_and(|(price, _, _)| price.is_negative())
2844 {
2845 return true;
2846 }
2847
2848 self.check_asset_balance(order, quantity, original, reducing)
2849 }
2850
2851 fn check_balance_funding(
2852 &mut self,
2853 order: &OrderAny,
2854 notional: Money,
2855 impact: Money,
2856 is_debit: bool,
2857 ) -> bool {
2858 if matches!(self.check, RiskCheck::Modify(_, _))
2859 && impact.is_zero()
2860 && (is_debit || self.account.base_currency().is_some())
2861 {
2862 return true;
2863 }
2864
2865 let Ok(impact) = self.account_currency_amount(order, impact, order.order_side()) else {
2866 return false;
2867 };
2868
2869 let Ok(free) = self.balance_free(order, impact.currency) else {
2870 return false;
2871 };
2872
2873 if !self.allow_borrowing && free.as_decimal() + impact.as_decimal() < Decimal::ZERO {
2874 self.check.reject(
2875 self.engine,
2876 order,
2877 &OrderDeniedReason::NotionalExceedsFreeBalance {
2878 free_balance: free,
2879 notional,
2880 }
2881 .to_string(),
2882 );
2883
2884 return false;
2885 }
2886
2887 if is_debit {
2888 let required = (-impact).max(Money::zero(impact.currency));
2889 return self.check_cumulative_balance(order, required, true);
2890 }
2891
2892 if self.instrument.base_currency().is_some() && self.account.base_currency().is_some() {
2895 return self.check_cumulative_balance(order, impact, false);
2896 }
2897
2898 true
2899 }
2900
2901 fn is_cash_disposal(&self, order: &OrderAny, price: Price) -> bool {
2902 matches!(self.account, AccountAny::Cash(_)) && order.is_sell() && price.is_negative()
2903 }
2904
2905 fn reserve_position(
2906 &mut self,
2907 order: &OrderAny,
2908 quantity: Quantity,
2909 reserved: QuantityRaw,
2910 ) -> bool {
2911 let (cumulative, available) = match order.order_side() {
2912 OrderSide::Buy => (&mut self.cum_buy_qty_raw, self.available_short_qty_raw),
2913 OrderSide::Sell => (&mut self.cum_sell_qty_raw, self.available_long_qty_raw),
2914 };
2915
2916 let reducing = self.full_position_exit
2917 || (order.is_reduce_only()
2918 && (matches!(self.account, AccountAny::Margin(_)) || order.is_sell()))
2919 || *cumulative + quantity.raw() <= available;
2920 *cumulative += reserved;
2921 let reducing = reducing && !matches!(self.account, AccountAny::Wallet(_));
2922 if !matches!(self.check, RiskCheck::Submit)
2923 || matches!(self.account, AccountAny::Wallet(_))
2924 || !quantity.is_positive()
2925 {
2926 return reducing;
2927 }
2928
2929 let unfilled_oto_parent = order.parent_order_id().is_some_and(|parent_id| {
2930 self.engine
2931 .cache
2932 .borrow()
2933 .order(&parent_id)
2934 .is_some_and(|parent| {
2935 parent.contingency_type() == Some(ContingencyType::Oto)
2936 && parent.filled_qty().is_zero()
2937 })
2938 });
2939
2940 if !unfilled_oto_parent {
2941 self.reservations.push(Reservation {
2942 client_order_id: order.client_order_id(),
2943 account_id: self.account.id(),
2944 exposure: ReservedExposure::Position {
2945 instrument_id: self.instrument.id(),
2946 side: order.order_side(),
2947 quantity,
2948 },
2949 wallet: false,
2950 });
2951 }
2952
2953 reducing
2954 }
2955
2956 fn balance_impact(
2957 &mut self,
2958 order: &OrderAny,
2959 quantity: Quantity,
2960 price: Price,
2961 ) -> Result<(Money, Money), ()> {
2962 let notional = self.notional_value(order, quantity, price).map_err(|e| {
2963 self.check.reject(
2964 self.engine,
2965 order,
2966 &OrderDeniedReason::NotionalCalculationFailed { detail: e }.to_string(),
2967 );
2968 })?;
2969
2970 let impact = if let AccountAny::Betting(betting) = &mut self.account {
2971 -betting
2972 .calculate_balance_locked(
2973 self.instrument,
2974 order.order_side(),
2975 quantity,
2976 price,
2977 None,
2978 )
2979 .map_err(|e| {
2980 self.check.reject(
2981 self.engine,
2982 order,
2983 &OrderDeniedReason::BettingBalanceLockedCalculationFailed {
2984 detail: e.to_string(),
2985 }
2986 .to_string(),
2987 );
2988 })?
2989 } else if let Some(funding) =
2990 self.wallet_buy_funding(order, quantity, price, notional.currency)
2991 {
2992 let funding = funding.map_err(|detail| {
2993 self.check.reject(
2994 self.engine,
2995 order,
2996 &OrderDeniedReason::NotionalCalculationFailed { detail }.to_string(),
2997 );
2998 })?;
2999
3000 return Ok((funding, -funding));
3002 } else {
3003 match order.order_side() {
3004 OrderSide::Buy => -notional,
3005 OrderSide::Sell => notional,
3006 }
3007 };
3008
3009 Ok((notional, impact))
3010 }
3011
3012 fn notional_value(
3013 &self,
3014 order: &OrderAny,
3015 quantity: Quantity,
3016 price: Price,
3017 ) -> Result<Money, String> {
3018 if self.is_cash_disposal(order, price)
3019 && let AccountAny::Cash(account) = &self.account
3020 {
3021 return account
3022 .calculate_balance_locked(self.instrument, OrderSide::Buy, quantity, -price, None)
3023 .map(|amount| -amount)
3024 .map_err(|e| e.to_string());
3025 }
3026
3027 self.instrument
3028 .try_calculate_notional_value(quantity, price, None)
3029 .map_err(|e| e.to_string())
3030 }
3031
3032 fn wallet_buy_funding(
3037 &self,
3038 order: &OrderAny,
3039 quantity: Quantity,
3040 price: Price,
3041 notional_currency: Currency,
3042 ) -> Option<Result<Money, String>> {
3043 let AccountAny::Wallet(wallet) = &self.account else {
3044 return None;
3045 };
3046
3047 if !order.is_buy() {
3048 return None;
3049 }
3050
3051 if order.is_quote_quantity() {
3052 let quote_currency = self.instrument.quote_currency();
3053 let currency = wallet
3054 .balance_total(Some(quote_currency))
3055 .map_or(quote_currency, |observed| observed.currency);
3056 return Some(
3057 Money::from_quantity(order.leaves_qty(), currency).map_err(|e| e.to_string()),
3058 );
3059 }
3060
3061 wallet.balance_total(Some(notional_currency))?;
3062 Some(
3063 wallet
3064 .calculate_balance_locked(self.instrument, OrderSide::Buy, quantity, price, None)
3065 .map_err(|e| e.to_string()),
3066 )
3067 }
3068
3069 fn balance_increase(
3070 &mut self,
3071 order: &OrderAny,
3072 impact: Money,
3073 original: Option<(Price, Quantity, bool)>,
3074 ) -> Result<Money, ()> {
3075 let Some((price, quantity, was_reducing)) = original else {
3076 return Ok(impact);
3077 };
3078
3079 let previous = if was_reducing {
3080 Ok(Money::zero(impact.currency))
3081 } else if let AccountAny::Betting(betting) = &mut self.account {
3082 betting
3083 .calculate_balance_locked(
3084 self.instrument,
3085 order.order_side(),
3086 quantity,
3087 price,
3088 None,
3089 )
3090 .map_err(|e| e.to_string())
3091 } else if let Some(funding) = self.check.original(order).and_then(|original| {
3092 self.wallet_buy_funding(original, quantity, price, impact.currency)
3093 }) {
3094 funding
3095 } else {
3096 self.notional_value(order, quantity, price)
3097 }
3098 .map_err(|detail| {
3099 self.check.reject(
3100 self.engine,
3101 order,
3102 &OrderDeniedReason::NotionalCalculationFailed { detail }.to_string(),
3103 );
3104 })?;
3105
3106 let cash_disposal = matches!(self.account, AccountAny::Cash(_))
3107 && order.is_sell()
3108 && (impact.is_negative() || price.is_negative());
3109
3110 let previous = if cash_disposal { -previous } else { previous };
3111 let is_debit =
3112 order.is_buy() || matches!(self.account, AccountAny::Betting(_)) || cash_disposal;
3113
3114 let current = if is_debit { -impact } else { impact };
3115 let increase = self
3116 .engine
3117 .check_risk_increase(self.check, order, current, previous)
3118 .ok_or(())?;
3119 Ok(if is_debit { -increase } else { increase })
3120 }
3121
3122 fn check_cumulative_balance(
3123 &mut self,
3124 order: &OrderAny,
3125 required: Money,
3126 is_debit: bool,
3127 ) -> bool {
3128 let (current, other) = if is_debit {
3129 (self.cum_notional_buy, self.cum_notional_sell)
3130 } else {
3131 (self.cum_notional_sell, self.cum_notional_buy)
3132 };
3133
3134 let Ok(current) = current
3135 .map(|amount| self.account_currency_amount(order, amount, OrderSide::Sell))
3136 .transpose()
3137 else {
3138 return false;
3139 };
3140
3141 let Ok(other) = other
3142 .map(|amount| self.account_currency_amount(order, amount, OrderSide::Sell))
3143 .transpose()
3144 else {
3145 return false;
3146 };
3147
3148 let cumulative = if is_debit {
3149 &mut self.cum_notional_buy
3150 } else {
3151 &mut self.cum_notional_sell
3152 };
3153
3154 *cumulative = current;
3155
3156 if !self
3157 .engine
3158 .accumulate_notional(self.check, order, cumulative, required)
3159 {
3160 return false;
3161 }
3162
3163 if self.engine.config.debug {
3164 log::debug!(
3165 "Cumulative balance required for {}: {cumulative:?}",
3166 order.order_side()
3167 );
3168 }
3169
3170 let cumulative = *cumulative;
3171
3172 let Ok(mut free) = self.balance_free(order, required.currency) else {
3173 return false;
3174 };
3175
3176 if let Some(other) = other.filter(|amount| amount.currency == required.currency) {
3177 let Ok(remaining) = self.deduct_reservation(order, free, other) else {
3178 return false;
3179 };
3180
3181 free = remaining;
3182 }
3183
3184 if !self.allow_borrowing
3185 && let Some(total) = cumulative
3186 && total > free
3187 {
3188 self.check.reject(
3189 self.engine,
3190 order,
3191 &OrderDeniedReason::CumulativeNotionalExceedsFreeBalance {
3192 free_balance: free,
3193 cumulative_notional: total,
3194 }
3195 .to_string(),
3196 );
3197
3198 return false;
3199 }
3200
3201 self.reserve_balance(order, required);
3202 true
3203 }
3204
3205 fn account_currency_amount(
3206 &self,
3207 order: &OrderAny,
3208 amount: Money,
3209 side: OrderSide,
3210 ) -> Result<Money, ()> {
3211 let Some(currency) = self.account.base_currency() else {
3212 return Ok(amount);
3213 };
3214
3215 if amount.currency == currency {
3216 return Ok(amount);
3217 }
3218
3219 if amount.is_zero() {
3220 return Ok(Money::zero(currency));
3221 }
3222
3223 let price_type = match side {
3225 OrderSide::Buy => PriceType::Bid,
3226 OrderSide::Sell => PriceType::Ask,
3227 };
3228
3229 let key = (amount.currency, side);
3230 let cached = self
3231 .xrates
3232 .borrow()
3233 .as_ref()
3234 .and_then(|xrates| xrates.get(&key).copied());
3235
3236 let xrate = match cached {
3237 Some(xrate) => Ok(Some(xrate)),
3238 None => {
3239 let xrate = self.engine.cache.borrow().try_get_xrate(
3240 self.instrument.id().venue,
3241 amount.currency,
3242 currency,
3243 price_type,
3244 );
3245
3246 if let Ok(Some(rate)) = &xrate {
3247 self.xrates
3248 .borrow_mut()
3249 .get_or_insert_with(AHashMap::new)
3250 .insert(key, *rate);
3251 }
3252
3253 xrate
3254 }
3255 };
3256
3257 xrate
3258 .map_err(|e| e.to_string())
3259 .and_then(|xrate| {
3260 let xrate = xrate.ok_or_else(|| {
3261 format!("No exchange rate from {} to {currency}", amount.currency)
3262 })?;
3263
3264 let value = amount.as_decimal().checked_mul(xrate).ok_or_else(|| {
3265 "Account currency conversion exceeds Decimal bounds".to_string()
3266 })?;
3267
3268 Money::from_decimal_native(value, currency).map_err(|e| e.to_string())
3269 })
3270 .map_err(|e| {
3271 self.check.reject(
3272 self.engine,
3273 order,
3274 &OrderDeniedReason::ValidationFailed {
3275 detail: format!("Account currency conversion failed: {e}"),
3276 }
3277 .to_string(),
3278 );
3279 })
3280 }
3281
3282 fn check_asset_balance(
3283 &mut self,
3284 order: &OrderAny,
3285 quantity: Quantity,
3286 original: Option<(Price, Quantity, bool)>,
3287 reducing: bool,
3288 ) -> bool {
3289 let Some(base_currency) = self.instrument.base_currency() else {
3290 return true;
3291 };
3292
3293 let quantity = match original {
3294 Some((_, previous, false)) => quantity.saturating_sub(previous),
3295 _ => quantity,
3296 };
3297
3298 let currency = self
3299 .account
3300 .balance_total(Some(base_currency))
3301 .map_or(base_currency, |balance| balance.currency);
3302
3303 let cash_value = match Money::from_quantity(quantity, currency) {
3304 Ok(value) => value,
3305 Err(e) => {
3306 self.check.reject(
3307 self.engine,
3308 order,
3309 &OrderDeniedReason::QuantityConversionFailed {
3310 detail: e.to_string(),
3311 }
3312 .to_string(),
3313 );
3314
3315 return false;
3316 }
3317 };
3318
3319 if reducing {
3320 if !self.engine.accumulate_notional(
3321 self.check,
3322 order,
3323 &mut self.cum_notional_sell,
3324 cash_value,
3325 ) {
3326 return false;
3327 }
3328
3329 self.reserve_balance(order, cash_value);
3330 return true;
3331 }
3332
3333 let Ok(cash_value) = self.account_currency_amount(order, cash_value, OrderSide::Sell)
3334 else {
3335 return false;
3336 };
3337
3338 self.check_cumulative_balance(order, cash_value, false)
3339 }
3340}
3341
3342fn cash_or_wallet_account(account: &AccountAny) -> Option<&dyn Account> {
3345 match account {
3346 AccountAny::Cash(cash) => Some(cash),
3347 AccountAny::Wallet(wallet) => Some(wallet),
3348 AccountAny::Margin(_) | AccountAny::Betting(_) => None,
3349 }
3350}
3351
3352#[cfg(test)]
3353mod tests;