projectx-client 2.0.0

An async, provider-native Rust client for the ProjectX Gateway API
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
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
// SPDX-FileCopyrightText: 2026 Kevin Monaghan
// SPDX-License-Identifier: MIT

//! Provider-native request and response models.

use std::collections::BTreeMap;

use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};
use serde_json::value::RawValue;
use serde_repr::{Deserialize_repr, Serialize_repr};
use thiserror::Error;

use crate::{
    AccountId, ContractId, OrderId, PositionId, ProviderDate, SymbolId, Timestamp, TradeId,
};

/// A `ProjectX` order side.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum Side {
    /// Bid (buy).
    Bid,
    /// Ask (sell).
    Ask,
    /// Provider code not known to this crate version.
    Unknown(i32),
}

impl Side {
    /// Returns the provider's numeric wire code.
    #[must_use]
    pub const fn code(self) -> i32 {
        match self {
            Self::Bid => 0,
            Self::Ask => 1,
            Self::Unknown(code) => code,
        }
    }
}

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

impl<'de> Deserialize<'de> for Side {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        Ok(match i32::deserialize(deserializer)? {
            0 => Self::Bid,
            1 => Self::Ask,
            code => Self::Unknown(code),
        })
    }
}

/// A `ProjectX` order type.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum OrderType {
    /// Limit order.
    Limit,
    /// Market order.
    Market,
    /// Stop-limit response code.
    ///
    /// The current provider request reference does not document this type for
    /// order placement or bracket creation, so validated request builders
    /// reject it while response decoding preserves the wire value.
    StopLimit,
    /// Stop order.
    Stop,
    /// Trailing-stop order.
    TrailingStop,
    /// Join the best bid.
    JoinBid,
    /// Join the best ask.
    JoinAsk,
    /// Provider code not known to this crate version.
    Unknown(i32),
}

impl OrderType {
    /// Returns the provider's numeric wire code.
    #[must_use]
    pub const fn code(self) -> i32 {
        match self {
            Self::Limit => 1,
            Self::Market => 2,
            Self::StopLimit => 3,
            Self::Stop => 4,
            Self::TrailingStop => 5,
            Self::JoinBid => 6,
            Self::JoinAsk => 7,
            Self::Unknown(code) => code,
        }
    }
}

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

impl<'de> Deserialize<'de> for OrderType {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        Ok(match i32::deserialize(deserializer)? {
            1 => Self::Limit,
            2 => Self::Market,
            3 => Self::StopLimit,
            4 => Self::Stop,
            5 => Self::TrailingStop,
            6 => Self::JoinBid,
            7 => Self::JoinAsk,
            code => Self::Unknown(code),
        })
    }
}

/// A `ProjectX` order lifecycle status.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum OrderStatus {
    /// Provider sentinel indicating no lifecycle status.
    None,
    /// Working order.
    Open,
    /// Completely filled order.
    Filled,
    /// Cancelled order.
    Cancelled,
    /// Expired order.
    Expired,
    /// Provider-rejected order.
    Rejected,
    /// Order awaiting activation or acknowledgement.
    Pending,
    /// Order awaiting cancellation.
    PendingCancellation,
    /// Suspended order, including inactive bracket children.
    Suspended,
    /// Provider code not known to this crate version.
    Unknown(i32),
}

/// Field used to sort an [`OrderQuery`] result page.
///
/// This enum is request-only: response order is represented by the returned
/// [`OrderPage::orders`] sequence.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize_repr)]
#[non_exhaustive]
#[repr(i32)]
pub enum OrderSortBy {
    /// Sort by order creation time.
    CreatedAt = 0,
    /// Sort by provider order identifier.
    Id = 1,
}

/// Direction used to sort an [`OrderQuery`] result page.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize_repr)]
#[non_exhaustive]
#[repr(i32)]
pub enum OrderSortDirection {
    /// Ascending order.
    Ascending = 0,
    /// Descending order.
    Descending = 1,
}

impl OrderStatus {
    /// Returns the provider's numeric wire code.
    #[must_use]
    pub const fn code(self) -> i32 {
        match self {
            Self::None => 0,
            Self::Open => 1,
            Self::Filled => 2,
            Self::Cancelled => 3,
            Self::Expired => 4,
            Self::Rejected => 5,
            Self::Pending => 6,
            Self::PendingCancellation => 7,
            Self::Suspended => 8,
            Self::Unknown(code) => code,
        }
    }
}

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

impl<'de> Deserialize<'de> for OrderStatus {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        Ok(match i32::deserialize(deserializer)? {
            0 => Self::None,
            1 => Self::Open,
            2 => Self::Filled,
            3 => Self::Cancelled,
            4 => Self::Expired,
            5 => Self::Rejected,
            6 => Self::Pending,
            7 => Self::PendingCancellation,
            8 => Self::Suspended,
            code => Self::Unknown(code),
        })
    }
}

/// A `ProjectX` market-trade aggressor classification.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum TradeLogType {
    /// Buyer-initiated trade.
    Buy,
    /// Seller-initiated trade.
    Sell,
    /// Provider code not known to this crate version.
    Unknown(i32),
}

impl TradeLogType {
    /// Returns the provider's numeric wire code.
    #[must_use]
    pub const fn code(self) -> i32 {
        match self {
            Self::Buy => 0,
            Self::Sell => 1,
            Self::Unknown(code) => code,
        }
    }
}

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

impl<'de> Deserialize<'de> for TradeLogType {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        Ok(match i32::deserialize(deserializer)? {
            0 => Self::Buy,
            1 => Self::Sell,
            code => Self::Unknown(code),
        })
    }
}

/// A `ProjectX` position direction.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum PositionType {
    /// No directional position.
    Undefined,
    /// Net long position.
    Long,
    /// Net short position.
    Short,
    /// Provider code not known to this crate version.
    Unknown(i32),
}

impl PositionType {
    /// Returns the provider's numeric wire code.
    #[must_use]
    pub const fn code(self) -> i32 {
        match self {
            Self::Undefined => 0,
            Self::Long => 1,
            Self::Short => 2,
            Self::Unknown(code) => code,
        }
    }
}

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

impl<'de> Deserialize<'de> for PositionType {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        Ok(match i32::deserialize(deserializer)? {
            0 => Self::Undefined,
            1 => Self::Long,
            2 => Self::Short,
            code => Self::Unknown(code),
        })
    }
}

/// A `ProjectX` depth-of-market update kind.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum DepthType {
    /// Provider sentinel with no book mutation.
    Unknown,
    /// Resting ask level.
    Ask,
    /// Resting bid level.
    Bid,
    /// Best ask update.
    BestAsk,
    /// Best bid update.
    BestBid,
    /// Trade notification carried on the depth stream.
    Trade,
    /// Full book reset.
    Reset,
    /// Session-low notification.
    Low,
    /// Session-high notification.
    High,
    /// New best bid.
    NewBestBid,
    /// New best ask.
    NewBestAsk,
    /// Fill notification carried on the depth stream.
    Fill,
    /// Provider code not known to this crate version.
    UnknownCode(i32),
}

