nautilus-model 0.55.0

Domain model for the Nautilus trading engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
// -------------------------------------------------------------------------------------------------
//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
//  https://nautechsystems.io
//
//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
//  You may not use this file except in compliance with the License.
//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
// -------------------------------------------------------------------------------------------------

//! Represents a price in a market with a specified precision.
//!
//! [`Price`] is an immutable value type for representing market prices, bid/ask quotes,
//! and price levels. Unlike [`Quantity`](super::Quantity), prices can be negative (useful for spreads,
//! basis trades, or certain derivative instruments).
//!
//! # Arithmetic behavior
//!
//! | Operation         | Result    | Notes                              |
//! |-------------------|-----------|------------------------------------|
//! | `Price + Price`   | `Price`   | Precision is max of both operands. |
//! | `Price - Price`   | `Price`   | Precision is max of both operands. |
//! | `Price + Decimal` | `Decimal` |                                    |
//! | `Price - Decimal` | `Decimal` |                                    |
//! | `Price * Decimal` | `Decimal` |                                    |
//! | `Price / Decimal` | `Decimal` |                                    |
//! | `Price + f64`     | `f64`     |                                    |
//! | `Price - f64`     | `f64`     |                                    |
//! | `Price * f64`     | `f64`     |                                    |
//! | `Price / f64`     | `f64`     |                                    |
//! | `-Price`          | `Price`   |                                    |
//!
//! # Immutability
//!
//! `Price` is immutable. All arithmetic operations return new instances.

use std::{
    cmp::Ordering,
    fmt::{Debug, Display},
    hash::{Hash, Hasher},
    ops::{Add, Deref, Div, Mul, Neg, Sub},
    str::FromStr,
};

use nautilus_core::{
    correctness::{FAILED, check_in_range_inclusive_f64},
    formatting::Separable,
};
use rust_decimal::Decimal;
use serde::{Deserialize, Deserializer, Serialize};

use super::fixed::{
    FIXED_PRECISION, FIXED_SCALAR, check_fixed_precision, mantissa_exponent_to_fixed_i128,
};
#[cfg(feature = "high-precision")]
use super::fixed::{PRECISION_DIFF_SCALAR, f64_to_fixed_i128, fixed_i128_to_f64};
#[cfg(not(feature = "high-precision"))]
use super::fixed::{f64_to_fixed_i64, fixed_i64_to_f64};
#[cfg(feature = "defi")]
use crate::types::fixed::MAX_FLOAT_PRECISION;

// -----------------------------------------------------------------------------
// PriceRaw
// -----------------------------------------------------------------------------

// Use 128-bit integers when either `high-precision` or `defi` features are enabled. This is
// required for the extended 18-decimal wei precision used in DeFi contexts.

#[cfg(feature = "high-precision")]
pub type PriceRaw = i128;

#[cfg(not(feature = "high-precision"))]
pub type PriceRaw = i64;

// -----------------------------------------------------------------------------

/// The maximum raw price integer value.
///
/// # Safety
///
/// This value is computed at compile time from PRICE_MAX * FIXED_SCALAR.
/// The multiplication is guaranteed not to overflow because PRICE_MAX and FIXED_SCALAR
/// are chosen such that their product fits within PriceRaw's range in both
/// high-precision (i128) and standard-precision (i64) modes.
#[unsafe(no_mangle)]
#[allow(unsafe_code)]
pub static PRICE_RAW_MAX: PriceRaw = (PRICE_MAX * FIXED_SCALAR) as PriceRaw;

/// The minimum raw price integer value.
///
/// # Safety
///
/// This value is computed at compile time from PRICE_MIN * FIXED_SCALAR.
/// The multiplication is guaranteed not to overflow because PRICE_MIN and FIXED_SCALAR
/// are chosen such that their product fits within PriceRaw's range in both
/// high-precision (i128) and standard-precision (i64) modes.
#[unsafe(no_mangle)]
#[allow(unsafe_code)]
pub static PRICE_RAW_MIN: PriceRaw = (PRICE_MIN * FIXED_SCALAR) as PriceRaw;

/// The sentinel value for an unset or null price.
pub const PRICE_UNDEF: PriceRaw = PriceRaw::MAX;

/// The sentinel value for an error or invalid price.
pub const PRICE_ERROR: PriceRaw = PriceRaw::MIN;

// -----------------------------------------------------------------------------
// PRICE_MAX
// -----------------------------------------------------------------------------

/// The maximum valid price value that can be represented.
#[cfg(feature = "high-precision")]
pub const PRICE_MAX: f64 = 17_014_118_346_046.0;

#[cfg(not(feature = "high-precision"))]
/// The maximum valid price value that can be represented.
pub const PRICE_MAX: f64 = 9_223_372_036.0;

// -----------------------------------------------------------------------------
// PRICE_MIN
// -----------------------------------------------------------------------------

#[cfg(feature = "high-precision")]
/// The minimum valid price value that can be represented.
pub const PRICE_MIN: f64 = -17_014_118_346_046.0;

#[cfg(not(feature = "high-precision"))]
/// The minimum valid price value that can be represented.
pub const PRICE_MIN: f64 = -9_223_372_036.0;

// -----------------------------------------------------------------------------

/// The sentinel `Price` representing errors (this will be removed when Cython is gone).
pub const ERROR_PRICE: Price = Price {
    raw: 0,
    precision: 255,
};

/// Represents a price in a market with a specified precision.
///
/// The number of decimal places may vary. For certain asset classes, prices may
/// have negative values. For example, prices for options instruments can be
/// negative under certain conditions.
///
/// Handles up to [`FIXED_PRECISION`] decimals of precision.
///
/// - [`PRICE_MAX`] - Maximum representable price value.
/// - [`PRICE_MIN`] - Minimum representable price value.
#[repr(C)]
#[derive(Clone, Copy, Default, Eq)]
#[cfg_attr(
    feature = "python",
    pyo3::pyclass(
        module = "nautilus_trader.core.nautilus_pyo3.model",
        frozen,
        from_py_object
    )
)]
#[cfg_attr(
    feature = "python",
    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.model")
)]
pub struct Price {
    /// Represents the raw fixed-point value, with `precision` defining the number of decimal places.
    pub raw: PriceRaw,
    /// The number of decimal places, with a maximum of [`FIXED_PRECISION`].
    pub precision: u8,
}

impl Price {
    /// Creates a new [`Price`] instance with correctness checking.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - `value` is invalid outside the representable range [`PRICE_MIN`, `PRICE_MAX`].
    /// - `precision` is invalid outside the representable range [0, `FIXED_PRECISION``].
    ///
    /// # Notes
    ///
    /// PyO3 requires a `Result` type for proper error handling and stacktrace printing in Python.
    pub fn new_checked(value: f64, precision: u8) -> anyhow::Result<Self> {
        check_in_range_inclusive_f64(value, PRICE_MIN, PRICE_MAX, "value")?;

        #[cfg(feature = "defi")]
        if precision > MAX_FLOAT_PRECISION {
            // Floats are only reliable up to ~16 decimal digits of precision regardless of feature flags
            anyhow::bail!(
                "`precision` exceeded maximum float precision ({MAX_FLOAT_PRECISION}), use `Price::from_wei()` for wei values instead"
            );
        }

        check_fixed_precision(precision)?;

        #[cfg(feature = "high-precision")]
        let raw = f64_to_fixed_i128(value, precision);

        #[cfg(not(feature = "high-precision"))]
        let raw = f64_to_fixed_i64(value, precision);

        Ok(Self { raw, precision })
    }

