chapaty 1.3.0

An event-driven Rust engine for building and evaluating quantitative trading agents. Features a Gym-style API for algorithmic backtesting and reinforcement learning.
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
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
use std::{cmp::Ordering, fmt, str::FromStr};

use chrono::{DateTime, NaiveDate, NaiveTime, Timelike, Utc};
use chrono_tz::Tz;
use polars::prelude::{Expr, col, lit};
use serde::{Deserialize, Serialize};
use strum::{AsRefStr, Display, EnumIter, IntoStaticStr};
use strum_macros::EnumString;

use crate::{
    error::{ChapatyError, DataError, TransportError},
    generated::chapaty::{
        bq_exporter::v1::{
            EconomicCategory as RpcEconomicCategory, EconomicImportance as RpcEconomicImportance,
        },
        data::v1::DataBroker as RpcDataBroker,
    },
    transport::schema::CanonicalCol,
};

// ================================================================================================
// Domain Strong Types (NewTypes)
// ================================================================================================

/// Represents a price level in the quote currency.
///
/// Used for: Open, High, Low, Close, Trade Price, Stops, and Take Profits.
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Default, Serialize, Deserialize)]
pub struct Price(pub f64);
impl_from_primitive!(Price, f64);
impl_add_sub_mul_div_primitive!(Price, f64);
impl_neg_primitive!(Price, f64);
impl_abs_primitive!(Price, f64);
impl_min_max_primitive!(Price, f64);

/// Represents a price level in the quote currency.
///
/// Used for: Open, High, Low, Close, Trade Price, Stops, and Take Profits.
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Default, Serialize, Deserialize)]
pub struct PriceDelta(pub f64);
impl_from_primitive!(PriceDelta, f64);
impl_add_sub_mul_div_primitive!(PriceDelta, f64);
impl_neg_primitive!(PriceDelta, f64);
impl_abs_primitive!(PriceDelta, f64);
impl_min_max_primitive!(PriceDelta, f64);

/// Represents the smallest discrete movement of an asset.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default, Serialize, Deserialize)]
pub struct Tick(pub i64);
impl_from_primitive!(Tick, i64);
impl_add_sub_mul_div_primitive!(Tick, i64);
impl_neg_primitive!(Tick, i64);
impl_abs_primitive!(Tick, i64);

/// Represents a precise amount of the **Base Asset**.
///
/// This is the fundamental unit for Orders (Quantity), Trades (Size), and
/// Market Data (Volume). It wraps `f64` to support fractional assets while
/// providing strong typing against Price or other metrics.
///
/// # Semantics
/// - **Negative values** are generally not allowed in storage but may appear in
///   delta calculations.
/// - **Precision** is handled via standard `f64` IEEE-754 semantics.
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Default, Serialize, Deserialize)]
pub struct Quantity(pub f64);
impl_from_primitive!(Quantity, f64);
impl_add_sub_mul_div_primitive!(Quantity, f64);
impl_min_max_primitive!(Quantity, f64);

/// Semantic alias for `Quantity` when referring to aggregated market activity.
///
/// Use this in contexts like `Ohlcv` or `DailyStats` to indicate the data
/// represents a summation of trades, rather than a single order size.
pub type Volume = Quantity;

/// Represents a generic count (e.g., number of trades, TPO slots).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default, Serialize, Deserialize)]
pub struct Count(pub i64);
impl_from_primitive!(Count, i64);

/// Represents a unique trade identifier from the exchange.
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default, Serialize, Deserialize,
)]
pub struct TradeId(pub i64);
impl_from_primitive!(TradeId, i64);

/// Represents the sequential index of a generic timeframe (e.g., "Week 42").
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct TimeframeIdx(pub u32);
impl_from_primitive!(TimeframeIdx, u32);

/// Represents a macro-economic indicator value (Actual, Forecast, Previous).
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Default, Serialize, Deserialize)]
pub struct EconomicValue(pub f64);
impl_from_primitive!(EconomicValue, f64);
impl_add_sub_mul_div_primitive!(EconomicValue, f64);
impl_min_max_primitive!(EconomicValue, f64);

/// Represents the directional outcome of a candlestick,
/// based on the relationship between its open and close prices.
///
/// - [`CandleDirection::Bullish`] — the close is higher than the open.
/// - [`CandleDirection::Bearish`] — the close is lower than the open.
/// - [`CandleDirection::Doji`] — the open and close are equal (indecision).
#[derive(
    Debug,
    Clone,
    Copy,
    PartialEq,
    PartialOrd,
    Eq,
    Hash,
    Serialize,
    Deserialize,
    EnumString,
    EnumIter,
)]
#[strum(serialize_all = "lowercase")]
pub enum CandleDirection {
    /// Close > Open (upward / bullish candle)
    Bullish,
    /// Close < Open (downward / bearish candle)
    Bearish,
    /// Close == Open (neutral / indecision candle, often called a "doji")
    Doji,
}

/// Represents the aggressor side of a trade (the "Taker").
///
/// This is the side that "crossed the spread" to make the trade happen.
/// - **Buy:** A market buy order lifted an ask.
/// - **Sell:** A market sell order hit a bid.
#[derive(
    Debug,
    Clone,
    Copy,
    PartialEq,
    PartialOrd,
    Eq,
    Hash,
    Serialize,
    Deserialize,
    EnumString,
    EnumIter,
)]
#[strum(serialize_all = "lowercase")]
pub enum TradeSide {
    Buy,
    Sell,
}

/// Indicates which side of the Order Book provided the liquidity.
///
/// This replaces the raw `is_buyer_maker` boolean:
/// - `true`  -> `LiquiditySide::Bid` (Maker was Buyer, Aggressor Sold)
/// - `false` -> `LiquiditySide::Ask` (Maker was Seller, Aggressor Bought)
#[derive(
    Debug,
    Clone,
    Copy,
    PartialEq,
    PartialOrd,
    Eq,
    Hash,
    Serialize,
    Deserialize,
    EnumString,
    EnumIter,
)]
#[strum(serialize_all = "lowercase")]
pub enum LiquiditySide {
    /// The liquidity was provided by a resting Buy order on the **Bid**.
    /// The Aggressor (Taker) was a Seller.
    Bid,

    /// The liquidity was provided by a resting Sell order on the **Ask**.
    /// The Aggressor (Taker) was a Buyer.
    Ask,
}

impl LiquiditySide {
    /// Returns the side of the aggressor (Taker).
    ///
    /// This is the "Trade Side" usually displayed in UI (Green/Red).
    ///
    /// # Logic
    /// * If Maker = Buyer, then Aggressor = **Sell** (Red).
    /// * If Maker = Seller, then Aggressor = **Buy** (Green).
    #[must_use]
    pub const fn trade_side(&self) -> TradeSide {
        match self {
            Self::Bid => TradeSide::Sell,
            Self::Ask => TradeSide::Buy,
        }
    }
}

// === Serialization Glue (Bool <-> Enum) ===

impl From<bool> for LiquiditySide {
    fn from(value: bool) -> Self {
        if value { Self::Bid } else { Self::Ask }
    }
}