impl DepthType {
    /// Returns the provider's numeric wire code.
    #[must_use]
    pub const fn code(self) -> i32 {
        match self {
            Self::Unknown => 0,
            Self::Ask => 1,
            Self::Bid => 2,
            Self::BestAsk => 3,
            Self::BestBid => 4,
            Self::Trade => 5,
            Self::Reset => 6,
            Self::Low => 7,
            Self::High => 8,
            Self::NewBestBid => 9,
            Self::NewBestAsk => 10,
            Self::Fill => 11,
            Self::UnknownCode(code) => code,
        }
    }
}

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

impl<'de> Deserialize<'de> for DepthType {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        Ok(match i32::deserialize(deserializer)? {
            0 => Self::Unknown,
            1 => Self::Ask,
            2 => Self::Bid,
            3 => Self::BestAsk,
            4 => Self::BestBid,
            5 => Self::Trade,
            6 => Self::Reset,
            7 => Self::Low,
            8 => Self::High,
            9 => Self::NewBestBid,
            10 => Self::NewBestAsk,
            11 => Self::Fill,
            code => Self::UnknownCode(code),
        })
    }
}

/// Historical-bar aggregation unit.
///
/// The provider's `Unspecified = 0` sentinel is intentionally omitted so a
/// request must select a concrete aggregation.
#[derive(Clone, Copy, Debug, Deserialize_repr, Eq, PartialEq, Serialize_repr)]
#[non_exhaustive]
#[repr(i32)]
pub enum BarUnit {
    /// Seconds.
    Second = 1,
    /// Minutes.
    Minute = 2,
    /// Hours.
    Hour = 3,
    /// Days.
    Day = 4,
    /// Weeks.
    Week = 5,
    /// Months.
    Month = 6,
    /// Individual trades (ticks).
    Tick = 7,
}

/// A `ProjectX` account.
#[derive(Clone, Debug, Deserialize, PartialEq)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
pub struct Account {
    /// Provider account identifier.
    pub id: AccountId,
    /// Provider display name.
    pub name: String,
    /// Current account balance, when included by the endpoint.
    #[serde(default, with = "crate::decimal_serde::option")]
    pub balance: Option<Decimal>,
    /// Whether the provider permits trading.
    pub can_trade: bool,
    /// Whether the provider marks the account visible.
    pub is_visible: bool,
    /// Whether this is a simulated account, when included by the endpoint.
    #[serde(default)]
    pub simulated: Option<bool>,
}

/// A `ProjectX` futures contract.
#[derive(Clone, Debug, Deserialize, PartialEq)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
pub struct Contract {
    /// Provider contract identifier.
    pub id: ContractId,
    /// Provider short name.
    pub name: String,
    /// Human-readable description.
    pub description: String,
    /// Minimum price increment.
    #[serde(with = "crate::decimal_serde")]
    pub tick_size: Decimal,
    /// Monetary value of one tick.
    #[serde(with = "crate::decimal_serde")]
    pub tick_value: Decimal,
    /// Whether this is the provider's active contract.
    pub active_contract: bool,
    /// Provider root symbol identifier.
    pub symbol_id: SymbolId,
}

/// Contract search parameters.
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SearchContracts {
    /// Whether to search the live-data catalog.
    pub live: bool,
    /// Provider search text.
    pub search_text: String,
}

/// Historical-bar request parameters.
///
/// Construct this request with [`HistoryRequest::builder`]. The builder starts
/// with one unit per bar, the provider maximum of 20,000 bars, and partial bars
/// excluded; each default can be overridden explicitly.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct HistoryRequest {
    /// Explicit provider contract.
    contract_id: ContractId,
    /// Whether to use the live-data subscription.
    live: bool,
    /// Absolute range start.
    start_time: Timestamp,
    /// Absolute range end.
    end_time: Timestamp,
    /// Aggregation unit.
    unit: BarUnit,
    /// Number of units per bar.
    unit_number: i32,
    /// Maximum number of bars, up to the provider limit of 20,000.
    limit: i32,
    /// Whether to include the current partial bar.
    include_partial_bar: bool,
}

impl HistoryRequest {
    /// Starts a validated historical-bar request.
    pub fn builder(
        contract_id: ContractId,
        live: bool,
        start_time: Timestamp,
        end_time: Timestamp,
        unit: BarUnit,
    ) -> HistoryRequestBuilder {
        HistoryRequestBuilder {
            contract_id,
            live,
            start_time,
            end_time,
            unit,
            unit_number: 1,
            limit: 20_000,
            include_partial_bar: false,
        }
    }

    /// Borrows the provider contract.
    #[must_use]
    pub const fn contract_id(&self) -> &ContractId {
        &self.contract_id
    }

    /// Returns whether the live-data subscription is selected.
    #[must_use]
    pub const fn is_live(&self) -> bool {
        self.live
    }

    /// Returns the absolute range start.
    #[must_use]
    pub const fn start_time(&self) -> Timestamp {
        self.start_time
    }

    /// Returns the absolute range end.
    #[must_use]
    pub const fn end_time(&self) -> Timestamp {
        self.end_time
    }

    /// Returns the aggregation unit.
    #[must_use]
    pub const fn unit(&self) -> BarUnit {
        self.unit
    }

    /// Returns the positive number of units per bar.
    #[must_use]
    pub const fn unit_number(&self) -> i32 {
        self.unit_number
    }

    /// Returns the requested bar limit in `1..=20_000`.
    #[must_use]
    pub const fn limit(&self) -> i32 {
        self.limit
    }

    /// Returns whether the current partial bar is requested.
    #[must_use]
    pub const fn includes_partial_bar(&self) -> bool {
        self.include_partial_bar
    }
}

/// Builder for a validated [`HistoryRequest`].
#[derive(Clone, Debug)]
#[must_use = "a HistoryRequestBuilder does nothing until build is called"]
pub struct HistoryRequestBuilder {
    contract_id: ContractId,
    live: bool,
    start_time: Timestamp,
    end_time: Timestamp,
    unit: BarUnit,
    unit_number: i32,
    limit: i32,
    include_partial_bar: bool,
}

impl HistoryRequestBuilder {
    /// Sets the positive number of units per bar.
    pub const fn unit_number(mut self, unit_number: i32) -> Self {
        self.unit_number = unit_number;
        self
    }

    /// Sets the maximum number of bars in `1..=20_000`.
    pub const fn limit(mut self, limit: i32) -> Self {
        self.limit = limit;
        self
    }

    /// Selects whether to include the current partial bar.
    pub const fn include_partial_bar(mut self, include: bool) -> Self {
        self.include_partial_bar = include;
        self
    }

    /// Validates and builds the historical-bar request.
    ///
    /// # Errors
    ///
    /// Returns an error when the range does not increase, the unit number is
    /// non-positive, or the limit falls outside `1..=20_000`.
    pub fn build(self) -> Result<HistoryRequest, RequestValidationError> {
        if self.start_time >= self.end_time {
            return Err(RequestValidationError::HistoryRangeNotIncreasing);
        }
        if self.unit_number <= 0 {
            return Err(RequestValidationError::NonPositiveHistoryUnitNumber);
        }
        if !(1..=20_000).contains(&self.limit) {
            return Err(RequestValidationError::HistoryLimitOutOfRange);
        }
        Ok(HistoryRequest {
            contract_id: self.contract_id,
            live: self.live,
            start_time: self.start_time,
            end_time: self.end_time,
            unit: self.unit,
            unit_number: self.unit_number,
            limit: self.limit,
            include_partial_bar: self.include_partial_bar,
        })
    }
}