    /// Creates a new [`Price`] instance.
    ///
    /// # Panics
    ///
    /// Panics if a correctness check fails. See [`Price::new_checked`] for more details.
    pub fn new(value: f64, precision: u8) -> Self {
        Self::new_checked(value, precision).expect(FAILED)
    }

    /// Creates a new [`Price`] instance from the given `raw` fixed-point value and `precision`.
    ///
    /// # Panics
    ///
    /// Panics if `raw` is outside the valid range and is not a sentinel value.
    /// Panics if `precision` exceeds [`FIXED_PRECISION`].
    pub fn from_raw(raw: PriceRaw, precision: u8) -> Self {
        assert!(
            raw == PRICE_ERROR
                || raw == PRICE_UNDEF
                || (raw >= PRICE_RAW_MIN && raw <= PRICE_RAW_MAX),
            "`raw` value {raw} outside valid range [{PRICE_RAW_MIN}, {PRICE_RAW_MAX}] for Price"
        );

        if raw == PRICE_UNDEF {
            assert!(
                precision == 0,
                "`precision` must be 0 when `raw` is PRICE_UNDEF"
            );
        }
        check_fixed_precision(precision).expect(FAILED);

        // TODO: Enforce spurious bits validation in v2
        // if !matches!(raw, PRICE_UNDEF | PRICE_ERROR) && raw != 0 {
        //     #[cfg(feature = "high-precision")]
        //     super::fixed::check_fixed_raw_i128(raw, precision).expect(FAILED);
        //     #[cfg(not(feature = "high-precision"))]
        //     super::fixed::check_fixed_raw_i64(raw, precision).expect(FAILED);
        // }

        Self { raw, precision }
    }

    /// Creates a new [`Price`] instance from the given `raw` fixed-point value and `precision`
    /// with correctness checking.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - `precision` exceeds the maximum fixed precision.
    /// - `precision` is not 0 when `raw` is `PRICE_UNDEF`.
    /// - `raw` is outside the valid range `[PRICE_RAW_MIN, PRICE_RAW_MAX]`
    ///   and is not a sentinel value.
    pub fn from_raw_checked(raw: PriceRaw, precision: u8) -> anyhow::Result<Self> {
        if raw == PRICE_UNDEF {
            anyhow::ensure!(
                precision == 0,
                "`precision` must be 0 when `raw` is PRICE_UNDEF"
            );
        }
        anyhow::ensure!(
            raw == PRICE_ERROR
                || raw == PRICE_UNDEF
                || (raw >= PRICE_RAW_MIN && raw <= PRICE_RAW_MAX),
            "raw value {raw} outside valid range [{PRICE_RAW_MIN}, {PRICE_RAW_MAX}]"
        );
        check_fixed_precision(precision)?;

        Ok(Self { raw, precision })
    }

    /// Creates a new [`Price`] instance with a value of zero with the given `precision`.
    ///
    /// # Panics
    ///
    /// Panics if a correctness check fails. See [`Price::new_checked`] for more details.
    #[must_use]
    pub fn zero(precision: u8) -> Self {
        check_fixed_precision(precision).expect(FAILED);
        Self { raw: 0, precision }
    }

    /// Creates a new [`Price`] instance with the maximum representable value with the given `precision`.
    ///
    /// # Panics
    ///
    /// Panics if a correctness check fails. See [`Price::new_checked`] for more details.
    #[must_use]
    pub fn max(precision: u8) -> Self {
        check_fixed_precision(precision).expect(FAILED);
        Self {
            raw: PRICE_RAW_MAX,
            precision,
        }
    }

    /// Creates a new [`Price`] instance with the minimum representable value with the given `precision`.
    ///
    /// # Panics
    ///
    /// Panics if a correctness check fails. See [`Price::new_checked`] for more details.
    #[must_use]
    pub fn min(precision: u8) -> Self {
        check_fixed_precision(precision).expect(FAILED);
        Self {
            raw: PRICE_RAW_MIN,
            precision,
        }
    }

    /// Returns `true` if the value of this instance is undefined.
    #[must_use]
    pub fn is_undefined(&self) -> bool {
        self.raw == PRICE_UNDEF
    }

    /// Returns `true` if the value of this instance is zero.
    #[must_use]
    pub fn is_zero(&self) -> bool {
        self.raw == 0
    }

    /// Returns `true` if the value of this instance is position (> 0).
    #[must_use]
    pub fn is_positive(&self) -> bool {
        self.raw != PRICE_UNDEF && self.raw > 0
    }

    #[cfg(feature = "high-precision")]
    /// Returns the value of this instance as an `f64`.
    ///
    /// # Panics
    ///
    /// Panics if precision is beyond `MAX_FLOAT_PRECISION` (16).
    #[must_use]
    pub fn as_f64(&self) -> f64 {
        #[cfg(feature = "defi")]
        assert!(
            self.precision <= MAX_FLOAT_PRECISION,
            "Invalid f64 conversion beyond `MAX_FLOAT_PRECISION` (16)"
        );

        fixed_i128_to_f64(self.raw)
    }

    #[cfg(not(feature = "high-precision"))]
    /// Returns the value of this instance as an `f64`.
    ///
    /// # Panics
    ///
    /// Panics if precision is beyond `MAX_FLOAT_PRECISION` (16).
    #[must_use]
    pub fn as_f64(&self) -> f64 {
        #[cfg(feature = "defi")]
        if self.precision > MAX_FLOAT_PRECISION {
            panic!("Invalid f64 conversion beyond `MAX_FLOAT_PRECISION` (16)");
        }

        fixed_i64_to_f64(self.raw)
    }

    /// Returns the value of this instance as a `Decimal`.
    #[must_use]
    pub fn as_decimal(&self) -> Decimal {
        // Scale down the raw value to match the precision
        let precision_diff = FIXED_PRECISION.saturating_sub(self.precision);
        let rescaled_raw = self.raw / PriceRaw::pow(10, u32::from(precision_diff));
        #[allow(clippy::unnecessary_cast)]
        Decimal::from_i128_with_scale(rescaled_raw as i128, u32::from(self.precision))
    }

    /// Returns a formatted string representation of this instance.
    #[must_use]
    pub fn to_formatted_string(&self) -> String {
        format!("{self}").separate_with_underscores()
    }

