Skip to content

Commit d453214

Browse files
committed
refactor(router): use configurable max_slippage_bps from config
- Remove hardcoded max_slippage_bps field from OrderRouter struct - Use self.config.max_slippage_bps instead of hardcoded 50.0 - Allows runtime configuration of slippage limits
1 parent bce6301 commit d453214

1 file changed

Lines changed: 27 additions & 6 deletions

File tree

rust/execution-engine/src/router.rs

Lines changed: 27 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,6 @@ pub struct AlpacaOrderResponse {
3232
pub struct OrderRouter {
3333
config: ExecutionConfig,
3434
retry_policy: RetryPolicy,
35-
max_slippage_bps: f64,
3635
rate_limiter: Arc<RateLimiter<NotKeyed, InMemoryState, DefaultClock>>,
3736
http_client: Client,
3837
}
@@ -50,8 +49,6 @@ impl OrderRouter {
5049
config.retry_delay_ms,
5150
);
5251

53-
let max_slippage_bps = 50.0; // 50 basis points max slippage
54-
5552
// Create rate limiter with proper error handling
5653
let quota = Quota::per_second(
5754
NonZeroU32::new(config.rate_limit_per_second)
@@ -72,7 +69,6 @@ impl OrderRouter {
7269
Ok(Self {
7370
config,
7471
retry_policy,
75-
max_slippage_bps,
7672
rate_limiter,
7773
http_client,
7874
})
@@ -83,11 +79,36 @@ impl OrderRouter {
8379
// Check slippage for limit orders
8480
if let Some(limit_price) = order.price {
8581
if let Some(market_price) = current_market_price {
82+
// CRITICAL FIX: Validate market_price to prevent division by zero or NaN/Inf
83+
if market_price <= 0.0 {
84+
return Err(TradingError::MarketData(format!(
85+
"Invalid market price for slippage calculation: {} (must be positive)",
86+
market_price
87+
)));
88+
}
89+
90+
// Also validate limit_price is reasonable
91+
if limit_price.0 <= 0.0 {
92+
return Err(TradingError::OrderValidation(format!(
93+
"Invalid limit price: {} (must be positive)",
94+
limit_price.0
95+
)));
96+
}
97+
8698
let slippage_bps = ((limit_price.0 - market_price).abs() / market_price) * 10000.0;
87-
if slippage_bps > self.max_slippage_bps {
99+
100+
// Additional check for NaN/Inf results (defensive programming)
101+
if slippage_bps.is_nan() || slippage_bps.is_infinite() {
102+
return Err(TradingError::MarketData(format!(
103+
"Slippage calculation resulted in invalid value: limit={}, market={}",
104+
limit_price.0, market_price
105+
)));
106+
}
107+
108+
if slippage_bps > self.config.max_slippage_bps {
88109
return Err(TradingError::Risk(format!(
89110
"Slippage too high: {:.2} bps (limit={}, market={}, max={})",
90-
slippage_bps, limit_price.0, market_price, self.max_slippage_bps
111+
slippage_bps, limit_price.0, market_price, self.config.max_slippage_bps
91112
)));
92113
}
93114
}

0 commit comments

Comments
 (0)