/// A historical OHLCV bar.
#[derive(Clone, Debug, Deserialize, PartialEq)]
#[non_exhaustive]
pub struct Bar {
    /// Provider timestamp.
    pub t: Timestamp,
    /// Open price.
    #[serde(with = "crate::decimal_serde")]
    pub o: Decimal,
    /// High price.
    #[serde(with = "crate::decimal_serde")]
    pub h: Decimal,
    /// Low price.
    #[serde(with = "crate::decimal_serde")]
    pub l: Decimal,
    /// Close price.
    #[serde(with = "crate::decimal_serde")]
    pub c: Decimal,
    /// Provider volume units.
    pub v: i64,
    /// Optional provider business date.
    #[serde(default)]
    pub d: Option<ProviderDate>,
    /// Optional provider aggregate key.
    #[serde(default)]
    pub k: Option<i64>,
}

/// Historical order search parameters.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct OrderSearch {
    /// Provider account.
    account_id: AccountId,
    /// Absolute range start.
    start_timestamp: Timestamp,
    /// Optional absolute range end.
    #[serde(skip_serializing_if = "Option::is_none")]
    end_timestamp: Option<Timestamp>,
}

impl OrderSearch {
    /// Creates a validated historical order search.
    ///
    /// # Errors
    ///
    /// Returns [`RequestValidationError::SearchRangeNotIncreasing`] when an
    /// end timestamp is not later than the start timestamp.
    pub fn new(
        account_id: AccountId,
        start_timestamp: Timestamp,
        end_timestamp: Option<Timestamp>,
    ) -> Result<Self, RequestValidationError> {
        validate_search_range(Some(start_timestamp), end_timestamp)?;
        Ok(Self {
            account_id,
            start_timestamp,
            end_timestamp,
        })
    }

    /// Returns the provider account.
    #[must_use]
    pub const fn account_id(&self) -> AccountId {
        self.account_id
    }

    /// Returns the range start.
    #[must_use]
    pub const fn start_timestamp(&self) -> Timestamp {
        self.start_timestamp
    }

    /// Returns the optional range end.
    #[must_use]
    pub const fn end_timestamp(&self) -> Option<Timestamp> {
        self.end_timestamp
    }
}

/// Filtered, paginated order-query parameters.
///
/// Construct this request with [`OrderQuery::builder`]. Unlike
/// [`Client::search_open_orders`](crate::Client::search_open_orders), the v2
/// query can explicitly include [`OrderStatus::Suspended`] bracket children.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct OrderQuery {
    filter: OrderFilter,
    #[serde(skip_serializing_if = "Option::is_none")]
    page_size: Option<i32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    page_offset: Option<i32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    sort_by: Option<OrderSortBy>,
    #[serde(skip_serializing_if = "Option::is_none")]
    sort_direction: Option<OrderSortDirection>,
    #[serde(skip_serializing_if = "Option::is_none")]
    include_total_count: Option<bool>,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
struct OrderFilter {
    account_id: AccountId,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    statuses: Vec<OrderStatus>,
    #[serde(skip_serializing_if = "Option::is_none")]
    contract_id: Option<ContractId>,
    #[serde(skip_serializing_if = "Option::is_none")]
    created_after: Option<Timestamp>,
    #[serde(skip_serializing_if = "Option::is_none")]
    created_before: Option<Timestamp>,
}

impl OrderQuery {
    /// Starts a validated v2 order query for an account.
    pub fn builder(account_id: AccountId) -> OrderQueryBuilder {
        OrderQueryBuilder {
            account_id,
            statuses: Vec::new(),
            contract_id: None,
            created_after: None,
            created_before: None,
            page_size: None,
            page_offset: None,
            sort_by: None,
            sort_direction: None,
            include_total_count: None,
        }
    }

    /// Returns the provider account being queried.
    #[must_use]
    pub const fn account_id(&self) -> AccountId {
        self.filter.account_id
    }

    /// Borrows the requested lifecycle statuses.
    #[must_use]
    pub fn statuses(&self) -> &[OrderStatus] {
        &self.filter.statuses
    }

    /// Borrows the optional provider contract filter.
    #[must_use]
    pub const fn contract_id(&self) -> Option<&ContractId> {
        self.filter.contract_id.as_ref()
    }

    /// Returns the optional lower creation-time bound.
    #[must_use]
    pub const fn created_after(&self) -> Option<Timestamp> {
        self.filter.created_after
    }

    /// Returns the optional upper creation-time bound.
    #[must_use]
    pub const fn created_before(&self) -> Option<Timestamp> {
        self.filter.created_before
    }

    /// Returns the optional positive page size.
    #[must_use]
    pub const fn page_size(&self) -> Option<i32> {
        self.page_size
    }

    /// Returns the optional non-negative page offset.
    #[must_use]
    pub const fn page_offset(&self) -> Option<i32> {
        self.page_offset
    }

    /// Returns the optional sort field.
    #[must_use]
    pub const fn sort_by(&self) -> Option<OrderSortBy> {
        self.sort_by
    }

    /// Returns the optional sort direction.
    #[must_use]
    pub const fn sort_direction(&self) -> Option<OrderSortDirection> {
        self.sort_direction
    }

    /// Returns the optional total-count request flag.
    #[must_use]
    pub const fn include_total_count(&self) -> Option<bool> {
        self.include_total_count
    }
}

/// Builder for a validated [`OrderQuery`].
#[derive(Clone, Debug)]
#[must_use = "an OrderQueryBuilder does nothing until build is called"]
pub struct OrderQueryBuilder {
    account_id: AccountId,
    statuses: Vec<OrderStatus>,
    contract_id: Option<ContractId>,
    created_after: Option<Timestamp>,
    created_before: Option<Timestamp>,
    page_size: Option<i32>,
    page_offset: Option<i32>,
    sort_by: Option<OrderSortBy>,
    sort_direction: Option<OrderSortDirection>,
    include_total_count: Option<bool>,
}

impl OrderQueryBuilder {
    /// Replaces the lifecycle-status filter.
    pub fn statuses(mut self, statuses: impl IntoIterator<Item = OrderStatus>) -> Self {
        self.statuses = statuses.into_iter().collect();
        self
    }

    /// Restricts results to one provider contract.
    pub fn contract_id(mut self, contract_id: ContractId) -> Self {
        self.contract_id = Some(contract_id);
        self
    }

    /// Sets the lower creation-time bound.
    pub const fn created_after(mut self, created_after: Timestamp) -> Self {
        self.created_after = Some(created_after);
        self
    }

    /// Sets the upper creation-time bound.
    pub const fn created_before(mut self, created_before: Timestamp) -> Self {
        self.created_before = Some(created_before);
        self
    }

    /// Sets the positive number of orders requested per page.
    pub const fn page_size(mut self, page_size: i32) -> Self {
        self.page_size = Some(page_size);
        self
    }

    /// Sets the non-negative result offset.
    pub const fn page_offset(mut self, page_offset: i32) -> Self {
        self.page_offset = Some(page_offset);
        self
    }