    /// Creates a new [`Price`] from a `Decimal` value with specified precision.
    ///
    /// Uses pure integer arithmetic on the Decimal's mantissa and scale for fast conversion.
    /// The value is rounded to the specified precision using banker's rounding (round half to even).
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - `precision` exceeds [`FIXED_PRECISION`].
    /// - The decimal value cannot be converted to the raw representation.
    /// - Overflow occurs during scaling.
    pub fn from_decimal_dp(decimal: Decimal, precision: u8) -> anyhow::Result<Self> {
        let exponent = -(decimal.scale() as i8);
        let raw_i128 = mantissa_exponent_to_fixed_i128(decimal.mantissa(), exponent, precision)?;

        #[allow(clippy::useless_conversion)]
        let raw: PriceRaw = raw_i128.try_into().map_err(|_| {
            anyhow::anyhow!(
                "Decimal value exceeds PriceRaw range [{PRICE_RAW_MIN}, {PRICE_RAW_MAX}]"
            )
        })?;
        anyhow::ensure!(
            raw >= PRICE_RAW_MIN && raw <= PRICE_RAW_MAX,
            "Raw value {raw} outside valid range [{PRICE_RAW_MIN}, {PRICE_RAW_MAX}] for Price"
        );

        Ok(Self { raw, precision })
    }

    /// Creates a new [`Price`] from a [`Decimal`] value with precision inferred from the decimal's scale.
    ///
    /// The precision is determined by the scale of the decimal (number of decimal places).
    /// The value is rounded to the inferred precision using banker's rounding (round half to even).
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The inferred precision exceeds [`FIXED_PRECISION`].
    /// - The decimal value cannot be converted to the raw representation.
    /// - Overflow occurs during scaling.
    pub fn from_decimal(decimal: Decimal) -> anyhow::Result<Self> {
        let precision = decimal.scale() as u8;
        Self::from_decimal_dp(decimal, precision)
    }

    /// Creates a new [`Price`] from a mantissa/exponent pair using pure integer arithmetic.
    ///
    /// The value is `mantissa * 10^exponent`. This avoids all floating-point and Decimal
    /// operations, making it ideal for exchange data that arrives as mantissa/exponent pairs.
    ///
    /// # Panics
    ///
    /// Panics if the resulting raw value exceeds [`PRICE_RAW_MAX`] or [`PRICE_RAW_MIN`].
    #[must_use]
    pub fn from_mantissa_exponent(mantissa: i64, exponent: i8, precision: u8) -> Self {
        check_fixed_precision(precision).expect(FAILED);

        if mantissa == 0 {
            return Self { raw: 0, precision };
        }

        let raw_i128 = mantissa_exponent_to_fixed_i128(mantissa as i128, exponent, precision)
            .expect("Overflow in Price::from_mantissa_exponent");

        #[allow(clippy::useless_conversion)]
        let raw: PriceRaw = raw_i128
            .try_into()
            .expect("Raw value exceeds PriceRaw range in Price::from_mantissa_exponent");
        assert!(
            raw >= PRICE_RAW_MIN && raw <= PRICE_RAW_MAX,
            "`raw` value {raw} exceeded bounds [{PRICE_RAW_MIN}, {PRICE_RAW_MAX}] for Price"
        );

        Self { raw, precision }
    }
}

impl FromStr for Price {
    type Err = String;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        let clean_value = value.replace('_', "");

        let decimal = if clean_value.contains('e') || clean_value.contains('E') {
            Decimal::from_scientific(&clean_value)
                .map_err(|e| format!("Error parsing `input` string '{value}' as Decimal: {e}"))?
        } else {
            Decimal::from_str(&clean_value)
                .map_err(|e| format!("Error parsing `input` string '{value}' as Decimal: {e}"))?
        };

        // Use decimal scale to preserve caller-specified precision (including trailing zeros)
        let precision = decimal.scale() as u8;

        Self::from_decimal_dp(decimal, precision).map_err(|e| e.to_string())
    }
}

impl<T: AsRef<str>> From<T> for Price {
    fn from(value: T) -> Self {
        Self::from_str(value.as_ref()).expect(FAILED)
    }
}

impl From<Price> for f64 {
    fn from(price: Price) -> Self {
        price.as_f64()
    }
}

impl From<&Price> for f64 {
    fn from(price: &Price) -> Self {
        price.as_f64()
    }
}

impl From<Price> for Decimal {
    fn from(value: Price) -> Self {
        value.as_decimal()
    }
}

impl From<&Price> for Decimal {
    fn from(value: &Price) -> Self {
        value.as_decimal()
    }
}

impl Hash for Price {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.raw.hash(state);
    }
}

impl PartialEq for Price {
    fn eq(&self, other: &Self) -> bool {
        self.raw == other.raw
    }
}

impl PartialOrd for Price {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }

    fn lt(&self, other: &Self) -> bool {
        self.raw.lt(&other.raw)
    }

    fn le(&self, other: &Self) -> bool {
        self.raw.le(&other.raw)
    }

    fn gt(&self, other: &Self) -> bool {
        self.raw.gt(&other.raw)
    }

    fn ge(&self, other: &Self) -> bool {
        self.raw.ge(&other.raw)
    }
}

impl Ord for Price {
    fn cmp(&self, other: &Self) -> Ordering {
        self.raw.cmp(&other.raw)
    }
}

impl Deref for Price {
    type Target = PriceRaw;

    fn deref(&self) -> &Self::Target {
        &self.raw
    }
}

impl Neg for Price {
    type Output = Self;
    fn neg(self) -> Self::Output {
        // Preserve sentinel values (negating PRICE_ERROR would also overflow)
        if self.raw == PRICE_ERROR || self.raw == PRICE_UNDEF {
            return self;
        }
        Self {
            raw: -self.raw,
            precision: self.precision,
        }
    }
}

impl Add for Price {
    type Output = Self;
    fn add(self, rhs: Self) -> Self::Output {
        Self {
            raw: self
                .raw
                .checked_add(rhs.raw)
                .expect("Overflow occurred when adding `Price`"),
            precision: self.precision.max(rhs.precision),
        }
    }
}

impl Sub for Price {
    type Output = Self;
    fn sub(self, rhs: Self) -> Self::Output {
        Self {
            raw: self
                .raw
                .checked_sub(rhs.raw)
                .expect("Underflow occurred when subtracting `Price`"),
            precision: self.precision.max(rhs.precision),
        }
    }
}

impl Add<Decimal> for Price {
    type Output = Decimal;
    fn add(self, rhs: Decimal) -> Self::Output {
        self.as_decimal() + rhs
    }
}

impl Sub<Decimal> for Price {
    type Output = Decimal;
    fn sub(self, rhs: Decimal) -> Self::Output {
        self.as_decimal() - rhs
    }
}

impl Mul<Decimal> for Price {
    type Output = Decimal;
    fn mul(self, rhs: Decimal) -> Self::Output {
        self.as_decimal() * rhs
    }
}

impl Div<Decimal> for Price {
    type Output = Decimal;
    fn div(self, rhs: Decimal) -> Self::Output {
        self.as_decimal() / rhs
    }
}