impl From<&LiquiditySide> for bool {
    fn from(value: &LiquiditySide) -> Self {
        match value {
            LiquiditySide::Bid => true,
            LiquiditySide::Ask => false,
        }
    }
}

impl From<LiquiditySide> for bool {
    fn from(value: LiquiditySide) -> Self {
        (&value).into()
    }
}

/// Selects which aggregated price of a bar is used for calculations.
///
/// Only meaningful for bar-like data that spans a range (e.g.
/// [`crate::data::event::Ohlcv`]).
#[derive(
    Debug, Clone, Copy, Serialize, Deserialize, Default, PartialEq, Eq, PartialOrd, Ord, Hash,
)]
pub enum AggregatedPrice {
    /// `(High + Low + Close) / 3`. The industry-standard typical price.
    #[default]
    Hlc3,
    /// `(High + Low) / 2`. Weights the bar by its extremes only (Median price).
    Hl2,
    /// `(Open + High + Low + Close) / 4`. Equal weight to all four prices.
    Ohlc4,
    /// `Close` only. Ignores intra-bar movement entirely.
    Close,
}

impl AggregatedPrice {
    /// Converts the price aggregation type into its corresponding Polars
    /// Expression.
    pub(crate) fn to_expr(self) -> Expr {
        match self {
            Self::Close => col(CanonicalCol::Close),
            Self::Hl2 => (col(CanonicalCol::High) + col(CanonicalCol::Low)) / lit(2.0),
            Self::Ohlc4 => {
                (col(CanonicalCol::Open)
                    + col(CanonicalCol::High)
                    + col(CanonicalCol::Low)
                    + col(CanonicalCol::Close))
                    / lit(4.0)
            }
            Self::Hlc3 => {
                (col(CanonicalCol::High) + col(CanonicalCol::Low) + col(CanonicalCol::Close))
                    / lit(3.0)
            }
        }
    }
}

/// Indicates the depth of the Order Book where the trade execution occurred.
///
/// This provides insight into the "aggressiveness" of the trade and the
/// liquidity state at the time of execution.
#[derive(
    Debug,
    Clone,
    Copy,
    PartialEq,
    PartialOrd,
    Eq,
    Hash,
    Serialize,
    Deserialize,
    EnumString,
    EnumIter,
)]
#[strum(serialize_all = "lowercase")]
pub enum ExecutionDepth {
    /// The trade matched exactly at the Best Bid or Best Ask (BBO).
    ///
    /// This indicates normal liquidity consumption where the resting order
    /// at the top of the book was sufficient to fill this portion of the trade.
    TopOfBook,

    /// The trade swept through the top of the book and matched at a worse
    /// price.
    ///
    /// This indicates that the Aggressor's order size exceeded the liquidity
    /// available at the BBO, forcing the engine to match against deeper
    /// levels of the order book (slippage).
    BookSweep,
}

impl From<bool> for ExecutionDepth {
    /// Converts a boolean value to a `TradeMatchQuality`.
    ///
    /// If `true`, it indicates that the trade was filled at the best available
    /// price (`BestMatch`). If `false`, it indicates that the best
    /// available quantity was insufficient (`NotBestMatch`).
    fn from(is_best_match: bool) -> Self {
        if is_best_match {
            Self::TopOfBook
        } else {
            Self::BookSweep
        }
    }
}

impl From<&ExecutionDepth> for bool {
    /// Converts a `TradeMatchQuality` into a boolean value.
    ///
    /// `TradeMatchQuality::BestMatch` converts to `true`, meaning that the
    /// trade was filled entirely at the best available price.
    /// `TradeMatchQuality::NotBestMatch` converts to `false`, indicating that
    /// the best available quantity was insufficient and additional price
    /// levels were used.
    fn from(trade_match_quality: &ExecutionDepth) -> Self {
        match trade_match_quality {
            ExecutionDepth::TopOfBook => true,
            ExecutionDepth::BookSweep => false,
        }
    }
}

impl From<ExecutionDepth> for bool {
    fn from(value: ExecutionDepth) -> Self {
        (&value).into()
    }
}

#[derive(
    Copy,
    Clone,
    Debug,
    EnumString,
    EnumIter,
    Display,
    PartialEq,
    Eq,
    Hash,
    Deserialize,
    Serialize,
    PartialOrd,
    Ord,
)]
#[strum(serialize_all = "lowercase")]
pub enum DataBroker {
    NinjaTrader,
    Binance,
    InvestingCom,
}

impl DataBroker {
    #[must_use]
    pub const fn supports_economic_calendar(&self) -> bool {
        matches!(self, Self::InvestingCom)
    }
}

impl From<&DataBroker> for RpcDataBroker {
    fn from(broker: &DataBroker) -> Self {
        match broker {
            DataBroker::Binance => Self::Binance,
            DataBroker::NinjaTrader => Self::NinjaTrader,
            DataBroker::InvestingCom => Self::InvestingCom,
        }
    }
}

impl From<DataBroker> for RpcDataBroker {
    fn from(broker: DataBroker) -> Self {
        (&broker).into()
    }
}

impl TryFrom<RpcDataBroker> for DataBroker {
    type Error = ChapatyError;

    fn try_from(proto: RpcDataBroker) -> Result<Self, Self::Error> {
        match proto {
            RpcDataBroker::Binance => Ok(Self::Binance),
            RpcDataBroker::NinjaTrader => Ok(Self::NinjaTrader),
            RpcDataBroker::InvestingCom => Ok(Self::InvestingCom),

            // Handle the 0-value case explicitly
            RpcDataBroker::Unspecified => Err(TransportError::RpcTypeNotFound(
                "Broker cannot be unspecified in this context".to_string(),
            )
            .into()),
        }
    }
}

#[derive(
    Copy,
    Clone,
    Debug,
    EnumString,
    Display,
    PartialEq,
    Eq,
    Hash,
    Deserialize,
    Serialize,
    PartialOrd,
    Ord,
)]
#[strum(serialize_all = "lowercase")]
pub enum Exchange {
    Cme,
    Binance,
}

impl TryFrom<DataBroker> for Exchange {
    type Error = ChapatyError;

    fn try_from(broker: DataBroker) -> Result<Self, Self::Error> {
        match broker {
            DataBroker::NinjaTrader => Ok(Self::Cme),
            DataBroker::Binance => Ok(Self::Binance),
            DataBroker::InvestingCom => Err(DataError::UnexpectedEnumVariant(format!(
                "{broker} does not map to an exchange"
            ))
            .into()),
        }
    }
}

#[derive(
    Copy,
    Clone,
    Debug,
    EnumString,
    Display,
    PartialEq,
    Eq,
    Hash,
    Deserialize,
    Serialize,
    PartialOrd,
    Ord,
)]
#[strum(serialize_all = "lowercase")]
pub enum EconomicDataSource {
    InvestingCom,
}

impl TryFrom<DataBroker> for EconomicDataSource {
    type Error = ChapatyError;