    /// Selects the result sort field.
    pub const fn sort_by(mut self, sort_by: OrderSortBy) -> Self {
        self.sort_by = Some(sort_by);
        self
    }

    /// Selects the result sort direction.
    pub const fn sort_direction(mut self, sort_direction: OrderSortDirection) -> Self {
        self.sort_direction = Some(sort_direction);
        self
    }

    /// Selects whether the response should include a total matching count.
    pub const fn include_total_count(mut self, include: bool) -> Self {
        self.include_total_count = Some(include);
        self
    }

    /// Validates and builds the v2 order query.
    ///
    /// # Errors
    ///
    /// Returns an error for an unknown request-status code, a creation range
    /// that does not increase, a non-positive page size, or a negative page
    /// offset.
    pub fn build(self) -> Result<OrderQuery, RequestValidationError> {
        if let Some(code) = self.statuses.iter().find_map(|status| match status {
            OrderStatus::Unknown(code) => Some(*code),
            _ => None,
        }) {
            return Err(RequestValidationError::UnsupportedOrderStatus { code });
        }
        if self
            .created_after
            .zip(self.created_before)
            .is_some_and(|(after, before)| after >= before)
        {
            return Err(RequestValidationError::SearchRangeNotIncreasing);
        }
        if self.page_size.is_some_and(|size| size <= 0) {
            return Err(RequestValidationError::NonPositiveOrderPageSize);
        }
        if self.page_offset.is_some_and(|offset| offset < 0) {
            return Err(RequestValidationError::NegativeOrderPageOffset);
        }
        Ok(OrderQuery {
            filter: OrderFilter {
                account_id: self.account_id,
                statuses: self.statuses,
                contract_id: self.contract_id,
                created_after: self.created_after,
                created_before: self.created_before,
            },
            page_size: self.page_size,
            page_offset: self.page_offset,
            sort_by: self.sort_by,
            sort_direction: self.sort_direction,
            include_total_count: self.include_total_count,
        })
    }
}

/// One page returned by [`Client::query_orders`](crate::Client::query_orders).
#[derive(Clone, Debug, Deserialize, PartialEq)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
pub struct OrderPage {
    /// Orders in provider-selected page order.
    #[serde(default, deserialize_with = "null_to_empty")]
    pub orders: Vec<Order>,
    /// Total matching order count when requested and supplied by the provider.
    #[serde(default)]
    pub total_count: Option<i32>,
}

/// A `ProjectX` order.
#[derive(Clone, Debug, Deserialize, PartialEq)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
pub struct Order {
    /// Provider order identifier.
    pub id: OrderId,
    /// Provider account.
    pub account_id: AccountId,
    /// Provider contract.
    pub contract_id: ContractId,
    /// Provider symbol, when included by the endpoint.
    #[serde(default)]
    pub symbol_id: Option<SymbolId>,
    /// Provider creation timestamp.
    pub creation_timestamp: Timestamp,
    /// Provider update timestamp.
    pub update_timestamp: Timestamp,
    /// Provider order status.
    pub status: OrderStatus,
    /// Provider order type.
    #[serde(rename = "type")]
    pub order_type: OrderType,
    /// Order side.
    pub side: Side,
    /// Ordered quantity.
    pub size: i32,
    /// Optional limit price.
    #[serde(default, with = "crate::decimal_serde::option")]
    pub limit_price: Option<Decimal>,
    /// Optional stop price.
    #[serde(default, with = "crate::decimal_serde::option")]
    pub stop_price: Option<Decimal>,
    /// Optional cumulative filled quantity.
    #[serde(default)]
    pub fill_volume: Option<i32>,
    /// Optional average fill price.
    #[serde(default, with = "crate::decimal_serde::option")]
    pub filled_price: Option<Decimal>,
    /// Optional caller tag.
    #[serde(default)]
    pub custom_tag: Option<String>,
    /// Optional trailing distance in provider ticks.
    #[serde(default)]
    pub trail_distance: Option<i32>,
    /// Optional current trailing-stop price.
    #[serde(default, with = "crate::decimal_serde::option")]
    pub trail_price: Option<Decimal>,
    /// Parent order for a bracket child, when supplied.
    #[serde(default)]
    pub parent_order_id: Option<OrderId>,
    /// Provider-linked peer order, when supplied.
    #[serde(default)]
    pub linked_order_id: Option<OrderId>,
}

/// Validation failures while constructing a provider request.
#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
#[non_exhaustive]
pub enum RequestValidationError {
    /// An order placement quantity was zero or negative.
    #[error("order size must be positive")]
    NonPositiveOrderSize,
    /// A replacement quantity was zero or negative.
    #[error("replacement order size must be positive")]
    NonPositiveReplacementSize,
    /// An order modification contained no replacement values.
    #[error("order modification requires at least one replacement value")]
    EmptyModification,
    /// A bracket distance was zero or negative.
    #[error("bracket ticks must be positive")]
    NonPositiveBracketTicks,
    /// An order request used an undocumented or unknown provider type code.
    #[error("unsupported order type code {code}")]
    UnsupportedOrderType {
        /// Unrecognized provider wire code.
        code: i32,
    },
    /// An order request used a provider side code unknown to this crate version.
    #[error("unsupported order side code {code}")]
    UnsupportedOrderSide {
        /// Unrecognized provider wire code.
        code: i32,
    },
    /// An order query used a provider status code unknown to this crate version.
    #[error("unsupported order status code {code}")]
    UnsupportedOrderStatus {
        /// Unrecognized provider wire code.
        code: i32,
    },
    /// A v2 order query requested a zero or negative page size.
    #[error("order-query page size must be positive")]
    NonPositiveOrderPageSize,
    /// A v2 order query requested a negative page offset.
    #[error("order-query page offset must not be negative")]
    NegativeOrderPageOffset,
    /// A historical-bar unit count was zero or negative.
    #[error("historical-bar unit number must be positive")]
    NonPositiveHistoryUnitNumber,
    /// A historical-bar limit exceeded the provider-supported range.
    #[error("historical-bar limit must be between 1 and 20,000")]
    HistoryLimitOutOfRange,
    /// A historical-bar range ended at or before its start.
    #[error("historical-bar end time must be later than its start time")]
    HistoryRangeNotIncreasing,
    /// An order or trade search ended at or before its start.
    #[error("search end time must be later than its start time")]
    SearchRangeNotIncreasing,
    /// A partial-close quantity was zero or negative.
    #[error("partial-close size must be positive")]
    NonPositivePartialCloseSize,
}

/// `ProjectX` bracket-leg configuration.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Bracket {
    /// Distance in provider ticks.
    ticks: i32,
    /// Bracket order type.
    #[serde(rename = "type")]
    order_type: OrderType,
}

impl Bracket {
    /// Creates a bracket leg with a positive distance in ticks.
    ///
    /// # Errors
    ///
    /// Returns an error when `ticks` is zero or negative, or when `order_type`
    /// is not documented by the provider for bracket requests.
    pub fn new(ticks: i32, order_type: OrderType) -> Result<Self, RequestValidationError> {
        if ticks <= 0 {
            return Err(RequestValidationError::NonPositiveBracketTicks);
        }
        validate_request_order_type(order_type)?;
        Ok(Self { ticks, order_type })
    }