impl Add<f64> for Price {
    type Output = f64;
    fn add(self, rhs: f64) -> Self::Output {
        self.as_f64() + rhs
    }
}

impl Sub<f64> for Price {
    type Output = f64;
    fn sub(self, rhs: f64) -> Self::Output {
        self.as_f64() - rhs
    }
}

impl Mul<f64> for Price {
    type Output = f64;
    fn mul(self, rhs: f64) -> Self::Output {
        self.as_f64() * rhs
    }
}

impl Div<f64> for Price {
    type Output = f64;
    fn div(self, rhs: f64) -> Self::Output {
        self.as_f64() / rhs
    }
}

impl Debug for Price {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if self.precision > crate::types::fixed::MAX_FLOAT_PRECISION {
            write!(f, "{}({})", stringify!(Price), self.raw)
        } else {
            write!(f, "{}({})", stringify!(Price), self.as_decimal())
        }
    }
}

impl Display for Price {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if self.precision > crate::types::fixed::MAX_FLOAT_PRECISION {
            write!(f, "{}", self.raw)
        } else {
            write!(f, "{}", self.as_decimal())
        }
    }
}

impl Serialize for Price {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_str(&self.to_string())
    }
}

impl<'de> Deserialize<'de> for Price {
    fn deserialize<D>(_deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let price_str: &str = Deserialize::deserialize(_deserializer)?;
        let price: Self = price_str.into();
        Ok(price)
    }
}

/// Checks the price `value` is positive.
///
/// # Errors
///
/// Returns an error if `value` is `PRICE_UNDEF` or not positive.
pub fn check_positive_price(value: Price, param: &str) -> anyhow::Result<()> {
    if value.raw == PRICE_UNDEF {
        anyhow::bail!("invalid `Price` for '{param}', was PRICE_UNDEF")
    }

    if !value.is_positive() {
        anyhow::bail!("invalid `Price` for '{param}' not positive, was {value}")
    }
    Ok(())
}

#[cfg(feature = "high-precision")]
/// The raw i64 price has already been scaled by 10^9. Further scale it by the difference to
/// `FIXED_PRECISION` to make it high/defi-precision raw price.
pub fn decode_raw_price_i64(value: i64) -> PriceRaw {
    value as PriceRaw * PRECISION_DIFF_SCALAR as PriceRaw
}

#[cfg(not(feature = "high-precision"))]
pub fn decode_raw_price_i64(value: i64) -> PriceRaw {
    value
}

#[cfg(test)]
mod tests {
    use nautilus_core::approx_eq;
    use rstest::rstest;
    use rust_decimal_macros::dec;

    use super::*;

    #[rstest]
    #[cfg(all(not(feature = "defi"), not(feature = "high-precision")))]
    #[should_panic(expected = "`precision` exceeded maximum `FIXED_PRECISION` (9), was 50")]
    fn test_invalid_precision_new() {
        // Precision exceeds float precision limit
        let _ = Price::new(1.0, 50);
    }

    #[rstest]
    #[cfg(all(not(feature = "defi"), feature = "high-precision"))]
    #[should_panic(expected = "`precision` exceeded maximum `FIXED_PRECISION` (16), was 50")]
    fn test_invalid_precision_new() {
        // Precision exceeds float precision limit
        let _ = Price::new(1.0, 50);
    }

    #[rstest]
    #[cfg(not(feature = "defi"))]
    #[should_panic(expected = "Condition failed: `precision` exceeded maximum `FIXED_PRECISION`")]
    fn test_invalid_precision_from_raw() {
        // Precision out of range for fixed
        let _ = Price::from_raw(1, FIXED_PRECISION + 1);
    }

    #[rstest]
    #[cfg(not(feature = "defi"))]
    #[should_panic(expected = "Condition failed: `precision` exceeded maximum `FIXED_PRECISION`")]
    fn test_invalid_precision_max() {
        // Precision out of range for fixed
        let _ = Price::max(FIXED_PRECISION + 1);
    }

    #[rstest]
    #[cfg(not(feature = "defi"))]
    #[should_panic(expected = "Condition failed: `precision` exceeded maximum `FIXED_PRECISION`")]
    fn test_invalid_precision_min() {
        // Precision out of range for fixed
        let _ = Price::min(FIXED_PRECISION + 1);
    }

    #[rstest]
    #[cfg(not(feature = "defi"))]
    #[should_panic(expected = "Condition failed: `precision` exceeded maximum `FIXED_PRECISION`")]
    fn test_invalid_precision_zero() {
        // Precision out of range for fixed
        let _ = Price::zero(FIXED_PRECISION + 1);
    }

    #[rstest]
    #[should_panic(expected = "Condition failed: invalid f64 for 'value' not in range")]
    fn test_max_value_exceeded() {
        Price::new(PRICE_MAX + 0.1, FIXED_PRECISION);
    }

    #[rstest]
    #[should_panic(expected = "Condition failed: invalid f64 for 'value' not in range")]
    fn test_min_value_exceeded() {
        Price::new(PRICE_MIN - 0.1, FIXED_PRECISION);
    }

    #[rstest]
    fn test_is_positive_ok() {
        // A normal, non‑zero price should be positive.
        let price = Price::new(42.0, 2);
        assert!(price.is_positive());

        // `check_positive_price` should accept it without error.
        check_positive_price(price, "price").unwrap();
    }

    #[rstest]
    #[should_panic(expected = "invalid `Price` for 'price' not positive")]
    fn test_is_positive_rejects_non_positive() {
        // Zero is NOT positive.
        let zero = Price::zero(2);
        check_positive_price(zero, "price").unwrap();
    }

    #[rstest]
    #[should_panic(expected = "invalid `Price` for 'price', was PRICE_UNDEF")]
    fn test_is_positive_rejects_undefined() {
        // PRICE_UNDEF must also be rejected.
        let undef = Price::from_raw(PRICE_UNDEF, 0);
        check_positive_price(undef, "price").unwrap();
    }

    #[rstest]
    fn test_construction() {
        let price = Price::new_checked(1.23456, 4);
        assert!(price.is_ok());
        let price = price.unwrap();
        assert_eq!(price.precision, 4);
        assert!(approx_eq!(f64, price.as_f64(), 1.23456, epsilon = 0.0001));
    }

    #[rstest]
    fn test_negative_price_in_range() {
        // Use max fixed precision which varies based on feature flags
        let neg_price = Price::new(PRICE_MIN / 2.0, FIXED_PRECISION);
        assert!(neg_price.raw < 0);
    }

    #[rstest]
    fn test_new_checked() {
        // Use max fixed precision which varies based on feature flags
        assert!(Price::new_checked(1.0, FIXED_PRECISION).is_ok());
        assert!(Price::new_checked(f64::NAN, FIXED_PRECISION).is_err());
        assert!(Price::new_checked(f64::INFINITY, FIXED_PRECISION).is_err());
    }