    fn try_from(broker: DataBroker) -> Result<Self, Self::Error> {
        match broker {
            DataBroker::InvestingCom => Ok(Self::InvestingCom),
            DataBroker::NinjaTrader | DataBroker::Binance => Err(DataError::UnexpectedEnumVariant(
                format!("{broker} does not map to an economic data source"),
            )
            .into()),
        }
    }
}

#[derive(
    Copy,
    Clone,
    Debug,
    Hash,
    PartialEq,
    Eq,
    Deserialize,
    Serialize,
    PartialOrd,
    Ord,
    EnumIter,
    EnumString,
    Display,
    AsRefStr,
    IntoStaticStr,
    Default,
)]
pub enum PriceSource {
    /// Evaluate the absolute extremes (High for peaks, Low for valleys)
    #[default]
    HighLow,
    /// Evaluate the candle bodies (Close for peaks, Open/Close for valleys)
    OpenClose,
}

#[derive(
    Copy,
    Clone,
    Debug,
    Hash,
    PartialEq,
    Eq,
    Deserialize,
    Serialize,
    PartialOrd,
    Ord,
    EnumIter,
    EnumString,
    Display,
    IntoStaticStr,
)]
#[strum(serialize_all = "lowercase")]
pub enum Period {
    #[strum(serialize = "{0}h")]
    Hour(u8),
    #[strum(serialize = "{0}m")]
    Minute(u8),
    #[strum(serialize = "{0}d")]
    Day(u8),
    #[strum(serialize = "{0}mo")]
    Month(u8),
    #[strum(serialize = "{0}s")]
    Second(u8),
    #[strum(serialize = "{0}w")]
    Week(u8),
}

/// Represents the classification of a market.
#[derive(
    Copy,
    Clone,
    Debug,
    Hash,
    PartialEq,
    Eq,
    Deserialize,
    Serialize,
    PartialOrd,
    Ord,
    EnumIter,
    EnumString,
    Display,
    IntoStaticStr,
)]
#[strum(serialize_all = "lowercase")]
pub enum MarketType {
    Spot,
    Future,
}

impl From<Symbol> for MarketType {
    fn from(value: Symbol) -> Self {
        match value {
            Symbol::Future(_) => Self::Future,
            Symbol::Spot(_) => Self::Spot,
        }
    }
}

#[derive(
    Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, PartialOrd, Ord, IntoStaticStr,
)]
pub enum Symbol {
    Spot(SpotPair),
    Future(FutureContract),
}

impl fmt::Display for Symbol {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Spot(s) => write!(f, "{s}"),
            Self::Future(s) => write!(f, "{s}"),
        }
    }
}

impl FromStr for Symbol {
    type Err = ChapatyError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        // Try parsing as SpotPair first
        if let Ok(spot) = SpotPair::from_str(s) {
            return Ok(Self::Spot(spot));
        }

        // Try parsing as FutureContract
        if let Ok(future) = FutureContract::from_str(s) {
            return Ok(Self::Future(future));
        }

        Err(DataError::InvalidSymbol(s.to_string()).into())
    }
}

impl Symbol {
    #[must_use]
    pub fn market_type(&self) -> MarketType {
        (*self).into()
    }
}

#[derive(
    Copy,
    Clone,
    Debug,
    PartialEq,
    Eq,
    Hash,
    Display,
    EnumString,
    Serialize,
    Deserialize,
    PartialOrd,
    Ord,
    IntoStaticStr,
)]
#[strum(serialize_all = "kebab-case")]
pub enum SpotPair {
    BtcUsdt,
    BnbUsdt,
    EthUsdt,
    SolUsdt,
    XrpUsdt,
    TrxUsdt,
    AdaUsdt,
    XlmUsdt,
}

/// Standard CME/Industry single-letter month codes.
#[derive(
    Clone,
    Copy,
    Debug,
    Display,
    EnumString,
    PartialEq,
    Eq,
    Hash,
    Serialize,
    Deserialize,
    PartialOrd,
    Ord,
)]
#[strum(serialize_all = "lowercase")]
pub enum ContractMonth {
    #[strum(serialize = "f")]
    January = 1,
    #[strum(serialize = "g")]
    February = 2,
    #[strum(serialize = "h")]
    March = 3,
    #[strum(serialize = "j")]
    April = 4,
    #[strum(serialize = "k")]
    May = 5,
    #[strum(serialize = "m")]
    June = 6,
    #[strum(serialize = "n")]
    July = 7,
    #[strum(serialize = "q")]
    August = 8,
    #[strum(serialize = "u")]
    September = 9,
    #[strum(serialize = "v")]
    October = 10,
    #[strum(serialize = "x")]
    November = 11,
    #[strum(serialize = "z")]
    December = 12,
}

/// Represents the underlying product code (CME "Root").
#[derive(
    Debug,
    Clone,
    Copy,
    PartialEq,
    Eq,
    Hash,
    Display,
    EnumString,
    Serialize,
    Deserialize,
    PartialOrd,
    Ord,
)]
#[strum(serialize_all = "lowercase")]
pub enum FutureRoot {
    #[strum(serialize = "6a")]
    AudUsd,
    #[strum(serialize = "6b")]
    GbpUsd,
    #[strum(serialize = "6c")]
    CadUsd,
    #[strum(serialize = "6e")]
    EurUsd,
    #[strum(serialize = "6j")]
    JpyUsd,
    #[strum(serialize = "6n")]
    NzdUsd,
    #[strum(serialize = "btc")]
    Btc,
    #[strum(serialize = "es")]
    EminiSp500,
    #[strum(serialize = "nq")]
    EminiNasdaq100,
}

#[derive(
    Debug,
    Clone,
    Copy,
    PartialEq,
    Eq,
    Hash,
    Display,
    EnumString,
    Serialize,
    Deserialize,
    PartialOrd,
    Ord,
)]
#[strum(serialize_all = "lowercase")]
pub enum ContractYear {
    #[strum(serialize = "0")]
    Y0 = 0,
    #[strum(serialize = "1")]
    Y1 = 1,
    #[strum(serialize = "2")]
    Y2 = 2,
    #[strum(serialize = "3")]
    Y3 = 3,
    #[strum(serialize = "4")]
    Y4 = 4,
    #[strum(serialize = "5")]
    Y5 = 5,
    #[strum(serialize = "6")]
    Y6 = 6,
    #[strum(serialize = "7")]
    Y7 = 7,
    #[strum(serialize = "8")]
    Y8 = 8,
    #[strum(serialize = "9")]
    Y9 = 9,
}

/// A concrete Futures contract (e.g., "6ez5").
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, PartialOrd, Ord)]
pub struct FutureContract {
    pub root: FutureRoot,
    pub month: ContractMonth,
    pub year: ContractYear,
}

impl fmt::Display for FutureContract {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}{}{}", self.root, self.month, self.year)
    }
}

impl FromStr for FutureContract {
    type Err = ChapatyError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let s = s.to_lowercase();

        // Expected format: root + month + year
        // e.g., "6ez5" = 6e (EurUsd) + z (December) + 5 (Year 5)