    /// Returns the distance in provider ticks.
    #[must_use]
    pub const fn ticks(&self) -> i32 {
        self.ticks
    }

    /// Returns the bracket order type.
    #[must_use]
    pub const fn order_type(&self) -> OrderType {
        self.order_type
    }
}

/// Order placement parameters.
///
/// Construct this request with [`PlaceOrder::builder`], which prevents an
/// invalid non-positive quantity from reaching the transport.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlaceOrder {
    /// Provider account.
    account_id: AccountId,
    /// Provider contract.
    contract_id: ContractId,
    /// Order type.
    #[serde(rename = "type")]
    order_type: OrderType,
    /// Order side.
    side: Side,
    /// Order quantity.
    size: i32,
    /// Optional limit price.
    #[serde(
        skip_serializing_if = "Option::is_none",
        with = "crate::decimal_serde::option"
    )]
    limit_price: Option<Decimal>,
    /// Optional stop price.
    #[serde(
        skip_serializing_if = "Option::is_none",
        with = "crate::decimal_serde::option"
    )]
    stop_price: Option<Decimal>,
    /// Optional trailing price.
    #[serde(
        skip_serializing_if = "Option::is_none",
        with = "crate::decimal_serde::option"
    )]
    trail_price: Option<Decimal>,
    /// Optional caller tag. It must be unique within the account.
    #[serde(skip_serializing_if = "Option::is_none")]
    custom_tag: Option<String>,
    /// Optional stop-loss bracket.
    #[serde(skip_serializing_if = "Option::is_none")]
    stop_loss_bracket: Option<Bracket>,
    /// Optional take-profit bracket.
    #[serde(skip_serializing_if = "Option::is_none")]
    take_profit_bracket: Option<Bracket>,
}

impl PlaceOrder {
    /// Starts a validated order-placement request.
    pub fn builder(
        account_id: AccountId,
        contract_id: ContractId,
        order_type: OrderType,
        side: Side,
        quantity: i32,
    ) -> PlaceOrderBuilder {
        PlaceOrderBuilder {
            account_id,
            contract_id,
            order_type,
            side,
            size: quantity,
            limit_price: None,
            stop_price: None,
            trail_price: None,
            custom_tag: None,
            stop_loss_bracket: None,
            take_profit_bracket: None,
        }
    }

    /// Returns the provider account.
    #[must_use]
    pub const fn account_id(&self) -> AccountId {
        self.account_id
    }

    /// Borrows the provider contract.
    #[must_use]
    pub const fn contract_id(&self) -> &ContractId {
        &self.contract_id
    }

    /// Returns the order type.
    #[must_use]
    pub const fn order_type(&self) -> OrderType {
        self.order_type
    }

    /// Returns the order side.
    #[must_use]
    pub const fn side(&self) -> Side {
        self.side
    }

    /// Returns the positive order quantity.
    #[must_use]
    pub const fn size(&self) -> i32 {
        self.size
    }

    /// Returns the optional limit price.
    #[must_use]
    pub const fn limit_price(&self) -> Option<Decimal> {
        self.limit_price
    }

    /// Returns the optional stop price.
    #[must_use]
    pub const fn stop_price(&self) -> Option<Decimal> {
        self.stop_price
    }

    /// Returns the optional trailing price.
    #[must_use]
    pub const fn trail_price(&self) -> Option<Decimal> {
        self.trail_price
    }

    /// Borrows the optional caller tag.
    #[must_use]
    pub fn custom_tag(&self) -> Option<&str> {
        self.custom_tag.as_deref()
    }

    /// Borrows the optional stop-loss bracket.
    #[must_use]
    pub const fn stop_loss_bracket(&self) -> Option<&Bracket> {
        self.stop_loss_bracket.as_ref()
    }

    /// Borrows the optional take-profit bracket.
    #[must_use]
    pub const fn take_profit_bracket(&self) -> Option<&Bracket> {
        self.take_profit_bracket.as_ref()
    }
}

/// Builder for a validated [`PlaceOrder`].
#[derive(Clone, Debug)]
#[must_use = "a PlaceOrderBuilder does nothing until build is called"]
pub struct PlaceOrderBuilder {
    account_id: AccountId,
    contract_id: ContractId,
    order_type: OrderType,
    side: Side,
    size: i32,
    limit_price: Option<Decimal>,
    stop_price: Option<Decimal>,
    trail_price: Option<Decimal>,
    custom_tag: Option<String>,
    stop_loss_bracket: Option<Bracket>,
    take_profit_bracket: Option<Bracket>,
}

impl PlaceOrderBuilder {
    /// Sets the optional limit price.
    pub const fn limit_price(mut self, limit_price: Decimal) -> Self {
        self.limit_price = Some(limit_price);
        self
    }

    /// Sets the optional stop price.
    pub const fn stop_price(mut self, stop_price: Decimal) -> Self {
        self.stop_price = Some(stop_price);
        self
    }

    /// Sets the optional trailing price.
    pub const fn trail_price(mut self, trail_price: Decimal) -> Self {
        self.trail_price = Some(trail_price);
        self
    }

    /// Sets the optional caller tag, which must be unique within the account.
    pub fn custom_tag(mut self, custom_tag: impl Into<String>) -> Self {
        self.custom_tag = Some(custom_tag.into());
        self
    }

    /// Sets the optional stop-loss bracket.
    pub fn stop_loss_bracket(mut self, stop_loss_bracket: Bracket) -> Self {
        self.stop_loss_bracket = Some(stop_loss_bracket);
        self
    }

    /// Sets the optional take-profit bracket.
    pub fn take_profit_bracket(mut self, take_profit_bracket: Bracket) -> Self {
        self.take_profit_bracket = Some(take_profit_bracket);
        self
    }

    /// Validates and builds the order-placement request.
    ///
    /// # Errors
    ///
    /// Returns an error when the order quantity is zero or negative, when its
    /// order type is undocumented for placement, or when its side code is
    /// unknown to this crate version.
    pub fn build(self) -> Result<PlaceOrder, RequestValidationError> {
        if self.size <= 0 {
            return Err(RequestValidationError::NonPositiveOrderSize);
        }
        validate_request_order_type(self.order_type)?;
        if let Side::Unknown(code) = self.side {
            return Err(RequestValidationError::UnsupportedOrderSide { code });
        }
        Ok(PlaceOrder {
            account_id: self.account_id,
            contract_id: self.contract_id,
            order_type: self.order_type,
            side: self.side,
            size: self.size,
            limit_price: self.limit_price,
            stop_price: self.stop_price,
            trail_price: self.trail_price,
            custom_tag: self.custom_tag,
            stop_loss_bracket: self.stop_loss_bracket,
            take_profit_bracket: self.take_profit_bracket,
        })
    }
}

fn validate_request_order_type(order_type: OrderType) -> Result<(), RequestValidationError> {
    match order_type {
        OrderType::Limit
        | OrderType::Market
        | OrderType::Stop
        | OrderType::TrailingStop
        | OrderType::JoinBid
        | OrderType::JoinAsk => Ok(()),
        OrderType::StopLimit => Err(RequestValidationError::UnsupportedOrderType { code: 3 }),
        OrderType::Unknown(code) => Err(RequestValidationError::UnsupportedOrderType { code }),
    }
}