    #[rstest]
    fn test_from_raw() {
        let raw = 100 * FIXED_SCALAR as PriceRaw;
        let price = Price::from_raw(raw, 2);
        assert_eq!(price.raw, raw);
        assert_eq!(price.precision, 2);
    }

    #[rstest]
    fn test_zero_constructor() {
        let zero = Price::zero(3);
        assert!(zero.is_zero());
        assert_eq!(zero.precision, 3);
    }

    #[rstest]
    fn test_max_constructor() {
        let max = Price::max(4);
        assert_eq!(max.raw, PRICE_RAW_MAX);
        assert_eq!(max.precision, 4);
    }

    #[rstest]
    fn test_min_constructor() {
        let min = Price::min(4);
        assert_eq!(min.raw, PRICE_RAW_MIN);
        assert_eq!(min.precision, 4);
    }

    #[rstest]
    fn test_nan_validation() {
        assert!(Price::new_checked(f64::NAN, FIXED_PRECISION).is_err());
    }

    #[rstest]
    fn test_infinity_validation() {
        assert!(Price::new_checked(f64::INFINITY, FIXED_PRECISION).is_err());
        assert!(Price::new_checked(f64::NEG_INFINITY, FIXED_PRECISION).is_err());
    }

    #[rstest]
    fn test_special_values() {
        let zero = Price::zero(5);
        assert!(zero.is_zero());
        assert_eq!(zero.to_string(), "0.00000");

        let undef = Price::from_raw(PRICE_UNDEF, 0);
        assert!(undef.is_undefined());

        let error = ERROR_PRICE;
        assert_eq!(error.precision, 255);
    }

    #[rstest]
    fn test_string_parsing() {
        let price: Price = "123.456".into();
        assert_eq!(price.precision, 3);
        assert_eq!(price, Price::from("123.456"));
    }

    #[rstest]
    fn test_negative_price_from_str() {
        let price: Price = "-123.45".parse().unwrap();
        assert_eq!(price.precision, 2);
        assert!(approx_eq!(f64, price.as_f64(), -123.45, epsilon = 1e-9));
    }

    #[rstest]
    fn test_string_parsing_errors() {
        assert!(Price::from_str("invalid").is_err());
    }

    #[rstest]
    #[case("1e7", 0, 10_000_000.0)]
    #[case("1.5e3", 0, 1_500.0)]
    #[case("1.234e-2", 5, 0.01234)]
    #[case("5E-3", 3, 0.005)]
    fn test_from_str_scientific_notation(
        #[case] input: &str,
        #[case] expected_precision: u8,
        #[case] expected_value: f64,
    ) {
        let price = Price::from_str(input).unwrap();
        assert_eq!(price.precision, expected_precision);
        assert!(approx_eq!(
            f64,
            price.as_f64(),
            expected_value,
            epsilon = 1e-10
        ));
    }

    #[rstest]
    #[case("1_234.56", 2, 1234.56)]
    #[case("1_000_000", 0, 1_000_000.0)]
    #[case("99_999.999_99", 5, 99_999.999_99)]
    fn test_from_str_with_underscores(
        #[case] input: &str,
        #[case] expected_precision: u8,
        #[case] expected_value: f64,
    ) {
        let price = Price::from_str(input).unwrap();
        assert_eq!(price.precision, expected_precision);
        assert!(approx_eq!(
            f64,
            price.as_f64(),
            expected_value,
            epsilon = 1e-10
        ));
    }

    #[rstest]
    fn test_from_decimal_dp_preservation() {
        // Test that decimal conversion preserves exact values
        let decimal = dec!(123.456789);
        let price = Price::from_decimal_dp(decimal, 6).unwrap();
        assert_eq!(price.precision, 6);
        assert!(approx_eq!(f64, price.as_f64(), 123.456789, epsilon = 1e-10));

        // Verify raw value is exact
        let expected_raw = 123456789 * 10_i64.pow((FIXED_PRECISION - 6) as u32);
        assert_eq!(price.raw, expected_raw as PriceRaw);
    }

    #[rstest]
    fn test_from_decimal_dp_rounding() {
        // Test banker's rounding (round half to even)
        let decimal = dec!(1.005);
        let price = Price::from_decimal_dp(decimal, 2).unwrap();
        assert_eq!(price.as_f64(), 1.0); // 1.005 rounds to 1.00 (even)

        let decimal = dec!(1.015);
        let price = Price::from_decimal_dp(decimal, 2).unwrap();
        assert_eq!(price.as_f64(), 1.02); // 1.015 rounds to 1.02 (even)
    }

    #[rstest]
    fn test_from_decimal_infers_precision() {
        // Test that precision is inferred from decimal's scale
        let decimal = dec!(123.456);
        let price = Price::from_decimal(decimal).unwrap();
        assert_eq!(price.precision, 3);
        assert!(approx_eq!(f64, price.as_f64(), 123.456, epsilon = 1e-10));

        // Test with integer (precision 0)
        let decimal = dec!(100);
        let price = Price::from_decimal(decimal).unwrap();
        assert_eq!(price.precision, 0);
        assert_eq!(price.as_f64(), 100.0);

        // Test with high precision
        let decimal = dec!(1.23456789);
        let price = Price::from_decimal(decimal).unwrap();
        assert_eq!(price.precision, 8);
        assert!(approx_eq!(f64, price.as_f64(), 1.23456789, epsilon = 1e-10));
    }

    #[rstest]
    fn test_from_decimal_trailing_zeros() {
        // Decimal preserves trailing zeros in scale
        let decimal = dec!(1.230);
        assert_eq!(decimal.scale(), 3); // Has 3 decimal places

        // from_decimal infers precision from scale (includes trailing zeros)
        let price = Price::from_decimal(decimal).unwrap();
        assert_eq!(price.precision, 3);
        assert!(approx_eq!(f64, price.as_f64(), 1.23, epsilon = 1e-10));

        // Normalized removes trailing zeros
        let normalized = decimal.normalize();
        assert_eq!(normalized.scale(), 2);
        let price_normalized = Price::from_decimal(normalized).unwrap();
        assert_eq!(price_normalized.precision, 2);
    }

    #[rstest]
    #[case("1.00", 2)]
    #[case("1.0", 1)]
    #[case("1.000", 3)]
    #[case("100.00", 2)]
    #[case("0.10", 2)]
    #[case("0.100", 3)]
    fn test_from_str_preserves_trailing_zeros(#[case] input: &str, #[case] expected_precision: u8) {
        let price = Price::from_str(input).unwrap();
        assert_eq!(price.precision, expected_precision);
    }

    #[rstest]
    fn test_from_decimal_excessive_precision_inference() {
        // Create a decimal with more precision than FIXED_PRECISION
        // Decimal supports up to 28 decimal places
        let decimal = dec!(1.1234567890123456789012345678);

        // If scale exceeds FIXED_PRECISION, from_decimal should error
        if decimal.scale() > FIXED_PRECISION as u32 {
            assert!(Price::from_decimal(decimal).is_err());
        }
    }

