Skip to main content

nautilus_model/types/
price.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//! Represents a price in a market with a specified precision.
17//!
18//! [`Price`] is an immutable value type for representing market prices, bid/ask quotes,
19//! and price levels. Unlike [`Quantity`](super::Quantity), prices can be negative (useful for spreads,
20//! basis trades, or certain derivative instruments).
21//!
22//! # Arithmetic behavior
23//!
24//! Adding or subtracting two `Price` values requires matching effective fixed-point scales.
25//! These operations panic on a scale mismatch.
26//! Comparisons and hashes account for scale differences without rounding.
27//! Without the `defi` feature, constructors restrict values to a single storage scale.
28//!
29//! | Operation         | Result    | Notes                              |
30//! |-------------------|-----------|------------------------------------|
31//! | `Price + Price`   | `Price`   | Precision is max of both operands. |
32//! | `Price - Price`   | `Price`   | Precision is max of both operands. |
33//! | `Price + Decimal` | `Decimal` |                                    |
34//! | `Price - Decimal` | `Decimal` |                                    |
35//! | `Price * Decimal` | `Decimal` |                                    |
36//! | `Price / Decimal` | `Decimal` |                                    |
37//! | `Price + f64`     | `f64`     |                                    |
38//! | `Price - f64`     | `f64`     |                                    |
39//! | `Price * f64`     | `f64`     |                                    |
40//! | `Price / f64`     | `f64`     |                                    |
41//! | `-Price`          | `Price`   |                                    |
42//!
43//! # Immutability
44//!
45//! `Price` is immutable. All arithmetic operations return new instances.
46
47use std::{
48    cmp::Ordering,
49    fmt::{Debug, Display},
50    hash::{Hash, Hasher},
51    ops::{Add, Deref, Div, Mul, Neg, Sub},
52    str::FromStr,
53};
54
55use nautilus_core::{
56    correctness::{
57        CorrectnessError, CorrectnessResult, CorrectnessResultExt, FAILED,
58        check_in_range_inclusive_f64,
59    },
60    string::formatting::Separable,
61};
62use rust_decimal::Decimal;
63use serde::{Deserialize, Deserializer, Serialize};
64
65#[cfg(feature = "defi")]
66use super::fixed::compare_raw_signed;
67use super::fixed::{
68    FIXED_PRECISION, FIXED_SCALAR, MAX_PRECISION, canonical_raw, check_fixed_precision,
69    format_scaled_i128, mantissa_exponent_to_fixed_i128, mantissa_exponent_to_raw_checked,
70    parse_decimal_mantissa, raw_scales_match, remove_underscores, scaled_raw_to_decimal,
71};
72#[cfg(feature = "high-precision")]
73use super::fixed::{
74    PRECISION_DIFF_SCALAR, check_fixed_raw_i128 as check_fixed_raw, f64_to_fixed_i128,
75    fixed_i128_to_f64,
76};
77#[cfg(not(feature = "high-precision"))]
78use super::fixed::{check_fixed_raw_i64 as check_fixed_raw, f64_to_fixed_i64, fixed_i64_to_f64};
79use crate::deserialization::StringInput;
80#[cfg(feature = "defi")]
81use crate::types::fixed::MAX_FLOAT_PRECISION;
82
83// -----------------------------------------------------------------------------
84// PriceRaw
85// -----------------------------------------------------------------------------
86
87// Use 128-bit integers when either `high-precision` or `defi` features are enabled. This is
88// required for the extended 18-decimal wei precision used in DeFi contexts.
89
90#[cfg(feature = "high-precision")]
91pub type PriceRaw = i128;
92
93#[cfg(not(feature = "high-precision"))]
94pub type PriceRaw = i64;
95
96// -----------------------------------------------------------------------------
97
98/// The maximum raw price integer value.
99///
100/// # Safety
101///
102/// `PRICE_MAX` and `FIXED_SCALAR` are cast to `PriceRaw` before multiplying, so the
103/// scaling uses exact integer arithmetic rather than a lossy `f64` product. The result
104/// fits within `PriceRaw`'s range in both high-precision (i128) and standard-precision
105/// (i64) modes, so the multiplication cannot overflow.
106#[unsafe(no_mangle)]
107#[allow(unsafe_code)]
108pub static PRICE_RAW_MAX: PriceRaw = (PRICE_MAX as PriceRaw) * (FIXED_SCALAR as PriceRaw);
109
110/// The minimum raw price integer value.
111///
112/// # Safety
113///
114/// `PRICE_MIN` and `FIXED_SCALAR` are cast to `PriceRaw` before multiplying, so the
115/// scaling uses exact integer arithmetic rather than a lossy `f64` product. The result
116/// fits within `PriceRaw`'s range in both high-precision (i128) and standard-precision
117/// (i64) modes, so the multiplication cannot overflow.
118#[unsafe(no_mangle)]
119#[allow(unsafe_code)]
120pub static PRICE_RAW_MIN: PriceRaw = (PRICE_MIN as PriceRaw) * (FIXED_SCALAR as PriceRaw);
121
122/// The sentinel value for an unset or null price.
123pub const PRICE_UNDEF: PriceRaw = PriceRaw::MAX;
124
125/// The sentinel value for an error or invalid price.
126pub const PRICE_ERROR: PriceRaw = PriceRaw::MIN;
127
128// -----------------------------------------------------------------------------
129// PRICE_MAX
130// -----------------------------------------------------------------------------
131
132/// The maximum valid price value that can be represented.
133#[cfg(feature = "high-precision")]
134pub const PRICE_MAX: f64 = 17_014_118_346_046.0;
135
136#[cfg(not(feature = "high-precision"))]
137/// The maximum valid price value that can be represented.
138pub const PRICE_MAX: f64 = 9_223_372_036.0;
139
140// -----------------------------------------------------------------------------
141// PRICE_MIN
142// -----------------------------------------------------------------------------
143
144#[cfg(feature = "high-precision")]
145/// The minimum valid price value that can be represented.
146pub const PRICE_MIN: f64 = -17_014_118_346_046.0;
147
148#[cfg(not(feature = "high-precision"))]
149/// The minimum valid price value that can be represented.
150pub const PRICE_MIN: f64 = -9_223_372_036.0;
151
152// -----------------------------------------------------------------------------
153
154/// The sentinel `Price` representing an error, returned by C FFI functions that
155/// cannot signal errors through `Option` or `Result`.
156pub const ERROR_PRICE: Price = Price {
157    raw: 0,
158    precision: 255,
159};
160
161/// Represents a price in a market with a specified precision.
162///
163/// The number of decimal places may vary. For certain asset classes, prices may
164/// have negative values. For example, prices for options instruments can be
165/// negative under certain conditions.
166///
167/// Handles up to [`FIXED_PRECISION`] decimals of precision.
168///
169/// - [`PRICE_MAX`] - Maximum representable price value.
170/// - [`PRICE_MIN`] - Minimum representable price value.
171#[repr(C)]
172#[derive(Clone, Copy, Default, Eq)]
173#[cfg_attr(
174    feature = "python",
175    pyo3::pyclass(module = "nautilus_trader.model", frozen, from_py_object)
176)]
177#[cfg_attr(
178    feature = "python",
179    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.model")
180)]
181pub struct Price {
182    pub(crate) raw: PriceRaw,
183    /// The number of decimal places, with a maximum of [`FIXED_PRECISION`].
184    pub precision: u8,
185}
186
187impl Price {
188    /// Creates a new [`Price`] instance with correctness checking.
189    ///
190    /// # Errors
191    ///
192    /// Returns an error if:
193    /// - `value` is invalid outside the representable range [`PRICE_MIN`, `PRICE_MAX`].
194    /// - `precision` is invalid outside the representable range [0, `FIXED_PRECISION`].
195    ///
196    /// # Notes
197    ///
198    /// PyO3 requires a `Result` type for proper error handling and stacktrace printing in Python.
199    pub fn new_checked(value: f64, precision: u8) -> CorrectnessResult<Self> {
200        check_in_range_inclusive_f64(value, PRICE_MIN, PRICE_MAX, "value")?;
201
202        #[cfg(feature = "defi")]
203        if precision > MAX_FLOAT_PRECISION {
204            // Floats are only reliable up to ~16 decimal digits of precision regardless of feature flags
205            return Err(CorrectnessError::PredicateViolation {
206                message: format!(
207                    "`precision` exceeded maximum float precision ({MAX_FLOAT_PRECISION}), use `Price::from_wei()` for wei values instead"
208                ),
209            });
210        }
211
212        check_fixed_precision(precision)?;
213
214        #[cfg(feature = "high-precision")]
215        let raw = f64_to_fixed_i128(value, precision);
216
217        #[cfg(not(feature = "high-precision"))]
218        let raw = f64_to_fixed_i64(value, precision);
219
220        Ok(Self { raw, precision })
221    }
222
223    /// Creates a new [`Price`] instance.
224    ///
225    /// # Panics
226    ///
227    /// Panics if a correctness check fails. See [`Price::new_checked`] for more details.
228    #[must_use]
229    pub fn new(value: f64, precision: u8) -> Self {
230        Self::new_checked(value, precision).expect_display(FAILED)
231    }
232
233    /// Creates a new [`Price`] instance from the given `raw` fixed-point value and `precision`.
234    ///
235    /// # Panics
236    ///
237    /// Panics if a correctness check fails. See [`Price::from_raw_checked`].
238    #[inline]
239    #[must_use]
240    pub fn from_raw(raw: PriceRaw, precision: u8) -> Self {
241        Self::from_raw_checked(raw, precision).expect_display(FAILED)
242    }
243
244    /// Creates a new [`Price`] instance from the given `raw` fixed-point value and `precision`
245    /// with correctness checking.
246    ///
247    /// # Errors
248    ///
249    /// Returns an error if:
250    /// - `precision` exceeds the maximum fixed precision.
251    /// - `precision` is not 0 when `raw` is `PRICE_UNDEF`.
252    /// - `raw` is outside the valid range `[PRICE_RAW_MIN, PRICE_RAW_MAX]`
253    ///   and is not a sentinel value.
254    /// - A non-sentinel `raw` contains fractional digits beyond `precision`.
255    #[inline]
256    pub fn from_raw_checked(raw: PriceRaw, precision: u8) -> CorrectnessResult<Self> {
257        if raw == PRICE_UNDEF && precision != 0 {
258            return Err(CorrectnessError::PredicateViolation {
259                message: "`precision` must be 0 when `raw` is PRICE_UNDEF".to_string(),
260            });
261        }
262
263        if raw != PRICE_ERROR && raw != PRICE_UNDEF && (raw < PRICE_RAW_MIN || raw > PRICE_RAW_MAX)
264        {
265            return Err(CorrectnessError::PredicateViolation {
266                message: format!(
267                    "raw value {raw} outside valid range [{PRICE_RAW_MIN}, {PRICE_RAW_MAX}]"
268                ),
269            });
270        }
271
272        check_fixed_precision(precision)?;
273        if !matches!(raw, PRICE_ERROR | PRICE_UNDEF) {
274            check_fixed_raw(raw, precision).map_err(|e| CorrectnessError::PredicateViolation {
275                message: e.to_string(),
276            })?;
277        }
278
279        Ok(Self { raw, precision })
280    }
281
282    /// Creates a new [`Price`] instance with a value of zero with the given `precision`.
283    ///
284    /// # Panics
285    ///
286    /// Panics if a correctness check fails. See [`Price::new_checked`] for more details.
287    #[must_use]
288    pub fn zero(precision: u8) -> Self {
289        check_fixed_precision(precision).expect_display(FAILED);
290        Self { raw: 0, precision }
291    }
292
293    /// Creates a new [`Price`] instance with the maximum representable value with the given `precision`.
294    ///
295    /// # Panics
296    ///
297    /// Panics if a correctness check fails. See [`Price::new_checked`] for more details.
298    #[must_use]
299    pub fn max(precision: u8) -> Self {
300        check_fixed_precision(precision).expect_display(FAILED);
301        Self {
302            raw: PRICE_RAW_MAX,
303            precision,
304        }
305    }
306
307    /// Creates a new [`Price`] instance with the minimum representable value with the given `precision`.
308    ///
309    /// # Panics
310    ///
311    /// Panics if a correctness check fails. See [`Price::new_checked`] for more details.
312    #[must_use]
313    pub fn min(precision: u8) -> Self {
314        check_fixed_precision(precision).expect_display(FAILED);
315        Self {
316            raw: PRICE_RAW_MIN,
317            precision,
318        }
319    }
320
321    /// Performs a checked addition, returning `None` on raw integer overflow, when the
322    /// result falls outside `[PRICE_RAW_MIN, PRICE_RAW_MAX]`, when either operand is a
323    /// sentinel (`PRICE_UNDEF`, `PRICE_ERROR`, or `ERROR_PRICE`), or when the operands
324    /// have mixed raw scales (one at `FIXED_PRECISION` scale, the other at a defi
325    /// `WEI_PRECISION` scale).
326    ///
327    /// Precision follows the `Add` implementation: uses the maximum precision of both operands.
328    #[must_use]
329    pub fn checked_add(self, rhs: Self) -> Option<Self> {
330        if self.is_sentinel() || rhs.is_sentinel() {
331            return None;
332        }
333
334        if !raw_scales_match(self.precision, rhs.precision) {
335            return None;
336        }
337
338        let raw = self.raw.checked_add(rhs.raw)?;
339        if raw < PRICE_RAW_MIN || raw > PRICE_RAW_MAX {
340            return None;
341        }
342
343        Some(Self {
344            raw,
345            precision: self.precision.max(rhs.precision),
346        })
347    }
348
349    /// Performs a checked subtraction, returning `None` on raw integer underflow, when
350    /// the result falls outside `[PRICE_RAW_MIN, PRICE_RAW_MAX]`, when either operand
351    /// is a sentinel (`PRICE_UNDEF`, `PRICE_ERROR`, or `ERROR_PRICE`), or when the
352    /// operands have mixed raw scales (one at `FIXED_PRECISION` scale, the other at a
353    /// defi `WEI_PRECISION` scale).
354    ///
355    /// Precision follows the `Sub` implementation: uses the maximum precision of both operands.
356    #[must_use]
357    pub fn checked_sub(self, rhs: Self) -> Option<Self> {
358        if self.is_sentinel() || rhs.is_sentinel() {
359            return None;
360        }
361
362        if !raw_scales_match(self.precision, rhs.precision) {
363            return None;
364        }
365
366        let raw = self.raw.checked_sub(rhs.raw)?;
367        if raw < PRICE_RAW_MIN || raw > PRICE_RAW_MAX {
368            return None;
369        }
370
371        Some(Self {
372            raw,
373            precision: self.precision.max(rhs.precision),
374        })
375    }
376
377    #[inline]
378    fn is_sentinel(self) -> bool {
379        // ERROR_PRICE uses precision == u8::MAX as its sentinel marker, distinct from
380        // valid high-precision values (e.g. defi `from_wei` uses precision 18 which is
381        // > FIXED_PRECISION but is not a sentinel).
382        self.raw == PRICE_UNDEF || self.raw == PRICE_ERROR || self.precision == u8::MAX
383    }
384
385    /// Returns `true` if the value of this instance is undefined.
386    #[must_use]
387    pub fn is_undefined(&self) -> bool {
388        self.raw == PRICE_UNDEF
389    }
390
391    /// Returns `true` if the value of this instance is the error sentinel.
392    #[must_use]
393    #[inline]
394    pub fn is_error(&self) -> bool {
395        self.raw == PRICE_ERROR
396    }
397
398    /// Returns the stored fixed-point integer without rescaling.
399    ///
400    /// Use this for serialization and explicit fixed-point conversions. Prefer domain
401    /// operations for calculations; the storage scale can differ from display precision.
402    ///
403    /// Direct field access is restricted to this crate:
404    ///
405    /// ```compile_fail
406    /// use nautilus_model::types::Price;
407    /// let value = Price::from("1");
408    /// let raw = value.raw;
409    /// ```
410    #[must_use]
411    #[inline]
412    pub const fn raw(&self) -> PriceRaw {
413        self.raw
414    }
415
416    /// Returns `true` if the value of this instance is zero.
417    #[must_use]
418    #[inline]
419    pub fn is_zero(&self) -> bool {
420        self.raw == 0
421    }
422
423    /// Returns `true` if the value of this instance is position (> 0).
424    #[must_use]
425    #[inline]
426    pub fn is_positive(&self) -> bool {
427        self.raw != PRICE_UNDEF && self.raw > 0
428    }
429
430    /// Returns `true` if the value of this instance is negative (< 0).
431    #[must_use]
432    #[inline]
433    pub fn is_negative(&self) -> bool {
434        self.raw != PRICE_UNDEF && self.raw < 0
435    }
436
437    #[cfg(feature = "high-precision")]
438    /// Returns the value of this instance as an `f64`.
439    ///
440    /// # Panics
441    ///
442    /// Panics if the `defi` feature is enabled and precision exceeds `MAX_FLOAT_PRECISION` (16).
443    #[must_use]
444    pub fn as_f64(&self) -> f64 {
445        #[cfg(feature = "defi")]
446        assert!(
447            self.precision <= MAX_FLOAT_PRECISION,
448            "Invalid f64 conversion beyond `MAX_FLOAT_PRECISION` (16)"
449        );
450
451        fixed_i128_to_f64(self.raw)
452    }
453
454    #[cfg(not(feature = "high-precision"))]
455    /// Returns the value of this instance as an `f64`.
456    #[must_use]
457    pub fn as_f64(&self) -> f64 {
458        fixed_i64_to_f64(self.raw)
459    }
460
461    /// Returns the value of this instance as a `Decimal`.
462    #[must_use]
463    pub fn as_decimal(&self) -> Decimal {
464        // Scale down the raw value to match the precision
465        let precision_diff = FIXED_PRECISION.saturating_sub(self.precision);
466        let rescaled_raw = self.raw / PriceRaw::pow(10, u32::from(precision_diff));
467        #[allow(
468            clippy::unnecessary_cast,
469            clippy::cast_lossless,
470            reason = "cast is real when PriceRaw is i64, no-op when i128"
471        )]
472        scaled_raw_to_decimal(rescaled_raw as i128, self.precision)
473    }
474
475    /// Returns a formatted string representation of this instance.
476    #[must_use]
477    pub fn to_formatted_string(&self) -> String {
478        format!("{self}").separate_with_underscores()
479    }
480
481    fn raw_at_precision(&self) -> i128 {
482        let precision_diff = FIXED_PRECISION.saturating_sub(self.precision);
483        let rescaled_raw = self.raw / PriceRaw::pow(10, u32::from(precision_diff));
484        Self::raw_as_i128(rescaled_raw)
485    }
486
487    fn raw_as_i128(raw: PriceRaw) -> i128 {
488        #[allow(
489            clippy::useless_conversion,
490            reason = "i128::from is a widening conversion when PriceRaw is i64"
491        )]
492        i128::from(raw)
493    }
494
495    /// Creates a new [`Price`] from a `Decimal` value with specified precision.
496    ///
497    /// Uses pure integer arithmetic on the Decimal's mantissa and scale for fast conversion.
498    /// The value is rounded to the specified precision using banker's rounding (round half to even).
499    ///
500    /// # Errors
501    ///
502    /// Returns an error if:
503    /// - `precision` exceeds [`FIXED_PRECISION`].
504    /// - The decimal value cannot be converted to the raw representation.
505    /// - Overflow occurs during scaling.
506    pub fn from_decimal_dp(decimal: Decimal, precision: u8) -> CorrectnessResult<Self> {
507        let exponent = -(decimal.scale() as i8);
508        let raw_i128 = mantissa_exponent_to_fixed_i128(decimal.mantissa(), exponent, precision)?;
509
510        #[allow(
511            clippy::useless_conversion,
512            reason = "i128 to PriceRaw is real when not high-precision"
513        )]
514        let raw: PriceRaw =
515            raw_i128
516                .try_into()
517                .map_err(|_| CorrectnessError::PredicateViolation {
518                    message: format!(
519                        "Decimal value exceeds PriceRaw range [{PRICE_RAW_MIN}, {PRICE_RAW_MAX}]"
520                    ),
521                })?;
522
523        if !(raw >= PRICE_RAW_MIN && raw <= PRICE_RAW_MAX) {
524            return Err(CorrectnessError::PredicateViolation {
525                message: format!(
526                    "Raw value {raw} outside valid range [{PRICE_RAW_MIN}, {PRICE_RAW_MAX}] for Price"
527                ),
528            });
529        }
530
531        Ok(Self { raw, precision })
532    }
533
534    /// Creates a [`Price`] from a [`Decimal`], inferring precision up to the supported maximum.
535    ///
536    /// Preserves the decimal's scale up to [`FIXED_PRECISION`] (18 with `defi`).
537    /// Rounds excess fractional digits using round half to even.
538    ///
539    /// # Errors
540    ///
541    /// Returns an error if:
542    /// - The decimal value cannot be converted to the raw representation.
543    /// - Overflow occurs during scaling.
544    pub fn from_decimal(decimal: Decimal) -> CorrectnessResult<Self> {
545        let precision = (decimal.scale() as u8).min(MAX_PRECISION);
546        Self::from_decimal_dp(decimal, precision)
547    }
548
549    /// Creates a new [`Price`] from a mantissa/exponent pair using pure integer arithmetic.
550    ///
551    /// The value is `mantissa * 10^exponent`. This avoids all floating-point and Decimal
552    /// operations, making it ideal for exchange data that arrives as mantissa/exponent pairs.
553    ///
554    /// # Panics
555    ///
556    /// Panics if the resulting raw value exceeds [`PRICE_RAW_MAX`] or [`PRICE_RAW_MIN`].
557    #[must_use]
558    pub fn from_mantissa_exponent(mantissa: i64, exponent: i8, precision: u8) -> Self {
559        check_fixed_precision(precision).expect_display(FAILED);
560
561        if mantissa == 0 {
562            return Self { raw: 0, precision };
563        }
564
565        let raw_i128 = mantissa_exponent_to_fixed_i128(i128::from(mantissa), exponent, precision)
566            .expect("Overflow in Price::from_mantissa_exponent");
567
568        #[allow(
569            clippy::useless_conversion,
570            reason = "i128 to PriceRaw is real when not high-precision"
571        )]
572        let raw: PriceRaw = raw_i128
573            .try_into()
574            .expect("Raw value exceeds PriceRaw range in Price::from_mantissa_exponent");
575        assert!(
576            raw >= PRICE_RAW_MIN && raw <= PRICE_RAW_MAX,
577            "`raw` value {raw} exceeded bounds [{PRICE_RAW_MIN}, {PRICE_RAW_MAX}] for Price"
578        );
579
580        Self { raw, precision }
581    }
582
583    /// Checked variant of [`Price::from_mantissa_exponent`].
584    ///
585    /// # Errors
586    ///
587    /// Returns an error if the precision is invalid or the resulting raw value
588    /// exceeds the `PriceRaw` bounds.
589    pub fn from_mantissa_exponent_checked(
590        mantissa: i64,
591        exponent: i8,
592        precision: u8,
593    ) -> CorrectnessResult<Self> {
594        let raw = mantissa_exponent_to_raw_checked::<PriceRaw>(
595            i128::from(mantissa),
596            exponent,
597            precision,
598            "Price::from_mantissa_exponent",
599            "PriceRaw",
600            "Price",
601        )?;
602
603        Self::from_raw_checked(raw, precision)
604    }
605}
606
607impl FromStr for Price {
608    type Err = String;
609
610    fn from_str(value: &str) -> Result<Self, Self::Err> {
611        let clean_value = remove_underscores(value);
612        if clean_value.contains('e') || clean_value.contains('E') {
613            let decimal = Decimal::from_scientific(&clean_value)
614                .map_err(|e| format!("Error parsing `input` string '{value}' as Decimal: {e}"))?;
615            let precision = decimal.scale() as u8;
616            return Self::from_decimal_dp(decimal, precision).map_err(|e| e.to_string());
617        }
618
619        let (mantissa, precision) = parse_decimal_mantissa(&clean_value)
620            .map_err(|e| format!("Error parsing `input` string '{value}' as Decimal: {e}"))?;
621        let exponent = -i8::try_from(precision).map_err(|e| e.to_string())?;
622        let raw = mantissa_exponent_to_raw_checked::<PriceRaw>(
623            mantissa,
624            exponent,
625            precision,
626            "Price::from_str",
627            "PriceRaw",
628            "Price",
629        )
630        .map_err(|e| e.to_string())?;
631        Self::from_raw_checked(raw, precision).map_err(|e| e.to_string())
632    }
633}
634
635impl<T: AsRef<str>> From<T> for Price {
636    fn from(value: T) -> Self {
637        Self::from_str(value.as_ref()).expect(FAILED)
638    }
639}
640
641impl From<Price> for f64 {
642    fn from(price: Price) -> Self {
643        price.as_f64()
644    }
645}
646
647impl From<&Price> for f64 {
648    fn from(price: &Price) -> Self {
649        price.as_f64()
650    }
651}
652
653impl From<Price> for Decimal {
654    fn from(value: Price) -> Self {
655        value.as_decimal()
656    }
657}
658
659impl From<&Price> for Decimal {
660    fn from(value: &Price) -> Self {
661        value.as_decimal()
662    }
663}
664
665impl Hash for Price {
666    fn hash<H: Hasher>(&self, state: &mut H) {
667        self.raw.signum().hash(state);
668        if self.raw == PRICE_ERROR {
669            self.raw.hash(state);
670        } else {
671            canonical_raw(self.raw.unsigned_abs(), self.precision).hash(state);
672        }
673    }
674}
675
676impl PartialEq for Price {
677    #[inline]
678    fn eq(&self, other: &Self) -> bool {
679        self.cmp(other) == Ordering::Equal
680    }
681}
682
683impl PartialOrd for Price {
684    #[inline]
685    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
686        Some(self.cmp(other))
687    }
688}
689
690impl Ord for Price {
691    #[inline]
692    fn cmp(&self, other: &Self) -> Ordering {
693        // PRICE_ERROR is a precision-independent sentinel below every valid price.
694        if self.raw == PRICE_ERROR || other.raw == PRICE_ERROR {
695            return self.raw.cmp(&other.raw);
696        }
697
698        #[cfg(feature = "defi")]
699        {
700            compare_raw_signed(self.raw, self.precision, other.raw, other.precision)
701        }
702
703        #[cfg(not(feature = "defi"))]
704        {
705            self.raw.cmp(&other.raw)
706        }
707    }
708}
709
710impl Deref for Price {
711    type Target = PriceRaw;
712
713    fn deref(&self) -> &Self::Target {
714        &self.raw
715    }
716}
717
718impl Neg for Price {
719    type Output = Self;
720    fn neg(self) -> Self::Output {
721        // Preserve sentinel values (negating PRICE_ERROR would also overflow)
722        if self.raw == PRICE_ERROR || self.raw == PRICE_UNDEF {
723            return self;
724        }
725        Self {
726            raw: -self.raw,
727            precision: self.precision,
728        }
729    }
730}
731
732impl Add for Price {
733    type Output = Self;
734    #[inline]
735    fn add(self, rhs: Self) -> Self::Output {
736        assert!(
737            raw_scales_match(self.precision, rhs.precision),
738            "Cannot add `Price` values with mismatched decimal scales"
739        );
740        Self {
741            raw: self
742                .raw
743                .checked_add(rhs.raw)
744                .expect("Overflow occurred when adding `Price`"),
745            precision: self.precision.max(rhs.precision),
746        }
747    }
748}
749
750impl Sub for Price {
751    type Output = Self;
752    #[inline]
753    fn sub(self, rhs: Self) -> Self::Output {
754        assert!(
755            raw_scales_match(self.precision, rhs.precision),
756            "Cannot subtract `Price` values with mismatched decimal scales"
757        );
758        Self {
759            raw: self
760                .raw
761                .checked_sub(rhs.raw)
762                .expect("Underflow occurred when subtracting `Price`"),
763            precision: self.precision.max(rhs.precision),
764        }
765    }
766}
767
768impl Add<Decimal> for Price {
769    type Output = Decimal;
770    fn add(self, rhs: Decimal) -> Self::Output {
771        self.as_decimal() + rhs
772    }
773}
774
775impl Sub<Decimal> for Price {
776    type Output = Decimal;
777    fn sub(self, rhs: Decimal) -> Self::Output {
778        self.as_decimal() - rhs
779    }
780}
781
782impl Mul<Decimal> for Price {
783    type Output = Decimal;
784    fn mul(self, rhs: Decimal) -> Self::Output {
785        self.as_decimal() * rhs
786    }
787}
788
789impl Div<Decimal> for Price {
790    type Output = Decimal;
791    fn div(self, rhs: Decimal) -> Self::Output {
792        self.as_decimal() / rhs
793    }
794}
795
796impl Add<f64> for Price {
797    type Output = f64;
798    fn add(self, rhs: f64) -> Self::Output {
799        self.as_f64() + rhs
800    }
801}
802
803impl Sub<f64> for Price {
804    type Output = f64;
805    fn sub(self, rhs: f64) -> Self::Output {
806        self.as_f64() - rhs
807    }
808}
809
810impl Mul<f64> for Price {
811    type Output = f64;
812    fn mul(self, rhs: f64) -> Self::Output {
813        self.as_f64() * rhs
814    }
815}
816
817impl Div<f64> for Price {
818    type Output = f64;
819    fn div(self, rhs: f64) -> Self::Output {
820        self.as_f64() / rhs
821    }
822}
823
824impl Debug for Price {
825    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
826        write!(f, "{}({self})", stringify!(Price))
827    }
828}
829
830impl Display for Price {
831    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
832        if self.precision == ERROR_PRICE.precision {
833            return write!(f, "{}", self.raw);
834        }
835
836        write!(
837            f,
838            "{}",
839            format_scaled_i128(self.raw_at_precision(), self.precision),
840        )
841    }
842}
843
844impl Serialize for Price {
845    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
846    where
847        S: serde::Serializer,
848    {
849        serializer.serialize_str(&self.to_string())
850    }
851}
852
853impl<'de> Deserialize<'de> for Price {
854    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
855    where
856        D: Deserializer<'de>,
857    {
858        let StringInput(price_str) = Deserialize::deserialize(deserializer)?;
859        Self::from_str(price_str.as_ref()).map_err(serde::de::Error::custom)
860    }
861}
862
863/// Checks the price `value` is positive.
864///
865/// # Errors
866///
867/// Returns an error if `value` is `PRICE_UNDEF` or not positive.
868pub fn check_positive_price(value: Price, param: &str) -> CorrectnessResult<()> {
869    if value.raw == PRICE_UNDEF {
870        return Err(CorrectnessError::InvalidValue {
871            param: param.to_string(),
872            value: "PRICE_UNDEF".to_string(),
873            type_name: "`Price`",
874        });
875    }
876
877    if !value.is_positive() {
878        return Err(CorrectnessError::NotPositive {
879            param: param.to_string(),
880            value: value.to_string(),
881            type_name: "`Price`",
882        });
883    }
884    Ok(())
885}
886
887#[cfg(feature = "high-precision")]
888/// The raw i64 price has already been scaled by 10^9. Further scale it by the difference to
889/// `FIXED_PRECISION` to make it high/defi-precision raw price.
890#[must_use]
891pub fn decode_raw_price_i64(value: i64) -> PriceRaw {
892    PriceRaw::from(value) * PRECISION_DIFF_SCALAR as PriceRaw
893}
894
895#[cfg(not(feature = "high-precision"))]
896#[must_use]
897pub fn decode_raw_price_i64(value: i64) -> PriceRaw {
898    value
899}
900
901#[cfg(test)]
902mod tests {
903    use nautilus_core::{approx_eq, correctness::CorrectnessError};
904    use rstest::rstest;
905    use rust_decimal_macros::dec;
906
907    use super::*;
908
909    #[cfg(feature = "high-precision")]
910    #[rstest]
911    #[case(PRICE_RAW_MAX, dec!(17014118346046))]
912    #[case(PRICE_RAW_MIN, dec!(-17014118346046))]
913    fn test_as_decimal_above_decimal_mantissa(#[case] raw: PriceRaw, #[case] expected: Decimal) {
914        // Regression: a precision-16 price above roughly 7.92e12 rescales to a raw value beyond
915        // `Decimal`'s 96-bit mantissa, which used to panic during conversion.
916        let price = Price::from_raw(raw, 16);
917
918        assert_eq!(price.as_decimal(), expected);
919    }
920
921    #[rstest]
922    fn test_error_sentinel_formatting() {
923        assert_eq!(ERROR_PRICE.to_string(), "0");
924        assert_eq!(format!("{ERROR_PRICE:?}"), "Price(0)");
925        assert_eq!(ERROR_PRICE.to_formatted_string(), "0");
926    }
927
928    #[rstest]
929    fn test_error_sentinel_comparisons_preserve_raw_zero_semantics() {
930        let zero = Price::zero(FIXED_PRECISION);
931        let positive = Price::from_mantissa_exponent(1, 0, FIXED_PRECISION);
932        let negative = -positive;
933
934        assert_eq!(ERROR_PRICE, zero);
935        assert_eq!(ERROR_PRICE.cmp(&zero), Ordering::Equal);
936        assert_eq!(ERROR_PRICE.cmp(&positive), Ordering::Less);
937        assert_eq!(negative.cmp(&ERROR_PRICE), Ordering::Less);
938    }
939
940    #[rstest]
941    fn test_extreme_prices_round_trip_through_raw() {
942        // Regression: a lossy `f64` scalar previously left `PRICE_RAW_MAX`/`PRICE_RAW_MIN`
943        // beyond the raw produced by `new` at the bounds, causing spurious panics and errors.
944        let max = Price::new(PRICE_MAX, 0);
945        let min = Price::new(PRICE_MIN, 0);
946
947        assert_eq!(max.raw, PRICE_RAW_MAX);
948        assert_eq!(min.raw, PRICE_RAW_MIN);
949        assert!(Price::from_raw_checked(max.raw, 0).is_ok());
950        assert!(Price::from_raw_checked(min.raw, 0).is_ok());
951    }
952
953    #[rstest]
954    #[cfg(all(not(feature = "defi"), not(feature = "high-precision")))]
955    #[should_panic(expected = "`precision` exceeded maximum `FIXED_PRECISION` (9), was 50")]
956    fn test_invalid_precision_new() {
957        // Precision exceeds float precision limit
958        let _ = Price::new(1.0, 50);
959    }
960
961    #[rstest]
962    #[cfg(all(not(feature = "defi"), feature = "high-precision"))]
963    #[should_panic(expected = "`precision` exceeded maximum `FIXED_PRECISION` (16), was 50")]
964    fn test_invalid_precision_new() {
965        // Precision exceeds float precision limit
966        let _ = Price::new(1.0, 50);
967    }
968
969    #[rstest]
970    #[cfg(not(feature = "defi"))]
971    #[should_panic(expected = "Condition failed: `precision` exceeded maximum `FIXED_PRECISION`")]
972    fn test_invalid_precision_from_raw() {
973        // Precision out of range for fixed
974        let _ = Price::from_raw(1, FIXED_PRECISION + 1);
975    }
976
977    #[rstest]
978    #[cfg(not(feature = "defi"))]
979    #[should_panic(expected = "Condition failed: `precision` exceeded maximum `FIXED_PRECISION`")]
980    fn test_invalid_precision_max() {
981        // Precision out of range for fixed
982        let _ = Price::max(FIXED_PRECISION + 1);
983    }
984
985    #[rstest]
986    #[cfg(not(feature = "defi"))]
987    #[should_panic(expected = "Condition failed: `precision` exceeded maximum `FIXED_PRECISION`")]
988    fn test_invalid_precision_min() {
989        // Precision out of range for fixed
990        let _ = Price::min(FIXED_PRECISION + 1);
991    }
992
993    #[rstest]
994    #[cfg(not(feature = "defi"))]
995    #[should_panic(expected = "Condition failed: `precision` exceeded maximum `FIXED_PRECISION`")]
996    fn test_invalid_precision_zero() {
997        // Precision out of range for fixed
998        let _ = Price::zero(FIXED_PRECISION + 1);
999    }
1000
1001    #[rstest]
1002    #[should_panic(expected = "Condition failed: invalid f64 for 'value' not in range")]
1003    fn test_max_value_exceeded() {
1004        let _ = Price::new(PRICE_MAX + 0.1, FIXED_PRECISION);
1005    }
1006
1007    #[rstest]
1008    #[should_panic(expected = "Condition failed: invalid f64 for 'value' not in range")]
1009    fn test_min_value_exceeded() {
1010        let _ = Price::new(PRICE_MIN - 0.1, FIXED_PRECISION);
1011    }
1012
1013    #[rstest]
1014    fn test_is_positive_ok() {
1015        // A normal, non-zero price should be positive.
1016        let price = Price::new(42.0, 2);
1017        assert!(price.is_positive());
1018
1019        // `check_positive_price` should accept it without error.
1020        check_positive_price(price, "price").unwrap();
1021    }
1022
1023    #[rstest]
1024    fn test_is_positive_rejects_non_positive() {
1025        // Zero is NOT positive.
1026        let zero = Price::zero(2);
1027        let error = check_positive_price(zero, "price").unwrap_err();
1028
1029        assert_eq!(
1030            error,
1031            CorrectnessError::NotPositive {
1032                param: "price".to_string(),
1033                value: "0.00".to_string(),
1034                type_name: "`Price`",
1035            }
1036        );
1037        assert_eq!(
1038            error.to_string(),
1039            "invalid `Price` for 'price' not positive, was 0.00"
1040        );
1041    }
1042
1043    #[rstest]
1044    fn test_is_positive_rejects_undefined() {
1045        // PRICE_UNDEF must also be rejected.
1046        let undef = Price::from_raw(PRICE_UNDEF, 0);
1047        let error = check_positive_price(undef, "price").unwrap_err();
1048
1049        assert_eq!(
1050            error,
1051            CorrectnessError::InvalidValue {
1052                param: "price".to_string(),
1053                value: "PRICE_UNDEF".to_string(),
1054                type_name: "`Price`",
1055            }
1056        );
1057        assert_eq!(
1058            error.to_string(),
1059            "invalid `Price` for 'price', was PRICE_UNDEF"
1060        );
1061    }
1062
1063    #[rstest]
1064    fn test_construction() {
1065        let price = Price::new_checked(1.23456, 4);
1066        assert!(price.is_ok());
1067        let price = price.unwrap();
1068        assert_eq!(price.precision, 4);
1069        assert!(approx_eq!(f64, price.as_f64(), 1.23456, epsilon = 0.0001));
1070    }
1071
1072    #[rstest]
1073    fn test_negative_price_in_range() {
1074        // Use max fixed precision which varies based on feature flags
1075        let neg_price = Price::new(PRICE_MIN / 2.0, FIXED_PRECISION);
1076        assert!(neg_price.raw < 0);
1077    }
1078
1079    #[rstest]
1080    fn test_new_checked() {
1081        // Use max fixed precision which varies based on feature flags
1082        assert!(Price::new_checked(1.0, FIXED_PRECISION).is_ok());
1083        assert!(Price::new_checked(f64::NAN, FIXED_PRECISION).is_err());
1084        assert!(Price::new_checked(f64::INFINITY, FIXED_PRECISION).is_err());
1085    }
1086
1087    #[rstest]
1088    fn test_new_checked_returns_typed_error_with_stable_display() {
1089        let error = Price::new_checked(PRICE_MAX + 1.0, FIXED_PRECISION).unwrap_err();
1090
1091        assert!(matches!(error, CorrectnessError::OutOfRange { .. }));
1092        assert_eq!(
1093            error.to_string(),
1094            format!(
1095                "invalid f64 for 'value' not in range [{PRICE_MIN}, {PRICE_MAX}], was {}",
1096                PRICE_MAX + 1.0
1097            )
1098        );
1099    }
1100
1101    #[rstest]
1102    fn test_from_raw_checked_returns_typed_error_with_stable_display() {
1103        let error = Price::from_raw_checked(PRICE_UNDEF, 3).unwrap_err();
1104
1105        assert_eq!(
1106            error,
1107            CorrectnessError::PredicateViolation {
1108                message: "`precision` must be 0 when `raw` is PRICE_UNDEF".to_string(),
1109            }
1110        );
1111        assert_eq!(
1112            error.to_string(),
1113            "`precision` must be 0 when `raw` is PRICE_UNDEF"
1114        );
1115    }
1116
1117    #[rstest]
1118    #[case::below_minimum(PRICE_RAW_MIN - 1)]
1119    #[case::above_maximum(PRICE_RAW_MAX + 1)]
1120    fn test_from_raw_checked_rejects_out_of_range_value(#[case] raw: PriceRaw) {
1121        let error = Price::from_raw_checked(raw, 0).unwrap_err();
1122
1123        assert_eq!(
1124            error,
1125            CorrectnessError::PredicateViolation {
1126                message: format!(
1127                    "raw value {raw} outside valid range [{PRICE_RAW_MIN}, {PRICE_RAW_MAX}]"
1128                ),
1129            }
1130        );
1131    }
1132
1133    #[rstest]
1134    #[should_panic(expected = "outside valid range")]
1135    fn test_from_raw_out_of_range_panics() {
1136        let _ = Price::from_raw(PRICE_RAW_MAX + 1, 0);
1137    }
1138
1139    #[rstest]
1140    fn test_from_raw() {
1141        let raw = 100 * FIXED_SCALAR as PriceRaw;
1142        let price = Price::from_raw(raw, 2);
1143        assert_eq!(price.raw, raw);
1144        assert_eq!(price.precision, 2);
1145    }
1146
1147    #[rstest]
1148    #[case(1, 0)]
1149    #[case(-1, 0)]
1150    #[case(11, FIXED_PRECISION - 1)]
1151    #[case(-11, FIXED_PRECISION - 1)]
1152    fn test_from_raw_checked_rejects_spurious_digits(#[case] raw: PriceRaw, #[case] precision: u8) {
1153        let scale = PriceRaw::pow(10, u32::from(FIXED_PRECISION - precision));
1154        let remainder = raw % scale;
1155        let error = Price::from_raw_checked(raw, precision).unwrap_err();
1156
1157        assert_eq!(
1158            error,
1159            CorrectnessError::PredicateViolation {
1160                message: format!(
1161                    "Invalid fixed-point raw value {raw} for precision {precision}: \
1162                 remainder {remainder} when divided by scale {scale}. \
1163                 Raw value should be a multiple of {scale}. \
1164                 This indicates data corruption or incorrect precision/scaling upstream"
1165                ),
1166            }
1167        );
1168    }
1169
1170    #[rstest]
1171    #[should_panic(expected = "Condition failed: Invalid fixed-point raw value")]
1172    fn test_from_raw_rejects_spurious_digits() {
1173        let _ = Price::from_raw(1, 0);
1174    }
1175
1176    #[rstest]
1177    #[case(0, 0)]
1178    #[case(0, FIXED_PRECISION)]
1179    #[case(10, FIXED_PRECISION - 1)]
1180    #[case(-10, FIXED_PRECISION - 1)]
1181    #[case(1, FIXED_PRECISION)]
1182    #[case(-1, FIXED_PRECISION)]
1183    #[case(PRICE_UNDEF, 0)]
1184    #[case(PRICE_ERROR, 2)]
1185    fn test_from_raw_checked_preserves_aligned_values(
1186        #[case] raw: PriceRaw,
1187        #[case] precision: u8,
1188    ) {
1189        let price = Price::from_raw_checked(raw, precision).unwrap();
1190
1191        assert_eq!(price.raw(), raw);
1192        assert_eq!(price.precision, precision);
1193        assert_eq!(Price::from_raw(raw, precision), price);
1194    }
1195
1196    #[rstest]
1197    fn test_zero_constructor() {
1198        let zero = Price::zero(3);
1199        assert!(zero.is_zero());
1200        assert_eq!(zero.precision, 3);
1201    }
1202
1203    #[rstest]
1204    fn test_max_constructor() {
1205        let max = Price::max(4);
1206        assert_eq!(max.raw, PRICE_RAW_MAX);
1207        assert_eq!(max.precision, 4);
1208    }
1209
1210    #[rstest]
1211    fn test_min_constructor() {
1212        let min = Price::min(4);
1213        assert_eq!(min.raw, PRICE_RAW_MIN);
1214        assert_eq!(min.precision, 4);
1215    }
1216
1217    #[rstest]
1218    fn test_nan_validation() {
1219        assert!(Price::new_checked(f64::NAN, FIXED_PRECISION).is_err());
1220    }
1221
1222    #[rstest]
1223    fn test_infinity_validation() {
1224        assert!(Price::new_checked(f64::INFINITY, FIXED_PRECISION).is_err());
1225        assert!(Price::new_checked(f64::NEG_INFINITY, FIXED_PRECISION).is_err());
1226    }
1227
1228    #[rstest]
1229    fn test_special_values() {
1230        let zero = Price::zero(5);
1231        assert!(zero.is_zero());
1232        assert_eq!(zero.to_string(), "0.00000");
1233
1234        let undef = Price::from_raw(PRICE_UNDEF, 0);
1235        assert!(undef.is_undefined());
1236
1237        let error = ERROR_PRICE;
1238        assert_eq!(error.precision, 255);
1239    }
1240
1241    #[rstest]
1242    fn test_string_parsing() {
1243        let price: Price = "123.456".into();
1244        assert_eq!(price.precision, 3);
1245        assert_eq!(price, Price::from("123.456"));
1246    }
1247
1248    #[rstest]
1249    #[case(PRICE_RAW_MIN)]
1250    #[case(PRICE_RAW_MAX)]
1251    fn test_from_str_raw_limits(#[case] raw: PriceRaw) {
1252        let original = Price::from_raw(raw, FIXED_PRECISION);
1253        let decoded = original.to_string().parse::<Price>().unwrap();
1254
1255        assert_eq!(decoded.raw, raw);
1256        assert_eq!(decoded.precision, FIXED_PRECISION);
1257    }
1258
1259    #[rstest]
1260    fn test_negative_price_from_str() {
1261        let price: Price = "-123.45".parse().unwrap();
1262        assert_eq!(price.precision, 2);
1263        assert!(approx_eq!(f64, price.as_f64(), -123.45, epsilon = 1e-9));
1264    }
1265
1266    #[rstest]
1267    fn test_string_parsing_errors() {
1268        assert!(Price::from_str("invalid").is_err());
1269    }
1270
1271    #[rstest]
1272    #[case("1e7", 0, 10_000_000.0)]
1273    #[case("1.5e3", 0, 1_500.0)]
1274    #[case("1.234e-2", 5, 0.01234)]
1275    #[case("5E-3", 3, 0.005)]
1276    fn test_from_str_scientific_notation(
1277        #[case] input: &str,
1278        #[case] expected_precision: u8,
1279        #[case] expected_value: f64,
1280    ) {
1281        let price = Price::from_str(input).unwrap();
1282        assert_eq!(price.precision, expected_precision);
1283        assert!(approx_eq!(
1284            f64,
1285            price.as_f64(),
1286            expected_value,
1287            epsilon = 1e-10
1288        ));
1289    }
1290
1291    #[rstest]
1292    #[case("1_234.56", 2, 1234.56)]
1293    #[case("1000000", 0, 1_000_000.0)]
1294    #[case("99_999.999_99", 5, 99_999.999_99)]
1295    fn test_from_str_with_underscores(
1296        #[case] input: &str,
1297        #[case] expected_precision: u8,
1298        #[case] expected_value: f64,
1299    ) {
1300        let price = Price::from_str(input).unwrap();
1301        assert_eq!(price.precision, expected_precision);
1302        assert!(approx_eq!(
1303            f64,
1304            price.as_f64(),
1305            expected_value,
1306            epsilon = 1e-10
1307        ));
1308    }
1309
1310    #[rstest]
1311    fn test_from_decimal_dp_preservation() {
1312        // Test that decimal conversion preserves exact values
1313        let decimal = dec!(123.456789);
1314        let price = Price::from_decimal_dp(decimal, 6).unwrap();
1315        assert_eq!(price.precision, 6);
1316        assert!(approx_eq!(
1317            f64,
1318            price.as_f64(),
1319            123.456_789,
1320            epsilon = 1e-10
1321        ));
1322
1323        // Verify raw value is exact
1324        let expected_raw = 123_456_789 * 10_i64.pow(u32::from(FIXED_PRECISION - 6));
1325        assert_eq!(price.raw, PriceRaw::from(expected_raw));
1326    }
1327
1328    #[rstest]
1329    fn test_from_decimal_dp_rounding() {
1330        // Test banker's rounding (round half to even)
1331        let decimal = dec!(1.005);
1332        let price = Price::from_decimal_dp(decimal, 2).unwrap();
1333        assert_eq!(price.as_f64(), 1.0); // 1.005 rounds to 1.00 (even)
1334
1335        let decimal = dec!(1.015);
1336        let price = Price::from_decimal_dp(decimal, 2).unwrap();
1337        assert_eq!(price.as_f64(), 1.02); // 1.015 rounds to 1.02 (even)
1338    }
1339
1340    #[rstest]
1341    fn test_from_decimal_infers_precision() {
1342        // Test that precision is inferred from decimal's scale
1343        let decimal = dec!(123.456);
1344        let price = Price::from_decimal(decimal).unwrap();
1345        assert_eq!(price.precision, 3);
1346        assert!(approx_eq!(f64, price.as_f64(), 123.456, epsilon = 1e-10));
1347
1348        // Test with integer (precision 0)
1349        let decimal = dec!(100);
1350        let price = Price::from_decimal(decimal).unwrap();
1351        assert_eq!(price.precision, 0);
1352        assert_eq!(price.as_f64(), 100.0);
1353
1354        // Test with high precision
1355        let decimal = dec!(1.23456789);
1356        let price = Price::from_decimal(decimal).unwrap();
1357        assert_eq!(price.precision, 8);
1358        assert!(approx_eq!(
1359            f64,
1360            price.as_f64(),
1361            1.234_567_89,
1362            epsilon = 1e-10
1363        ));
1364    }
1365
1366    #[rstest]
1367    fn test_from_decimal_trailing_zeros() {
1368        // Decimal preserves trailing zeros in scale
1369        let decimal = dec!(1.230);
1370        assert_eq!(decimal.scale(), 3); // Has 3 decimal places
1371
1372        // from_decimal infers precision from scale (includes trailing zeros)
1373        let price = Price::from_decimal(decimal).unwrap();
1374        assert_eq!(price.precision, 3);
1375        assert!(approx_eq!(f64, price.as_f64(), 1.23, epsilon = 1e-10));
1376
1377        // Normalized removes trailing zeros
1378        let normalized = decimal.normalize();
1379        assert_eq!(normalized.scale(), 2);
1380        let price_normalized = Price::from_decimal(normalized).unwrap();
1381        assert_eq!(price_normalized.precision, 2);
1382    }
1383
1384    #[rstest]
1385    #[case("1.00", 2)]
1386    #[case("1.0", 1)]
1387    #[case("1.000", 3)]
1388    #[case("100.00", 2)]
1389    #[case("0.10", 2)]
1390    #[case("0.100", 3)]
1391    fn test_from_str_preserves_trailing_zeros(#[case] input: &str, #[case] expected_precision: u8) {
1392        let price = Price::from_str(input).unwrap();
1393        assert_eq!(price.precision, expected_precision);
1394    }
1395
1396    #[rstest]
1397    #[case(0, 0)]
1398    #[case(1, 0)]
1399    #[case(5, 0)]
1400    #[case(10, 1)]
1401    #[case(14, 1)]
1402    #[case(15, 2)]
1403    #[case(16, 2)]
1404    #[case(25, 2)]
1405    #[case(35, 4)]
1406    #[case(-1, 0)]
1407    #[case(-5, 0)]
1408    #[case(-14, -1)]
1409    #[case(-15, -2)]
1410    #[case(-16, -2)]
1411    #[case(-25, -2)]
1412    #[case(-35, -4)]
1413    fn test_from_decimal_rounds_excess_precision(
1414        #[case] mantissa: i128,
1415        #[case] expected_raw: PriceRaw,
1416        #[values(1, 10)] excess: u32,
1417    ) {
1418        let decimal = Decimal::from_i128_with_scale(
1419            mantissa * 10_i128.pow(excess - 1),
1420            u32::from(MAX_PRECISION) + excess,
1421        );
1422
1423        let price = Price::from_decimal(decimal).unwrap();
1424
1425        assert_eq!(
1426            (price.raw(), price.precision),
1427            (expected_raw, MAX_PRECISION)
1428        );
1429    }
1430
1431    #[rstest]
1432    fn test_from_decimal_rounding_carries_into_integer() {
1433        let precision = u32::from(MAX_PRECISION);
1434        let decimal = Decimal::from_i128_with_scale(10_i128.pow(precision + 1) - 5, precision + 1);
1435
1436        let price = Price::from_decimal(decimal).unwrap();
1437
1438        assert_eq!(price.raw(), PriceRaw::pow(10, precision));
1439        assert_eq!(price.precision, MAX_PRECISION);
1440    }
1441
1442    #[rstest]
1443    fn test_from_decimal_rejects_overflow() {
1444        let error = Price::from_decimal(Decimal::MAX).unwrap_err();
1445
1446        let expected = if cfg!(feature = "high-precision") {
1447            "Overflow when scaling mantissa to fixed precision".to_string()
1448        } else {
1449            format!("Decimal value exceeds PriceRaw range [{PRICE_RAW_MIN}, {PRICE_RAW_MAX}]")
1450        };
1451
1452        assert_eq!(error.to_string(), expected);
1453    }
1454
1455    #[rstest]
1456    fn test_from_decimal_dp_rejects_raw_between_price_and_raw_bounds() {
1457        let at_max = Decimal::try_from(PRICE_MAX).unwrap();
1458        let above_max = at_max + dec!(0.5);
1459        let expected_raw = PRICE_RAW_MAX + 5 * PriceRaw::pow(10, u32::from(FIXED_PRECISION - 1));
1460
1461        let error = Price::from_decimal_dp(above_max, 1).unwrap_err();
1462
1463        assert_eq!(
1464            error.to_string(),
1465            format!(
1466                "Raw value {expected_raw} outside valid range [{PRICE_RAW_MIN}, {PRICE_RAW_MAX}] for Price"
1467            )
1468        );
1469        assert_eq!(
1470            Price::from_decimal_dp(at_max, 1).unwrap().raw,
1471            PRICE_RAW_MAX
1472        );
1473    }
1474
1475    #[rstest]
1476    fn test_from_decimal_dp_out_of_range_returns_typed_error_with_stable_display() {
1477        let huge = Decimal::from_str("99999999999999999999.99").unwrap();
1478        let error = Price::from_decimal_dp(huge, 2).unwrap_err();
1479        match error {
1480            CorrectnessError::PredicateViolation { ref message } => {
1481                assert!(
1482                    message.contains("PriceRaw range") || message.contains("for Price"),
1483                    "unexpected message: {message:?}",
1484                );
1485            }
1486            _ => panic!("expected PredicateViolation, was {error:?}"),
1487        }
1488    }
1489
1490    #[rstest]
1491    fn test_from_decimal_negative_price() {
1492        // Negative prices are valid for Price
1493        let decimal = dec!(-123.45);
1494        let price = Price::from_decimal(decimal).unwrap();
1495        assert_eq!(price.precision, 2);
1496        assert!(approx_eq!(f64, price.as_f64(), -123.45, epsilon = 1e-10));
1497        assert!(price.raw < 0);
1498    }
1499
1500    #[rstest]
1501    fn test_string_formatting() {
1502        assert_eq!(format!("{}", Price::new(1234.5678, 4)), "1234.5678");
1503        assert_eq!(
1504            format!("{:?}", Price::new(1234.5678, 4)),
1505            "Price(1234.5678)"
1506        );
1507        assert_eq!(Price::new(1234.5678, 4).to_formatted_string(), "1_234.5678");
1508    }
1509
1510    #[rstest]
1511    #[case(1234.5678, 4, "Price(1234.5678)", "1234.5678")] // Normal precision
1512    #[case(123.456_789_012_345, 8, "Price(123.45678901)", "123.45678901")] // At max normal precision
1513    #[cfg_attr(
1514        feature = "defi",
1515        case(
1516            2_000_000_000_000_000_000.0,
1517            18,
1518            "Price(2.000000000000000000)",
1519            "2.000000000000000000"
1520        )
1521    )] // High precision
1522    fn test_string_formatting_precision_handling(
1523        #[case] value: f64,
1524        #[case] precision: u8,
1525        #[case] expected_debug: &str,
1526        #[case] expected_display: &str,
1527    ) {
1528        let price = if precision > crate::types::fixed::MAX_FLOAT_PRECISION {
1529            Price::from_raw(value as PriceRaw, precision)
1530        } else {
1531            Price::new(value, precision)
1532        };
1533
1534        assert_eq!(format!("{price:?}"), expected_debug);
1535        assert_eq!(format!("{price}"), expected_display);
1536        assert_eq!(
1537            price.to_formatted_string().replace('_', ""),
1538            expected_display
1539        );
1540    }
1541
1542    #[rstest]
1543    fn test_decimal_conversions() {
1544        let price = Price::new(123.456, 3);
1545        assert_eq!(price.as_decimal(), dec!(123.456));
1546
1547        let price = Price::new(0.000_001, 6);
1548        assert_eq!(price.as_decimal(), dec!(0.000001));
1549    }
1550
1551    #[rstest]
1552    #[case(PRICE_ERROR, true)]
1553    #[case(PRICE_UNDEF, false)]
1554    #[case(-(FIXED_SCALAR as PriceRaw), false)]
1555    #[case(0, false)]
1556    #[case(FIXED_SCALAR as PriceRaw, false)]
1557    fn test_is_error(#[case] raw: PriceRaw, #[case] expected: bool) {
1558        let price = Price::from_raw(raw, 0);
1559        assert_eq!(price.is_error(), expected);
1560    }
1561
1562    #[rstest]
1563    fn test_basic_arithmetic() {
1564        let p1 = Price::new(10.5, 2);
1565        let p2 = Price::new(5.25, 2);
1566        assert_eq!(p1 + p2, Price::from("15.75"));
1567        assert_eq!(p1 - p2, Price::from("5.25"));
1568        assert_eq!(-p1, Price::from("-10.5"));
1569    }
1570
1571    #[rstest]
1572    #[case::error(PRICE_ERROR)]
1573    #[case::undefined(PRICE_UNDEF)]
1574    fn test_neg_preserves_sentinel(#[case] raw: PriceRaw) {
1575        let price = Price::from_raw(raw, 0);
1576
1577        assert_eq!(-price, price);
1578    }
1579
1580    #[rstest]
1581    fn test_price_checked_add_within_bounds() {
1582        let a = Price::new(10.0, 2);
1583        let b = Price::new(5.0, 2);
1584        assert_eq!(a.checked_add(b), Some(Price::new(15.0, 2)));
1585
1586        let neg = Price::new(-3.0, 2);
1587        assert_eq!(a.checked_add(neg), Some(Price::new(7.0, 2)));
1588    }
1589
1590    #[rstest]
1591    fn test_price_checked_add_above_max_returns_none() {
1592        let near_max = Price::from_raw(PRICE_RAW_MAX, 0);
1593        let one = Price::new(1.0, 0);
1594        assert_eq!(near_max.checked_add(one), None);
1595    }
1596
1597    #[rstest]
1598    fn test_price_checked_sub_within_bounds() {
1599        let a = Price::new(10.0, 2);
1600        let b = Price::new(3.0, 2);
1601        assert_eq!(a.checked_sub(b), Some(Price::new(7.0, 2)));
1602        assert_eq!(b.checked_sub(a), Some(Price::new(-7.0, 2)));
1603    }
1604
1605    #[rstest]
1606    fn test_price_checked_sub_below_min_returns_none() {
1607        let near_min = Price::from_raw(PRICE_RAW_MIN, 0);
1608        let one = Price::new(1.0, 0);
1609        assert_eq!(near_min.checked_sub(one), None);
1610    }
1611
1612    #[rstest]
1613    fn test_price_checked_arith_uses_max_precision() {
1614        let a = Price::new(10.5, 1);
1615        let b = Price::new(5.25, 2);
1616        let sum = a.checked_add(b).unwrap();
1617        assert_eq!(sum.precision, 2);
1618        assert_eq!(sum.as_f64(), 15.75);
1619    }
1620
1621    #[rstest]
1622    fn test_price_checked_add_rejects_sentinel_undef() {
1623        let undef = Price::from_raw(PRICE_UNDEF, 0);
1624        let one = Price::new(1.0, 0);
1625        assert_eq!(undef.checked_add(one), None);
1626        assert_eq!(one.checked_add(undef), None);
1627    }
1628
1629    #[rstest]
1630    fn test_price_checked_sub_rejects_sentinel_undef() {
1631        let undef = Price::from_raw(PRICE_UNDEF, 0);
1632        let neg_one = Price::new(-1.0, 0);
1633        assert_eq!(undef.checked_sub(neg_one), None);
1634    }
1635
1636    #[rstest]
1637    fn test_price_is_zero() {
1638        assert!(!Price::new(1.5, 2).is_zero());
1639        assert!(Price::new(0.0, 2).is_zero());
1640    }
1641
1642    #[rstest]
1643    fn test_price_as_f64() {
1644        assert_eq!(Price::new(1.5, 2).as_f64(), 1.5);
1645        assert_eq!(Price::new(0.0, 2).as_f64(), 0.0);
1646    }
1647
1648    #[rstest]
1649    fn test_price_checked_arith_rejects_out_of_bounds_without_integer_overflow() {
1650        let one_unit = Price::from_raw(1, FIXED_PRECISION);
1651
1652        assert_eq!(
1653            Price::from_raw(PRICE_RAW_MAX, FIXED_PRECISION).checked_add(one_unit),
1654            None
1655        );
1656        assert_eq!(
1657            Price::from_raw(PRICE_RAW_MIN, FIXED_PRECISION).checked_sub(one_unit),
1658            None
1659        );
1660    }
1661
1662    #[rstest]
1663    fn test_price_checked_sub_rejects_sentinel_before_bounds_check() {
1664        let undef = Price::from_raw(PRICE_UNDEF, 0);
1665        let max = Price::from_raw(PRICE_RAW_MAX, FIXED_PRECISION);
1666
1667        assert_eq!(undef.checked_sub(max), None);
1668    }
1669
1670    #[rstest]
1671    fn test_price_checked_arith_rejects_error_price() {
1672        let one = Price::new(1.0, 0);
1673        assert_eq!(ERROR_PRICE.checked_add(one), None);
1674        assert_eq!(one.checked_sub(ERROR_PRICE), None);
1675    }
1676
1677    #[rstest]
1678    fn test_price_checked_arith_rejects_raw_error() {
1679        let error = Price::from_raw(PRICE_ERROR, 0);
1680        let one = Price::new(1.0, 0);
1681        assert_eq!(error.checked_add(one), None);
1682        assert_eq!(one.checked_add(error), None);
1683        assert_eq!(error.checked_sub(one), None);
1684        assert_eq!(one.checked_sub(error), None);
1685    }
1686
1687    #[rstest]
1688    fn test_price_checked_add_at_exact_max_returns_some() {
1689        let near_max = Price::from_raw(PRICE_RAW_MAX - 1, FIXED_PRECISION);
1690        let one_unit = Price::from_raw(1, FIXED_PRECISION);
1691        assert_eq!(
1692            near_max.checked_add(one_unit),
1693            Some(Price::from_raw(PRICE_RAW_MAX, FIXED_PRECISION)),
1694        );
1695    }
1696
1697    #[rstest]
1698    fn test_price_checked_sub_at_exact_min_returns_some() {
1699        let near_min = Price::from_raw(PRICE_RAW_MIN + 1, FIXED_PRECISION);
1700        let one_unit = Price::from_raw(1, FIXED_PRECISION);
1701        assert_eq!(
1702            near_min.checked_sub(one_unit),
1703            Some(Price::from_raw(PRICE_RAW_MIN, FIXED_PRECISION)),
1704        );
1705    }
1706
1707    #[rstest]
1708    fn test_mixed_precision_add() {
1709        let p1 = Price::new(10.5, 1);
1710        let p2 = Price::new(5.25, 2);
1711        let result = p1 + p2;
1712        assert_eq!(result.precision, 2);
1713        assert_eq!(result.as_f64(), 15.75);
1714    }
1715
1716    #[rstest]
1717    fn test_mixed_precision_sub() {
1718        let p1 = Price::new(10.5, 1);
1719        let p2 = Price::new(5.25, 2);
1720        let result = p1 - p2;
1721        assert_eq!(result.precision, 2);
1722        assert_eq!(result.as_f64(), 5.25);
1723    }
1724
1725    #[rstest]
1726    fn test_f64_operations() {
1727        let p = Price::new(10.5, 2);
1728        assert_eq!(p + 1.0, 11.5);
1729        assert_eq!(p - 1.0, 9.5);
1730        assert_eq!(p * 2.0, 21.0);
1731        assert_eq!(p / 2.0, 5.25);
1732    }
1733
1734    #[rstest]
1735    fn test_equality_and_comparisons() {
1736        let p1 = Price::new(10.0, 1);
1737        let p2 = Price::new(20.0, 1);
1738        let p3 = Price::new(10.0, 1);
1739
1740        assert!(p1 < p2);
1741        assert!(p2 > p1);
1742        assert!(p1 <= p3);
1743        assert!(p1 >= p3);
1744        assert_eq!(p1, p3);
1745        assert_ne!(p1, p2);
1746
1747        assert_eq!(Price::from("1.0"), Price::from("1.0"));
1748        assert_ne!(Price::from("1.1"), Price::from("1.0"));
1749        assert!(Price::from("1.0") <= Price::from("1.0"));
1750        assert!(Price::from("1.1") > Price::from("1.0"));
1751        assert!(Price::from("1.0") >= Price::from("1.0"));
1752        assert!(Price::from("1.0") >= Price::from("1.0"));
1753        assert!(Price::from("1.0") >= Price::from("1.0"));
1754        assert!(Price::from("0.9") < Price::from("1.0"));
1755        assert!(Price::from("0.9") <= Price::from("1.0"));
1756        assert!(Price::from("0.9") <= Price::from("1.0"));
1757    }
1758
1759    #[rstest]
1760    fn test_deref() {
1761        let price = Price::new(10.0, 1);
1762        assert_eq!(*price, price.raw);
1763    }
1764
1765    #[rstest]
1766    fn test_decode_raw_price_i64() {
1767        let raw_scaled_by_1e9 = 42_000_000_000i64; // 42.0 * 10^9
1768        let decoded = decode_raw_price_i64(raw_scaled_by_1e9);
1769        let price = Price::from_raw(decoded, FIXED_PRECISION);
1770        assert!(
1771            approx_eq!(f64, price.as_f64(), 42.0, epsilon = 1e-9),
1772            "Expected 42.0 f64, was {} (precision = {})",
1773            price.as_f64(),
1774            price.precision
1775        );
1776    }
1777
1778    #[rstest]
1779    fn test_hash() {
1780        use std::{
1781            collections::hash_map::DefaultHasher,
1782            hash::{Hash, Hasher},
1783        };
1784
1785        let price1 = Price::new(1.0, 2);
1786        let price2 = Price::new(1.0, 2);
1787        let price3 = Price::new(1.1, 2);
1788
1789        let mut hasher1 = DefaultHasher::new();
1790        let mut hasher2 = DefaultHasher::new();
1791        let mut hasher3 = DefaultHasher::new();
1792
1793        price1.hash(&mut hasher1);
1794        price2.hash(&mut hasher2);
1795        price3.hash(&mut hasher3);
1796
1797        assert_eq!(hasher1.finish(), hasher2.finish());
1798        assert_ne!(hasher1.finish(), hasher3.finish());
1799    }
1800
1801    #[rstest]
1802    fn test_price_serde_json_round_trip() {
1803        let price = Price::new(1.0500, 4);
1804        let json = serde_json::to_string(&price).unwrap();
1805        let deserialized: Price = serde_json::from_str(&json).unwrap();
1806        assert_eq!(deserialized, price);
1807    }
1808
1809    #[rstest]
1810    fn test_price_serde_json_from_value_round_trip() {
1811        let price = Price::new(1.0500, 4);
1812        let value = serde_json::to_value(price).unwrap();
1813
1814        let deserialized: Price = serde_json::from_value(value).unwrap();
1815        assert_eq!(deserialized, price);
1816        assert_eq!(deserialized.precision, 4);
1817    }
1818
1819    #[cfg(feature = "high-precision")]
1820    #[rstest]
1821    fn test_high_precision_16_serde_json_round_trip() {
1822        let price = Price::from_raw(1_234_567_890_123_456_789_i128, 16);
1823        let json = serde_json::to_string(&price).unwrap();
1824        let deserialized: Price = serde_json::from_str(&json).unwrap();
1825
1826        assert_eq!(deserialized, price);
1827        assert_eq!(deserialized.precision, 16);
1828        assert_eq!(deserialized.raw, 1_234_567_890_123_456_789_i128);
1829    }
1830
1831    #[cfg(all(feature = "high-precision", feature = "defi"))]
1832    #[rstest]
1833    #[case(17, 12_345_678_901_234_567_891_i128)]
1834    #[case(18, 123_456_789_012_345_678_901_i128)]
1835    fn test_defi_precision_serde_json_round_trip(#[case] precision: u8, #[case] raw: PriceRaw) {
1836        let price = Price::from_raw(raw, precision);
1837        let json = serde_json::to_string(&price).unwrap();
1838        let deserialized: Price = serde_json::from_str(&json).unwrap();
1839
1840        assert_eq!(deserialized, price);
1841        assert_eq!(deserialized.precision, precision);
1842        assert_eq!(deserialized.raw, raw);
1843    }
1844
1845    #[rstest]
1846    fn test_price_deserialize_invalid_string_returns_error() {
1847        let result = serde_json::from_str::<Price>("\"not-a-price\"");
1848        let error = result.unwrap_err();
1849        assert!(
1850            error.to_string().contains("Error parsing"),
1851            "unexpected message: {error}"
1852        );
1853    }
1854
1855    #[rstest]
1856    fn test_price_deserialize_out_of_range_returns_error() {
1857        let result = serde_json::from_str::<Price>("\"99999999999999999999.99\"");
1858        assert!(result.is_err());
1859    }
1860
1861    #[rstest]
1862    fn test_from_mantissa_exponent_exact_precision() {
1863        let price = Price::from_mantissa_exponent(12345, -2, 2);
1864        assert_eq!(price.as_f64(), 123.45);
1865    }
1866
1867    #[rstest]
1868    fn test_from_mantissa_exponent_excess_rounds_down() {
1869        // 12.345 rounds to 12.34 (4 is even, banker's rounding)
1870        let price = Price::from_mantissa_exponent(12345, -3, 2);
1871        assert_eq!(price.as_f64(), 12.34);
1872    }
1873
1874    #[rstest]
1875    fn test_from_mantissa_exponent_excess_rounds_up() {
1876        // 12.355 rounds to 12.36 (5 is odd, banker's rounding)
1877        let price = Price::from_mantissa_exponent(12355, -3, 2);
1878        assert_eq!(price.as_f64(), 12.36);
1879    }
1880
1881    #[rstest]
1882    fn test_from_mantissa_exponent_positive_exponent() {
1883        let price = Price::from_mantissa_exponent(5, 2, 0);
1884        assert_eq!(price.as_f64(), 500.0);
1885    }
1886
1887    #[rstest]
1888    fn test_from_mantissa_exponent_negative_mantissa() {
1889        let price = Price::from_mantissa_exponent(-12345, -2, 2);
1890        assert_eq!(price.as_f64(), -123.45);
1891    }
1892
1893    #[rstest]
1894    fn test_from_mantissa_exponent_zero() {
1895        let price = Price::from_mantissa_exponent(0, 2, 2);
1896        assert_eq!(price.as_f64(), 0.0);
1897    }
1898
1899    #[cfg(all(feature = "defi", feature = "high-precision"))]
1900    #[rstest]
1901    fn test_wei_above_decimal_mantissa_formats_exactly() {
1902        let raw = 80_000_000_000_000_000_250_000_000_000_i128;
1903        let price = Price::from_raw(raw, 18);
1904
1905        assert_eq!(price.to_string(), "80000000000.000000250000000000");
1906        assert_eq!(Price::from_str(&price.to_string()).unwrap(), price);
1907        assert_eq!(
1908            serde_json::from_str::<Price>(&serde_json::to_string(&price).unwrap()).unwrap(),
1909            price,
1910        );
1911    }
1912
1913    #[rstest]
1914    fn test_from_mantissa_exponent_checked_exact_precision() {
1915        let price = Price::from_mantissa_exponent_checked(12345, -2, 2).unwrap();
1916        assert_eq!(price.as_decimal(), dec!(123.45));
1917    }
1918
1919    #[rstest]
1920    fn test_from_mantissa_exponent_checked_zero_with_large_exponent() {
1921        let price = Price::from_mantissa_exponent_checked(0, 119, 2).unwrap();
1922        assert_eq!(price.as_decimal(), dec!(0.00));
1923    }
1924
1925    #[rstest]
1926    fn test_from_mantissa_exponent_checked_invalid_precision() {
1927        #[cfg(feature = "defi")]
1928        let invalid_precision = crate::defi::WEI_PRECISION + 1;
1929        #[cfg(not(feature = "defi"))]
1930        let invalid_precision = FIXED_PRECISION + 1;
1931
1932        let error = Price::from_mantissa_exponent_checked(1, 0, invalid_precision).unwrap_err();
1933        assert!(error.to_string().contains("`precision` exceeded maximum"));
1934    }
1935
1936    #[rstest]
1937    fn test_from_mantissa_exponent_checked_overflow_returns_error() {
1938        let error = Price::from_mantissa_exponent_checked(i64::MAX, 100, 0).unwrap_err();
1939        assert!(
1940            error
1941                .to_string()
1942                .contains("Overflow in Price::from_mantissa_exponent")
1943        );
1944    }
1945
1946    #[rstest]
1947    #[should_panic(expected = "Price::from_mantissa_exponent")]
1948    fn test_from_mantissa_exponent_overflow_panics() {
1949        let _ = Price::from_mantissa_exponent(i64::MAX, 9, 0);
1950    }
1951
1952    #[rstest]
1953    #[should_panic(expected = "exceeds i128 range")]
1954    fn test_from_mantissa_exponent_large_exponent_panics() {
1955        let _ = Price::from_mantissa_exponent(1, 119, 0);
1956    }
1957
1958    #[rstest]
1959    fn test_from_mantissa_exponent_zero_with_large_exponent() {
1960        let price = Price::from_mantissa_exponent(0, 119, 0);
1961        assert_eq!(price.as_f64(), 0.0);
1962    }
1963
1964    #[rstest]
1965    fn test_from_mantissa_exponent_very_negative_exponent_rounds_to_zero() {
1966        let price = Price::from_mantissa_exponent(12345, -120, 2);
1967        assert_eq!(price.as_f64(), 0.0);
1968    }
1969
1970    #[rstest]
1971    fn test_decimal_arithmetic_operations() {
1972        let price = Price::new(100.0, 2);
1973        assert_eq!(price + dec!(50.25), dec!(150.25));
1974        assert_eq!(price - dec!(30.50), dec!(69.50));
1975        assert_eq!(price * dec!(1.5), dec!(150.00));
1976        assert_eq!(price / dec!(4), dec!(25.00));
1977    }
1978}
1979
1980#[cfg(test)]
1981mod property_tests {
1982    use proptest::prelude::*;
1983    use rstest::rstest;
1984
1985    use super::*;
1986
1987    /// Strategy to generate valid price values within the allowed range.
1988    fn price_value_strategy() -> impl Strategy<Value = f64> {
1989        // Use a reasonable range that's well within PRICE_MIN/PRICE_MAX
1990        // but still tests edge cases with various scales
1991        prop_oneof![
1992            // Small positive values
1993            0.00001..1.0,
1994            // Normal trading range
1995            1.0..100_000.0,
1996            // Large values (but safe)
1997            100_000.0..1_000_000.0,
1998            // Small negative values (for spreads, etc.)
1999            -1_000.0..0.0,
2000            // Boundary values close to the extremes
2001            Just(PRICE_MIN / 2.0),
2002            Just(PRICE_MAX / 2.0),
2003        ]
2004    }
2005
2006    fn float_precision_upper_bound() -> u8 {
2007        FIXED_PRECISION.min(crate::types::fixed::MAX_FLOAT_PRECISION)
2008    }
2009
2010    /// Strategy to exercise both typical and extreme precision values.
2011    fn precision_strategy() -> impl Strategy<Value = u8> {
2012        let upper = float_precision_upper_bound();
2013        prop_oneof![Just(0u8), 0u8..=upper, Just(FIXED_PRECISION),]
2014    }
2015
2016    fn precision_strategy_non_zero() -> impl Strategy<Value = u8> {
2017        let upper = float_precision_upper_bound().max(1);
2018        prop_oneof![Just(upper), Just(FIXED_PRECISION.max(1)), 1u8..=upper,]
2019    }
2020
2021    /// Strategy to generate a valid (precision, raw) pair where raw is properly scaled.
2022    ///
2023    /// Raw values must be multiples of `10^(FIXED_PRECISION` - precision) to pass validation.
2024    fn valid_precision_raw_strategy() -> impl Strategy<Value = (u8, PriceRaw)> {
2025        precision_strategy().prop_flat_map(|precision| {
2026            let scale: PriceRaw = if precision >= FIXED_PRECISION {
2027                1
2028            } else {
2029                (10 as PriceRaw).pow(u32::from(FIXED_PRECISION - precision))
2030            };
2031            // Generate a base value, then multiply by scale to ensure valid raw
2032            let max_base = PRICE_RAW_MAX / scale;
2033            let min_base = PRICE_RAW_MIN / scale;
2034            (min_base..=max_base).prop_map(move |base| (precision, base * scale))
2035        })
2036    }
2037
2038    /// Strategy to generate valid precision values for float-based constructors.
2039    fn float_precision_strategy() -> impl Strategy<Value = u8> {
2040        precision_strategy()
2041    }
2042
2043    const DECIMAL_MAX_MANTISSA: i128 = 79_228_162_514_264_337_593_543_950_335;
2044
2045    #[allow(
2046        clippy::useless_conversion,
2047        reason = "PriceRaw is i64 or i128 depending on feature; the conversion is only useless in high-precision builds"
2048    )]
2049    fn decimal_compatible(raw: PriceRaw, precision: u8) -> bool {
2050        if precision > crate::types::fixed::MAX_FLOAT_PRECISION {
2051            return false;
2052        }
2053        let precision_diff = u32::from(FIXED_PRECISION.saturating_sub(precision));
2054        let divisor = (10 as PriceRaw).pow(precision_diff);
2055        let rescaled_raw = raw / divisor;
2056        i128::from(rescaled_raw.abs()) <= DECIMAL_MAX_MANTISSA
2057    }
2058
2059    proptest! {
2060        /// Property: Price string serialization round-trip should preserve value and precision
2061        #[rstest]
2062        fn prop_price_serde_round_trip(
2063            (precision, raw) in valid_precision_raw_strategy()
2064        ) {
2065            let original = Price::from_raw(raw, precision);
2066
2067            // String round-trip (this should be exact and is the most important)
2068            let string_repr = original.to_string();
2069            let from_string: Price = string_repr.parse().unwrap();
2070            prop_assert_eq!(from_string.raw, original.raw);
2071            prop_assert_eq!(from_string.precision, original.precision);
2072
2073            // JSON uses the same canonical decimal string as Display, so it must be exact.
2074            let json = serde_json::to_string(&original).unwrap();
2075            let from_json: Price = serde_json::from_str(&json).unwrap();
2076            prop_assert_eq!(from_json.precision, original.precision);
2077            prop_assert_eq!(from_json.raw, original.raw);
2078        }
2079
2080        /// Property: Price arithmetic should be associative for same precision
2081        #[rstest]
2082        fn prop_price_arithmetic_associative(
2083            a in price_value_strategy().prop_filter("Reasonable values", |&x| x.abs() > 1e-3 && x.abs() < 1e6),
2084            b in price_value_strategy().prop_filter("Reasonable values", |&x| x.abs() > 1e-3 && x.abs() < 1e6),
2085            c in price_value_strategy().prop_filter("Reasonable values", |&x| x.abs() > 1e-3 && x.abs() < 1e6),
2086            precision in precision_strategy()
2087        ) {
2088            let p_a = Price::new(a, precision);
2089            let p_b = Price::new(b, precision);
2090            let p_c = Price::new(c, precision);
2091
2092            let expected = p_a
2093                .raw
2094                .checked_add(p_b.raw)
2095                .and_then(|sum| sum.checked_add(p_c.raw))
2096                .filter(|sum| (PRICE_RAW_MIN..=PRICE_RAW_MAX).contains(sum));
2097
2098            if let Some(expected) = expected {
2099                let left = (p_a + p_b) + p_c;
2100                let right = p_a + (p_b + p_c);
2101                prop_assert_eq!(left.raw, expected);
2102                prop_assert_eq!(right.raw, expected);
2103            }
2104        }
2105
2106        /// Property: Price addition/subtraction should be inverse operations
2107        #[rstest]
2108        fn prop_price_addition_subtraction_inverse(
2109            base in price_value_strategy().prop_filter("Reasonable values", |&x| x.abs() < 1e6),
2110            delta in price_value_strategy().prop_filter("Reasonable values", |&x| x.abs() > 1e-3 && x.abs() < 1e6),
2111            precision in precision_strategy()
2112        ) {
2113            let p_base = Price::new(base, precision);
2114            let p_delta = Price::new(delta, precision);
2115
2116            if p_base
2117                .raw
2118                .checked_add(p_delta.raw)
2119                .is_some_and(|sum| (PRICE_RAW_MIN..=PRICE_RAW_MAX).contains(&sum))
2120            {
2121                prop_assert_eq!((p_base + p_delta) - p_delta, p_base);
2122            }
2123        }
2124
2125        /// Property: Price ordering should be transitive
2126        #[rstest]
2127        fn prop_price_ordering_transitive(
2128            a in price_value_strategy(),
2129            b in price_value_strategy(),
2130            c in price_value_strategy(),
2131            precision in float_precision_strategy()
2132        ) {
2133            let p_a = Price::new(a, precision);
2134            let p_b = Price::new(b, precision);
2135            let p_c = Price::new(c, precision);
2136
2137            // If a <= b and b <= c, then a <= c
2138            if p_a <= p_b && p_b <= p_c {
2139                prop_assert!(p_a <= p_c, "Transitivity failed: {} <= {} <= {} but {} > {}",
2140                    p_a.as_f64(), p_b.as_f64(), p_c.as_f64(), p_a.as_f64(), p_c.as_f64());
2141            }
2142        }
2143
2144        /// Property: String parsing should be consistent with precision inference
2145        #[rstest]
2146        fn prop_price_string_parsing_precision(
2147            integral in 0u32..1_000_000,
2148            fractional in 0u32..1_000_000,
2149            precision in precision_strategy_non_zero()
2150        ) {
2151            // Create a decimal string with exactly 'precision' decimal places
2152            let pow = 10u128.pow(u32::from(precision));
2153            let fractional_mod = u128::from(fractional) % pow;
2154            let fractional_str = format!("{:0width$}", fractional_mod, width = precision as usize);
2155            let price_str = format!("{integral}.{fractional_str}");
2156
2157            let parsed: Price = price_str.parse().unwrap();
2158            prop_assert_eq!(parsed.precision, precision);
2159
2160            // Round-trip should preserve the original string (after normalization)
2161            let round_trip = parsed.to_string();
2162            let expected_value = format!("{integral}.{fractional_str}");
2163            prop_assert_eq!(round_trip, expected_value);
2164        }
2165
2166        /// Property: Price arithmetic should never produce invalid values
2167        #[rstest]
2168        fn prop_price_arithmetic_bounds(
2169            a in price_value_strategy(),
2170            b in price_value_strategy(),
2171            precision in float_precision_strategy()
2172        ) {
2173            let p_a = Price::new(a, precision);
2174            let p_b = Price::new(b, precision);
2175
2176            // Addition should either succeed or fail predictably
2177            let sum_f64 = p_a.as_f64() + p_b.as_f64();
2178            if sum_f64.is_finite() && (PRICE_MIN..=PRICE_MAX).contains(&sum_f64) {
2179                let sum = p_a + p_b;
2180                prop_assert!(sum.as_f64().is_finite());
2181                prop_assert!(!sum.is_undefined());
2182            }
2183
2184            // Subtraction should either succeed or fail predictably
2185            let diff_f64 = p_a.as_f64() - p_b.as_f64();
2186            if diff_f64.is_finite() && (PRICE_MIN..=PRICE_MAX).contains(&diff_f64) {
2187                let diff = p_a - p_b;
2188                prop_assert!(diff.as_f64().is_finite());
2189                prop_assert!(!diff.is_undefined());
2190            }
2191        }
2192
2193        /// Property: checked_add agrees with Add when bounds and sentinel guards hold,
2194        /// and returns None otherwise.
2195        #[rstest]
2196        fn prop_price_checked_add_matches_spec(
2197            a in price_value_strategy(),
2198            b in price_value_strategy(),
2199            precision in float_precision_strategy()
2200        ) {
2201            let p_a = Price::new(a, precision);
2202            let p_b = Price::new(b, precision);
2203            let expected = p_a.raw
2204                .checked_add(p_b.raw)
2205                .filter(|r| (PRICE_RAW_MIN..=PRICE_RAW_MAX).contains(r))
2206                .filter(|_| !p_a.is_sentinel() && !p_b.is_sentinel())
2207                .map(|raw| Price { raw, precision: p_a.precision.max(p_b.precision) });
2208            prop_assert_eq!(p_a.checked_add(p_b), expected);
2209        }
2210
2211        /// Property: checked_sub agrees with Sub when bounds and sentinel guards hold,
2212        /// and returns None otherwise.
2213        #[rstest]
2214        fn prop_price_checked_sub_matches_spec(
2215            a in price_value_strategy(),
2216            b in price_value_strategy(),
2217            precision in float_precision_strategy()
2218        ) {
2219            let p_a = Price::new(a, precision);
2220            let p_b = Price::new(b, precision);
2221            let expected = p_a.raw
2222                .checked_sub(p_b.raw)
2223                .filter(|r| (PRICE_RAW_MIN..=PRICE_RAW_MAX).contains(r))
2224                .filter(|_| !p_a.is_sentinel() && !p_b.is_sentinel())
2225                .map(|raw| Price { raw, precision: p_a.precision.max(p_b.precision) });
2226            prop_assert_eq!(p_a.checked_sub(p_b), expected);
2227        }
2228    }
2229
2230    proptest! {
2231        /// Property: as_decimal scale always matches precision
2232        #[rstest]
2233        fn prop_price_as_decimal_preserves_precision(
2234            (precision, raw) in valid_precision_raw_strategy()
2235        ) {
2236            prop_assume!(decimal_compatible(raw, precision));
2237            let price = Price::from_raw(raw, precision);
2238            let decimal = price.as_decimal();
2239            prop_assert_eq!(decimal.scale(), u32::from(precision));
2240        }
2241
2242        /// Property: as_decimal and Display produce the same string
2243        #[rstest]
2244        fn prop_price_as_decimal_matches_display(
2245            value in price_value_strategy().prop_filter("Reasonable values", |&x| x.abs() < 1e6),
2246            precision in float_precision_strategy()
2247        ) {
2248            let price = Price::new(value, precision);
2249            prop_assume!(decimal_compatible(price.raw, precision));
2250            let display_str = format!("{price}");
2251            let decimal_str = price.as_decimal().to_string();
2252            prop_assert_eq!(display_str, decimal_str);
2253        }
2254
2255        /// Property: from_decimal roundtrip preserves exact value
2256        #[rstest]
2257        fn prop_price_from_decimal_roundtrip(
2258            (precision, raw) in valid_precision_raw_strategy()
2259        ) {
2260            prop_assume!(decimal_compatible(raw, precision));
2261            let original = Price::from_raw(raw, precision);
2262            let decimal = original.as_decimal();
2263            let reconstructed = Price::from_decimal(decimal).unwrap();
2264            prop_assert_eq!(original.raw, reconstructed.raw);
2265            prop_assert_eq!(original.precision, reconstructed.precision);
2266        }
2267
2268        /// Property: constructing from valid raw values preserves raw/precision fields
2269        #[rstest]
2270        fn prop_price_from_raw_round_trip(
2271            (precision, raw) in valid_precision_raw_strategy()
2272        ) {
2273            let price = Price::from_raw(raw, precision);
2274            prop_assert_eq!(price.raw, raw);
2275            prop_assert_eq!(price.precision, precision);
2276        }
2277    }
2278}