/// Successful order-placement result.
#[derive(Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub struct OrderResponse {
    /// Provider order identifier.
    pub order_id: OrderId,
}

/// Order cancellation parameters.
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CancelOrder {
    /// Provider account.
    pub account_id: AccountId,
    /// Provider order.
    pub order_id: OrderId,
}

/// Order modification parameters.
///
/// Construct this request with [`ModifyOrder::builder`], which requires at
/// least one replacement value and rejects non-positive replacement sizes.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ModifyOrder {
    /// Provider account.
    account_id: AccountId,
    /// Provider order.
    order_id: OrderId,
    /// Optional replacement quantity.
    #[serde(skip_serializing_if = "Option::is_none")]
    size: Option<i32>,
    /// Optional replacement limit price.
    #[serde(
        skip_serializing_if = "Option::is_none",
        with = "crate::decimal_serde::option"
    )]
    limit_price: Option<Decimal>,
    /// Optional replacement stop price.
    #[serde(
        skip_serializing_if = "Option::is_none",
        with = "crate::decimal_serde::option"
    )]
    stop_price: Option<Decimal>,
    /// Optional replacement trailing price.
    #[serde(
        skip_serializing_if = "Option::is_none",
        with = "crate::decimal_serde::option"
    )]
    trail_price: Option<Decimal>,
}

impl ModifyOrder {
    /// Starts a validated order-modification request.
    pub const fn builder(account_id: AccountId, order_id: OrderId) -> ModifyOrderBuilder {
        ModifyOrderBuilder {
            account_id,
            order_id,
            size: None,
            limit_price: None,
            stop_price: None,
            trail_price: None,
        }
    }

    /// Returns the provider account.
    #[must_use]
    pub const fn account_id(&self) -> AccountId {
        self.account_id
    }

    /// Returns the provider order.
    #[must_use]
    pub const fn order_id(&self) -> OrderId {
        self.order_id
    }

    /// Returns the optional positive replacement quantity.
    #[must_use]
    pub const fn size(&self) -> Option<i32> {
        self.size
    }

    /// Returns the optional replacement limit price.
    #[must_use]
    pub const fn limit_price(&self) -> Option<Decimal> {
        self.limit_price
    }

    /// Returns the optional replacement stop price.
    #[must_use]
    pub const fn stop_price(&self) -> Option<Decimal> {
        self.stop_price
    }

    /// Returns the optional replacement trailing price.
    #[must_use]
    pub const fn trail_price(&self) -> Option<Decimal> {
        self.trail_price
    }
}

/// Builder for a validated [`ModifyOrder`].
#[derive(Clone, Copy, Debug)]
#[must_use = "a ModifyOrderBuilder does nothing until build is called"]
pub struct ModifyOrderBuilder {
    account_id: AccountId,
    order_id: OrderId,
    size: Option<i32>,
    limit_price: Option<Decimal>,
    stop_price: Option<Decimal>,
    trail_price: Option<Decimal>,
}

impl ModifyOrderBuilder {
    /// Sets the replacement quantity.
    pub const fn size(mut self, size: i32) -> Self {
        self.size = Some(size);
        self
    }

    /// Sets the replacement limit price.
    pub const fn limit_price(mut self, limit_price: Decimal) -> Self {
        self.limit_price = Some(limit_price);
        self
    }

    /// Sets the replacement stop price.
    pub const fn stop_price(mut self, stop_price: Decimal) -> Self {
        self.stop_price = Some(stop_price);
        self
    }

    /// Sets the replacement trailing price.
    pub const fn trail_price(mut self, trail_price: Decimal) -> Self {
        self.trail_price = Some(trail_price);
        self
    }

    /// Validates and builds the order-modification request.
    ///
    /// # Errors
    ///
    /// Returns [`RequestValidationError::NonPositiveReplacementSize`] when a
    /// replacement quantity is zero or negative, or
    /// [`RequestValidationError::EmptyModification`] when no replacement value was
    /// supplied.
    pub fn build(self) -> Result<ModifyOrder, RequestValidationError> {
        if self.size.is_some_and(|size| size <= 0) {
            return Err(RequestValidationError::NonPositiveReplacementSize);
        }
        if self.size.is_none()
            && self.limit_price.is_none()
            && self.stop_price.is_none()
            && self.trail_price.is_none()
        {
            return Err(RequestValidationError::EmptyModification);
        }
        Ok(ModifyOrder {
            account_id: self.account_id,
            order_id: self.order_id,
            size: self.size,
            limit_price: self.limit_price,
            stop_price: self.stop_price,
            trail_price: self.trail_price,
        })
    }
}

/// Position close parameters.
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CloseContract {
    /// Provider account.
    pub account_id: AccountId,
    /// Provider contract.
    pub contract_id: ContractId,
}

/// Partial-position close parameters.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PartialCloseContract {
    /// Provider account.
    account_id: AccountId,
    /// Provider contract.
    contract_id: ContractId,
    /// Positive quantity to close.
    size: i32,
}

impl PartialCloseContract {
    /// Creates a partial-position close with a positive quantity.
    ///
    /// # Errors
    ///
    /// Returns [`RequestValidationError::NonPositivePartialCloseSize`] when
    /// `size` is zero or negative.
    pub fn new(
        account_id: AccountId,
        contract_id: ContractId,
        size: i32,
    ) -> Result<Self, RequestValidationError> {
        if size <= 0 {
            return Err(RequestValidationError::NonPositivePartialCloseSize);
        }
        Ok(Self {
            account_id,
            contract_id,
            size,
        })
    }

    /// Returns the provider account.
    #[must_use]
    pub const fn account_id(&self) -> AccountId {
        self.account_id
    }

    /// Borrows the provider contract.
    #[must_use]
    pub const fn contract_id(&self) -> &ContractId {
        &self.contract_id
    }

    /// Returns the positive quantity to close.
    #[must_use]
    pub const fn size(&self) -> i32 {
        self.size
    }
}

/// A `ProjectX` open position.
#[derive(Clone, Debug, Deserialize, PartialEq)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
pub struct Position {
    /// Provider position identifier.
    pub id: PositionId,
    /// Provider account.
    pub account_id: AccountId,
    /// Provider contract.
    pub contract_id: ContractId,
    /// Provider contract display name, when supplied.
    #[serde(default)]
    pub contract_display_name: Option<String>,
    /// Provider creation timestamp.
    pub creation_timestamp: Timestamp,
    /// Provider position-type code.
    #[serde(rename = "type")]
    pub position_type: PositionType,
    /// Signed or directional provider quantity.
    pub size: i32,
    /// Average entry price.
    #[serde(with = "crate::decimal_serde")]
    pub average_price: Decimal,
}

/// Trade search parameters.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TradeSearch {
    /// Provider account.
    account_id: AccountId,
    /// Absolute range start.
    start_timestamp: Timestamp,
    /// Optional absolute range end.
    #[serde(skip_serializing_if = "Option::is_none")]
    end_timestamp: Option<Timestamp>,
}