    #[rstest]
    fn test_from_decimal_negative_price() {
        // Negative prices are valid for Price
        let decimal = dec!(-123.45);
        let price = Price::from_decimal(decimal).unwrap();
        assert_eq!(price.precision, 2);
        assert!(approx_eq!(f64, price.as_f64(), -123.45, epsilon = 1e-10));
        assert!(price.raw < 0);
    }

    #[rstest]
    fn test_string_formatting() {
        assert_eq!(format!("{}", Price::new(1234.5678, 4)), "1234.5678");
        assert_eq!(
            format!("{:?}", Price::new(1234.5678, 4)),
            "Price(1234.5678)"
        );
        assert_eq!(Price::new(1234.5678, 4).to_formatted_string(), "1_234.5678");
    }

    #[rstest]
    #[case(1234.5678, 4, "Price(1234.5678)", "1234.5678")] // Normal precision
    #[case(123.456789012345, 8, "Price(123.45678901)", "123.45678901")] // At max normal precision
    #[cfg_attr(
        feature = "defi",
        case(
            2_000_000_000_000_000_000.0,
            18,
            "Price(2000000000000000000)",
            "2000000000000000000"
        )
    )] // High precision
    fn test_string_formatting_precision_handling(
        #[case] value: f64,
        #[case] precision: u8,
        #[case] expected_debug: &str,
        #[case] expected_display: &str,
    ) {
        let price = if precision > crate::types::fixed::MAX_FLOAT_PRECISION {
            Price::from_raw(value as PriceRaw, precision)
        } else {
            Price::new(value, precision)
        };

        assert_eq!(format!("{price:?}"), expected_debug);
        assert_eq!(format!("{price}"), expected_display);
        assert_eq!(
            price.to_formatted_string().replace('_', ""),
            expected_display
        );
    }

    #[rstest]
    fn test_decimal_conversions() {
        let price = Price::new(123.456, 3);
        assert_eq!(price.as_decimal(), dec!(123.456));

        let price = Price::new(0.000001, 6);
        assert_eq!(price.as_decimal(), dec!(0.000001));
    }

    #[rstest]
    fn test_basic_arithmetic() {
        let p1 = Price::new(10.5, 2);
        let p2 = Price::new(5.25, 2);
        assert_eq!(p1 + p2, Price::from("15.75"));
        assert_eq!(p1 - p2, Price::from("5.25"));
        assert_eq!(-p1, Price::from("-10.5"));
    }

    #[rstest]
    fn test_mixed_precision_add() {
        let p1 = Price::new(10.5, 1);
        let p2 = Price::new(5.25, 2);
        let result = p1 + p2;
        assert_eq!(result.precision, 2);
        assert_eq!(result.as_f64(), 15.75);
    }

    #[rstest]
    fn test_mixed_precision_sub() {
        let p1 = Price::new(10.5, 1);
        let p2 = Price::new(5.25, 2);
        let result = p1 - p2;
        assert_eq!(result.precision, 2);
        assert_eq!(result.as_f64(), 5.25);
    }

    #[rstest]
    fn test_f64_operations() {
        let p = Price::new(10.5, 2);
        assert_eq!(p + 1.0, 11.5);
        assert_eq!(p - 1.0, 9.5);
        assert_eq!(p * 2.0, 21.0);
        assert_eq!(p / 2.0, 5.25);
    }

    #[rstest]
    fn test_equality_and_comparisons() {
        let p1 = Price::new(10.0, 1);
        let p2 = Price::new(20.0, 1);
        let p3 = Price::new(10.0, 1);

        assert!(p1 < p2);
        assert!(p2 > p1);
        assert!(p1 <= p3);
        assert!(p1 >= p3);
        assert_eq!(p1, p3);
        assert_ne!(p1, p2);

        assert_eq!(Price::from("1.0"), Price::from("1.0"));
        assert_ne!(Price::from("1.1"), Price::from("1.0"));
        assert!(Price::from("1.0") <= Price::from("1.0"));
        assert!(Price::from("1.1") > Price::from("1.0"));
        assert!(Price::from("1.0") >= Price::from("1.0"));
        assert!(Price::from("1.0") >= Price::from("1.0"));
        assert!(Price::from("1.0") >= Price::from("1.0"));
        assert!(Price::from("0.9") < Price::from("1.0"));
        assert!(Price::from("0.9") <= Price::from("1.0"));
        assert!(Price::from("0.9") <= Price::from("1.0"));
    }

    #[rstest]
    fn test_deref() {
        let price = Price::new(10.0, 1);
        assert_eq!(*price, price.raw);
    }

    #[rstest]
    fn test_decode_raw_price_i64() {
        let raw_scaled_by_1e9 = 42_000_000_000i64; // 42.0 * 10^9
        let decoded = decode_raw_price_i64(raw_scaled_by_1e9);
        let price = Price::from_raw(decoded, FIXED_PRECISION);
        assert!(
            approx_eq!(f64, price.as_f64(), 42.0, epsilon = 1e-9),
            "Expected 42.0 f64, was {} (precision = {})",
            price.as_f64(),
            price.precision
        );
    }

    #[rstest]
    fn test_hash() {
        use std::{
            collections::hash_map::DefaultHasher,
            hash::{Hash, Hasher},
        };

        let price1 = Price::new(1.0, 2);
        let price2 = Price::new(1.0, 2);
        let price3 = Price::new(1.1, 2);

        let mut hasher1 = DefaultHasher::new();
        let mut hasher2 = DefaultHasher::new();
        let mut hasher3 = DefaultHasher::new();

        price1.hash(&mut hasher1);
        price2.hash(&mut hasher2);
        price3.hash(&mut hasher3);

        assert_eq!(hasher1.finish(), hasher2.finish());
        assert_ne!(hasher1.finish(), hasher3.finish());
    }

    #[rstest]
    fn test_price_serde_json_round_trip() {
        let price = Price::new(1.0500, 4);
        let json = serde_json::to_string(&price).unwrap();
        let deserialized: Price = serde_json::from_str(&json).unwrap();
        assert_eq!(deserialized, price);
    }

    #[rstest]
    fn test_from_mantissa_exponent_exact_precision() {
        let price = Price::from_mantissa_exponent(12345, -2, 2);
        assert_eq!(price.as_f64(), 123.45);
    }

    #[rstest]
    fn test_from_mantissa_exponent_excess_rounds_down() {
        // 12.345 rounds to 12.34 (4 is even, banker's rounding)
        let price = Price::from_mantissa_exponent(12345, -3, 2);
        assert_eq!(price.as_f64(), 12.34);
    }

    #[rstest]
    fn test_from_mantissa_exponent_excess_rounds_up() {
        // 12.355 rounds to 12.36 (5 is odd, banker's rounding)
        let price = Price::from_mantissa_exponent(12355, -3, 2);
        assert_eq!(price.as_f64(), 12.36);
    }

    #[rstest]
    fn test_from_mantissa_exponent_positive_exponent() {
        let price = Price::from_mantissa_exponent(5, 2, 0);
        assert_eq!(price.as_f64(), 500.0);
    }

    #[rstest]
    fn test_from_mantissa_exponent_negative_mantissa() {
        let price = Price::from_mantissa_exponent(-12345, -2, 2);
        assert_eq!(price.as_f64(), -123.45);
    }

    #[rstest]
    fn test_from_mantissa_exponent_zero() {
        let price = Price::from_mantissa_exponent(0, 2, 2);
        assert_eq!(price.as_f64(), 0.0);
    }

    #[rstest]
    #[should_panic]
    fn test_from_mantissa_exponent_overflow_panics() {
        let _ = Price::from_mantissa_exponent(i64::MAX, 9, 0);
    }

    #[rstest]
    #[should_panic(expected = "exceeds i128 range")]
    fn test_from_mantissa_exponent_large_exponent_panics() {
        let _ = Price::from_mantissa_exponent(1, 119, 0);
    }

    #[rstest]
    fn test_from_mantissa_exponent_zero_with_large_exponent() {
        let price = Price::from_mantissa_exponent(0, 119, 0);
        assert_eq!(price.as_f64(), 0.0);
    }

    #[rstest]
    fn test_from_mantissa_exponent_very_negative_exponent_rounds_to_zero() {
        let price = Price::from_mantissa_exponent(12345, -120, 2);
        assert_eq!(price.as_f64(), 0.0);
    }

    #[rstest]
    fn test_decimal_arithmetic_operations() {
        let price = Price::new(100.0, 2);
        assert_eq!(price + dec!(50.25), dec!(150.25));
        assert_eq!(price - dec!(30.50), dec!(69.50));
        assert_eq!(price * dec!(1.5), dec!(150.00));
        assert_eq!(price / dec!(4), dec!(25.00));
    }
}