        if !s.is_ascii() {
            return Err(DataError::InvalidSymbol(format!(
                "Future contract string is not ASCII: {s}"
            ))
            .into());
        }

        if s.len() < 3 {
            return Err(
                DataError::InvalidSymbol(format!("Future contract string too short: {s}")).into(),
            );
        }

        // Find where the root ends by trying to parse progressively longer prefixes
        let (root, remainder) = if s.len() >= 3 && FutureRoot::from_str(&s[..2]).is_ok() {
            // 2-character root (e.g., "6e")
            (&s[..2], &s[2..])
        } else if s.len() >= 4 && FutureRoot::from_str(&s[..3]).is_ok() {
            // 3-character root (e.g., "btc")
            (&s[..3], &s[3..])
        } else {
            return Err(DataError::InvalidSymbol(format!("Invalid future root in: {s}")).into());
        };

        if remainder.len() != 2 {
            return Err(
                DataError::InvalidSymbol(format!("Invalid future contract format: {s}")).into(),
            );
        }

        let root = FutureRoot::from_str(root).map_err(DataError::ParseEnum)?;
        let month = ContractMonth::from_str(&remainder[..1]).map_err(DataError::ParseEnum)?;
        let year = ContractYear::from_str(&remainder[1..]).map_err(DataError::ParseEnum)?;

        Ok(Self { root, month, year })
    }
}

/// Economic impact category for calendar events.
///
/// Categorizes economic indicators by their type, helping filter events
/// based on the area of economic data you're interested in monitoring.
#[derive(
    PartialEq,
    Copy,
    Clone,
    Debug,
    Display,
    EnumString,
    EnumIter,
    Hash,
    Eq,
    PartialOrd,
    Ord,
    Serialize,
    Deserialize,
)]
#[strum(serialize_all = "camelCase")]
pub enum EconomicCategory {
    /// Employment-related indicators (e.g., Non-Farm Payrolls, Unemployment
    /// Rate).
    Employment = 1,

    /// Economic activity indicators (e.g., GDP, PMI, Retail Sales).
    EconomicActivity = 2,

    /// Inflation-related indicators (e.g., CPI, PPI, PCE).
    Inflation = 3,

    /// Credit and lending indicators (e.g., Consumer Credit, Bank Lending).
    Credit = 4,

    /// Central bank policy and actions (e.g., FOMC meetings, Rate Decisions).
    CentralBanks = 5,

    /// Consumer and business confidence indicators (e.g., Consumer Confidence,
    /// Business Sentiment).
    ConfidenceIndex = 6,

    /// Balance of payments or trade balance indicators.
    Balance = 7,

    /// Bond market-related indicators (e.g., Treasury Yields, Bond Auctions).
    #[strum(serialize = "Bonds")]
    Bonds = 8,
}

impl From<&EconomicCategory> for RpcEconomicCategory {
    fn from(category: &EconomicCategory) -> Self {
        match category {
            EconomicCategory::Employment => Self::Employment,
            EconomicCategory::EconomicActivity => Self::EconomicActivity,
            EconomicCategory::Inflation => Self::Inflation,
            EconomicCategory::Credit => Self::Credit,
            EconomicCategory::CentralBanks => Self::CentralBanks,
            EconomicCategory::ConfidenceIndex => Self::ConfidenceIndex,
            EconomicCategory::Balance => Self::Balance,
            EconomicCategory::Bonds => Self::Bonds,
        }
    }
}

impl From<EconomicCategory> for RpcEconomicCategory {
    fn from(category: EconomicCategory) -> Self {
        (&category).into()
    }
}

impl TryFrom<RpcEconomicCategory> for EconomicCategory {
    type Error = ChapatyError;

    fn try_from(proto: RpcEconomicCategory) -> Result<Self, Self::Error> {
        match proto {
            RpcEconomicCategory::Employment => Ok(Self::Employment),
            RpcEconomicCategory::EconomicActivity => Ok(Self::EconomicActivity),
            RpcEconomicCategory::Inflation => Ok(Self::Inflation),
            RpcEconomicCategory::Credit => Ok(Self::Credit),
            RpcEconomicCategory::CentralBanks => Ok(Self::CentralBanks),
            RpcEconomicCategory::ConfidenceIndex => Ok(Self::ConfidenceIndex),
            RpcEconomicCategory::Balance => Ok(Self::Balance),
            RpcEconomicCategory::Bonds => Ok(Self::Bonds),

            RpcEconomicCategory::Unspecified => Err(TransportError::RpcTypeNotFound(
                "Economic category cannot be unspecified in this context".to_string(),
            )
            .into()),
        }
    }
}

/// Importance level of an economic event as of investing.com (e.g., from 1 to 3
/// stars).
#[derive(
    Debug,
    Clone,
    Copy,
    Hash,
    PartialEq,
    Eq,
    EnumIter,
    Display,
    Serialize,
    Deserialize,
    PartialOrd,
    Ord,
)]
#[strum(serialize_all = "lowercase")]
pub enum EconomicEventImpact {
    Low = 1,
    Medium = 2,
    High = 3,
}

impl From<&EconomicEventImpact> for RpcEconomicImportance {
    fn from(value: &EconomicEventImpact) -> Self {
        match value {
            EconomicEventImpact::Low => Self::Low,
            EconomicEventImpact::Medium => Self::Moderate,
            EconomicEventImpact::High => Self::High,
        }
    }
}

impl From<EconomicEventImpact> for RpcEconomicImportance {
    fn from(value: EconomicEventImpact) -> Self {
        (&value).into()
    }
}

impl TryFrom<RpcEconomicImportance> for EconomicEventImpact {
    type Error = ChapatyError;

    fn try_from(proto: RpcEconomicImportance) -> Result<Self, Self::Error> {
        match proto {
            RpcEconomicImportance::Low => Ok(Self::Low),
            RpcEconomicImportance::Moderate => Ok(Self::Medium),
            RpcEconomicImportance::High => Ok(Self::High),
            RpcEconomicImportance::Unspecified => Err(TransportError::RpcTypeNotFound(
                "Economic importance cannot be unspecified in this context".to_string(),
            )
            .into()),
        }
    }
}

/// ISO 3166-1 alpha-2 country or economic region code.
///
/// Identifies the primary economic jurisdiction associated with
/// a macroeconomic calendar event (e.g., "US", "GB", "JP", "EZ").
#[derive(
    PartialEq,
    Copy,
    Clone,
    Debug,
    Display,
    EnumIter,
    EnumString,
    Hash,
    Eq,
    PartialOrd,
    Ord,
    Serialize,
    Deserialize,
)]
#[strum(serialize_all = "UPPERCASE")]
pub enum CountryCode {
    /// Australia
    Au,
    /// Brazil
    Br,
    /// Canada
    Ca,
    /// China
    Cn,
    /// Euro Zone
    Ez,
    /// United Kingdom
    Gb,
    /// India
    In,
    /// Japan
    Jp,
    /// New Zealand
    Nz,
    /// United States
    Us,
}