/// Trade search parameters with independently optional timestamp bounds.
///
/// Construct this request with [`TradeQuery::builder`]. Omitting both bounds
/// requests every trade available for the selected account.
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TradeQuery {
    /// Provider account.
    account_id: AccountId,
    /// Optional absolute range start.
    #[serde(skip_serializing_if = "Option::is_none")]
    start_timestamp: Option<Timestamp>,
    /// Optional absolute range end.
    #[serde(skip_serializing_if = "Option::is_none")]
    end_timestamp: Option<Timestamp>,
}

impl TradeQuery {
    /// Starts a trade query for an account with no timestamp bounds.
    pub const fn builder(account_id: AccountId) -> TradeQueryBuilder {
        TradeQueryBuilder {
            account_id,
            start_timestamp: None,
            end_timestamp: None,
        }
    }

    /// Returns the provider account.
    #[must_use]
    pub const fn account_id(&self) -> AccountId {
        self.account_id
    }

    /// Returns the optional lower timestamp bound.
    #[must_use]
    pub const fn start_timestamp(&self) -> Option<Timestamp> {
        self.start_timestamp
    }

    /// Returns the optional upper timestamp bound.
    #[must_use]
    pub const fn end_timestamp(&self) -> Option<Timestamp> {
        self.end_timestamp
    }
}

/// Builder for a validated [`TradeQuery`].
#[derive(Clone, Copy, Debug)]
#[must_use = "a TradeQueryBuilder does nothing until build is called"]
pub struct TradeQueryBuilder {
    account_id: AccountId,
    start_timestamp: Option<Timestamp>,
    end_timestamp: Option<Timestamp>,
}

impl TradeQueryBuilder {
    /// Sets the optional lower timestamp bound.
    pub const fn start_timestamp(mut self, start_timestamp: Timestamp) -> Self {
        self.start_timestamp = Some(start_timestamp);
        self
    }

    /// Sets the optional upper timestamp bound.
    pub const fn end_timestamp(mut self, end_timestamp: Timestamp) -> Self {
        self.end_timestamp = Some(end_timestamp);
        self
    }

    /// Validates and builds the trade query.
    ///
    /// # Errors
    ///
    /// Returns [`RequestValidationError::SearchRangeNotIncreasing`] when both
    /// bounds are present and the end is not later than the start.
    pub fn build(self) -> Result<TradeQuery, RequestValidationError> {
        validate_search_range(self.start_timestamp, self.end_timestamp)?;
        Ok(TradeQuery {
            account_id: self.account_id,
            start_timestamp: self.start_timestamp,
            end_timestamp: self.end_timestamp,
        })
    }
}

impl TradeSearch {
    /// Creates a validated execution search.
    ///
    /// # Errors
    ///
    /// Returns [`RequestValidationError::SearchRangeNotIncreasing`] when an
    /// end timestamp is present and is not later than the start.
    pub fn new(
        account_id: AccountId,
        start_timestamp: Timestamp,
        end_timestamp: Option<Timestamp>,
    ) -> Result<Self, RequestValidationError> {
        validate_search_range(Some(start_timestamp), end_timestamp)?;
        Ok(Self {
            account_id,
            start_timestamp,
            end_timestamp,
        })
    }

    /// Returns the provider account.
    #[must_use]
    pub const fn account_id(&self) -> AccountId {
        self.account_id
    }

    /// Returns the range start.
    #[must_use]
    pub const fn start_timestamp(&self) -> Timestamp {
        self.start_timestamp
    }

    /// Returns the optional range end.
    #[must_use]
    pub const fn end_timestamp(&self) -> Option<Timestamp> {
        self.end_timestamp
    }
}

fn validate_search_range(
    start_timestamp: Option<Timestamp>,
    end_timestamp: Option<Timestamp>,
) -> Result<(), RequestValidationError> {
    if start_timestamp
        .zip(end_timestamp)
        .is_some_and(|(start, end)| end <= start)
    {
        Err(RequestValidationError::SearchRangeNotIncreasing)
    } else {
        Ok(())
    }
}

/// A `ProjectX` execution trade.
#[derive(Clone, Debug, Deserialize, PartialEq)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
pub struct Trade {
    /// Provider trade identifier.
    pub id: TradeId,
    /// Provider account.
    pub account_id: AccountId,
    /// Provider contract.
    pub contract_id: ContractId,
    /// Provider creation timestamp.
    pub creation_timestamp: Timestamp,
    /// Execution price.
    #[serde(with = "crate::decimal_serde")]
    pub price: Decimal,
    /// Optional realized P&L.
    #[serde(default, with = "crate::decimal_serde::option")]
    pub profit_and_loss: Option<Decimal>,
    /// Provider fees.
    #[serde(with = "crate::decimal_serde")]
    pub fees: Decimal,
    /// Optional provider commissions, separate from fees.
    #[serde(default, with = "crate::decimal_serde::option")]
    pub commissions: Option<Decimal>,
    /// Execution side.
    pub side: Side,
    /// Execution quantity.
    pub size: i32,
    /// Whether the provider voided this trade.
    pub voided: bool,
    /// Originating order.
    pub order_id: OrderId,
}

/// Sparse quote update from the market hub.
///
/// The provider may send only the fields that changed. Callers that need a
/// consolidated snapshot must merge updates by symbol and preserve `None` as
/// unavailable data rather than substituting a zero price or volume.
#[derive(Clone, Debug, Deserialize, PartialEq)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
pub struct MarketQuote {
    /// Provider symbol identifier.
    #[serde(alias = "symbol")]
    pub raw_symbol: SymbolId,
    /// Human-readable symbol name, when supplied.
    #[serde(default)]
    pub symbol_name: Option<String>,
    /// Last trade price, when supplied by this update.
    #[serde(default, with = "crate::decimal_serde::option")]
    pub last_price: Option<Decimal>,
    /// Best bid price, when supplied by this update.
    #[serde(default, with = "crate::decimal_serde::option")]
    pub best_bid: Option<Decimal>,
    /// Best ask price, when supplied by this update.
    #[serde(default, with = "crate::decimal_serde::option")]
    pub best_ask: Option<Decimal>,
    /// Session price change, when supplied by this update.
    #[serde(default, with = "crate::decimal_serde::option")]
    pub change: Option<Decimal>,
    /// Session percent change, when supplied by this update.
    #[serde(default, with = "crate::decimal_serde::option")]
    pub change_percent: Option<Decimal>,
    /// Session open, when supplied by this update.
    #[serde(default, with = "crate::decimal_serde::option")]
    pub open: Option<Decimal>,
    /// Session high, when supplied by this update.
    #[serde(default, with = "crate::decimal_serde::option")]
    pub high: Option<Decimal>,
    /// Session low, when supplied by this update.
    #[serde(default, with = "crate::decimal_serde::option")]
    pub low: Option<Decimal>,
    /// Session cumulative volume, when supplied by this update.
    #[serde(default)]
    pub volume: Option<i64>,
    /// Provider last-updated timestamp.
    pub last_updated: Timestamp,
    /// Event timestamp, when supplied separately from [`Self::last_updated`].
    #[serde(default)]
    pub timestamp: Option<Timestamp>,
}

