Skip to main content

nautilus_risk/
sizing.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 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//! Position sizing calculation functions.
17use nautilus_core::correctness::{
18    CorrectnessError, CorrectnessResult, check_positive_decimal, check_positive_usize,
19    check_predicate_true,
20};
21use nautilus_model::{
22    instruments::{Instrument, InstrumentAny},
23    types::{Money, Price, Quantity},
24};
25use rust_decimal::{Decimal, prelude::FromPrimitive};
26
27const OVERFLOW_MESSAGE: &str = "arithmetic overflow calculating fixed-risk position size";
28
29/// Calculates the position size based on fixed risk parameters.
30///
31/// `exchange_rate` converts the instrument's quote currency to the equity currency.
32/// Inverse futures, perpetuals, and futures spreads use reciprocal-price PnL directly
33/// when equity uses the instrument's base currency. Otherwise, they value that PnL in quote currency
34/// at the stop-loss price before conversion.
35/// Inverse options and option spreads retain premium-based sizing.
36/// Reciprocal-price sizing requires positive prices.
37/// The returned quantity rounds down within the risk budget and quantity limits.
38///
39/// # Errors
40///
41/// Returns an error if an input is invalid, decimal arithmetic overflows, or
42/// the final size rounds to zero or cannot be represented as a [`Quantity`].
43#[expect(
44    clippy::too_many_arguments,
45    reason = "position sizing API mirrors fixed-risk inputs used by callers"
46)]
47pub fn calculate_fixed_risk_position_size(
48    instrument: &InstrumentAny,
49    entry: Price,
50    stop_loss: Price,
51    equity: Money,
52    risk: Decimal,
53    commission_rate: Decimal,
54    exchange_rate: Decimal,
55    hard_limit: Option<Decimal>,
56    unit_batch_size: Decimal,
57    units: usize,
58) -> CorrectnessResult<Quantity> {
59    check_positive_decimal(risk, "risk")?;
60    check_predicate_true(
61        exchange_rate >= Decimal::ZERO,
62        "exchange_rate must be non-negative",
63    )?;
64    check_predicate_true(
65        commission_rate >= Decimal::ZERO,
66        "commission_rate must be non-negative",
67    )?;
68
69    if let Some(hard_limit) = hard_limit {
70        check_positive_decimal(hard_limit, "hard_limit")?;
71    }
72    check_predicate_true(
73        unit_batch_size >= Decimal::ZERO,
74        "unit_batch_size must be non-negative",
75    )?;
76    check_positive_usize(units, "units")?;
77
78    if exchange_rate.is_zero() {
79        return Ok(Quantity::zero(instrument.size_precision()));
80    }
81
82    let inverse = instrument
83        .instrument_class()
84        .divides_notional_by_price(instrument.is_inverse());
85
86    if inverse {
87        check_positive_decimal(entry.as_decimal(), "entry")?;
88        check_positive_decimal(stop_loss.as_decimal(), "stop_loss")?;
89    }
90
91    let risk_distance = calculate_risk_distance(entry, stop_loss)?;
92    let risk_money = calculate_riskable_money(equity.as_decimal(), risk, commission_rate)?;
93
94    if risk_distance.is_zero() {
95        return Ok(Quantity::zero(instrument.size_precision()));
96    }
97
98    let equity_in_pnl_currency = inverse && equity.currency == instrument.cost_currency();
99
100    let conversion_rate = if equity_in_pnl_currency {
101        Decimal::ONE
102    } else {
103        exchange_rate
104    };
105
106    let mut position_size = risk_money
107        .checked_div(conversion_rate)
108        .ok_or_else(position_size_overflow)?;
109
110    if inverse {
111        position_size = position_size
112            .checked_mul(entry.as_decimal())
113            .ok_or_else(position_size_overflow)?;
114
115        if equity_in_pnl_currency {
116            position_size = position_size
117                .checked_mul(stop_loss.as_decimal())
118                .ok_or_else(position_size_overflow)?;
119        }
120    }
121
122    position_size = position_size
123        .checked_div(risk_distance)
124        .and_then(|value| value.checked_div(instrument.multiplier().as_decimal()))
125        .ok_or_else(position_size_overflow)?;
126
127    if let Some(hard_limit) = hard_limit {
128        position_size = position_size.min(hard_limit);
129    }
130
131    let units_decimal = Decimal::from_usize(units).ok_or_else(position_size_overflow)?;
132    let mut position_size_batched = position_size
133        .checked_div(units_decimal)
134        .map(|value| value.max(Decimal::ZERO))
135        .ok_or_else(position_size_overflow)?;
136
137    if unit_batch_size > Decimal::ZERO {
138        position_size_batched = position_size_batched
139            .checked_div(unit_batch_size)
140            .map(|value| value.floor())
141            .and_then(|value| value.checked_mul(unit_batch_size))
142            .ok_or_else(position_size_overflow)?;
143    }
144
145    let final_size = instrument
146        .max_quantity()
147        .map_or(position_size_batched, |max_quantity| {
148            position_size_batched.min(max_quantity.as_decimal())
149        });
150
151    instrument
152        .try_make_qty_from_decimal(final_size, Some(true))
153        .map_err(|e| CorrectnessError::PredicateViolation {
154            message: e.to_string(),
155        })
156}
157
158fn calculate_risk_distance(entry: Price, stop_loss: Price) -> CorrectnessResult<Decimal> {
159    entry
160        .as_decimal()
161        .checked_sub(stop_loss.as_decimal())
162        .map(|value| value.abs())
163        .ok_or_else(position_size_overflow)
164}
165
166fn calculate_riskable_money(
167    equity: Decimal,
168    risk: Decimal,
169    commission_rate: Decimal,
170) -> CorrectnessResult<Decimal> {
171    if equity <= Decimal::ZERO {
172        return Ok(Decimal::ZERO);
173    }
174
175    let risk_money = equity
176        .checked_mul(risk)
177        .ok_or_else(position_size_overflow)?;
178    let commission = risk_money
179        .checked_mul(commission_rate)
180        .and_then(|value| value.checked_mul(Decimal::TWO))
181        .ok_or_else(position_size_overflow)?;
182
183    risk_money
184        .checked_sub(commission)
185        .ok_or_else(position_size_overflow)
186}
187
188fn position_size_overflow() -> CorrectnessError {
189    CorrectnessError::PredicateViolation {
190        message: OVERFLOW_MESSAGE.to_string(),
191    }
192}
193
194#[cfg(test)]
195mod tests {
196    use nautilus_model::{
197        identifiers::Symbol,
198        instruments::stubs::{
199            btcusd_bybit, crypto_option_btc_deribit, default_fx_ccy, futures_contract_es,
200        },
201        types::Currency,
202    };
203    use rstest::*;
204    use rust_decimal_macros::dec;
205
206    use super::*;
207
208    const EXCHANGE_RATE: Decimal = Decimal::ONE;
209
210    #[fixture]
211    fn instrument_gbpusd() -> InstrumentAny {
212        InstrumentAny::CurrencyPair(default_fx_ccy(Symbol::from_str_unchecked("GBP/USD"), None))
213    }
214
215    #[fixture]
216    fn instrument_futures_with_multiplier() -> InstrumentAny {
217        // A futures contract whose multiplier scales the per-unit dollar risk,
218        // as it does for position P&L (e.g. ES, CL, NG).
219        let mut instrument = futures_contract_es(None, None);
220        instrument.multiplier = Quantity::from(1000);
221        InstrumentAny::FuturesContract(instrument)
222    }
223
224    #[fixture]
225    fn instrument_gbpusd_without_max_quantity() -> InstrumentAny {
226        let mut instrument = default_fx_ccy(Symbol::from_str_unchecked("GBP/USD"), None);
227        instrument.max_quantity = None;
228        InstrumentAny::CurrencyPair(instrument)
229    }
230
231    #[rstest]
232    #[case::risk_budget("160 USD", None)]
233    #[case::hard_limit("260 USD", Some(dec!(1.6)))]
234    fn test_calculate_rounds_down_within_limits(
235        #[case] equity: &str,
236        #[case] hard_limit: Option<Decimal>,
237    ) {
238        let instrument = InstrumentAny::FuturesContract(futures_contract_es(None, None));
239
240        let quantity = calculate_fixed_risk_position_size(
241            &instrument,
242            Price::from("100.00"),
243            Price::from("99.00"),
244            Money::from(equity),
245            dec!(0.01),
246            Decimal::ZERO,
247            Decimal::ONE,
248            hard_limit,
249            Decimal::ZERO,
250            1,
251        )
252        .unwrap();
253
254        assert_eq!(quantity.as_decimal(), Decimal::ONE);
255    }
256
257    #[rstest]
258    fn test_calculate_rejects_size_below_one_increment() {
259        let instrument = InstrumentAny::FuturesContract(futures_contract_es(None, None));
260
261        let error = calculate_fixed_risk_position_size(
262            &instrument,
263            Price::from("100.00"),
264            Price::from("99.00"),
265            Money::from("60 USD"),
266            dec!(0.01),
267            Decimal::ZERO,
268            Decimal::ONE,
269            Some(dec!(0.6)),
270            Decimal::ZERO,
271            1,
272        )
273        .unwrap_err();
274
275        assert_eq!(error.to_string(), "value rounded to zero for quantity");
276    }
277
278    #[rstest]
279    #[case::long("20000.0", "19000.0", "1 BTC", dec!(1), dec!(3800))]
280    #[case::quote_rate("20000.0", "19000.0", "1 BTC", Decimal::ONE / dec!(19000), dec!(3800))]
281    #[case::entry_rate("20000.0", "19000.0", "1 BTC", Decimal::ONE / dec!(20000), dec!(3800))]
282    #[case::short("19000.0", "20000.0", "1 BTC", dec!(1), dec!(3800))]
283    #[case::account_currency("20000.0", "19000.0", "1000 USD", dec!(1), dec!(200))]
284    #[case::third_currency("20000.0", "19000.0", "1000 EUR", dec!(0.8), dec!(250))]
285    #[case::zero_rate("20000.0", "19000.0", "1 BTC", dec!(0), dec!(0))]
286    fn test_calculate_inverse_contract_size(
287        #[case] entry: &str,
288        #[case] stop_loss: &str,
289        #[case] equity: &str,
290        #[case] exchange_rate: Decimal,
291        #[case] expected: Decimal,
292        #[values(1_u32, 10_u32)] multiplier: u32,
293    ) {
294        let mut contract = btcusd_bybit();
295        contract.multiplier = Quantity::from_decimal_dp(Decimal::from(multiplier), 0).unwrap();
296        let instrument = InstrumentAny::CryptoPerpetual(contract);
297
298        let quantity = calculate_fixed_risk_position_size(
299            &instrument,
300            Price::from(entry),
301            Price::from(stop_loss),
302            Money::from(equity),
303            dec!(0.01),
304            Decimal::ZERO,
305            exchange_rate,
306            None,
307            Decimal::ONE,
308            1,
309        )
310        .unwrap();
311
312        assert_eq!(quantity.as_decimal(), expected / Decimal::from(multiplier));
313    }
314
315    #[rstest]
316    #[case::zero_entry("0.0", "19000.0", "invalid Decimal for 'entry' not positive, was 0.0")]
317    #[case::zero_stop(
318        "20000.0",
319        "0.0",
320        "invalid Decimal for 'stop_loss' not positive, was 0.0"
321    )]
322    #[case::negative_entry(
323        "-1.0",
324        "19000.0",
325        "invalid Decimal for 'entry' not positive, was -1.0"
326    )]
327    #[case::negative_stop(
328        "20000.0",
329        "-1.0",
330        "invalid Decimal for 'stop_loss' not positive, was -1.0"
331    )]
332    fn test_calculate_inverse_rejects_nonpositive_prices(
333        #[case] entry: &str,
334        #[case] stop_loss: &str,
335        #[case] expected: &str,
336    ) {
337        let instrument = InstrumentAny::CryptoPerpetual(btcusd_bybit());
338
339        let error = calculate_fixed_risk_position_size(
340            &instrument,
341            Price::from(entry),
342            Price::from(stop_loss),
343            Money::from("1 BTC"),
344            dec!(0.01),
345            Decimal::ZERO,
346            Decimal::ONE,
347            None,
348            Decimal::ONE,
349            1,
350        )
351        .unwrap_err();
352
353        assert_eq!(error.to_string(), expected);
354    }
355
356    #[rstest]
357    fn test_calculate_inverse_option_uses_premium_distance() {
358        let mut option =
359            crypto_option_btc_deribit(3, 1, Price::from("0.001"), Quantity::from("0.1"));
360        option.is_inverse = true;
361        option.quote_currency = Currency::BTC();
362        let instrument = InstrumentAny::CryptoOption(option);
363
364        let quantity = calculate_fixed_risk_position_size(
365            &instrument,
366            Price::from("0.100"),
367            Price::from("0.090"),
368            Money::from("1 BTC"),
369            dec!(0.01),
370            Decimal::ZERO,
371            Decimal::ONE,
372            None,
373            Decimal::ONE,
374            1,
375        )
376        .unwrap();
377
378        assert_eq!(quantity.as_decimal(), Decimal::ONE);
379    }
380
381    #[rstest]
382    fn test_calculate_with_zero_equity_returns_quantity_zero(instrument_gbpusd: InstrumentAny) {
383        let equity = Money::zero(instrument_gbpusd.quote_currency());
384        let entry = Price::new(1.00100, instrument_gbpusd.price_precision());
385        let stop_loss = Price::new(1.00000, instrument_gbpusd.price_precision());
386
387        let result = calculate_fixed_risk_position_size(
388            &instrument_gbpusd,
389            entry,
390            stop_loss,
391            equity,
392            Decimal::new(1, 3), // 0.001%
393            Decimal::ZERO,
394            EXCHANGE_RATE,
395            None,
396            Decimal::from(1000),
397            1,
398        )
399        .unwrap();
400
401        assert_eq!(result, Quantity::from("0.0"));
402    }
403
404    #[rstest]
405    fn test_calculate_with_zero_exchange_rate(instrument_gbpusd: InstrumentAny) {
406        let equity = Money::new(100_000.0, instrument_gbpusd.quote_currency());
407        let entry = Price::new(1.00100, instrument_gbpusd.price_precision());
408        let stop_loss = Price::new(1.00000, instrument_gbpusd.price_precision());
409
410        let result = calculate_fixed_risk_position_size(
411            &instrument_gbpusd,
412            entry,
413            stop_loss,
414            equity,
415            Decimal::new(1, 3), // 0.001%
416            Decimal::ZERO,
417            Decimal::ZERO, // Zero exchange rate
418            None,
419            Decimal::from(1000),
420            1,
421        )
422        .unwrap();
423
424        assert_eq!(result, Quantity::from("0.0"));
425    }
426
427    #[rstest]
428    fn test_calculate_with_zero_risk(instrument_gbpusd: InstrumentAny) {
429        let equity = Money::new(100_000.0, instrument_gbpusd.quote_currency());
430        let price = Price::new(1.00100, instrument_gbpusd.price_precision());
431
432        let result = calculate_fixed_risk_position_size(
433            &instrument_gbpusd,
434            price,
435            price, // Same price = no risk
436            equity,
437            Decimal::new(1, 3), // 0.001%
438            Decimal::ZERO,
439            EXCHANGE_RATE,
440            None,
441            Decimal::from(1000),
442            1,
443        )
444        .unwrap();
445
446        assert_eq!(result, Quantity::from("0.0"));
447    }
448
449    #[rstest]
450    fn test_calculate_single_unit_size(instrument_gbpusd: InstrumentAny) {
451        let equity = Money::new(1_000_000.0, instrument_gbpusd.quote_currency());
452        let entry = Price::new(1.00100, instrument_gbpusd.price_precision());
453        let stop_loss = Price::new(1.00000, instrument_gbpusd.price_precision());
454
455        let result = calculate_fixed_risk_position_size(
456            &instrument_gbpusd,
457            entry,
458            stop_loss,
459            equity,
460            Decimal::new(1, 3), // 0.001%
461            Decimal::ZERO,
462            EXCHANGE_RATE,
463            None,
464            Decimal::from(1000),
465            1,
466        )
467        .unwrap();
468
469        assert_eq!(result, Quantity::from("1000000.0"));
470    }
471
472    #[rstest]
473    fn test_calculate_accounts_for_instrument_multiplier(
474        instrument_futures_with_multiplier: InstrumentAny,
475    ) {
476        // Multiplier = 1000: a $1.00 stop risks $1,000/contract, so $10,000 of
477        // risk targets 10 contracts.
478        let equity = Money::new(1_000_000.0, Currency::USD());
479        let entry = Price::new(100.00, instrument_futures_with_multiplier.price_precision());
480        let stop_loss = Price::new(99.00, instrument_futures_with_multiplier.price_precision());
481
482        let result = calculate_fixed_risk_position_size(
483            &instrument_futures_with_multiplier,
484            entry,
485            stop_loss,
486            equity,
487            Decimal::new(1, 2), // 1%
488            Decimal::ZERO,
489            EXCHANGE_RATE,
490            None,
491            Decimal::from(1),
492            1,
493        )
494        .unwrap();
495
496        assert_eq!(result.as_decimal(), dec!(10));
497    }
498
499    #[rstest]
500    fn test_calculate_single_unit_with_exchange_rate(instrument_gbpusd: InstrumentAny) {
501        let equity = Money::new(1_000_000.0, Currency::USD());
502        let entry = Price::new(110.010, instrument_gbpusd.price_precision());
503        let stop_loss = Price::new(110.000, instrument_gbpusd.price_precision());
504
505        let result = calculate_fixed_risk_position_size(
506            &instrument_gbpusd,
507            entry,
508            stop_loss,
509            equity,
510            Decimal::new(1, 3), // 0.1%
511            Decimal::ZERO,
512            Decimal::from_f64(0.00909).unwrap(), // 1/110
513            None,
514            Decimal::from(1),
515            1,
516        )
517        .unwrap();
518
519        assert_eq!(result, Quantity::from("1000000.0"));
520    }
521
522    #[rstest]
523    fn test_calculate_single_unit_size_when_risk_too_high(instrument_gbpusd: InstrumentAny) {
524        let equity = Money::new(100_000.0, Currency::USD());
525        let entry = Price::new(3.00000, instrument_gbpusd.price_precision());
526        let stop_loss = Price::new(1.00000, instrument_gbpusd.price_precision());
527
528        let result = calculate_fixed_risk_position_size(
529            &instrument_gbpusd,
530            entry,
531            stop_loss,
532            equity,
533            Decimal::new(1, 2), // 1%
534            Decimal::ZERO,
535            EXCHANGE_RATE,
536            None,
537            Decimal::from(1000),
538            1,
539        )
540        .unwrap();
541
542        assert_eq!(result, Quantity::from("0.0"));
543    }
544
545    #[rstest]
546    #[case::single(1, dec!(500000))]
547    #[case::split(3, dec!(166000))]
548    fn test_impose_hard_limit(
549        #[case] units: usize,
550        #[case] expected: Decimal,
551        instrument_gbpusd: InstrumentAny,
552    ) {
553        let equity = Money::new(1_000_000.0, instrument_gbpusd.quote_currency());
554        let entry = Price::new(1.00010, instrument_gbpusd.price_precision());
555        let stop_loss = Price::new(1.00000, instrument_gbpusd.price_precision());
556
557        let result = calculate_fixed_risk_position_size(
558            &instrument_gbpusd,
559            entry,
560            stop_loss,
561            equity,
562            Decimal::new(1, 2), // 1%
563            Decimal::ZERO,
564            EXCHANGE_RATE,
565            Some(Decimal::from(500_000)),
566            Decimal::from(1000),
567            units,
568        )
569        .unwrap();
570
571        assert_eq!(result.as_decimal(), expected);
572    }
573
574    #[rstest]
575    fn test_calculate_without_max_quantity_leaves_size_uncapped(
576        instrument_gbpusd_without_max_quantity: InstrumentAny,
577    ) {
578        let equity = Money::from("1000000 USD");
579        let entry = Price::from("1.00010");
580        let stop_loss = Price::from("1.00000");
581
582        let result = calculate_fixed_risk_position_size(
583            &instrument_gbpusd_without_max_quantity,
584            entry,
585            stop_loss,
586            equity,
587            dec!(0.01),
588            Decimal::ZERO,
589            EXCHANGE_RATE,
590            None,
591            Decimal::from(1000),
592            1,
593        )
594        .unwrap();
595
596        assert_eq!(result.as_decimal(), dec!(100000000));
597    }
598
599    #[rstest]
600    fn test_calculate_multiple_unit_size(instrument_gbpusd: InstrumentAny) {
601        let equity = Money::new(1_000_000.0, instrument_gbpusd.quote_currency());
602        let entry = Price::new(1.00010, instrument_gbpusd.price_precision());
603        let stop_loss = Price::new(1.00000, instrument_gbpusd.price_precision());
604
605        let result = calculate_fixed_risk_position_size(
606            &instrument_gbpusd,
607            entry,
608            stop_loss,
609            equity,
610            Decimal::new(1, 3), // 0.1%
611            Decimal::ZERO,
612            EXCHANGE_RATE,
613            None,
614            Decimal::from(1000),
615            3, // 3 units
616        )
617        .unwrap();
618
619        assert_eq!(result, Quantity::from("1000000.0"));
620    }
621
622    #[rstest]
623    fn test_calculate_multiple_unit_size_larger_batches(instrument_gbpusd: InstrumentAny) {
624        let equity = Money::new(1_000_000.0, instrument_gbpusd.quote_currency());
625        let entry = Price::new(1.00087, instrument_gbpusd.price_precision());
626        let stop_loss = Price::new(1.00000, instrument_gbpusd.price_precision());
627
628        let result = calculate_fixed_risk_position_size(
629            &instrument_gbpusd,
630            entry,
631            stop_loss,
632            equity,
633            Decimal::new(1, 3), // 0.1%
634            Decimal::ZERO,
635            EXCHANGE_RATE,
636            None,
637            Decimal::from(25000),
638            4, // 4 units
639        )
640        .unwrap();
641
642        assert_eq!(result, Quantity::from("275000.0"));
643    }
644
645    #[rstest]
646    fn test_calculate_for_gbpusd_with_commission(instrument_gbpusd: InstrumentAny) {
647        let equity = Money::new(1_000_000.0, instrument_gbpusd.quote_currency());
648        let entry = Price::new(107.703, instrument_gbpusd.price_precision());
649        let stop_loss = Price::new(107.403, instrument_gbpusd.price_precision());
650
651        let result = calculate_fixed_risk_position_size(
652            &instrument_gbpusd,
653            entry,
654            stop_loss,
655            equity,
656            Decimal::new(1, 2),                    // 1%
657            Decimal::new(2, 4),                    // 0.0002
658            Decimal::from_f64(0.009_931).unwrap(), // 1/107.403
659            None,
660            Decimal::from(1000),
661            1,
662        )
663        .unwrap();
664
665        assert_eq!(result, Quantity::from("1000000.0"));
666    }
667
668    #[rstest]
669    #[case(
670        (
671            Decimal::ZERO,
672            Decimal::ZERO,
673            EXCHANGE_RATE,
674            None,
675            Decimal::ONE,
676            1,
677        ),
678        "invalid Decimal for 'risk' not positive, was 0"
679    )]
680    #[case(
681        (
682            dec!(0.001),
683            Decimal::ZERO,
684            dec!(-1),
685            None,
686            Decimal::ONE,
687            1,
688        ),
689        "exchange_rate must be non-negative"
690    )]
691    #[case(
692        (
693            dec!(0.001),
694            dec!(-0.001),
695            EXCHANGE_RATE,
696            None,
697            Decimal::ONE,
698            1,
699        ),
700        "commission_rate must be non-negative"
701    )]
702    #[case(
703        (
704            dec!(0.001),
705            Decimal::ZERO,
706            EXCHANGE_RATE,
707            Some(Decimal::ZERO),
708            Decimal::ONE,
709            1,
710        ),
711        "invalid Decimal for 'hard_limit' not positive, was 0"
712    )]
713    #[case(
714        (
715            dec!(0.001),
716            Decimal::ZERO,
717            EXCHANGE_RATE,
718            None,
719            dec!(-1),
720            1,
721        ),
722        "unit_batch_size must be non-negative"
723    )]
724    #[case(
725        (
726            dec!(0.001),
727            Decimal::ZERO,
728            EXCHANGE_RATE,
729            None,
730            Decimal::ONE,
731            0,
732        ),
733        "invalid usize for 'units' not positive, was 0"
734    )]
735    fn test_calculate_rejects_invalid_inputs(
736        #[case] inputs: (Decimal, Decimal, Decimal, Option<Decimal>, Decimal, usize),
737        #[case] expected: &str,
738        instrument_gbpusd: InstrumentAny,
739    ) {
740        let (risk, commission_rate, exchange_rate, hard_limit, unit_batch_size, units) = inputs;
741        let equity = Money::new(1_000_000.0, instrument_gbpusd.quote_currency());
742        let entry = Price::new(1.00100, instrument_gbpusd.price_precision());
743        let stop_loss = Price::new(1.00000, instrument_gbpusd.price_precision());
744
745        let error = calculate_fixed_risk_position_size(
746            &instrument_gbpusd,
747            entry,
748            stop_loss,
749            equity,
750            risk,
751            commission_rate,
752            exchange_rate,
753            hard_limit,
754            unit_batch_size,
755            units,
756        )
757        .unwrap_err();
758
759        assert_eq!(error.to_string(), expected);
760    }
761
762    #[rstest]
763    #[case::large_risk(dec!(1e23), Decimal::ZERO, EXCHANGE_RATE)]
764    #[case::large_commission_rate(dec!(0.001), dec!(1e26), EXCHANGE_RATE)]
765    #[case::tiny_exchange_rate(dec!(0.001), Decimal::ZERO, dec!(1e-28))]
766    fn test_calculate_returns_error_on_arithmetic_overflow(
767        #[case] risk: Decimal,
768        #[case] commission_rate: Decimal,
769        #[case] exchange_rate: Decimal,
770        instrument_gbpusd: InstrumentAny,
771    ) {
772        let equity = Money::new(1_000_000.0, instrument_gbpusd.quote_currency());
773        let entry = Price::new(1.00100, instrument_gbpusd.price_precision());
774        let stop_loss = Price::new(1.00000, instrument_gbpusd.price_precision());
775
776        let error = calculate_fixed_risk_position_size(
777            &instrument_gbpusd,
778            entry,
779            stop_loss,
780            equity,
781            risk,
782            commission_rate,
783            exchange_rate,
784            None,
785            Decimal::from(1000),
786            1,
787        )
788        .unwrap_err();
789
790        assert_eq!(
791            error,
792            CorrectnessError::PredicateViolation {
793                message: OVERFLOW_MESSAGE.to_string(),
794            }
795        );
796    }
797}