// ================================================================================================
// Traits
// ================================================================================================

/// Defines the core financial properties of a tradable instrument.
pub trait Instrument {
    /// The minimum price movement (e.g., 0.00005 for EUR/USD futures).
    fn tick_size(&self) -> f64;

    /// The value of one tick in the quote currency (USD).
    ///
    /// - For Spot (BTC/USDT), if tick is 0.01, tick value is $0.01.
    /// - For Futures (6E/EUR), if tick is 0.00005, tick value is $6.25.
    fn tick_value_usd(&self) -> f64;

    // === CONVERSION LOGIC (Default Implementations) ===

    /// Converts a raw USD `PnL` target into discrete Tick steps.
    /// Uses `round` to snap to the nearest valid grid point.
    ///
    /// # Panics
    ///
    /// Panics if the calculated value is `NaN`, or if it falls outside the
    /// representable range of a signed 64-bit integer (`i64::MIN` to
    /// `i64::MAX`).
    #[expect(
        clippy::cast_precision_loss,
        clippy::cast_possible_truncation,
        reason = "raw_ticks is rounded and asserted to be finite and within i64 bounds before the cast, so the conversion is exact"
    )]
    fn usd_to_ticks(&self, usd: f64) -> Tick {
        let raw_ticks = (usd / self.tick_value_usd()).round();

        assert!(
            raw_ticks.is_finite()
                && raw_ticks >= (i64::MIN as f64)
                && raw_ticks <= (i64::MAX as f64),
            "USD conversion overflowed signed i64 bounds or resulted in NaN"
        );

        let ticks = raw_ticks as i64;
        Tick(ticks)
    }

    /// Converts discrete Ticks back into a USD value.
    /// This is the safest way to calculate realized `PnL`.
    ///
    /// # Panics
    ///
    /// Panics if the internal tick count exceeds standard i32 ranges.
    fn ticks_to_usd(&self, ticks: Tick) -> f64 {
        #[expect(
            clippy::expect_used,
            reason = "Tick spaces for valid assets realistically never exceed i32 max (~2.1B ticks); \
                      a panic here implies highly corrupted input data."
        )]
        let tick_count = i32::try_from(ticks.0).expect("tick count exceeds i32 range");
        f64::from(tick_count) * self.tick_value_usd()
    }
    /// Converts a raw price distance (e.g., target - entry) into Ticks.
    /// Uses `round` to snap to the nearest valid grid point.
    ///
    /// # Panics
    ///
    /// Panics if the calculated value is `NaN`, or if it falls outside the
    /// representable range of a signed 64-bit integer (`i64::MIN` to
    /// `i64::MAX`).
    #[expect(
        clippy::cast_precision_loss,
        reason = "The standard i64 bounds (±9.22e18) fit completely within the safe \
                      lossless precision range of an f64 (~±9.0e15) for all realistic financial prices."
    )]
    #[expect(
        clippy::cast_possible_truncation,
        reason = "The upstream `.round()` call ensures the floating-point value is an exact \
                      mathematical integer, meaning no fractional data is truncated during the `as i64` cast."
    )]
    fn price_to_ticks(&self, price_dist: Price) -> Tick {
        let raw_ticks = (price_dist.0 / self.tick_size()).round();

        assert!(
            raw_ticks.is_finite()
                && raw_ticks >= (i64::MIN as f64)
                && raw_ticks <= (i64::MAX as f64),
            "Price distance conversion overflowed signed i64 bounds or resulted in NaN"
        );

        let ticks = raw_ticks as i64;
        Tick(ticks)
    }

    /// Converts Ticks into a valid price distance.
    fn ticks_to_price(&self, ticks: Tick) -> Price {
        #[expect(
            clippy::expect_used,
            reason = "Tick movements never realistically exceed i32 max (~2.1B ticks); \
                          an overflow here implies critical data corruption."
        )]
        let tick_count = i32::try_from(ticks.0).expect("tick count exceeds i32 range");
        Price(f64::from(tick_count) * self.tick_size())
    }

    /// Converts a USD target directly to a Price distance.
    ///
    /// Example: "I want to risk $50. How far away should my stop loss be?"
    fn usd_to_price_dist(&self, usd: f64) -> Price {
        let ticks = self.usd_to_ticks(usd);
        self.ticks_to_price(ticks)
    }

    /// Normalizes a raw price to the nearest valid tick.
    /// Crucial for order entry validation to prevent "Invalid Tick Size"
    /// errors.
    fn normalize_price(&self, price: f64) -> f64 {
        let ticks = (price / self.tick_size()).round();
        ticks * self.tick_size()
    }
}

impl Instrument for SpotPair {
    fn tick_size(&self) -> f64 {
        match self {
            Self::BtcUsdt | Self::BnbUsdt | Self::EthUsdt | Self::SolUsdt => 0.01,
            Self::XrpUsdt | Self::TrxUsdt | Self::AdaUsdt | Self::XlmUsdt => 0.0001,
        }
    }

    fn tick_value_usd(&self) -> f64 {
        self.tick_size()
    }
}

impl Instrument for FutureRoot {
    fn tick_size(&self) -> f64 {
        match self {
            Self::AudUsd | Self::CadUsd | Self::EurUsd | Self::NzdUsd => 0.00005,
            Self::GbpUsd => 0.0001,
            Self::JpyUsd => 0.000_000_5,
            Self::Btc => 5.0,
            Self::EminiSp500 | Self::EminiNasdaq100 => 0.25,
        }
    }

    fn tick_value_usd(&self) -> f64 {
        match self {
            Self::EurUsd | Self::GbpUsd | Self::JpyUsd => 6.25,
            Self::AudUsd | Self::CadUsd | Self::NzdUsd | Self::EminiNasdaq100 => 5.0,
            Self::EminiSp500 => 12.50,
            Self::Btc => 25.0,
        }
    }
}

impl Instrument for Symbol {
    fn tick_size(&self) -> f64 {
        match self {
            Self::Spot(spot) => spot.tick_size(),
            Self::Future(future) => future.root.tick_size(),
        }
    }

    fn tick_value_usd(&self) -> f64 {
        match self {
            Self::Spot(spot) => spot.tick_value_usd(),
            Self::Future(future) => future.root.tick_value_usd(),
        }
    }
}

// ================================================================================================
// Session Window
// ================================================================================================

/// A timezone-aware accumulation window defined by a local start and end
/// time-of-day.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct SessionWindow {
    pub timezone: Tz,
    pub start: NaiveTime,
    pub end: NaiveTime,
}

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

impl Ord for SessionWindow {
    fn cmp(&self, other: &Self) -> Ordering {
        (self.start, self.end, self.timezone as usize).cmp(&(
            other.start,
            other.end,
            other.timezone as usize,
        ))
    }
}

#[expect(
    clippy::expect_used,
    reason = "Used inside a `const fn` constructor where inputs are hardcoded, static literals. \
              Any out-of-bounds inputs (e.g., hour > 23) will fail to compile immediately at build time."
)]
const fn hm(h: u32, m: u32) -> NaiveTime {
    NaiveTime::from_hms_opt(h, m, 0).expect("invalid hour or minute")
}