/// Depth-of-market update from the market hub.
#[derive(Clone, Debug, Deserialize, PartialEq)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
pub struct MarketDepth {
    /// Provider symbol identifier, when supplied.
    #[serde(default, alias = "symbolId")]
    pub symbol_id: Option<SymbolId>,
    /// Event timestamp.
    pub timestamp: Timestamp,
    /// Provider depth event code.
    #[serde(rename = "type")]
    pub depth_type: DepthType,
    /// Price level.
    #[serde(with = "crate::decimal_serde")]
    pub price: Decimal,
    /// Incremental volume for the update.
    pub volume: i64,
    /// Resting volume after the update.
    pub current_volume: i64,
    /// Zero-based level index, when supplied.
    #[serde(default)]
    pub index: Option<i32>,
}

/// Trade print from the market hub.
#[derive(Clone, Debug, Deserialize, PartialEq)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
pub struct MarketTrade {
    /// Provider symbol identifier.
    pub symbol_id: SymbolId,
    /// Trade price.
    #[serde(with = "crate::decimal_serde")]
    pub price: Decimal,
    /// Event timestamp.
    pub timestamp: Timestamp,
    /// Provider aggressor classification.
    #[serde(rename = "type")]
    pub trade_type: TradeLogType,
    /// Trade quantity.
    pub volume: i64,
}

/// Successful response for an operation without a result body.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub struct OperationResponse;

#[derive(Debug)]
pub(crate) enum Envelope<T> {
    Accepted(T),
    Rejected { error_code: i32 },
    InconsistentStatus { success: bool, error_code: i32 },
}

impl<'de, T> Deserialize<'de> for Envelope<T>
where
    T: serde::de::DeserializeOwned,
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        use serde::de::Error as _;

        let mut object = BTreeMap::<String, Box<RawValue>>::deserialize(deserializer)?;
        let success = object
            .remove("success")
            .ok_or_else(|| D::Error::custom("provider response success flag is missing"))
            .and_then(|value| serde_json::from_str(value.get()).map_err(D::Error::custom))?;
        let error_code = object
            .remove("errorCode")
            .ok_or_else(|| D::Error::custom("provider response error code is missing"))
            .and_then(|value| serde_json::from_str(value.get()).map_err(D::Error::custom))?;
        object.remove("errorMessage");
        if success != (error_code == 0) {
            return Ok(Self::InconsistentStatus {
                success,
                error_code,
            });
        }
        if !success {
            return Ok(Self::Rejected { error_code });
        }
        let mut body_json = String::from("{");
        for (index, (key, value)) in object.into_iter().enumerate() {
            if index > 0 {
                body_json.push(',');
            }
            body_json.push_str(&serde_json::to_string(&key).map_err(D::Error::custom)?);
            body_json.push(':');
            body_json.push_str(value.get());
        }
        body_json.push('}');
        let body = serde_json::from_str(&body_json).map_err(D::Error::custom)?;
        Ok(Self::Accepted(body))
    }
}

#[derive(Debug, Deserialize)]
pub(crate) struct AccountsBody {
    #[serde(default, deserialize_with = "null_to_empty")]
    pub(crate) accounts: Vec<Account>,
}

#[derive(Debug, Deserialize)]
pub(crate) struct ContractsBody {
    #[serde(default, deserialize_with = "null_to_empty")]
    pub(crate) contracts: Vec<Contract>,
}

#[derive(Debug, Deserialize)]
pub(crate) struct ContractBody {
    pub(crate) contract: Contract,
}

#[derive(Debug, Deserialize)]
pub(crate) struct BarsBody {
    #[serde(default, deserialize_with = "null_to_empty")]
    pub(crate) bars: Vec<Bar>,
}

#[derive(Debug, Deserialize)]
pub(crate) struct OrdersBody {
    #[serde(default, deserialize_with = "null_to_empty")]
    pub(crate) orders: Vec<Order>,
}

#[derive(Debug, Deserialize)]
pub(crate) struct OrderBody {
    pub(crate) order: Order,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct PlaceOrderBody {
    pub(crate) order_id: Option<OrderId>,
}

#[derive(Debug, Deserialize)]
pub(crate) struct PositionsBody {
    #[serde(default, deserialize_with = "null_to_empty")]
    pub(crate) positions: Vec<Position>,
}

#[derive(Debug, Deserialize)]
pub(crate) struct TradesBody {
    #[serde(default, deserialize_with = "null_to_empty")]
    pub(crate) trades: Vec<Trade>,
}

#[derive(Debug, Deserialize)]
pub(crate) struct EmptyBody {}

pub(crate) fn null_to_empty<'de, D, T>(deserializer: D) -> Result<Vec<T>, D::Error>
where
    D: serde::Deserializer<'de>,
    T: Deserialize<'de>,
{
    Ok(Option::<Vec<T>>::deserialize(deserializer)?.unwrap_or_default())
}

#[cfg(test)]
mod tests {
    use super::*;

    macro_rules! assert_empty_list {
        ($body:ty, $field:ident, $json:literal) => {{
            let envelope: Envelope<$body> = serde_json::from_str($json)
                .unwrap_or_else(|error| panic!("fixture envelope must decode: {error}"));
            let Envelope::Accepted(body) = envelope else {
                panic!("fixture envelope must be accepted");
            };
            assert!(body.$field.is_empty());
        }};
    }

    #[test]
    fn optional_list_bodies_normalize_missing_and_null_to_empty() {
        assert_empty_list!(
            AccountsBody,
            accounts,
            r#"{"success":true,"errorCode":0,"accounts":null}"#
        );
        assert_empty_list!(
            ContractsBody,
            contracts,
            r#"{"success":true,"errorCode":0}"#
        );
        assert_empty_list!(
            OrdersBody,
            orders,
            r#"{"success":true,"errorCode":0,"orders":null}"#
        );
        assert_empty_list!(
            OrderPage,
            orders,
            r#"{"success":true,"errorCode":0,"orders":null}"#
        );
        assert_empty_list!(
            PositionsBody,
            positions,
            r#"{"success":true,"errorCode":0}"#
        );
        assert_empty_list!(
            TradesBody,
            trades,
            r#"{"success":true,"errorCode":0,"trades":null}"#
        );
    }

    #[test]
    fn rejected_envelope_does_not_require_an_endpoint_body() {
        let envelope: Envelope<AccountsBody> =
            serde_json::from_str(r#"{"success":false,"errorCode":17,"errorMessage":"synthetic"}"#)
                .unwrap_or_else(|error| panic!("rejection envelope must decode: {error}"));

        assert!(matches!(envelope, Envelope::Rejected { error_code: 17 }));
    }

    #[test]
    fn envelope_requires_a_consistent_provider_status() {
        assert!(
            serde_json::from_str::<Envelope<AccountsBody>>(r#"{"success":true,"accounts":[]}"#)
                .is_err()
        );
        for (json, success, error_code) in [
            (r#"{"success":true,"errorCode":17}"#, true, 17),
            (r#"{"success":false,"errorCode":0}"#, false, 0),
        ] {
            let envelope: Envelope<AccountsBody> = serde_json::from_str(json)
                .unwrap_or_else(|error| panic!("inconsistent envelope must decode: {error}"));
            assert!(matches!(
                envelope,
                Envelope::InconsistentStatus {
                    success: actual_success,
                    error_code: actual_error_code,
                } if actual_success == success && actual_error_code == error_code
            ));
        }
    }
}