Skip to main content

nautilus_model/instruments/
mod.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//! Instrument definitions for the trading domain model.
17
18pub mod any;
19pub mod betting;
20pub mod binary_option;
21pub mod cfd;
22pub mod commodity;
23pub mod crypto_future;
24pub mod crypto_futures_spread;
25pub mod crypto_option;
26pub mod crypto_option_spread;
27pub mod crypto_perpetual;
28pub mod currency_pair;
29pub mod equity;
30pub mod futures_contract;
31pub mod futures_spread;
32pub mod index_instrument;
33pub mod option_contract;
34pub mod option_spread;
35pub mod perpetual_contract;
36pub mod synthetic;
37pub mod tick_scheme;
38pub mod tokenized_asset;
39
40#[cfg(any(test, feature = "test-support"))]
41pub mod stubs;
42
43use std::{any::Any, fmt::Display, str::FromStr};
44
45use enum_dispatch::enum_dispatch;
46use nautilus_core::{
47    Params, UnixNanos,
48    correctness::{
49        CorrectnessError, CorrectnessResult, check_equal_u8, check_positive_decimal,
50        check_predicate_true,
51    },
52    string::parsing::min_increment_precision_from_str,
53};
54use rust_decimal::{Decimal, RoundingStrategy};
55use rust_decimal_macros::dec;
56use serde::{Deserialize, Serialize};
57use ustr::Ustr;
58
59pub use crate::instruments::{
60    any::InstrumentAny,
61    betting::BettingInstrument,
62    binary_option::BinaryOption,
63    cfd::Cfd,
64    commodity::Commodity,
65    crypto_future::CryptoFuture,
66    crypto_futures_spread::CryptoFuturesSpread,
67    crypto_option::CryptoOption,
68    crypto_option_spread::CryptoOptionSpread,
69    crypto_perpetual::CryptoPerpetual,
70    currency_pair::CurrencyPair,
71    equity::Equity,
72    futures_contract::FuturesContract,
73    futures_spread::FuturesSpread,
74    index_instrument::IndexInstrument,
75    option_contract::OptionContract,
76    option_spread::OptionSpread,
77    perpetual_contract::PerpetualContract,
78    synthetic::{SyntheticInstrument, SyntheticInstrumentError},
79    tick_scheme::{
80        FixedTickScheme, TickScheme, TickSchemeError, TickSchemeRule, TieredTickScheme,
81        get_tick_scheme, list_tick_schemes, register_tick_scheme, tick_scheme_rule_from_name,
82    },
83    tokenized_asset::TokenizedAsset,
84};
85/// Instrument family selector used by streaming persistence filters.
86#[derive(
87    Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, strum::Display, strum::EnumIter,
88)]
89pub enum NautilusInstrumentType {
90    BettingInstrument,
91    BinaryOption,
92    Cfd,
93    Commodity,
94    CryptoFuture,
95    CryptoFuturesSpread,
96    CryptoOption,
97    CryptoOptionSpread,
98    CryptoPerpetual,
99    CurrencyPair,
100    Equity,
101    FuturesContract,
102    FuturesSpread,
103    IndexInstrument,
104    OptionContract,
105    OptionSpread,
106    PerpetualContract,
107    TokenizedAsset,
108}
109
110impl FromStr for NautilusInstrumentType {
111    type Err = anyhow::Error;
112
113    fn from_str(s: &str) -> anyhow::Result<Self> {
114        match s {
115            "BettingInstrument" | "Betting" | "betting_instrument" => Ok(Self::BettingInstrument),
116            "BinaryOption" | "binary_option" => Ok(Self::BinaryOption),
117            "Cfd" | "cfd" => Ok(Self::Cfd),
118            "Commodity" | "commodity" => Ok(Self::Commodity),
119            "CryptoFuture" | "crypto_future" => Ok(Self::CryptoFuture),
120            "CryptoFuturesSpread" | "crypto_futures_spread" => Ok(Self::CryptoFuturesSpread),
121            "CryptoOption" | "crypto_option" => Ok(Self::CryptoOption),
122            "CryptoOptionSpread" | "crypto_option_spread" => Ok(Self::CryptoOptionSpread),
123            "CryptoPerpetual" | "crypto_perpetual" => Ok(Self::CryptoPerpetual),
124            "CurrencyPair" | "currency_pair" => Ok(Self::CurrencyPair),
125            "Equity" | "equity" => Ok(Self::Equity),
126            "FuturesContract" | "futures_contract" => Ok(Self::FuturesContract),
127            "FuturesSpread" | "futures_spread" => Ok(Self::FuturesSpread),
128            "IndexInstrument" | "index_instrument" => Ok(Self::IndexInstrument),
129            "OptionContract" | "option_contract" => Ok(Self::OptionContract),
130            "OptionSpread" | "option_spread" => Ok(Self::OptionSpread),
131            "PerpetualContract" | "perpetual_contract" => Ok(Self::PerpetualContract),
132            "TokenizedAsset" | "tokenized_asset" => Ok(Self::TokenizedAsset),
133            _ => anyhow::bail!("Invalid `NautilusInstrumentType`: '{s}'"),
134        }
135    }
136}
137use crate::{
138    enums::{AssetClass, InstrumentClass, OptionKind},
139    identifiers::{InstrumentId, Symbol, Venue},
140    types::{
141        Currency, ERROR_PRICE, Money, Price, Quantity,
142        fixed::{FIXED_PRECISION, raw_scales_match},
143        money::check_positive_money,
144        price::{PriceRaw, check_positive_price},
145        quantity::{QuantityRaw, check_positive_quantity},
146    },
147};
148
149#[expect(clippy::missing_errors_doc, clippy::too_many_arguments)]
150pub fn validate_instrument_common(
151    price_precision: u8,
152    size_precision: u8,
153    size_increment: Quantity,
154    multiplier: Quantity,
155    margin_init: Decimal,
156    margin_maint: Decimal,
157    price_increment: Option<Price>,
158    lot_size: Option<Quantity>,
159    max_quantity: Option<Quantity>,
160    min_quantity: Option<Quantity>,
161    max_notional: Option<Money>,
162    min_notional: Option<Money>,
163    max_price: Option<Price>,
164    min_price: Option<Price>,
165) -> CorrectnessResult<()> {
166    check_positive_quantity(size_increment, "size_increment")?;
167    check_equal_u8(
168        size_increment.precision,
169        size_precision,
170        "size_increment.precision",
171        "size_precision",
172    )?;
173    check_positive_quantity(multiplier, "multiplier")?;
174    check_positive_decimal(margin_init, "margin_init")?;
175    check_positive_decimal(margin_maint, "margin_maint")?;
176
177    if let Some(price_increment) = price_increment {
178        check_positive_price(price_increment, "price_increment")?;
179        check_equal_u8(
180            price_increment.precision,
181            price_precision,
182            "price_increment.precision",
183            "price_precision",
184        )?;
185    }
186
187    if let Some(lot) = lot_size {
188        check_positive_quantity(lot, "lot_size")?;
189    }
190
191    if let Some(quantity) = max_quantity {
192        check_positive_quantity(quantity, "max_quantity")?;
193    }
194
195    if let Some(quantity) = min_quantity {
196        check_positive_quantity(quantity, "min_quantity")?;
197    }
198
199    if let Some(notional) = max_notional {
200        check_positive_money(notional, "max_notional")?;
201    }
202
203    if let Some(notional) = min_notional {
204        check_positive_money(notional, "min_notional")?;
205    }
206
207    if let Some(max_price) = max_price {
208        check_positive_price(max_price, "max_price")?;
209        check_equal_u8(
210            max_price.precision,
211            price_precision,
212            "max_price.precision",
213            "price_precision",
214        )?;
215    }
216
217    if let Some(min_price) = min_price {
218        check_positive_price(min_price, "min_price")?;
219        check_equal_u8(
220            min_price.precision,
221            price_precision,
222            "min_price.precision",
223            "price_precision",
224        )?;
225    }
226
227    if let (Some(min), Some(max)) = (min_price, max_price) {
228        check_predicate_true(min <= max, "min_price exceeds max_price")?;
229    }
230
231    Ok(())
232}
233
234fn currencies_equivalent_for_quanto(left: Currency, right: Currency) -> bool {
235    if left == right {
236        return true;
237    }
238
239    is_usd_equivalent_currency(left) && is_usd_equivalent_currency(right)
240}
241
242fn is_usd_equivalent_currency(currency: Currency) -> bool {
243    matches!(
244        currency.code.as_str(),
245        "BUSD" | "FDUSD" | "pUSD" | "TUSD" | "USD" | "USDC" | "USDC.e" | "USDP" | "USDT"
246    )
247}
248
249#[enum_dispatch]
250pub trait Instrument: Any + Send {
251    fn tick_scheme(&self) -> Option<Ustr> {
252        None
253    }
254
255    fn tick_scheme_rule(&self) -> Option<&dyn TickSchemeRule> {
256        self.tick_scheme()
257            .and_then(|scheme| tick_scheme_rule_from_name(scheme.as_str()))
258    }
259
260    fn into_any(self) -> InstrumentAny
261    where
262        Self: Sized,
263        InstrumentAny: From<Self>,
264    {
265        self.into()
266    }
267
268    fn id(&self) -> InstrumentId;
269    fn symbol(&self) -> Symbol {
270        self.id().symbol
271    }
272    fn venue(&self) -> Venue {
273        self.id().venue
274    }
275
276    fn raw_symbol(&self) -> Symbol;
277    fn asset_class(&self) -> AssetClass;
278    fn instrument_class(&self) -> InstrumentClass;
279
280    fn underlying(&self) -> Option<Ustr>;
281    fn base_currency(&self) -> Option<Currency>;
282    fn quote_currency(&self) -> Currency;
283    fn settlement_currency(&self) -> Currency;
284
285    /// # Panics
286    ///
287    /// Panics if the instrument is inverse and does not have a base currency.
288    fn cost_currency(&self) -> Currency {
289        if self.is_inverse() {
290            self.base_currency()
291                .expect("inverse instrument without base_currency")
292        } else if self.is_quanto() {
293            self.settlement_currency()
294        } else {
295            self.quote_currency()
296        }
297    }
298
299    fn isin(&self) -> Option<Ustr>;
300    fn option_kind(&self) -> Option<OptionKind>;
301    fn exchange(&self) -> Option<Ustr>;
302    fn strike_price(&self) -> Option<Price>;
303    fn strategy_type(&self) -> Option<Ustr> {
304        None
305    }
306
307    fn activation_ns(&self) -> Option<UnixNanos>;
308    fn expiration_ns(&self) -> Option<UnixNanos>;
309    fn has_expiration(&self) -> bool {
310        self.instrument_class().has_expiration()
311    }
312
313    fn allows_negative_price(&self) -> bool {
314        // Inverse valuation divides by price, so it requires a positive price
315        let instrument_class = self.instrument_class();
316        instrument_class.allows_negative_price()
317            && !instrument_class.divides_notional_by_price(self.is_inverse())
318    }
319
320    fn is_inverse(&self) -> bool;
321    fn is_quanto(&self) -> bool {
322        self.base_currency().is_some_and(|base_currency| {
323            self.settlement_currency() != base_currency
324                && !currencies_equivalent_for_quanto(
325                    self.settlement_currency(),
326                    self.quote_currency(),
327                )
328        })
329    }
330
331    fn price_precision(&self) -> u8;
332    fn size_precision(&self) -> u8;
333    fn price_increment(&self) -> Price;
334    fn size_increment(&self) -> Quantity;
335
336    fn multiplier(&self) -> Quantity;
337    fn lot_size(&self) -> Option<Quantity>;
338    fn max_quantity(&self) -> Option<Quantity>;
339    fn min_quantity(&self) -> Option<Quantity>;
340    fn max_notional(&self) -> Option<Money>;
341    fn min_notional(&self) -> Option<Money>;
342    fn max_price(&self) -> Option<Price>;
343    fn min_price(&self) -> Option<Price>;
344
345    fn margin_init(&self) -> Decimal {
346        dec!(0)
347    }
348    fn margin_maint(&self) -> Decimal {
349        dec!(0)
350    }
351
352    /// Returns additional instrument metadata, when provided.
353    fn info(&self) -> Option<&Params>;
354
355    fn ts_event(&self) -> UnixNanos;
356    fn ts_init(&self) -> UnixNanos;
357
358    fn min_price_increment_precision(&self) -> u8 {
359        // TODO: Optimize by storing min price increment precision (without trailing zeros)
360        min_increment_precision_from_str(&self.price_increment().to_string())
361    }
362
363    fn min_size_increment_precision(&self) -> u8 {
364        // TODO: Optimize by storing min size increment precision (without trailing zeros)
365        min_increment_precision_from_str(&self.size_increment().to_string())
366    }
367
368    /// # Errors
369    ///
370    /// Returns an error if the value cannot be converted to a `Price`.
371    #[inline(always)]
372    fn try_make_price_from_decimal(&self, value: Decimal) -> anyhow::Result<Price> {
373        let precision = u32::from(self.min_price_increment_precision());
374        let rounded_decimal =
375            value.round_dp_with_strategy(precision, RoundingStrategy::MidpointNearestEven);
376        Price::from_decimal_dp(rounded_decimal, self.price_precision()).map_err(Into::into)
377    }
378
379    /// # Panics
380    ///
381    /// Panics if the value cannot be converted to a `Price` (see `try_make_price_from_decimal`).
382    fn make_price_from_decimal(&self, value: Decimal) -> Price {
383        self.try_make_price_from_decimal(value).unwrap()
384    }
385
386    /// # Errors
387    ///
388    /// Returns an error if the value is not finite, not representable as a `Decimal`, or cannot
389    /// be converted to a `Price`.
390    #[inline(always)]
391    fn try_make_price(&self, value: f64) -> anyhow::Result<Price> {
392        let dec_value = Decimal::from_str(&value.to_string())
393            .map_err(|_| anyhow::anyhow!("invalid `value` for make_price, was {value}"))?;
394        self.try_make_price_from_decimal(dec_value)
395    }
396
397    /// # Panics
398    ///
399    /// Panics if the value cannot be converted to a `Price` (see `try_make_price`).
400    fn make_price(&self, value: f64) -> Price {
401        self.try_make_price(value).unwrap()
402    }
403
404    /// Returns `price` rebuilt with the instrument precision when it is on the price grid.
405    ///
406    /// # Errors
407    ///
408    /// Returns an error if `price` is a sentinel value or would require rounding.
409    #[inline(always)]
410    fn try_normalize_price(&self, price: Price) -> CorrectnessResult<Price> {
411        if price.precision == ERROR_PRICE.precision {
412            return Err(CorrectnessError::InvalidValue {
413                param: "price".to_string(),
414                value: "ERROR_PRICE".to_string(),
415                type_name: "`Price`",
416            });
417        }
418
419        if price.is_error() {
420            return Err(CorrectnessError::InvalidValue {
421                param: "price".to_string(),
422                value: "PRICE_ERROR".to_string(),
423                type_name: "`Price`",
424            });
425        }
426
427        if price.is_undefined() {
428            return Err(CorrectnessError::InvalidValue {
429                param: "price".to_string(),
430                value: "PRICE_UNDEF".to_string(),
431                type_name: "`Price`",
432            });
433        }
434
435        let precision = self.price_precision();
436        let increment = self.price_increment();
437
438        if !raw_scales_match(price.precision, precision) {
439            return Err(CorrectnessError::PredicateViolation {
440                message: format!(
441                    "`price` raw scale does not match instrument price precision, price precision was {}, instrument price precision was {precision}",
442                    price.precision
443                ),
444            });
445        }
446
447        if !raw_scales_match(price.precision, increment.precision) {
448            return Err(CorrectnessError::PredicateViolation {
449                message: format!(
450                    "`price` raw scale does not match price increment precision, price precision was {}, price increment precision was {}",
451                    price.precision, increment.precision
452                ),
453            });
454        }
455
456        let precision_diff = FIXED_PRECISION.saturating_sub(precision);
457        let scale = PriceRaw::pow(10, u32::from(precision_diff));
458
459        if price.raw() % scale != 0 {
460            return Err(CorrectnessError::PredicateViolation {
461                message: format!(
462                    "`price` requires rounding to instrument price precision {precision}, was {price}"
463                ),
464            });
465        }
466
467        let increment_raw = increment.raw().abs();
468        if increment_raw != 0 && price.raw() % increment_raw != 0 {
469            return Err(CorrectnessError::PredicateViolation {
470                message: format!(
471                    "`price` is not aligned to price increment {increment}, was {price}"
472                ),
473            });
474        }
475
476        Price::from_raw_checked(price.raw(), precision)
477    }
478
479    /// # Errors
480    ///
481    /// Returns an error if the value rounds to zero or cannot be converted to a `Quantity`.
482    #[inline(always)]
483    fn try_make_qty_from_decimal(
484        &self,
485        value: Decimal,
486        round_down: Option<bool>,
487    ) -> anyhow::Result<Quantity> {
488        let precision = u32::from(self.min_size_increment_precision());
489
490        let strategy = if round_down.unwrap_or(false) {
491            RoundingStrategy::ToZero
492        } else {
493            RoundingStrategy::MidpointNearestEven
494        };
495
496        let rounded = value.round_dp_with_strategy(precision, strategy);
497        if value > Decimal::ZERO && rounded.is_zero() {
498            anyhow::bail!("value rounded to zero for quantity");
499        }
500
501        Quantity::from_decimal_dp(rounded, self.size_precision()).map_err(Into::into)
502    }
503
504    /// # Panics
505    ///
506    /// Panics if the value cannot be converted to a `Quantity` (see `try_make_qty_from_decimal`).
507    fn make_qty_from_decimal(&self, value: Decimal, round_down: Option<bool>) -> Quantity {
508        self.try_make_qty_from_decimal(value, round_down).unwrap()
509    }
510
511    /// # Errors
512    ///
513    /// Returns an error if the value is not finite, not representable as a `Decimal`, rounds to
514    /// zero, or cannot be converted to a `Quantity`.
515    #[inline(always)]
516    fn try_make_qty(&self, value: f64, round_down: Option<bool>) -> anyhow::Result<Quantity> {
517        let dec_value = Decimal::from_str(&value.to_string())
518            .map_err(|_| anyhow::anyhow!("invalid `value` for make_qty, was {value}"))?;
519        self.try_make_qty_from_decimal(dec_value, round_down)
520    }
521
522    /// # Panics
523    ///
524    /// Panics if the value cannot be converted to a `Quantity` (see `try_make_qty`).
525    fn make_qty(&self, value: f64, round_down: Option<bool>) -> Quantity {
526        self.try_make_qty(value, round_down).unwrap()
527    }
528
529    /// Returns `quantity` rebuilt with the instrument precision when it is on the size grid.
530    ///
531    /// # Errors
532    ///
533    /// Returns an error if `quantity` is undefined or would require rounding.
534    #[inline(always)]
535    fn try_normalize_qty(&self, quantity: Quantity) -> CorrectnessResult<Quantity> {
536        if quantity.is_undefined() {
537            return Err(CorrectnessError::InvalidValue {
538                param: "quantity".to_string(),
539                value: "QUANTITY_UNDEF".to_string(),
540                type_name: "`Quantity`",
541            });
542        }
543
544        let precision = self.size_precision();
545        let increment = self.size_increment();
546
547        if !raw_scales_match(quantity.precision, precision) {
548            return Err(CorrectnessError::PredicateViolation {
549                message: format!(
550                    "`quantity` raw scale does not match instrument size precision, quantity precision was {}, instrument size precision was {precision}",
551                    quantity.precision
552                ),
553            });
554        }
555
556        if !raw_scales_match(quantity.precision, increment.precision) {
557            return Err(CorrectnessError::PredicateViolation {
558                message: format!(
559                    "`quantity` raw scale does not match size increment precision, quantity precision was {}, size increment precision was {}",
560                    quantity.precision, increment.precision
561                ),
562            });
563        }
564
565        let precision_diff = FIXED_PRECISION.saturating_sub(precision);
566        let scale = QuantityRaw::pow(10, u32::from(precision_diff));
567
568        if !quantity.raw().is_multiple_of(scale) {
569            return Err(CorrectnessError::PredicateViolation {
570                message: format!(
571                    "`quantity` requires rounding to instrument size precision {precision}, was {quantity}"
572                ),
573            });
574        }
575
576        if increment.non_zero() && !quantity.raw().is_multiple_of(increment.raw()) {
577            return Err(CorrectnessError::PredicateViolation {
578                message: format!(
579                    "`quantity` is not aligned to size increment {increment}, was {quantity}"
580                ),
581            });
582        }
583
584        Quantity::from_raw_checked(quantity.raw(), precision)
585    }
586
587    /// # Errors
588    ///
589    /// Returns an error if `last_price` is zero, or if the value cannot be converted to a
590    /// `Quantity`.
591    fn try_calculate_base_quantity(
592        &self,
593        quantity: Quantity,
594        last_price: Price,
595    ) -> anyhow::Result<Quantity> {
596        let last_px = last_price.as_decimal();
597        if last_px.is_zero() {
598            anyhow::bail!("`last_price` was zero when calculating base quantity");
599        }
600        let precision = u32::from(self.min_size_increment_precision());
601        let value = quantity
602            .as_decimal()
603            .checked_div(last_px)
604            .ok_or_else(|| anyhow::anyhow!("Base quantity exceeds Decimal bounds"))?
605            .round_dp_with_strategy(precision, RoundingStrategy::MidpointNearestEven);
606        Quantity::from_decimal_dp(value, self.size_precision()).map_err(Into::into)
607    }
608
609    /// # Panics
610    ///
611    /// Panics if `last_price` is zero, or if the value cannot be converted to a `Quantity`
612    /// (see `try_calculate_base_quantity`).
613    fn calculate_base_quantity(&self, quantity: Quantity, last_price: Price) -> Quantity {
614        self.try_calculate_base_quantity(quantity, last_price)
615            .unwrap()
616    }
617
618    /// Calculates the notional value for the given quantity and price.
619    ///
620    /// Inverse instruments value notional in the base currency as `quantity * multiplier / price`,
621    /// or as `quantity` in the quote currency when `use_quote_for_inverse` is set. Premium-based
622    /// inverse instruments, such as coin-settled options, quote the premium in the base currency,
623    /// so their base notional is `quantity * multiplier * price`.
624    ///
625    /// # Errors
626    ///
627    /// Returns an error if base-denominated inverse valuation lacks a base currency, if a
628    /// non-premium inverse instrument receives a nonpositive price, or if the result cannot be
629    /// represented as [`Money`].
630    #[inline(always)]
631    fn try_calculate_notional_value(
632        &self,
633        quantity: Quantity,
634        price: Price,
635        use_quote_for_inverse: Option<bool>,
636    ) -> anyhow::Result<Money> {
637        let use_quote_inverse = use_quote_for_inverse.unwrap_or(false);
638        let currency = if self.is_inverse() {
639            if use_quote_inverse {
640                self.quote_currency()
641            } else {
642                self.base_currency().ok_or_else(|| {
643                    anyhow::anyhow!("inverse instrument {} has no base currency", self.id())
644                })?
645            }
646        } else if self.is_quanto() {
647            self.settlement_currency()
648        } else {
649            self.quote_currency()
650        };
651
652        try_notional_value(
653            quantity,
654            price,
655            self.multiplier(),
656            self.instrument_class(),
657            self.is_inverse(),
658            use_quote_inverse,
659            currency,
660        )
661    }
662
663    /// # Panics
664    ///
665    /// Panics if [`Instrument::try_calculate_notional_value`] returns an error.
666    #[inline(always)]
667    fn calculate_notional_value(
668        &self,
669        quantity: Quantity,
670        price: Price,
671        use_quote_for_inverse: Option<bool>,
672    ) -> Money {
673        self.try_calculate_notional_value(quantity, price, use_quote_for_inverse)
674            .expect("invalid notional value")
675    }
676
677    #[inline(always)]
678    fn next_bid_price(&self, value: f64, n: i32) -> Option<Price> {
679        if n < 0 {
680            return None;
681        }
682
683        let price = if let Some(scheme) = self.tick_scheme_rule() {
684            scheme.next_bid_price(value, n, self.price_precision())?
685        } else {
686            let value = Decimal::from_str(&value.to_string()).ok()?;
687            let increment = self.price_increment().as_decimal();
688            if increment.is_zero() {
689                return None;
690            }
691            let base = (value / increment).floor() * increment;
692            let result = base - Decimal::from(n) * increment;
693            Price::from_decimal_dp(result, self.price_precision()).ok()?
694        };
695
696        if self.min_price().is_some_and(|min| price < min)
697            || self.max_price().is_some_and(|max| price > max)
698        {
699            return None;
700        }
701
702        Some(price)
703    }
704
705    #[inline(always)]
706    fn next_ask_price(&self, value: f64, n: i32) -> Option<Price> {
707        if n < 0 {
708            return None;
709        }
710
711        let price = if let Some(scheme) = self.tick_scheme_rule() {
712            scheme.next_ask_price(value, n, self.price_precision())?
713        } else {
714            let value = Decimal::from_str(&value.to_string()).ok()?;
715            let increment = self.price_increment().as_decimal();
716            if increment.is_zero() {
717                return None;
718            }
719            let base = (value / increment).ceil() * increment;
720            let result = base + Decimal::from(n) * increment;
721            Price::from_decimal_dp(result, self.price_precision()).ok()?
722        };
723
724        if self.min_price().is_some_and(|min| price < min)
725            || self.max_price().is_some_and(|max| price > max)
726        {
727            return None;
728        }
729
730        Some(price)
731    }
732
733    #[inline]
734    fn next_bid_prices(&self, value: f64, n: usize) -> Vec<Price> {
735        let mut prices = Vec::with_capacity(n);
736
737        for i in 0..n {
738            let Ok(i) = i32::try_from(i) else { break };
739            if let Some(price) = self.next_bid_price(value, i) {
740                prices.push(price);
741            } else {
742                break;
743            }
744        }
745
746        prices
747    }
748
749    #[inline]
750    fn next_ask_prices(&self, value: f64, n: usize) -> Vec<Price> {
751        let mut prices = Vec::with_capacity(n);
752
753        for i in 0..n {
754            let Ok(i) = i32::try_from(i) else { break };
755            if let Some(price) = self.next_ask_price(value, i) {
756                prices.push(price);
757            } else {
758                break;
759            }
760        }
761
762        prices
763    }
764}
765
766pub(crate) fn try_notional_value(
767    quantity: Quantity,
768    price: Price,
769    multiplier: Quantity,
770    instrument_class: InstrumentClass,
771    is_inverse: bool,
772    use_quote_for_inverse: bool,
773    currency: Currency,
774) -> anyhow::Result<Money> {
775    let amount = if is_inverse && use_quote_for_inverse {
776        quantity.as_decimal()
777    } else if instrument_class.divides_notional_by_price(is_inverse) {
778        anyhow::ensure!(
779            price.is_positive(),
780            "price must be positive for inverse notional valuation"
781        );
782        quantity
783            .as_decimal()
784            .checked_mul(multiplier.as_decimal())
785            .and_then(|value| value.checked_div(price.as_decimal()))
786            .ok_or_else(|| anyhow::anyhow!("inverse notional calculation overflow"))?
787    } else {
788        quantity
789            .as_decimal()
790            .checked_mul(multiplier.as_decimal())
791            .and_then(|value| value.checked_mul(price.as_decimal()))
792            .ok_or_else(|| anyhow::anyhow!("notional calculation overflow"))?
793    };
794
795    Money::from_decimal(amount, currency).map_err(Into::into)
796}
797
798impl Display for CurrencyPair {
799    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
800        write!(
801            f,
802            "{}(instrument_id='{}', tick_scheme='{}', price_precision={}, size_precision={}, \
803price_increment={}, size_increment={}, multiplier={}, margin_init={}, margin_maint={})",
804            stringify!(CurrencyPair),
805            self.id,
806            self.tick_scheme()
807                .map_or_else(|| "None".into(), |s| s.to_string()),
808            self.price_precision(),
809            self.size_precision(),
810            self.price_increment(),
811            self.size_increment(),
812            self.multiplier(),
813            self.margin_init(),
814            self.margin_maint(),
815        )
816    }
817}
818
819#[cfg(test)]
820mod tests {
821    use nautilus_core::correctness::{CorrectnessResultExt, FAILED};
822    use proptest::prelude::*;
823    use rstest::rstest;
824    use rust_decimal::{Decimal, prelude::*};
825
826    use super::*;
827    use crate::{
828        instruments::stubs::*,
829        types::{ERROR_PRICE, Money, PRICE_ERROR, PRICE_UNDEF, QUANTITY_UNDEF},
830    };
831
832    #[cfg(feature = "defi")]
833    #[rstest]
834    fn test_try_normalize_price_rejects_wei_scale_against_standard_instrument(
835        audusd_sim: CurrencyPair,
836    ) {
837        let wei_price =
838            Price::from_wei(alloy_primitives::U256::from(1_000_000_000_000_000_000_u64));
839
840        let error = audusd_sim.try_normalize_price(wei_price).unwrap_err();
841
842        assert_eq!(
843            error.to_string(),
844            format!(
845                "`price` raw scale does not match instrument price precision, price precision was 18, instrument price precision was {}",
846                audusd_sim.price_precision()
847            )
848        );
849    }
850
851    #[cfg(feature = "defi")]
852    #[rstest]
853    fn test_try_normalize_qty_rejects_wei_scale_against_standard_instrument(
854        audusd_sim: CurrencyPair,
855    ) {
856        let wei_qty =
857            Quantity::from_wei(alloy_primitives::U256::from(1_000_000_000_000_000_000_u64));
858
859        let error = audusd_sim.try_normalize_qty(wei_qty).unwrap_err();
860
861        assert_eq!(
862            error.to_string(),
863            format!(
864                "`quantity` raw scale does not match instrument size precision, quantity precision was 18, instrument size precision was {}",
865                audusd_sim.size_precision()
866            )
867        );
868    }
869
870    pub(super) fn default_price_increment(precision: u8) -> Price {
871        let step = 10f64.powi(-i32::from(precision));
872        Price::new(step, precision)
873    }
874
875    #[rstest]
876    fn default_increment_precision() {
877        let inc = default_price_increment(2);
878        assert_eq!(inc, Price::new(0.01, 2));
879    }
880
881    #[rstest]
882    #[case(Price::new(0.5, 1), 1)] // 0.5 -> precision 1
883    #[case(Price::new(0.50, 2), 1)] // 0.50 -> precision 1 (trailing zero ignored)
884    #[case(Price::new(0.500, 3), 1)] // 0.500 -> precision 1
885    #[case(Price::new(0.01, 2), 2)] // 0.01 -> precision 2
886    #[case(Price::new(0.010, 3), 2)] // 0.010 -> precision 2
887    #[case(Price::new(0.25, 2), 2)] // 0.25 -> precision 2
888    #[case(Price::new(1.0, 1), 1)] // 1.0 -> precision 1
889    #[case(Price::new(1.00, 2), 2)] // 1.00 -> precision 2 (all zeros)
890    #[case(Price::new(100.0, 0), 0)] // 100 -> precision 0
891    #[case(Price::new(0.001, 3), 3)] // 0.001 -> precision 3
892    fn test_min_increment_precision(#[case] price: Price, #[case] expected: u8) {
893        assert_eq!(
894            nautilus_core::string::parsing::min_increment_precision_from_str(&price.to_string()),
895            expected
896        );
897    }
898
899    #[rstest]
900    #[case(1.5, "1.500000")]
901    #[case(2.5, "2.500000")]
902    #[case(1.234_567_8, "1.234568")]
903    #[case(0.000_123, "0.000123")]
904    #[case(99_999.999_999, "99999.999999")]
905    fn make_qty_rounding(
906        currency_pair_btcusdt: CurrencyPair,
907        #[case] input: f64,
908        #[case] expected: &str,
909    ) {
910        assert_eq!(
911            currency_pair_btcusdt.make_qty(input, None).to_string(),
912            expected
913        );
914    }
915
916    #[rstest]
917    #[case(1.234_567_8, "1.234567")]
918    #[case(1.999_999_9, "1.999999")]
919    #[case(0.000_123_45, "0.000123")]
920    #[case(10.999_999_9, "10.999999")]
921    fn make_qty_round_down(
922        currency_pair_btcusdt: CurrencyPair,
923        #[case] input: f64,
924        #[case] expected: &str,
925    ) {
926        assert_eq!(
927            currency_pair_btcusdt
928                .make_qty(input, Some(true))
929                .to_string(),
930            expected
931        );
932    }
933
934    #[rstest]
935    #[case(1.234_567_8, "1.23457")]
936    #[case(2.345_678_1, "2.34568")]
937    #[case(0.00001, "0.00001")]
938    fn make_qty_precision(
939        currency_pair_ethusdt: CurrencyPair,
940        #[case] input: f64,
941        #[case] expected: &str,
942    ) {
943        assert_eq!(
944            currency_pair_ethusdt.make_qty(input, None).to_string(),
945            expected
946        );
947    }
948
949    #[rstest]
950    #[case(1.234_567_5, "1.234568")]
951    #[case(1.234_566_5, "1.234566")]
952    fn make_qty_half_even(
953        currency_pair_btcusdt: CurrencyPair,
954        #[case] input: f64,
955        #[case] expected: &str,
956    ) {
957        assert_eq!(
958            currency_pair_btcusdt.make_qty(input, None).to_string(),
959            expected
960        );
961    }
962
963    #[rstest]
964    #[case(dec!(1.5), None, dec!(1.5))]
965    #[case(dec!(1.2345678), None, dec!(1.234568))]
966    #[case(dec!(1.2345678), Some(true), dec!(1.234567))]
967    #[case(dec!(1.9999999), Some(true), dec!(1.999999))]
968    #[case(dec!(0.000123), None, dec!(0.000123))]
969    fn make_qty_from_decimal_matches_f64_path(
970        currency_pair_btcusdt: CurrencyPair,
971        #[case] value: Decimal,
972        #[case] round_down: Option<bool>,
973        #[case] expected: Decimal,
974    ) {
975        let from_decimal = currency_pair_btcusdt.make_qty_from_decimal(value, round_down);
976        let from_f64 =
977            currency_pair_btcusdt.make_qty(value.to_string().parse::<f64>().unwrap(), round_down);
978        assert_eq!(from_decimal, from_f64);
979        assert_eq!(from_decimal.as_decimal(), expected);
980    }
981
982    #[rstest]
983    #[should_panic(expected = "value rounded to zero")]
984    fn make_qty_from_decimal_rounds_to_zero(currency_pair_btcusdt: CurrencyPair) {
985        currency_pair_btcusdt.make_qty_from_decimal(dec!(0.0000001), None);
986    }
987
988    #[rstest]
989    #[case(Price::from("10000"), "10000.00")]
990    #[case(Price::from("10000.0000"), "10000.00")]
991    #[case(Price::from("0"), "0.00")]
992    #[case(Price::from("0.0000"), "0.00")]
993    fn try_normalize_price_rewrites_grid_aligned_values(
994        currency_pair_btcusdt: CurrencyPair,
995        #[case] input: Price,
996        #[case] expected: &str,
997    ) {
998        let normalized = currency_pair_btcusdt.try_normalize_price(input).unwrap();
999
1000        assert_eq!(normalized.raw(), input.raw());
1001        assert_eq!(
1002            normalized.precision,
1003            currency_pair_btcusdt.price_precision()
1004        );
1005        assert_eq!(normalized, Price::from(expected));
1006    }
1007
1008    #[rstest]
1009    fn try_normalize_price_rejects_sub_precision_value(currency_pair_btcusdt: CurrencyPair) {
1010        let error = currency_pair_btcusdt
1011            .try_normalize_price(Price::from("10000.001"))
1012            .unwrap_err();
1013
1014        assert!(matches!(
1015            error,
1016            CorrectnessError::PredicateViolation { ref message }
1017                if message.contains("requires rounding to instrument price precision")
1018        ));
1019    }
1020
1021    #[rstest]
1022    #[case(Price::from_raw(PRICE_UNDEF, 0), "PRICE_UNDEF")]
1023    #[case(Price::from_raw(PRICE_ERROR, 0), "PRICE_ERROR")]
1024    #[case(ERROR_PRICE, "ERROR_PRICE")]
1025    fn try_normalize_price_rejects_sentinel_values(
1026        currency_pair_btcusdt: CurrencyPair,
1027        #[case] input: Price,
1028        #[case] expected_value: &str,
1029    ) {
1030        let error = currency_pair_btcusdt
1031            .try_normalize_price(input)
1032            .unwrap_err();
1033
1034        match error {
1035            CorrectnessError::InvalidValue {
1036                param,
1037                value,
1038                type_name,
1039            } => {
1040                assert_eq!(param, "price");
1041                assert_eq!(value, expected_value);
1042                assert_eq!(type_name, "`Price`");
1043            }
1044            _ => panic!("expected invalid price error, was {error}"),
1045        }
1046    }
1047
1048    #[rstest]
1049    #[case(Price::from("-10000"), Some(Price::from("-10000.00")))]
1050    #[case(Price::from("-10000.001"), None)]
1051    fn try_normalize_price_handles_negative_values(
1052        currency_pair_btcusdt: CurrencyPair,
1053        #[case] input: Price,
1054        #[case] expected: Option<Price>,
1055    ) {
1056        let normalized = currency_pair_btcusdt.try_normalize_price(input).ok();
1057
1058        assert_eq!(normalized, expected);
1059    }
1060
1061    #[rstest]
1062    fn try_normalize_price_rejects_sub_increment_value() {
1063        let instrument = CurrencyPair::builder()
1064            .instrument_id(InstrumentId::from("TEST.VENUE"))
1065            .raw_symbol(Symbol::from("TEST"))
1066            .base_currency(Currency::from("BTC"))
1067            .quote_currency(Currency::from("USD"))
1068            .price_precision(2)
1069            .size_precision(2)
1070            .price_increment(Price::from("0.50"))
1071            .size_increment(Quantity::from("0.01"))
1072            .ts_event(UnixNanos::default())
1073            .ts_init(UnixNanos::default())
1074            .build()
1075            .unwrap();
1076
1077        assert_eq!(
1078            instrument.try_normalize_price(Price::from("1.500")),
1079            Ok(Price::from("1.50"))
1080        );
1081        let error = instrument
1082            .try_normalize_price(Price::from("1.20"))
1083            .unwrap_err();
1084
1085        assert!(matches!(
1086            error,
1087            CorrectnessError::PredicateViolation { ref message }
1088                if message.contains("not aligned to price increment")
1089        ));
1090    }
1091
1092    #[rstest]
1093    #[case(Quantity::from("1"), "1.000000")]
1094    #[case(Quantity::from("1.0000000"), "1.000000")]
1095    fn try_normalize_qty_rewrites_grid_aligned_values(
1096        currency_pair_btcusdt: CurrencyPair,
1097        #[case] input: Quantity,
1098        #[case] expected: &str,
1099    ) {
1100        let normalized = currency_pair_btcusdt.try_normalize_qty(input).unwrap();
1101
1102        assert_eq!(normalized.raw(), input.raw());
1103        assert_eq!(normalized.precision, currency_pair_btcusdt.size_precision());
1104        assert_eq!(normalized, Quantity::from(expected));
1105    }
1106
1107    #[rstest]
1108    fn try_normalize_qty_rejects_sub_precision_value(currency_pair_btcusdt: CurrencyPair) {
1109        let error = currency_pair_btcusdt
1110            .try_normalize_qty(Quantity::from("1.0000001"))
1111            .unwrap_err();
1112
1113        assert!(matches!(
1114            error,
1115            CorrectnessError::PredicateViolation { ref message }
1116                if message.contains("requires rounding to instrument size precision")
1117        ));
1118    }
1119
1120    #[rstest]
1121    fn try_normalize_qty_rejects_undefined_value(currency_pair_btcusdt: CurrencyPair) {
1122        let error = currency_pair_btcusdt
1123            .try_normalize_qty(Quantity::from_raw(QUANTITY_UNDEF, 0))
1124            .unwrap_err();
1125
1126        match error {
1127            CorrectnessError::InvalidValue {
1128                param,
1129                value,
1130                type_name,
1131            } => {
1132                assert_eq!(param, "quantity");
1133                assert_eq!(value, "QUANTITY_UNDEF");
1134                assert_eq!(type_name, "`Quantity`");
1135            }
1136            _ => panic!("expected invalid quantity error, was {error}"),
1137        }
1138    }
1139
1140    #[cfg(feature = "defi")]
1141    #[rstest]
1142    fn try_normalize_values_reject_mixed_raw_scales() {
1143        let defi_precision = 18;
1144        let price_increment = Price::from_raw(PriceRaw::from(5) * PriceRaw::pow(10, 17), 18);
1145        let size_increment =
1146            Quantity::from_raw(QuantityRaw::from(5_u8) * QuantityRaw::pow(10, 17), 18);
1147        let instrument = CurrencyPair::builder()
1148            .instrument_id(InstrumentId::from("TEST.VENUE"))
1149            .raw_symbol(Symbol::from("TEST"))
1150            .base_currency(Currency::from("BTC"))
1151            .quote_currency(Currency::from("USD"))
1152            .price_precision(defi_precision)
1153            .size_precision(defi_precision)
1154            .price_increment(price_increment)
1155            .size_increment(size_increment)
1156            .ts_event(UnixNanos::default())
1157            .ts_init(UnixNanos::default())
1158            .build()
1159            .unwrap();
1160        let fixed_scale = u32::from(FIXED_PRECISION);
1161        let fixed_price = Price::from_raw(
1162            PriceRaw::pow(10, fixed_scale) * PriceRaw::from(100),
1163            FIXED_PRECISION,
1164        );
1165        let fixed_qty = Quantity::from_raw(
1166            QuantityRaw::pow(10, fixed_scale) * QuantityRaw::from(100_u8),
1167            FIXED_PRECISION,
1168        );
1169
1170        let price_error = instrument.try_normalize_price(fixed_price).unwrap_err();
1171        let qty_error = instrument.try_normalize_qty(fixed_qty).unwrap_err();
1172
1173        assert!(matches!(
1174            price_error,
1175            CorrectnessError::PredicateViolation { ref message }
1176                if message.contains("raw scale does not match instrument price precision")
1177        ));
1178        assert!(matches!(
1179            qty_error,
1180            CorrectnessError::PredicateViolation { ref message }
1181                if message.contains("raw scale does not match instrument size precision")
1182        ));
1183    }
1184
1185    #[rstest]
1186    fn try_normalize_qty_rejects_sub_increment_value() {
1187        let instrument = CurrencyPair::builder()
1188            .instrument_id(InstrumentId::from("TEST.VENUE"))
1189            .raw_symbol(Symbol::from("TEST"))
1190            .base_currency(Currency::from("BTC"))
1191            .quote_currency(Currency::from("USD"))
1192            .price_precision(2)
1193            .size_precision(2)
1194            .price_increment(Price::from("0.01"))
1195            .size_increment(Quantity::from("0.50"))
1196            .ts_event(UnixNanos::default())
1197            .ts_init(UnixNanos::default())
1198            .build()
1199            .unwrap();
1200
1201        assert_eq!(
1202            instrument.try_normalize_qty(Quantity::from("1.500")),
1203            Ok(Quantity::from("1.50"))
1204        );
1205        let error = instrument
1206            .try_normalize_qty(Quantity::from("1.20"))
1207            .unwrap_err();
1208
1209        assert!(matches!(
1210            error,
1211            CorrectnessError::PredicateViolation { ref message }
1212                if message.contains("not aligned to size increment")
1213        ));
1214    }
1215
1216    #[rstest]
1217    #[should_panic(expected = "value rounded to zero")]
1218    fn make_qty_rounds_to_zero(currency_pair_btcusdt: CurrencyPair) {
1219        currency_pair_btcusdt.make_qty(1e-12, None);
1220    }
1221
1222    #[rstest]
1223    fn notional_linear(currency_pair_btcusdt: CurrencyPair) {
1224        let quantity = currency_pair_btcusdt.make_qty(2.0, None);
1225        let price = currency_pair_btcusdt.make_price(10_000.0);
1226        let notional = currency_pair_btcusdt.calculate_notional_value(quantity, price, None);
1227        let expected = Money::new(20_000.0, currency_pair_btcusdt.quote_currency());
1228        assert_eq!(notional, expected);
1229    }
1230
1231    #[rstest]
1232    fn currency_pair_is_not_quanto(currency_pair_btcusdt: CurrencyPair) {
1233        assert!(!currency_pair_btcusdt.is_quanto());
1234        assert_eq!(currency_pair_btcusdt.cost_currency(), Currency::USDT());
1235    }
1236
1237    #[rstest]
1238    fn tick_navigation(currency_pair_btcusdt: CurrencyPair) {
1239        let start = 10_000.123_4;
1240        let bid_0 = currency_pair_btcusdt.next_bid_price(start, 0).unwrap();
1241        let bid_1 = currency_pair_btcusdt.next_bid_price(start, 1).unwrap();
1242        assert!(bid_1 < bid_0);
1243        let asks = currency_pair_btcusdt.next_ask_prices(start, 3);
1244        assert_eq!(asks.len(), 3);
1245        assert!(asks[0] > bid_0);
1246    }
1247
1248    #[rstest]
1249    fn tick_navigation_uses_tick_scheme() {
1250        let instrument = CurrencyPair::builder()
1251            .instrument_id(InstrumentId::from("TEST.VENUE"))
1252            .raw_symbol(Symbol::from("TEST"))
1253            .base_currency(Currency::from("BTC"))
1254            .quote_currency(Currency::from("USD"))
1255            .price_precision(2)
1256            .size_precision(2)
1257            .price_increment(Price::new(0.01, 2))
1258            .size_increment(Quantity::from("0.01"))
1259            .tick_scheme(Ustr::from("FIXED_PRECISION_1"))
1260            .ts_event(UnixNanos::default())
1261            .ts_init(UnixNanos::default())
1262            .build()
1263            .unwrap();
1264
1265        assert_eq!(
1266            instrument.tick_scheme(),
1267            Some(Ustr::from("FIXED_PRECISION_1"))
1268        );
1269        assert_eq!(instrument.next_bid_price(1.23, 0), Some(Price::new(1.2, 2)));
1270        assert_eq!(instrument.next_ask_price(1.23, 0), Some(Price::new(1.3, 2)));
1271    }
1272
1273    #[rstest]
1274    #[case("BOGUS")]
1275    #[case("FIXED_PRECISION_99")]
1276    fn invalid_tick_scheme_returns_error(#[case] tick_scheme: &str) {
1277        let err = CurrencyPair::builder()
1278            .instrument_id(InstrumentId::from("TEST.VENUE"))
1279            .raw_symbol(Symbol::from("TEST"))
1280            .base_currency(Currency::from("BTC"))
1281            .quote_currency(Currency::from("USD"))
1282            .price_precision(2)
1283            .size_precision(2)
1284            .price_increment(Price::new(0.01, 2))
1285            .size_increment(Quantity::from("0.01"))
1286            .tick_scheme(Ustr::from(tick_scheme))
1287            .ts_event(UnixNanos::default())
1288            .ts_init(UnixNanos::default())
1289            .build()
1290            .expect_err("invalid tick scheme must fail");
1291
1292        assert!(
1293            err.to_string()
1294                .contains("tick_scheme not found in tick schemes"),
1295            "{err}"
1296        );
1297    }
1298
1299    #[rstest]
1300    #[should_panic(expected = "'margin_init' not positive")]
1301    fn validate_negative_margin_init() {
1302        let size_increment = Quantity::new(0.01, 2);
1303        let multiplier = Quantity::new(1.0, 0);
1304
1305        validate_instrument_common(
1306            2,
1307            2,              // size_precision
1308            size_increment, // size_increment
1309            multiplier,     // multiplier
1310            dec!(-0.01),    // margin_init
1311            dec!(0.01),     // margin_maint
1312            None,           // price_increment
1313            None,           // lot_size
1314            None,           // max_quantity
1315            None,           // min_quantity
1316            None,           // max_notional
1317            None,           // min_notional
1318            None,           // max_price
1319            None,           // min_price
1320        )
1321        .expect_display(FAILED);
1322    }
1323
1324    #[rstest]
1325    #[should_panic(expected = "'margin_maint' not positive")]
1326    fn validate_negative_margin_maint() {
1327        let size_increment = Quantity::new(0.01, 2);
1328        let multiplier = Quantity::new(1.0, 0);
1329
1330        validate_instrument_common(
1331            2,
1332            2,              // size_precision
1333            size_increment, // size_increment
1334            multiplier,     // multiplier
1335            dec!(0.01),     // margin_init
1336            dec!(-0.01),    // margin_maint
1337            None,           // price_increment
1338            None,           // lot_size
1339            None,           // max_quantity
1340            None,           // min_quantity
1341            None,           // max_notional
1342            None,           // min_notional
1343            None,           // max_price
1344            None,           // min_price
1345        )
1346        .expect_display(FAILED);
1347    }
1348
1349    #[rstest]
1350    fn validate_negative_max_qty() {
1351        let quantity = Quantity::new(0.0, 0);
1352        let error = validate_instrument_common(
1353            2,
1354            2,
1355            Quantity::new(0.01, 2),
1356            Quantity::new(1.0, 0),
1357            dec!(0.01),
1358            dec!(0.01),
1359            None,
1360            None,
1361            Some(quantity),
1362            None,
1363            None,
1364            None,
1365            None,
1366            None,
1367        )
1368        .unwrap_err();
1369
1370        assert_eq!(
1371            error,
1372            CorrectnessError::NotPositive {
1373                param: "max_quantity".to_string(),
1374                value: "0".to_string(),
1375                type_name: "`Quantity`",
1376            }
1377        );
1378    }
1379
1380    #[rstest]
1381    fn make_price_negative_rounding(currency_pair_ethusdt: CurrencyPair) {
1382        let price = currency_pair_ethusdt.make_price(-123.456_789);
1383        assert!(price.as_f64() < 0.0);
1384    }
1385
1386    #[rstest]
1387    fn base_quantity_linear(currency_pair_btcusdt: CurrencyPair) {
1388        let quantity = currency_pair_btcusdt.make_qty(2.0, None);
1389        let price = currency_pair_btcusdt.make_price(10_000.0);
1390        let base = currency_pair_btcusdt.calculate_base_quantity(quantity, price);
1391        assert_eq!(base.to_string(), "0.000200");
1392    }
1393
1394    #[rstest]
1395    fn base_quantity_zero_last_price_returns_error(currency_pair_btcusdt: CurrencyPair) {
1396        let quantity = currency_pair_btcusdt.make_qty(2.0, None);
1397        let error = currency_pair_btcusdt
1398            .try_calculate_base_quantity(quantity, Price::new(0.0, 2))
1399            .unwrap_err();
1400        assert!(
1401            error.to_string().contains("`last_price` was zero"),
1402            "{error}"
1403        );
1404    }
1405
1406    #[rstest]
1407    fn base_quantity_out_of_range_returns_error(currency_pair_btcusdt: CurrencyPair) {
1408        let error = currency_pair_btcusdt
1409            .try_calculate_base_quantity(Quantity::from("1000000000"), Price::from("0.00001"))
1410            .unwrap_err();
1411
1412        let expected = Quantity::from_decimal_dp(
1413            dec!(100000000000000),
1414            currency_pair_btcusdt.size_precision(),
1415        )
1416        .unwrap_err();
1417
1418        assert_eq!(error.downcast_ref::<CorrectnessError>(), Some(&expected));
1419    }
1420
1421    #[cfg(feature = "high-precision")]
1422    #[rstest]
1423    fn base_quantity_decimal_overflow_returns_error(currency_pair_btcusdt: CurrencyPair) {
1424        let error = currency_pair_btcusdt
1425            .try_calculate_base_quantity(
1426                Quantity::from("10000000000000"),
1427                Price::from("0.0000000000000001"),
1428            )
1429            .unwrap_err();
1430
1431        assert_eq!(error.to_string(), "Base quantity exceeds Decimal bounds");
1432    }
1433
1434    #[rstest]
1435    #[case(f64::NAN)]
1436    #[case(f64::INFINITY)]
1437    #[case(1e30)] // Finite but not representable as a Decimal
1438    fn make_price_invalid_value_returns_error(
1439        currency_pair_btcusdt: CurrencyPair,
1440        #[case] value: f64,
1441    ) {
1442        let error = currency_pair_btcusdt.try_make_price(value).unwrap_err();
1443        assert!(
1444            error.to_string().contains("invalid `value` for make_price"),
1445            "{error}"
1446        );
1447    }
1448
1449    #[rstest]
1450    fn make_qty_invalid_value_returns_error(currency_pair_btcusdt: CurrencyPair) {
1451        let error = currency_pair_btcusdt
1452            .try_make_qty(f64::NAN, None)
1453            .unwrap_err();
1454        assert!(
1455            error.to_string().contains("invalid `value` for make_qty"),
1456            "{error}"
1457        );
1458    }
1459
1460    #[rstest]
1461    fn next_bid_prices_sequence(currency_pair_btcusdt: CurrencyPair) {
1462        let start = 10_000.0;
1463        let bids = currency_pair_btcusdt.next_bid_prices(start, 5);
1464        assert_eq!(bids.len(), 5);
1465        for i in 1..bids.len() {
1466            assert!(bids[i] < bids[i - 1]);
1467        }
1468    }
1469
1470    #[rstest]
1471    fn next_ask_prices_sequence(currency_pair_btcusdt: CurrencyPair) {
1472        let start = 10_000.0;
1473        let asks = currency_pair_btcusdt.next_ask_prices(start, 5);
1474        assert_eq!(asks.len(), 5);
1475        for i in 1..asks.len() {
1476            assert!(asks[i] > asks[i - 1]);
1477        }
1478    }
1479
1480    #[rstest]
1481    #[case::bid(true)]
1482    #[case::ask(false)]
1483    fn tick_navigation_rejects_negative_offset(
1484        currency_pair_btcusdt: CurrencyPair,
1485        #[case] bid: bool,
1486    ) {
1487        let price = if bid {
1488            currency_pair_btcusdt.next_bid_price(10_000.0, -1)
1489        } else {
1490            currency_pair_btcusdt.next_ask_price(10_000.0, -1)
1491        };
1492
1493        assert_eq!(price, None);
1494    }
1495
1496    #[rstest]
1497    fn validate_price_increment_precision_mismatch() {
1498        let size_increment = Quantity::new(0.01, 2);
1499        let multiplier = Quantity::new(1.0, 0);
1500        let price_increment = Price::new(0.001, 3);
1501        let error = validate_instrument_common(
1502            2,
1503            2,
1504            size_increment,
1505            multiplier,
1506            dec!(0.01),
1507            dec!(0.01),
1508            Some(price_increment),
1509            None,
1510            None,
1511            None,
1512            None,
1513            None,
1514            None,
1515            None,
1516        )
1517        .unwrap_err();
1518
1519        assert_eq!(
1520            error,
1521            CorrectnessError::EqualityMismatch {
1522                lhs_param: "price_increment.precision".to_string(),
1523                rhs_param: "price_precision".to_string(),
1524                lhs: "3".to_string(),
1525                rhs: "2".to_string(),
1526                type_name: "u8",
1527            }
1528        );
1529    }
1530
1531    #[rstest]
1532    fn validate_min_price_exceeds_max_price() {
1533        let size_increment = Quantity::new(0.01, 2);
1534        let multiplier = Quantity::new(1.0, 0);
1535        let min_price = Price::new(10.0, 2);
1536        let max_price = Price::new(5.0, 2);
1537        let error = validate_instrument_common(
1538            2,
1539            2,
1540            size_increment,
1541            multiplier,
1542            dec!(0.01),
1543            dec!(0.01),
1544            None,
1545            None,
1546            None,
1547            None,
1548            None,
1549            None,
1550            Some(max_price),
1551            Some(min_price),
1552        )
1553        .unwrap_err();
1554
1555        assert_eq!(
1556            error,
1557            CorrectnessError::PredicateViolation {
1558                message: "min_price exceeds max_price".to_string(),
1559            }
1560        );
1561    }
1562
1563    #[rstest]
1564    fn validate_instrument_common_ok() {
1565        let res = validate_instrument_common(
1566            2,
1567            4,
1568            Quantity::new(0.0001, 4),
1569            Quantity::new(1.0, 0),
1570            dec!(0.02),
1571            dec!(0.01),
1572            Some(Price::new(0.01, 2)),
1573            None,
1574            None,
1575            None,
1576            None,
1577            None,
1578            None,
1579            None,
1580        );
1581        assert!(matches!(res, Ok(())));
1582    }
1583
1584    #[rstest]
1585    #[should_panic(expected = "not in range")]
1586    fn validate_multiple_errors() {
1587        validate_instrument_common(
1588            2,
1589            2,
1590            Quantity::new(-0.01, 2),
1591            Quantity::new(0.0, 0),
1592            dec!(0),
1593            dec!(0),
1594            None,
1595            None,
1596            None,
1597            None,
1598            None,
1599            None,
1600            None,
1601            None,
1602        )
1603        .expect_display(FAILED);
1604    }
1605
1606    #[rstest]
1607    #[case(1.234_999_9, false, "1.235000")]
1608    #[case(1.234_999_9, true, "1.234999")]
1609    fn make_qty_boundary(
1610        currency_pair_btcusdt: CurrencyPair,
1611        #[case] input: f64,
1612        #[case] round_down: bool,
1613        #[case] expected: &str,
1614    ) {
1615        let quantity = currency_pair_btcusdt.make_qty(input, Some(round_down));
1616        assert_eq!(quantity.to_string(), expected);
1617    }
1618
1619    #[rstest]
1620    #[case(1.234_999, 1.23)]
1621    #[case(1.235, 1.24)]
1622    #[case(1.235_001, 1.24)]
1623    fn make_price_rounding_parity(
1624        currency_pair_btcusdt: CurrencyPair,
1625        #[case] input: f64,
1626        #[case] expected: f64,
1627    ) {
1628        let price = currency_pair_btcusdt.make_price(input);
1629        assert!((price.as_f64() - expected).abs() < 1e-9);
1630    }
1631
1632    #[rstest]
1633    fn make_price_half_even_parity(currency_pair_btcusdt: CurrencyPair) {
1634        let rounding_precision = std::cmp::min(
1635            currency_pair_btcusdt.price_precision(),
1636            currency_pair_btcusdt.min_price_increment_precision(),
1637        );
1638        let step = 10f64.powi(-i32::from(rounding_precision));
1639        let base_even_multiple = 42.0;
1640        let base_value = step * base_even_multiple;
1641        let delta = step / 2000.0;
1642        let value_below = base_value + 0.5 * step - delta;
1643        let value_exact = base_value + 0.5 * step;
1644        let value_above = base_value + 0.5 * step + delta;
1645        let price_below = currency_pair_btcusdt.make_price(value_below);
1646        let price_exact = currency_pair_btcusdt.make_price(value_exact);
1647        let price_above = currency_pair_btcusdt.make_price(value_above);
1648        assert_eq!(price_below, price_exact);
1649        assert_ne!(price_exact, price_above);
1650    }
1651
1652    #[rstest]
1653    #[case(dec!(1.234999), dec!(1.23))]
1654    #[case(dec!(1.235), dec!(1.24))]
1655    #[case(dec!(1.235001), dec!(1.24))]
1656    #[case(dec!(10000.0), dec!(10000.0))]
1657    fn make_price_from_decimal_matches_f64_path(
1658        currency_pair_btcusdt: CurrencyPair,
1659        #[case] value: Decimal,
1660        #[case] expected: Decimal,
1661    ) {
1662        let from_decimal = currency_pair_btcusdt.make_price_from_decimal(value);
1663        let from_f64 = currency_pair_btcusdt.make_price(value.to_string().parse::<f64>().unwrap());
1664        assert_eq!(from_decimal, from_f64);
1665        assert_eq!(from_decimal.as_decimal(), expected);
1666    }
1667
1668    #[rstest]
1669    fn is_quanto_flag(ethbtc_quanto: CryptoFuture) {
1670        assert!(ethbtc_quanto.is_quanto());
1671    }
1672
1673    #[rstest]
1674    fn notional_quanto(ethbtc_quanto: CryptoFuture) {
1675        let quantity = ethbtc_quanto.make_qty(5.0, None);
1676        let price = ethbtc_quanto.make_price(0.036);
1677        let notional = ethbtc_quanto.calculate_notional_value(quantity, price, None);
1678        let expected = Money::new(0.18, ethbtc_quanto.settlement_currency());
1679        assert_eq!(notional, expected);
1680    }
1681
1682    #[rstest]
1683    #[case("USD", "BUSD")]
1684    #[case("USD", "FDUSD")]
1685    #[case("USD", "pUSD")]
1686    #[case("USD", "TUSD")]
1687    #[case("USD", "USD")]
1688    #[case("USD", "USDC")]
1689    #[case("USD", "USDC.e")]
1690    #[case("USD", "USDP")]
1691    #[case("USD", "USDT")]
1692    #[case("BUSD", "USD")]
1693    #[case("FDUSD", "USD")]
1694    #[case("pUSD", "USD")]
1695    #[case("TUSD", "USD")]
1696    #[case("USDC", "USD")]
1697    #[case("USDC.e", "USD")]
1698    #[case("USDP", "USD")]
1699    #[case("USDT", "USD")]
1700    fn usd_equivalent_settlement_is_not_quanto(
1701        #[case] quote_currency_code: &str,
1702        #[case] settlement_currency_code: &str,
1703    ) {
1704        let quote_currency =
1705            Currency::try_from_str(quote_currency_code).expect("quote currency must exist");
1706        let settlement_currency = Currency::try_from_str(settlement_currency_code)
1707            .expect("settlement currency must exist");
1708        let instrument = crypto_future_with_quote_settlement(quote_currency, settlement_currency);
1709        let quantity = instrument.make_qty(5.0, None);
1710        let price = instrument.make_price(1000.0);
1711        let notional = instrument.calculate_notional_value(quantity, price, None);
1712
1713        assert!(!instrument.is_quanto());
1714        assert_eq!(instrument.cost_currency(), quote_currency);
1715        assert_eq!(notional, Money::new(5000.0, quote_currency));
1716    }
1717
1718    #[rstest]
1719    fn notional_inverse_base(btcusd_inverse_perp: CryptoPerpetual) {
1720        let quantity = btcusd_inverse_perp.make_qty(100.0, None);
1721        let price = btcusd_inverse_perp.make_price(50_000.0);
1722        let notional = btcusd_inverse_perp.calculate_notional_value(quantity, price, Some(false));
1723        let expected = Money::new(
1724            100.0 * btcusd_inverse_perp.multiplier().as_f64() * (1.0 / 50_000.0),
1725            btcusd_inverse_perp.base_currency().unwrap(),
1726        );
1727        assert_eq!(notional, expected);
1728    }
1729
1730    #[rstest]
1731    fn notional_inverse_quote_use_quote(btcusd_inverse_perp: CryptoPerpetual) {
1732        let quantity = btcusd_inverse_perp.make_qty(100.0, None);
1733        let price = btcusd_inverse_perp.make_price(50_000.0);
1734        let notional = btcusd_inverse_perp.calculate_notional_value(quantity, price, Some(true));
1735        let expected = Money::new(100.0, btcusd_inverse_perp.quote_currency());
1736        assert_eq!(notional, expected);
1737    }
1738
1739    #[rstest]
1740    fn notional_inverse_option_values_premium_in_base(mut crypto_option_btc_deribit: CryptoOption) {
1741        crypto_option_btc_deribit.is_inverse = true;
1742        crypto_option_btc_deribit.multiplier = Quantity::from("0.01");
1743
1744        let notional = crypto_option_btc_deribit.calculate_notional_value(
1745            Quantity::from("10.0"),
1746            Price::from("0.020"),
1747            None,
1748        );
1749
1750        assert_eq!(notional, Money::from("0.002 BTC"));
1751    }
1752
1753    #[rstest]
1754    fn try_notional_inverse_zero_price_returns_error(btcusd_inverse_perp: CryptoPerpetual) {
1755        let result = btcusd_inverse_perp.try_calculate_notional_value(
1756            btcusd_inverse_perp.make_qty(100.0, None),
1757            Price::new(0.0, 1),
1758            Some(false),
1759        );
1760
1761        assert_eq!(
1762            result.unwrap_err().to_string(),
1763            "price must be positive for inverse notional valuation"
1764        );
1765    }
1766
1767    #[rstest]
1768    fn try_notional_unrepresentable_money_returns_error(currency_pair_btcusdt: CurrencyPair) {
1769        let result = currency_pair_btcusdt.try_calculate_notional_value(
1770            Quantity::from("100000000"),
1771            Price::from("100000000"),
1772            None,
1773        );
1774
1775        assert!(result.is_err());
1776    }
1777
1778    #[rstest]
1779    fn try_notional_decimal_overflow_returns_error() {
1780        let result = try_notional_value(
1781            Quantity::from("9000000000"),
1782            Price::from("9000000000"),
1783            Quantity::from("9000000000"),
1784            InstrumentClass::Spot,
1785            false,
1786            false,
1787            Currency::USD(),
1788        );
1789
1790        assert_eq!(
1791            result.unwrap_err().to_string(),
1792            "notional calculation overflow"
1793        );
1794    }
1795
1796    #[rstest]
1797    fn validate_non_positive_max_price() {
1798        let size_increment = Quantity::new(0.01, 2);
1799        let multiplier = Quantity::new(1.0, 0);
1800        let max_price = Price::new(0.0, 2);
1801        let error = validate_instrument_common(
1802            2,
1803            2,
1804            size_increment,
1805            multiplier,
1806            dec!(0.01),
1807            dec!(0.01),
1808            None,
1809            None,
1810            None,
1811            None,
1812            None,
1813            None,
1814            Some(max_price),
1815            None,
1816        )
1817        .unwrap_err();
1818
1819        assert_eq!(
1820            error,
1821            CorrectnessError::NotPositive {
1822                param: "max_price".to_string(),
1823                value: "0.00".to_string(),
1824                type_name: "`Price`",
1825            }
1826        );
1827    }
1828
1829    #[rstest]
1830    fn validate_non_positive_max_notional(currency_pair_btcusdt: CurrencyPair) {
1831        let size_increment = Quantity::new(0.01, 2);
1832        let multiplier = Quantity::new(1.0, 0);
1833        let max_notional = Money::new(0.0, currency_pair_btcusdt.quote_currency());
1834        let error = validate_instrument_common(
1835            2,
1836            2,
1837            size_increment,
1838            multiplier,
1839            dec!(0.01),
1840            dec!(0.01),
1841            None,
1842            None,
1843            None,
1844            None,
1845            Some(max_notional),
1846            None,
1847            None,
1848            None,
1849        )
1850        .unwrap_err();
1851
1852        assert_eq!(
1853            error,
1854            CorrectnessError::NotPositive {
1855                param: "max_notional".to_string(),
1856                value: "0.00000000 USDT".to_string(),
1857                type_name: "`Money`",
1858            }
1859        );
1860    }
1861
1862    #[rstest]
1863    fn validate_price_increment_min_price_precision_mismatch() {
1864        let size_increment = Quantity::new(0.01, 2);
1865        let multiplier = Quantity::new(1.0, 0);
1866        let price_increment = Price::new(0.01, 2);
1867        let min_price = Price::new(1.0, 3);
1868        let error = validate_instrument_common(
1869            2,
1870            2,
1871            size_increment,
1872            multiplier,
1873            dec!(0.01),
1874            dec!(0.01),
1875            Some(price_increment),
1876            None,
1877            None,
1878            None,
1879            None,
1880            None,
1881            None,
1882            Some(min_price),
1883        )
1884        .unwrap_err();
1885
1886        assert_eq!(
1887            error,
1888            CorrectnessError::EqualityMismatch {
1889                lhs_param: "min_price.precision".to_string(),
1890                rhs_param: "price_precision".to_string(),
1891                lhs: "3".to_string(),
1892                rhs: "2".to_string(),
1893                type_name: "u8",
1894            }
1895        );
1896    }
1897
1898    #[rstest]
1899    fn validate_negative_min_notional(currency_pair_btcusdt: CurrencyPair) {
1900        let size_increment = Quantity::new(0.01, 2);
1901        let multiplier = Quantity::new(1.0, 0);
1902        let min_notional = Money::new(-1.0, currency_pair_btcusdt.quote_currency());
1903        let max_notional = Money::new(1.0, currency_pair_btcusdt.quote_currency());
1904        let error = validate_instrument_common(
1905            2,
1906            2,
1907            size_increment,
1908            multiplier,
1909            dec!(0.01),
1910            dec!(0.01),
1911            None,
1912            None,
1913            None,
1914            None,
1915            Some(max_notional),
1916            Some(min_notional),
1917            None,
1918            None,
1919        )
1920        .unwrap_err();
1921
1922        assert_eq!(
1923            error,
1924            CorrectnessError::NotPositive {
1925                param: "min_notional".to_string(),
1926                value: "-1.00000000 USDT".to_string(),
1927                type_name: "`Money`",
1928            }
1929        );
1930    }
1931
1932    #[rstest]
1933    #[case::dp0(Decimal::new(1_000, 0), Decimal::new(2, 0), 500.0)]
1934    #[case::dp1(Decimal::new(10_000, 1), Decimal::new(2, 0), 500.0)]
1935    #[case::dp2(Decimal::new(100_000, 2), Decimal::new(2, 0), 500.0)]
1936    #[case::dp3(Decimal::new(1_000_000, 3), Decimal::new(2, 0), 500.0)]
1937    #[case::dp4(Decimal::new(10_000_000, 4), Decimal::new(2, 0), 500.0)]
1938    #[case::dp5(Decimal::new(100_000_000, 5), Decimal::new(2, 0), 500.0)]
1939    #[case::dp6(Decimal::new(1_000_000_000, 6), Decimal::new(2, 0), 500.0)]
1940    #[case::dp7(Decimal::new(10_000_000_000, 7), Decimal::new(2, 0), 500.0)]
1941    #[case::dp8(Decimal::new(100_000_000_000, 8), Decimal::new(2, 0), 500.0)]
1942    fn base_qty_rounding(
1943        currency_pair_btcusdt: CurrencyPair,
1944        #[case] q: Decimal,
1945        #[case] px: Decimal,
1946        #[case] expected: f64,
1947    ) {
1948        let qty = Quantity::new(q.to_f64().unwrap(), 8);
1949        let price = Price::new(px.to_f64().unwrap(), 8);
1950        let base = currency_pair_btcusdt.calculate_base_quantity(qty, price);
1951        assert!((base.as_f64() - expected).abs() < 1e-9);
1952    }
1953
1954    proptest! {
1955        #[rstest]
1956        fn make_price_qty_fuzz(input in 0.0001f64..1e8) {
1957            let instrument = currency_pair_btcusdt();
1958            let price = instrument.make_price(input);
1959            prop_assert!(price.as_f64().is_finite());
1960            let quantity = instrument.make_qty(input, None);
1961            prop_assert!(quantity.as_f64().is_finite());
1962        }
1963    }
1964
1965    #[rstest]
1966    fn tick_walk_limits_btcusdt_ask(currency_pair_btcusdt: CurrencyPair) {
1967        if let Some(max_price) = currency_pair_btcusdt.max_price() {
1968            assert!(
1969                currency_pair_btcusdt
1970                    .next_ask_price(max_price.as_f64(), 1)
1971                    .is_none()
1972            );
1973        }
1974    }
1975
1976    #[rstest]
1977    fn tick_walk_limits_ethusdt_ask(currency_pair_ethusdt: CurrencyPair) {
1978        if let Some(max_price) = currency_pair_ethusdt.max_price() {
1979            assert!(
1980                currency_pair_ethusdt
1981                    .next_ask_price(max_price.as_f64(), 1)
1982                    .is_none()
1983            );
1984        }
1985    }
1986
1987    #[rstest]
1988    fn tick_walk_limits_btcusdt_bid(currency_pair_btcusdt: CurrencyPair) {
1989        if let Some(min_price) = currency_pair_btcusdt.min_price() {
1990            assert!(
1991                currency_pair_btcusdt
1992                    .next_bid_price(min_price.as_f64(), 1)
1993                    .is_none()
1994            );
1995        }
1996    }
1997
1998    #[rstest]
1999    fn tick_walk_limits_ethusdt_bid(currency_pair_ethusdt: CurrencyPair) {
2000        if let Some(min_price) = currency_pair_ethusdt.min_price() {
2001            assert!(
2002                currency_pair_ethusdt
2003                    .next_bid_price(min_price.as_f64(), 1)
2004                    .is_none()
2005            );
2006        }
2007    }
2008
2009    #[rstest]
2010    fn tick_walk_limits_quanto_ask(ethbtc_quanto: CryptoFuture) {
2011        if let Some(max_price) = ethbtc_quanto.max_price() {
2012            assert!(
2013                ethbtc_quanto
2014                    .next_ask_price(max_price.as_f64(), 1)
2015                    .is_none()
2016            );
2017        }
2018    }
2019
2020    #[rstest]
2021    #[case(0.999_999, false)]
2022    #[case(0.999_999, true)]
2023    #[case(1.000_000_1, false)]
2024    #[case(1.000_000_1, true)]
2025    #[case(1.234_5, false)]
2026    #[case(1.234_5, true)]
2027    #[case(2.345_5, false)]
2028    #[case(2.345_5, true)]
2029    #[case(0.000_999_999, false)]
2030    #[case(0.000_999_999, true)]
2031    fn quantity_rounding_grid(
2032        currency_pair_btcusdt: CurrencyPair,
2033        #[case] input: f64,
2034        #[case] round_down: bool,
2035    ) {
2036        let qty = currency_pair_btcusdt.make_qty(input, Some(round_down));
2037        assert!(qty.as_f64().is_finite());
2038    }
2039
2040    #[rstest]
2041    fn validate_price_increment_max_price_precision_mismatch() {
2042        let size_increment = Quantity::new(0.01, 2);
2043        let multiplier = Quantity::new(1.0, 0);
2044        let price_increment = Price::new(0.01, 2);
2045        let max_price = Price::new(1.0, 3);
2046        let error = validate_instrument_common(
2047            2,
2048            2,
2049            size_increment,
2050            multiplier,
2051            dec!(0.01),
2052            dec!(0.01),
2053            Some(price_increment),
2054            None,
2055            None,
2056            None,
2057            None,
2058            None,
2059            Some(max_price),
2060            None,
2061        )
2062        .unwrap_err();
2063
2064        assert_eq!(
2065            error,
2066            CorrectnessError::EqualityMismatch {
2067                lhs_param: "max_price.precision".to_string(),
2068                rhs_param: "price_precision".to_string(),
2069                lhs: "3".to_string(),
2070                rhs: "2".to_string(),
2071                type_name: "u8",
2072            }
2073        );
2074    }
2075
2076    #[rstest]
2077    #[case::dp9(Decimal::new(1_000_000_000_000, 9), Decimal::new(2, 0), 500.0)]
2078    #[case::dp10(Decimal::new(10_000_000_000_000, 10), Decimal::new(2, 0), 500.0)]
2079    #[case::dp11(Decimal::new(100_000_000_000_000, 11), Decimal::new(2, 0), 500.0)]
2080    #[case::dp12(Decimal::new(1_000_000_000_000_000, 12), Decimal::new(2, 0), 500.0)]
2081    #[case::dp13(Decimal::new(10_000_000_000_000_000, 13), Decimal::new(2, 0), 500.0)]
2082    #[case::dp14(Decimal::new(100_000_000_000_000_000, 14), Decimal::new(2, 0), 500.0)]
2083    #[case::dp15(Decimal::new(1_000_000_000_000_000_000, 15), Decimal::new(2, 0), 500.0)]
2084    #[case::dp16(
2085        Decimal::from_i128_with_scale(10_000_000_000_000_000_000i128, 16),
2086        Decimal::new(2, 0),
2087        500.0
2088    )]
2089    #[case::dp17(
2090        Decimal::from_i128_with_scale(100_000_000_000_000_000_000i128, 17),
2091        Decimal::new(2, 0),
2092        500.0
2093    )]
2094    fn base_qty_rounding_high_dp(
2095        currency_pair_btcusdt: CurrencyPair,
2096        #[case] q: Decimal,
2097        #[case] px: Decimal,
2098        #[case] expected: f64,
2099    ) {
2100        let qty = Quantity::new(q.to_f64().unwrap(), 8);
2101        let price = Price::new(px.to_f64().unwrap(), 8);
2102        let base = currency_pair_btcusdt.calculate_base_quantity(qty, price);
2103        assert!((base.as_f64() - expected).abs() < 1e-9);
2104    }
2105
2106    #[rstest]
2107    fn check_positive_money_ok(currency_pair_btcusdt: CurrencyPair) {
2108        let money = Money::new(100.0, currency_pair_btcusdt.quote_currency());
2109        assert!(check_positive_money(money, "money").is_ok());
2110    }
2111
2112    #[rstest]
2113    #[should_panic(expected = "NotPositive")]
2114    fn check_positive_money_zero(currency_pair_btcusdt: CurrencyPair) {
2115        let money = Money::new(0.0, currency_pair_btcusdt.quote_currency());
2116        check_positive_money(money, "money").unwrap();
2117    }
2118
2119    #[rstest]
2120    #[should_panic(expected = "NotPositive")]
2121    fn check_positive_money_negative(currency_pair_btcusdt: CurrencyPair) {
2122        let money = Money::new(-0.01, currency_pair_btcusdt.quote_currency());
2123        check_positive_money(money, "money").unwrap();
2124    }
2125
2126    fn crypto_future_with_quote_settlement(
2127        quote_currency: Currency,
2128        settlement_currency: Currency,
2129    ) -> CryptoFuture {
2130        CryptoFuture::builder()
2131            .instrument_id(InstrumentId::from("ETHUSD-QUANTO-TEST.BINANCE"))
2132            .raw_symbol(Symbol::from("ETHUSD-QUANTO-TEST"))
2133            .underlying(Currency::ETH())
2134            .quote_currency(quote_currency)
2135            .settlement_currency(settlement_currency)
2136            .is_inverse(false)
2137            .activation_ns(0.into())
2138            .expiration_ns(0.into())
2139            .price_precision(2)
2140            .size_precision(0)
2141            .price_increment(Price::from("0.01"))
2142            .size_increment(Quantity::from("1"))
2143            .ts_event(0.into())
2144            .ts_init(0.into())
2145            .build()
2146            .unwrap()
2147    }
2148
2149    #[rstest]
2150    fn make_price_with_trailing_zeros_in_increment() {
2151        // Test instrument with price_increment 0.50 (precision 2, but min_increment_precision 1)
2152        // This verifies that trailing zeros in price_increment are handled correctly
2153        let instrument = CurrencyPair::builder()
2154            .instrument_id(InstrumentId::from("TEST.VENUE"))
2155            .raw_symbol(Symbol::from("TEST"))
2156            .base_currency(Currency::from("BTC"))
2157            .quote_currency(Currency::from("USD"))
2158            .price_precision(2)
2159            .size_precision(2)
2160            // price_increment with trailing zero
2161            .price_increment(Price::new(0.50, 2))
2162            .size_increment(Quantity::from("0.01"))
2163            .ts_event(UnixNanos::default())
2164            .ts_init(UnixNanos::default())
2165            .build()
2166            .unwrap();
2167
2168        // Verify min_increment_precision is 1 (ignoring trailing zero)
2169        assert_eq!(instrument.min_price_increment_precision(), 1);
2170
2171        // Test that make_price rounds to min_increment_precision (1)
2172        // 1.234 should round to 1.2 (not 1.23)
2173        let price = instrument.make_price(1.234);
2174        assert_eq!(price.as_f64(), 1.2);
2175
2176        // 1.25 should round to 1.2 (half-even rounding)
2177        let price = instrument.make_price(1.25);
2178        assert_eq!(price.as_f64(), 1.2);
2179
2180        // 1.35 should round to 1.4 (half-even rounding)
2181        let price = instrument.make_price(1.35);
2182        assert_eq!(price.as_f64(), 1.4);
2183
2184        // But output precision should still be 2
2185        assert_eq!(price.precision, 2);
2186    }
2187
2188    #[rstest]
2189    fn make_qty_with_trailing_zeros_in_increment() {
2190        // Test instrument with size_increment 0.50 (precision 2, but min_increment_precision 1)
2191        let instrument = CurrencyPair::builder()
2192            .instrument_id(InstrumentId::from("TEST.VENUE"))
2193            .raw_symbol(Symbol::from("TEST"))
2194            .base_currency(Currency::from("BTC"))
2195            .quote_currency(Currency::from("USD"))
2196            .price_precision(2)
2197            .size_precision(2)
2198            .price_increment(Price::new(0.01, 2))
2199            // size_increment with trailing zero
2200            .size_increment(Quantity::new(0.50, 2))
2201            .ts_event(UnixNanos::default())
2202            .ts_init(UnixNanos::default())
2203            .build()
2204            .unwrap();
2205
2206        // Verify min_increment_precision is 1 (ignoring trailing zero)
2207        assert_eq!(instrument.min_size_increment_precision(), 1);
2208
2209        // Test that make_qty rounds to min_increment_precision (1)
2210        // 1.234 should round to 1.2 (not 1.23)
2211        let qty = instrument.make_qty(1.234, None);
2212        assert_eq!(qty.as_f64(), 1.2);
2213
2214        // 1.25 should round to 1.2 (half-even rounding)
2215        let qty = instrument.make_qty(1.25, None);
2216        assert_eq!(qty.as_f64(), 1.2);
2217
2218        // 1.35 should round to 1.4 (half-even rounding)
2219        let qty = instrument.make_qty(1.35, None);
2220        assert_eq!(qty.as_f64(), 1.4);
2221
2222        // But output precision should still be 2
2223        assert_eq!(qty.precision, 2);
2224
2225        // Test round_down option
2226        let qty = instrument.make_qty(1.99, Some(true));
2227        assert_eq!(qty.as_f64(), 1.9);
2228    }
2229
2230    #[rstest]
2231    #[case(InstrumentClass::Future, true)]
2232    #[case(InstrumentClass::FuturesSpread, true)]
2233    #[case(InstrumentClass::Option, true)]
2234    #[case(InstrumentClass::OptionSpread, true)]
2235    #[case(InstrumentClass::Spot, false)]
2236    #[case(InstrumentClass::Swap, false)]
2237    #[case(InstrumentClass::Forward, false)]
2238    #[case(InstrumentClass::Cfd, false)]
2239    #[case(InstrumentClass::Bond, false)]
2240    #[case(InstrumentClass::Warrant, false)]
2241    #[case(InstrumentClass::SportsBetting, false)]
2242    #[case(InstrumentClass::BinaryOption, false)]
2243    fn test_instrument_class_has_expiration(
2244        #[case] instrument_class: InstrumentClass,
2245        #[case] expected: bool,
2246    ) {
2247        assert_eq!(instrument_class.has_expiration(), expected);
2248    }
2249
2250    #[rstest]
2251    #[case::linear(false, true)]
2252    #[case::inverse(true, false)]
2253    fn test_crypto_future_allows_negative_price(
2254        mut crypto_future_btcusdt: CryptoFuture,
2255        #[case] is_inverse: bool,
2256        #[case] expected: bool,
2257    ) {
2258        crypto_future_btcusdt.is_inverse = is_inverse;
2259
2260        assert_eq!(crypto_future_btcusdt.allows_negative_price(), expected);
2261    }
2262
2263    #[rstest]
2264    fn test_inverse_crypto_option_allows_negative_price(
2265        mut crypto_option_btc_deribit: CryptoOption,
2266    ) {
2267        crypto_option_btc_deribit.is_inverse = true;
2268
2269        assert!(crypto_option_btc_deribit.allows_negative_price());
2270    }
2271}