impl SessionWindow {
    #[must_use]
    pub const fn new(timezone: Tz, start: NaiveTime, end: NaiveTime) -> Self {
        Self {
            timezone,
            start,
            end,
        }
    }

    /// US Core Session: 09:30 to 16:00 New York time.
    #[must_use]
    pub const fn us_core_session() -> Self {
        Self::new(Tz::America__New_York, hm(9, 30), hm(16, 0))
    }

    /// London Core Session: 08:00 to 16:30 London time.
    #[must_use]
    pub const fn london_core_session() -> Self {
        Self::new(Tz::Europe__London, hm(8, 0), hm(16, 30))
    }

    /// US/Europe Overlap: 13:00 to 17:00 London time.
    #[must_use]
    pub const fn us_europe_overlap() -> Self {
        Self::new(Tz::Europe__London, hm(13, 0), hm(17, 0))
    }

    /// Singapore Core Session: 09:00 to 17:00 Singapore time.
    #[must_use]
    pub const fn singapore_core_session() -> Self {
        Self::new(Tz::Asia__Singapore, hm(9, 0), hm(17, 0))
    }

    /// Sydney Core Session: 10:00 to 16:00 Sydney time.
    #[must_use]
    pub const fn sydney_core_session() -> Self {
        Self::new(Tz::Australia__Sydney, hm(10, 0), hm(16, 0))
    }

    /// US Overnight: 16:00 to 09:30 New York time.
    #[must_use]
    pub const fn us_overnight() -> Self {
        Self::new(Tz::America__New_York, hm(16, 0), hm(9, 30))
    }

    /// US Extended Overnight: 18:00 to 09:30 New York time.
    #[must_use]
    pub const fn us_extended_overnight() -> Self {
        Self::new(Tz::America__New_York, hm(18, 0), hm(9, 30))
    }

    /// Tokyo Core Session: 09:00 to 15:00 Tokyo time.
    #[must_use]
    pub const fn tokyo_core_session() -> Self {
        Self::new(Tz::Asia__Tokyo, hm(9, 0), hm(15, 0))
    }

    /// Asia Institutional Core: 09:00 to 17:00 Singapore time.
    #[must_use]
    pub const fn asia_institutional_core() -> Self {
        Self::new(Tz::Asia__Singapore, hm(9, 0), hm(17, 0))
    }

    /// Hong Kong Core Session: 09:30 to 16:00 Hong Kong time.
    #[must_use]
    pub const fn hong_kong_core_session() -> Self {
        Self::new(Tz::Asia__Hong_Kong, hm(9, 30), hm(16, 0))
    }

    /// APAC Overnight: 17:00 to 08:00 Singapore time.
    #[must_use]
    pub const fn apac_overnight() -> Self {
        Self::new(Tz::Asia__Singapore, hm(17, 0), hm(8, 0))
    }

    #[must_use]
    pub fn pl_time_zone(&self) -> polars::datatypes::TimeZone {
        polars::datatypes::TimeZone::from_chrono(&self.timezone)
    }

    #[must_use]
    pub fn start_nanos_since_midnight(&self) -> i64 {
        (i64::from(self.start.num_seconds_from_midnight()) * 1_000_000_000)
            + i64::from(self.start.nanosecond())
    }

    #[must_use]
    pub fn end_nanos_since_midnight(&self) -> i64 {
        (i64::from(self.end.num_seconds_from_midnight()) * 1_000_000_000)
            + i64::from(self.end.nanosecond())
    }

    #[must_use]
    pub fn window_kind(&self) -> WindowKind {
        match self.start.cmp(&self.end) {
            Ordering::Less => WindowKind::Intraday,
            Ordering::Equal | Ordering::Greater => WindowKind::Overnight,
        }
    }

    /// Classifies a UTC timestamp against the window, resolving the session it
    /// belongs to when inside.
    ///
    /// # Panics
    /// Panics when classifying overnight windows if the local date is Chrono's
    /// minimum representable date and cannot be decremented (`pred_opt` is
    /// `None`).
    #[must_use]
    pub fn classify(&self, utc_ts: DateTime<Utc>) -> WindowPosition {
        let local = utc_ts.with_timezone(&self.timezone);
        let date = local.date_naive();
        let now = local.time();

        match self.window_kind() {
            WindowKind::Intraday => {
                if (self.start..self.end).contains(&now) {
                    WindowPosition::Within(SessionDate(date))
                } else {
                    WindowPosition::Outside
                }
            }
            WindowKind::Overnight => {
                if now >= self.start {
                    WindowPosition::Within(SessionDate(date))
                } else if now < self.end {
                    #[expect(
                        clippy::expect_used,
                        reason = "Active trading market data timestamps are bound to modern historical/real-time \
                                      eras and cannot reasonably trigger Chrono's absolute minimum date boundary."
                    )]
                    let anchor_date = date.pred_opt().expect(
                        "Market data timestamp violates Chrono's minimum representable date",
                    );
                    WindowPosition::Within(SessionDate(anchor_date))
                } else {
                    WindowPosition::Outside
                }
            }
        }
    }
}

/// Where an event falls relative to an accumulation window.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WindowPosition {
    /// Inside `[start, end)`, belonging to the given session.
    Within(SessionDate),
    /// Outside the window.
    Outside,
}

/// The chronological shape of the session window.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WindowKind {
    Intraday,
    Overnight,
}

impl WindowKind {
    #[must_use]
    pub const fn is_intraday(&self) -> bool {
        matches!(self, Self::Intraday)
    }

    #[must_use]
    pub const fn is_overnight(&self) -> bool {
        matches!(self, Self::Overnight)
    }
}

/// Identifies one accumulation session by its anchor date.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct SessionDate(pub NaiveDate);