#[cfg(test)]
mod property_tests {
    use proptest::prelude::*;
    use rstest::rstest;

    use super::*;

    /// Strategy to generate valid price values within the allowed range.
    fn price_value_strategy() -> impl Strategy<Value = f64> {
        // Use a reasonable range that's well within PRICE_MIN/PRICE_MAX
        // but still tests edge cases with various scales
        prop_oneof![
            // Small positive values
            0.00001..1.0,
            // Normal trading range
            1.0..100_000.0,
            // Large values (but safe)
            100_000.0..1_000_000.0,
            // Small negative values (for spreads, etc.)
            -1_000.0..0.0,
            // Boundary values close to the extremes
            Just(PRICE_MIN / 2.0),
            Just(PRICE_MAX / 2.0),
        ]
    }

    fn float_precision_upper_bound() -> u8 {
        FIXED_PRECISION.min(crate::types::fixed::MAX_FLOAT_PRECISION)
    }

    /// Strategy to exercise both typical and extreme precision values.
    fn precision_strategy() -> impl Strategy<Value = u8> {
        let upper = float_precision_upper_bound();
        prop_oneof![Just(0u8), 0u8..=upper, Just(FIXED_PRECISION),]
    }

    fn precision_strategy_non_zero() -> impl Strategy<Value = u8> {
        let upper = float_precision_upper_bound().max(1);
        prop_oneof![Just(upper), Just(FIXED_PRECISION.max(1)), 1u8..=upper,]
    }

    /// Strategy to generate a valid (precision, raw) pair where raw is properly scaled.
    ///
    /// Raw values must be multiples of 10^(FIXED_PRECISION - precision) to pass validation.
    fn valid_precision_raw_strategy() -> impl Strategy<Value = (u8, PriceRaw)> {
        precision_strategy().prop_flat_map(|precision| {
            let scale: PriceRaw = if precision >= FIXED_PRECISION {
                1
            } else {
                (10 as PriceRaw).pow(u32::from(FIXED_PRECISION - precision))
            };
            // Generate a base value, then multiply by scale to ensure valid raw
            let max_base = PRICE_RAW_MAX / scale;
            let min_base = PRICE_RAW_MIN / scale;
            (min_base..=max_base).prop_map(move |base| (precision, base * scale))
        })
    }

    /// Strategy to generate valid precision values for float-based constructors.
    fn float_precision_strategy() -> impl Strategy<Value = u8> {
        precision_strategy()
    }

    const DECIMAL_MAX_MANTISSA: i128 = 79_228_162_514_264_337_593_543_950_335;