#[cfg(test)]
mod tests {
    #![expect(
        clippy::unwrap_used,
        reason = "tests assert against known-valid fixtures; unwrap surfaces failures as panics that fail the test"
    )]

    use chrono::TimeZone;
    use chrono_tz::America::New_York;

    use super::*;

    // ============================================================================================
    // Market Session Tetsts
    // ============================================================================================

    /// Helper to easily construct a UTC timestamp from a local timezone date
    /// and time.
    fn local_to_utc(
        tz: Tz,
        year: i32,
        month: u32,
        day: u32,
        hour: u32,
        min: u32,
        sec: u32,
    ) -> DateTime<Utc> {
        tz.with_ymd_and_hms(year, month, day, hour, min, sec)
            .unwrap()
            .with_timezone(&Utc)
    }

    /// Helper to easily create a `NaiveDate`
    fn date(year: i32, month: u32, day: u32) -> NaiveDate {
        NaiveDate::from_ymd_opt(year, month, day).unwrap()
    }

    #[test]
    fn test_intraday_classify() {
        let session = SessionWindow::us_core_session(); // 09:30 -> 16:00 ET

        let test_date = date(2026, 6, 10);
        let expected_session = WindowPosition::Within(SessionDate(test_date));

        // 1. Before session starts (09:29:59) -> Outside
        let before = local_to_utc(New_York, 2026, 6, 10, 9, 29, 59);
        assert_eq!(session.classify(before), WindowPosition::Outside);

        // 2. Exactly at start (09:30:00) -> [inclusive boundary] -> Within
        let start = local_to_utc(New_York, 2026, 6, 10, 9, 30, 0);
        assert_eq!(session.classify(start), expected_session);

        // 3. Inside session (12:00:00) -> Within
        let mid = local_to_utc(New_York, 2026, 6, 10, 12, 0, 0);
        assert_eq!(session.classify(mid), expected_session);

        // 4. Exactly at end (16:00:00) -> [exclusive boundary] -> Outside
        let end = local_to_utc(New_York, 2026, 6, 10, 16, 0, 0);
        assert_eq!(session.classify(end), WindowPosition::Outside);

        // 5. After session ends (16:00:01) -> Outside
        let after = local_to_utc(New_York, 2026, 6, 10, 16, 0, 1);
        assert_eq!(session.classify(after), WindowPosition::Outside);
    }

    #[test]
    fn test_overnight_classify() {
        let session = SessionWindow::us_extended_overnight(); // 18:00 -> 09:30 ET

        let anchor = date(2026, 6, 10); // The evening the session opened
        let expected_session = WindowPosition::Within(SessionDate(anchor));

        // 1. Just before the evening leg opens (17:59:59) -> Outside
        let before_eve = local_to_utc(New_York, 2026, 6, 10, 17, 59, 59);
        assert_eq!(session.classify(before_eve), WindowPosition::Outside);

        // 2. Evening leg opens (18:00:00 on June 10) -> Within(June 10)
        let eve_start = local_to_utc(New_York, 2026, 6, 10, 18, 0, 0);
        assert_eq!(session.classify(eve_start), expected_session);

        // 3. Evening leg middle (23:00:00 on June 10) -> Within(June 10)
        let eve_mid = local_to_utc(New_York, 2026, 6, 10, 23, 0, 0);
        assert_eq!(session.classify(eve_mid), expected_session);

        // 4. Cross midnight / Morning leg begins (00:00:00 on June 11) -> Within(June
        //    10)
        let morn_start = local_to_utc(New_York, 2026, 6, 11, 0, 0, 0);
        assert_eq!(session.classify(morn_start), expected_session);

        // 5. Morning leg middle (08:00:00 on June 11) -> Within(June 10)
        let morn_mid = local_to_utc(New_York, 2026, 6, 11, 8, 0, 0);
        assert_eq!(session.classify(morn_mid), expected_session);

        // 6. Morning leg ends (09:30:00 on June 11) -> [exclusive boundary] -> Outside
        let morn_end = local_to_utc(New_York, 2026, 6, 11, 9, 30, 0);
        assert_eq!(session.classify(morn_end), WindowPosition::Outside);

        // 7. Middle of the daytime (12:00:00 on June 11) -> Outside
        let day_mid = local_to_utc(New_York, 2026, 6, 11, 12, 0, 0);
        assert_eq!(session.classify(day_mid), WindowPosition::Outside);
    }

    #[test]
    fn test_24_hour_classify() {
        // A 24-hour window wrapping at 17:00 (start == end implies Overnight logic)
        let session = SessionWindow::new(New_York, hm(17, 0), hm(17, 0));

        let anchor = date(2026, 6, 10);
        let expected_session = WindowPosition::Within(SessionDate(anchor));

        // 1. Right at start (17:00 on June 10) -> Anchored on June 10
        let start = local_to_utc(New_York, 2026, 6, 10, 17, 0, 0);
        assert_eq!(session.classify(start), expected_session);

        // 2. Late evening (23:59 on June 10) -> Anchored on June 10
        let eve = local_to_utc(New_York, 2026, 6, 10, 23, 59, 0);
        assert_eq!(session.classify(eve), expected_session);

        // 3. Next morning (08:00 on June 11) -> Anchored on June 10
        let morn = local_to_utc(New_York, 2026, 6, 11, 8, 0, 0);
        assert_eq!(session.classify(morn), expected_session);

        // 4. Right before wrap (16:59:59 on June 11) -> Anchored on June 10
        let before_wrap = local_to_utc(New_York, 2026, 6, 11, 16, 59, 59);
        assert_eq!(session.classify(before_wrap), expected_session);

        // 5. Window wraps/restarts (17:00:00 on June 11) -> Now anchored on June 11
        let next_anchor = date(2026, 6, 11);
        let next_expected_session = WindowPosition::Within(SessionDate(next_anchor));
        let restart = local_to_utc(New_York, 2026, 6, 11, 17, 0, 0);
        assert_eq!(session.classify(restart), next_expected_session);
    }

    // ============================================================================================
    // Symbol String Conversion Tests
    // ============================================================================================

    #[test]
    fn future_contracts_format_as_root_month_year() {
        let cases = [
            (
                FutureRoot::EurUsd,
                ContractMonth::December,
                ContractYear::Y5,
                "6ez5",
            ),
            (
                FutureRoot::GbpUsd,
                ContractMonth::March,
                ContractYear::Y4,
                "6bh4",
            ),
            (
                FutureRoot::AudUsd,
                ContractMonth::June,
                ContractYear::Y3,
                "6am3",
            ),
            (
                FutureRoot::CadUsd,
                ContractMonth::September,
                ContractYear::Y2,
                "6cu2",
            ),
            (
                FutureRoot::JpyUsd,
                ContractMonth::January,
                ContractYear::Y1,
                "6jf1",
            ),
            (
                FutureRoot::NzdUsd,
                ContractMonth::July,
                ContractYear::Y0,
                "6nn0",
            ),
            (
                FutureRoot::Btc,
                ContractMonth::November,
                ContractYear::Y9,
                "btcx9",
            ),
        ];

        for (root, month, year, expected) in cases {
            let contract = FutureContract { root, month, year };
            let symbol = Symbol::Future(contract);
            assert_eq!(symbol.to_string(), expected, "Failed for {contract:?}");
        }
    }

    #[test]
    fn parses_future_contracts_case_insensitive() {
        let cases = [
            (
                "6ez5",
                FutureRoot::EurUsd,
                ContractMonth::December,
                ContractYear::Y5,
            ),
            (
                "6EZ5",
                FutureRoot::EurUsd,
                ContractMonth::December,
                ContractYear::Y5,
            ),
            (
                "6bh4",
                FutureRoot::GbpUsd,
                ContractMonth::March,
                ContractYear::Y4,
            ),
            (
                "btcx9",
                FutureRoot::Btc,
                ContractMonth::November,
                ContractYear::Y9,
            ),
            (
                "BTCX9",
                FutureRoot::Btc,
                ContractMonth::November,
                ContractYear::Y9,
            ),
        ];

        for (input, root, month, year) in cases {
            let parsed: Symbol = input
                .parse()
                .unwrap_or_else(|_| panic!("Failed to parse '{input}'"));
            let expected = Symbol::Future(FutureContract { root, month, year });
            assert_eq!(parsed, expected, "Mismatch for '{input}'");
        }
    }

    #[test]
    fn parses_all_future_roots() {
        let cases = [
            ("6az5", FutureRoot::AudUsd),
            ("6bz5", FutureRoot::GbpUsd),
            ("6cz5", FutureRoot::CadUsd),
            ("6ez5", FutureRoot::EurUsd),
            ("6jz5", FutureRoot::JpyUsd),
            ("6nz5", FutureRoot::NzdUsd),
            ("btcz5", FutureRoot::Btc),
        ];

        for (input, expected_root) in cases {
            let parsed: Symbol = input
                .parse()
                .unwrap_or_else(|_| panic!("Failed to parse '{input}'"));
            match parsed {
                Symbol::Future(contract) => assert_eq!(contract.root, expected_root),
                Symbol::Spot(_) => panic!("Expected Future variant for '{input}'"),
            }
        }
    }

    #[test]
    fn rejects_invalid_symbols() {
        let invalid = [
            "", "invalid", "btc",     // missing month/year
            "6e",      // missing month/year
            "6ez",     // missing year
            "btc-",    // incomplete spot
            "-usdt",   // incomplete spot
            "btcusdt", // wrong spot format (missing hyphen)
            "6ez55",   // too long
            "xxz5",    // invalid root
        ];

        for input in invalid {
            let result: Result<Symbol, _> = input.parse();
            assert!(result.is_err(), "Expected '{input}' to fail parsing");
        }
    }

    #[test]
    fn future_contracts_survive_round_trip() {
        let contracts = [
            FutureContract {
                root: FutureRoot::EurUsd,
                month: ContractMonth::December,
                year: ContractYear::Y5,
            },
            FutureContract {
                root: FutureRoot::Btc,
                month: ContractMonth::March,
                year: ContractYear::Y0,
            },
            FutureContract {
                root: FutureRoot::JpyUsd,
                month: ContractMonth::September,
                year: ContractYear::Y9,
            },
        ];

        for contract in contracts {
            let original = Symbol::Future(contract);
            let serialized = original.to_string();
            let deserialized: Symbol = serialized.parse().unwrap();
            assert_eq!(original, deserialized, "Round-trip failed for {contract:?}");
        }
    }

    #[test]
    fn canonical_strings_parse_back_unchanged() {
        let canonical = ["btc-usdt", "eth-usdt", "6ez5", "6bh4", "btcx9"];

        for input in canonical {
            let parsed: Symbol = input.parse().unwrap();
            let output = parsed.to_string();
            assert_eq!(input, output, "Canonical form changed for '{input}'");
        }
    }

    #[test]
    fn importance_numeration() {
        assert_eq!(EconomicEventImpact::Low as u8, 1, "Low should be 1");
        assert_eq!(EconomicEventImpact::Medium as u8, 2, "Medium should be 2");
        assert_eq!(EconomicEventImpact::High as u8, 3, "High should be 3");
    }

    /// Helper to create a dummy future for testing logic
    fn future_sym(root: FutureRoot) -> Symbol {
        Symbol::Future(FutureContract {
            root,
            month: ContractMonth::December, // Dummy
            year: ContractYear::Y5,         // Dummy
        })
    }

    #[test]
    fn test_quant_math_eur_usd() {
        let eur = future_sym(FutureRoot::EurUsd);

        // 1. Tick Size & Value Check
        assert_f64_eq!(eur.tick_size(), 0.00005);
        assert_f64_eq!(eur.tick_value_usd(), 6.25);

        // 2. Risk Calculation: "I want to risk $100"
        // $100 / $6.25 = 16 ticks
        // 16 ticks * 0.00005 = 0.0008 price distance
        let risk_dist = eur.usd_to_price_dist(100.0);
        assert!((risk_dist.0 - 0.0008).abs() < f64::EPSILON);

        // 3. Normalization (Rounding)
        // Price 1.00003 is invalid. Should snap to 1.00005 or 1.00000.
        // 1.00003 is closer to 1.00005
        // 0.00003 / 0.00005 = 0.6 -> Rounds to 1.
        let norm = eur.normalize_price(1.00003);
        assert!((norm - 1.00005).abs() < f64::EPSILON);
    }

    #[test]
    fn test_quant_math_btc_future() {
        let btc = future_sym(FutureRoot::Btc);

        // Tick: 5.0, Value: $25.0

        // PnL Check: Price moves from 50,000 to 50,100 (diff 100)
        // 100 / 5.0 = 20 ticks
        // 20 ticks * $25.0 = $500 profit
        let entry = 50_000.0;
        let exit = 50_100.0;
        let ticks = btc.price_to_ticks(Price(exit - entry));
        let pnl = btc.ticks_to_usd(ticks);

        assert_eq!(ticks.0, 20);
        assert_f64_eq!(pnl, 500.0);
    }

    #[test]
    fn handling_floating_point_artifacts() {
        // EUR/USD tick size is 0.00005
        let eur = future_sym(FutureRoot::EurUsd);

        // 1.10000 is a valid grid price (1.10000 / 0.00005 = 22,000 ticks)
        let valid_price = 1.10000;

        // Case 1: Artifact just ABOVE the valid price (e.g. 1.10000001)
        // Should round DOWN to 1.10000
        let dirty_high = valid_price + 0.000_000_01;
        let norm_high = eur.normalize_price(dirty_high);

        assert!(
            (norm_high - valid_price).abs() < f64::EPSILON,
            "Failed to round down dirty high input: {dirty_high:.8} -> {norm_high:.8}"
        );

        // Case 2: Artifact just BELOW the valid price (e.g. 1.09999999)
        // Should round UP to 1.10000
        let dirty_low = valid_price - 0.000_000_01;
        let norm_low = eur.normalize_price(dirty_low);

        assert!(
            (norm_low - valid_price).abs() < f64::EPSILON,
            "Failed to round up dirty low input: {dirty_low:.8} -> {norm_low:.8}"
        );
    }

    #[test]
    fn tick_conversion_ignores_noise() {
        let eur = future_sym(FutureRoot::EurUsd);

        // We expect a price distance of 0.00050 (10 ticks)
        // 0.00050 / 0.00005 = 10.0
        let clean_dist = 0.00050;
        let expected_ticks = 10;

        // Test with positive noise (0.00050001 -> 10.0002 -> round to 10)
        let noisy_dist = Price(clean_dist + 0.000_000_01);
        let ticks = eur.price_to_ticks(noisy_dist);
        assert_eq!(
            ticks.0, expected_ticks,
            "Positive noise caused tick mismatch"
        );

        // Test with negative noise (0.00049999 -> 9.9998 -> round to 10)
        let noisy_dist_neg = Price(clean_dist - 0.000_000_01);
        let ticks_neg = eur.price_to_ticks(noisy_dist_neg);
        assert_eq!(
            ticks_neg.0, expected_ticks,
            "Negative noise caused tick mismatch"
        );
    }
}