    #[allow(
        clippy::useless_conversion,
        reason = "PriceRaw is i64 or i128 depending on feature"
    )]
    fn decimal_compatible(raw: PriceRaw, precision: u8) -> bool {
        if precision > crate::types::fixed::MAX_FLOAT_PRECISION {
            return false;
        }
        let precision_diff = u32::from(FIXED_PRECISION.saturating_sub(precision));
        let divisor = (10 as PriceRaw).pow(precision_diff);
        let rescaled_raw = raw / divisor;
        i128::from(rescaled_raw.abs()) <= DECIMAL_MAX_MANTISSA
    }

    proptest! {
        /// Property: Price string serialization round-trip should preserve value and precision
        #[rstest]
        fn prop_price_serde_round_trip(
            value in price_value_strategy().prop_filter("Reasonable values", |&x| x.abs() < 1e6),
            precision in precision_strategy()
        ) {
            let original = Price::new(value, precision);

            // String round-trip (this should be exact and is the most important)
            let string_repr = original.to_string();
            let from_string: Price = string_repr.parse().unwrap();
            prop_assert_eq!(from_string.raw, original.raw);
            prop_assert_eq!(from_string.precision, original.precision);

            // JSON round-trip basic validation (just ensure it doesn't crash and preserves precision)
            let json = serde_json::to_string(&original).unwrap();
            let from_json: Price = serde_json::from_str(&json).unwrap();
            prop_assert_eq!(from_json.precision, original.precision);
            // Note: JSON may have minor floating-point precision differences due to f64 limitations
        }

        /// Property: Price arithmetic should be associative for same precision
        #[rstest]
        fn prop_price_arithmetic_associative(
            a in price_value_strategy().prop_filter("Reasonable values", |&x| x.abs() > 1e-3 && x.abs() < 1e6),
            b in price_value_strategy().prop_filter("Reasonable values", |&x| x.abs() > 1e-3 && x.abs() < 1e6),
            c in price_value_strategy().prop_filter("Reasonable values", |&x| x.abs() > 1e-3 && x.abs() < 1e6),
            precision in precision_strategy()
        ) {
            let p_a = Price::new(a, precision);
            let p_b = Price::new(b, precision);
            let p_c = Price::new(c, precision);

            // Check if we can perform the operations without overflow using raw arithmetic
            let ab_raw = p_a.raw.checked_add(p_b.raw);
            let bc_raw = p_b.raw.checked_add(p_c.raw);

            if let (Some(ab_raw), Some(bc_raw)) = (ab_raw, bc_raw) {
                let ab_c_raw = ab_raw.checked_add(p_c.raw);
                let a_bc_raw = p_a.raw.checked_add(bc_raw);

                if let (Some(ab_c_raw), Some(a_bc_raw)) = (ab_c_raw, a_bc_raw) {
                    // (a + b) + c == a + (b + c) using raw arithmetic (exact)
                    prop_assert_eq!(ab_c_raw, a_bc_raw, "Associativity failed in raw arithmetic");
                }
            }
        }

        /// Property: Price addition/subtraction should be inverse operations
        #[rstest]
        fn prop_price_addition_subtraction_inverse(
            base in price_value_strategy().prop_filter("Reasonable values", |&x| x.abs() < 1e6),
            delta in price_value_strategy().prop_filter("Reasonable values", |&x| x.abs() > 1e-3 && x.abs() < 1e6),
            precision in precision_strategy()
        ) {
            let p_base = Price::new(base, precision);
            let p_delta = Price::new(delta, precision);

            // Use raw arithmetic to avoid floating-point precision issues
            if let Some(added_raw) = p_base.raw.checked_add(p_delta.raw)
                && let Some(result_raw) = added_raw.checked_sub(p_delta.raw) {
                    // (base + delta) - delta should equal base exactly using raw arithmetic
                    prop_assert_eq!(result_raw, p_base.raw, "Inverse operation failed in raw arithmetic");
                }
        }

        /// Property: Price ordering should be transitive
        #[rstest]
        fn prop_price_ordering_transitive(
            a in price_value_strategy(),
            b in price_value_strategy(),
            c in price_value_strategy(),
            precision in float_precision_strategy()
        ) {
            let p_a = Price::new(a, precision);
            let p_b = Price::new(b, precision);
            let p_c = Price::new(c, precision);

            // If a <= b and b <= c, then a <= c
            if p_a <= p_b && p_b <= p_c {
                prop_assert!(p_a <= p_c, "Transitivity failed: {} <= {} <= {} but {} > {}",
                    p_a.as_f64(), p_b.as_f64(), p_c.as_f64(), p_a.as_f64(), p_c.as_f64());
            }
        }

        /// Property: String parsing should be consistent with precision inference
        #[rstest]
        fn prop_price_string_parsing_precision(
            integral in 0u32..1000000,
            fractional in 0u32..1000000,
            precision in precision_strategy_non_zero()
        ) {
            // Create a decimal string with exactly 'precision' decimal places
            let pow = 10u128.pow(u32::from(precision));
            let fractional_mod = (fractional as u128) % pow;
            let fractional_str = format!("{:0width$}", fractional_mod, width = precision as usize);
            let price_str = format!("{integral}.{fractional_str}");

            let parsed: Price = price_str.parse().unwrap();
            prop_assert_eq!(parsed.precision, precision);

            // Round-trip should preserve the original string (after normalization)
            let round_trip = parsed.to_string();
            let expected_value = format!("{integral}.{fractional_str}");
            prop_assert_eq!(round_trip, expected_value);
        }

        /// Property: Price with higher precision should contain more or equal information
        #[rstest]
        fn prop_price_precision_information_preservation(
            value in price_value_strategy().prop_filter("Reasonable values", |&x| x.abs() < 1e6),
            precision1 in precision_strategy_non_zero(),
            precision2 in precision_strategy_non_zero()
        ) {
            // Skip cases where precisions are equal (trivial case)
            prop_assume!(precision1 != precision2);

            let _p1 = Price::new(value, precision1);
            let _p2 = Price::new(value, precision2);

            // When both prices are created from the same value with different precisions,
            // converting both to the lower precision should yield the same result
            let min_precision = precision1.min(precision2);

            // Round the original value to the minimum precision first
            let scale = 10.0_f64.powi(min_precision as i32);
            let rounded_value = (value * scale).round() / scale;

            let p1_reduced = Price::new(rounded_value, min_precision);
            let p2_reduced = Price::new(rounded_value, min_precision);

            // They should be exactly equal when created from the same rounded value
            prop_assert_eq!(p1_reduced.raw, p2_reduced.raw, "Precision reduction inconsistent");
        }

        /// Property: Price arithmetic should never produce invalid values
        #[rstest]
        fn prop_price_arithmetic_bounds(
            a in price_value_strategy(),
            b in price_value_strategy(),
            precision in float_precision_strategy()
        ) {
            let p_a = Price::new(a, precision);
            let p_b = Price::new(b, precision);

            // Addition should either succeed or fail predictably
            let sum_f64 = p_a.as_f64() + p_b.as_f64();
            if sum_f64.is_finite() && (PRICE_MIN..=PRICE_MAX).contains(&sum_f64) {
                let sum = p_a + p_b;
                prop_assert!(sum.as_f64().is_finite());
                prop_assert!(!sum.is_undefined());
            }

            // Subtraction should either succeed or fail predictably
            let diff_f64 = p_a.as_f64() - p_b.as_f64();
            if diff_f64.is_finite() && (PRICE_MIN..=PRICE_MAX).contains(&diff_f64) {
                let diff = p_a - p_b;
                prop_assert!(diff.as_f64().is_finite());
                prop_assert!(!diff.is_undefined());
            }
        }
    }

    proptest! {
        /// Property: as_decimal scale always matches precision
        #[rstest]
        fn prop_price_as_decimal_preserves_precision(
            (precision, raw) in valid_precision_raw_strategy()
        ) {
            prop_assume!(decimal_compatible(raw, precision));
            let price = Price::from_raw(raw, precision);
            let decimal = price.as_decimal();
            prop_assert_eq!(decimal.scale(), u32::from(precision));
        }

        /// Property: as_decimal and Display produce the same string
        #[rstest]
        fn prop_price_as_decimal_matches_display(
            value in price_value_strategy().prop_filter("Reasonable values", |&x| x.abs() < 1e6),
            precision in float_precision_strategy()
        ) {
            let price = Price::new(value, precision);
            prop_assume!(decimal_compatible(price.raw, precision));
            let display_str = format!("{price}");
            let decimal_str = price.as_decimal().to_string();
            prop_assert_eq!(display_str, decimal_str);
        }

        /// Property: from_decimal roundtrip preserves exact value
        #[rstest]
        fn prop_price_from_decimal_roundtrip(
            (precision, raw) in valid_precision_raw_strategy()
        ) {
            prop_assume!(decimal_compatible(raw, precision));
            let original = Price::from_raw(raw, precision);
            let decimal = original.as_decimal();
            let reconstructed = Price::from_decimal(decimal).unwrap();
            prop_assert_eq!(original.raw, reconstructed.raw);
            prop_assert_eq!(original.precision, reconstructed.precision);
        }

        /// Property: constructing from valid raw values preserves raw/precision fields
        #[rstest]
        fn prop_price_from_raw_round_trip(
            (precision, raw) in valid_precision_raw_strategy()
        ) {
            let price = Price::from_raw(raw, precision);
            prop_assert_eq!(price.raw, raw);
            prop_assert_eq!(price.precision, precision);
        }
    }
}