openpit 0.7.0

Embeddable pre-trade risk SDK
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
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
// Copyright The Pit Project Owners. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Please see https://openpit.dev and the OWNERS file for details.

use rust_decimal::Decimal;

use crate::core::{PnlHaltReason, PnlOutcome as PnlOperationOutcome, PnlOutcomeAmount};
use crate::param::{AdjustmentAmount, Pnl, PositionSize, Price};

use super::error::{AdjustmentOverflowError, HoldError};

/// Per-asset slot tracking `available`, `held`, and `incoming` quantities
/// plus the net position's `avg_entry_price` and cumulative `realized_pnl`.
///
/// `available` is free to be locked by new pre-trade reservations. `held`
/// is locked by pending reservations and is released back to `available`
/// on cancel or consumed on fill. `incoming` tracks expected future inflows
/// not yet settled: a pre-trade reservation projects the acquiring leg's
/// expected inflow into it ([`Holdings::reserve_incoming`]), a fill or cancel
/// drains the consumed/released portion ([`Holdings::consume_incoming`]), and
/// account adjustments may force it directly. `incoming` is purely
/// informational: it is never part of spendable capacity and never gates a
/// reservation (see [`Holdings::try_hold`]).
///
/// `avg_entry_price` is the average entry price of the current net owned
/// position (`available + held`), denominated in the account currency; it is
/// `None` when that net is flat or average tracking is unavailable.
/// `realized_pnl` is the cumulative realized profit and loss for this slot,
/// also denominated in the account currency. This position-PnL state is sticky
/// after a failed calculation: subsequent fills keep changing quantities but
/// do not recalculate it. A position outcome reports the halt when it changes;
/// later outcomes may omit an unchanged halted position PnL. These omission
/// rules apply only to this position slot: account PnL has separate publication
/// and kill-switch semantics. Only an explicit position-PnL account adjustment
/// re-arms a halted slot. Folding an execution-report fee only accrues into an
/// already active slot. Reservation and cancel move funds between `available`
/// and `held` without touching position PnL.
///
/// `try_hold` is the only operation that enforces a financial invariant:
/// the reservation requires `amount <= available + min(held, 0)`. A
/// negative `held` (manager-initiated adjustment) reduces the spendable
/// capacity below `available`. All other mutating operations apply
/// arithmetic directly without non-negative guards — negative `amount`
/// inverts the direction — and only fail on decimal-range overflow.
///
/// Operations return a new `Holdings` (immutable update). This makes
/// rollback straightforward for the caller: capture the old value, write
/// the new value synchronously, and push a rollback `Mutation` that
/// restores the old value.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Holdings {
    available: PositionSize,
    held: PositionSize,
    incoming: PositionSize,
    avg_entry_price: Option<Price>,
    realized_pnl: Option<PositionPnlState>,
}

/// Current realized-PnL state for a position slot.
///
/// The outer [`Option`] on [`Holdings::realized_pnl`] retains the established
/// absence semantics. A present value is either the accumulated PnL or the
/// reason why its calculation was stopped.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum PositionPnlState {
    /// Accumulated realized PnL in the current account currency.
    Pnl(Pnl),
    /// Reason why the position-PnL calculation was stopped.
    Halted(PnlHaltReason),
}

/// Result of one position realized-PnL operation.
///
/// `outcome` is present only when this operation changed realized PnL or
/// stopped its calculation. It is never repeated for a slot that was already
/// halted before the operation.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct PositionPnlOperation {
    holdings: Holdings,
    outcome: Option<PnlOperationOutcome>,
    realized_delta: Option<Pnl>,
    average_entry_price: Option<Price>,
}

impl PositionPnlOperation {
    fn unchanged(holdings: Holdings) -> Self {
        Self {
            holdings,
            outcome: None,
            realized_delta: None,
            average_entry_price: None,
        }
    }

    fn updated(
        holdings: Holdings,
        outcome: Option<PnlOperationOutcome>,
        realized_delta: Option<Pnl>,
        average_entry_price: Option<Price>,
    ) -> Self {
        Self {
            holdings,
            outcome,
            realized_delta,
            average_entry_price,
        }
    }

    /// Holdings after this operation.
    pub(crate) fn holdings(&self) -> Holdings {
        self.holdings
    }

    /// Changed PnL or the halt reason produced by this operation.
    pub(crate) fn outcome(&self) -> Option<PnlOperationOutcome> {
        self.outcome
    }

    /// Economic realized-PnL delta calculated independently of the position
    /// accumulator's active or halted state.
    pub(crate) fn realized_delta(&self) -> Option<Pnl> {
        self.realized_delta
    }

    /// Average entry price to surface for a fill that calculated position PnL.
    pub(crate) fn average_entry_price(&self) -> Option<Price> {
        self.average_entry_price
    }
}

impl Default for Holdings {
    fn default() -> Self {
        Self::zero()
    }
}

/// Selects the field targeted by [`Holdings::apply_adjustment`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AdjustmentTarget {
    /// Adjust `available`.
    Available,
    /// Adjust `held`.
    Held,
    /// Adjust `incoming`.
    Incoming,
}

impl Holdings {
    /// Returns a holdings with all quantities at zero and no tracked average
    /// entry price or realized PnL.
    pub fn zero() -> Self {
        Self {
            avg_entry_price: None,
            available: PositionSize::ZERO,
            held: PositionSize::ZERO,
            incoming: PositionSize::ZERO,
            realized_pnl: None,
        }
    }

    /// Builds a holdings from available and held; incoming is set to zero,
    /// the average entry price to `None`, and realized PnL is not tracked.
    pub fn new(available: PositionSize, held: PositionSize) -> Self {
        Self {
            avg_entry_price: None,
            available,
            held,
            incoming: PositionSize::ZERO,
            realized_pnl: None,
        }
    }

    pub fn available(&self) -> PositionSize {
        self.available
    }

    pub fn held(&self) -> PositionSize {
        self.held
    }

    pub fn incoming(&self) -> PositionSize {
        self.incoming
    }

    /// Average entry price of the current net owned position, or `None` when
    /// the net (`available + held`) is flat.
    pub fn avg_entry_price(&self) -> Option<Price> {
        self.avg_entry_price
    }

    /// Cumulative realized PnL for this slot, in the account currency.
    ///
    /// `None` means realized PnL is not tracked for the slot.
    pub fn realized_pnl(&self) -> Option<Pnl> {
        self.realized_pnl.and_then(|outcome| match outcome {
            PositionPnlState::Pnl(value) => Some(value),
            PositionPnlState::Halted(_) => None,
        })
    }

    /// Halt reason retained for a position-PnL calculation that cannot resume
    /// until a new PnL is force-set.
    pub(crate) fn realized_pnl_halt_reason(&self) -> Option<PnlHaltReason> {
        match self.realized_pnl {
            Some(PositionPnlState::Halted(reason)) => Some(reason),
            None | Some(PositionPnlState::Pnl(_)) => None,
        }
    }

    /// Complete optional position-PnL outcome for an adjustment rollback.
    pub(crate) fn realized_pnl_outcome(&self) -> Option<PositionPnlState> {
        self.realized_pnl
    }

    /// Returns whether a prior operation stopped position PnL calculation.
    pub(crate) fn realized_pnl_is_halted(&self) -> bool {
        self.realized_pnl_halt_reason().is_some()
    }

    /// Force-sets `realized_pnl` to an absolute account-currency value.
    ///
    /// Used when a manager adjustment writes a new absolute cumulative realized
    /// PnL. Like [`Holdings::with_avg_entry_price`], this explicit write re-arms
    /// a halted slot. Price-based fill realization accrues through
    /// `realize_position_fill`; execution-report fees accrue through
    /// `Holdings::add_realized_pnl` and never re-arm a halted slot.
    pub fn with_realized_pnl(&self, realized_pnl: Pnl) -> Self {
        Self {
            realized_pnl: Some(PositionPnlState::Pnl(realized_pnl)),
            ..*self
        }
    }

    /// Force-sets `realized_pnl` to an absolute value or clears tracking.
    ///
    /// Unlike [`Holdings::with_realized_pnl`], which can only set `Some`, this
    /// accepts the full `Option<Pnl>` so a prior untracked state (`None`) can be
    /// restored exactly. A new `Some` re-arms calculation; `None` preserves a
    /// prior halt. Rollback uses `with_realized_pnl_state` when it
    /// must restore the complete optional outcome.
    pub fn with_realized_pnl_opt(&self, realized_pnl: Option<Pnl>) -> Self {
        Self {
            realized_pnl: match (self.realized_pnl, realized_pnl) {
                (_, Some(value)) => Some(PositionPnlState::Pnl(value)),
                (Some(PositionPnlState::Halted(reason)), None) => {
                    Some(PositionPnlState::Halted(reason))
                }
                (None | Some(PositionPnlState::Pnl(_)), None) => None,
            },
            ..*self
        }
    }

    /// Restores a complete realized-PnL snapshot for account-adjustment rollback.
    pub(crate) fn with_realized_pnl_state(&self, realized_pnl: Option<PositionPnlState>) -> Self {
        Self {
            realized_pnl,
            ..*self
        }
    }

    /// Permanently stops position realized-PnL calculation until a new
    /// realized PnL is force-set through account adjustment.
    pub(crate) fn halt_realized_pnl(&self, reason: PnlHaltReason) -> PositionPnlOperation {
        self.halt_realized_pnl_with_average(reason, None)
    }

    pub(crate) fn halt_realized_pnl_preserving_average(
        &self,
        reason: PnlHaltReason,
    ) -> PositionPnlOperation {
        self.halt_realized_pnl_with_average(reason, self.avg_entry_price)
    }

    pub(crate) fn halt_realized_pnl_for_unpriced_fill(
        &self,
        signed_quantity: PositionSize,
        reason: PnlHaltReason,
    ) -> Result<PositionPnlOperation, AdjustmentOverflowError> {
        let owned = self
            .available
            .checked_add(self.held)
            .map_err(|_| AdjustmentOverflowError::ArithmeticOverflow)?;
        let new_owned = owned
            .checked_add(signed_quantity)
            .map_err(|_| AdjustmentOverflowError::ArithmeticOverflow)?;
        let owned = owned.to_decimal();
        let signed_quantity = signed_quantity.to_decimal();
        let avg_entry_price = if signed_quantity == Decimal::ZERO {
            self.avg_entry_price
        } else if owned == Decimal::ZERO
            || (owned > Decimal::ZERO) == (signed_quantity > Decimal::ZERO)
            || signed_quantity.abs() > owned.abs()
            || new_owned.is_zero()
        {
            None
        } else {
            self.avg_entry_price
        };

        let (realized_pnl, outcome) = match self.realized_pnl {
            Some(PositionPnlState::Halted(existing)) => (PositionPnlState::Halted(existing), None),
            None | Some(PositionPnlState::Pnl(_)) => {
                (PositionPnlState::Halted(reason), Some(Err(reason)))
            }
        };
        Ok(PositionPnlOperation::updated(
            Self {
                avg_entry_price,
                realized_pnl: Some(realized_pnl),
                ..*self
            },
            outcome,
            None,
            avg_entry_price,
        ))
    }

    fn halt_realized_pnl_with_average(
        &self,
        reason: PnlHaltReason,
        avg_entry_price: Option<Price>,
    ) -> PositionPnlOperation {
        if self.realized_pnl_is_halted() {
            return PositionPnlOperation::unchanged(*self);
        }
        PositionPnlOperation::updated(
            Self {
                avg_entry_price,
                realized_pnl: Some(PositionPnlState::Halted(reason)),
                ..*self
            },
            Some(Err(reason)),
            None,
            None,
        )
    }

    /// Clears average-entry-price and realized-PnL tracking.
    pub fn without_position_tracking(&self) -> Self {
        Self {
            avg_entry_price: None,
            realized_pnl: None,
            ..*self
        }
    }

    /// Moves `amount` from `available` to `held`.
    ///
    /// Negative `amount` inverts the direction (moves funds from `held`
    /// back to `available`). The financial reject fires when
    /// `amount > available + min(held, 0)`: a negative `held`
    /// (set by a manager-initiated adjustment) reduces the spendable
    /// capacity below `available`, because those funds are owed back.
    ///
    /// # Errors
    ///
    /// - [`HoldError::InsufficientAvailable`] if
    ///   `amount > available + min(held, 0)`.
    /// - [`HoldError::ArithmeticOverflow`] if the underlying decimal
    ///   addition or subtraction overflows the value range.
    pub fn try_hold(&self, amount: PositionSize) -> Result<Self, HoldError> {
        let spendable = if self.held < PositionSize::ZERO {
            self.available
                .checked_add(self.held)
                .map_err(|_| HoldError::ArithmeticOverflow)?
        } else {
            self.available
        };
        if amount > spendable {
            return Err(HoldError::InsufficientAvailable {
                available: spendable,
                requested: amount,
            });
        }

        let available = self
            .available
            .checked_sub(amount)
            .map_err(|_| HoldError::ArithmeticOverflow)?;
        let held = self
            .held
            .checked_add(amount)
            .map_err(|_| HoldError::ArithmeticOverflow)?;
        Ok(Self {
            avg_entry_price: self.avg_entry_price,
            available,
            held,
            incoming: self.incoming,
            realized_pnl: self.realized_pnl,
        })
    }

    /// Moves `amount` from `available` to `held` without the solvency gate.
    ///
    /// Sibling of [`Holdings::try_hold`] for the spot-funds track-only mode: it
    /// performs the same checked `available - amount` / `held + amount`
    /// arithmetic but never refuses on insufficiency, so `available` is allowed
    /// to go negative. Decimal-range overflow is still an integrity failure and
    /// is surfaced, never silently absorbed.
    ///
    /// # Errors
    ///
    /// - [`HoldError::ArithmeticOverflow`] if the underlying decimal addition or
    ///   subtraction overflows the value range.
    pub fn hold_allow_negative(&self, amount: PositionSize) -> Result<Self, HoldError> {
        let available = self
            .available
            .checked_sub(amount)
            .map_err(|_| HoldError::ArithmeticOverflow)?;
        let held = self
            .held
            .checked_add(amount)
            .map_err(|_| HoldError::ArithmeticOverflow)?;
        Ok(Self {
            avg_entry_price: self.avg_entry_price,
            available,
            held,
            incoming: self.incoming,
            realized_pnl: self.realized_pnl,
        })
    }

    /// Moves `amount` from `held` back to `available`.
    ///
    /// Negative `amount` inverts the direction. The result may have
    /// negative `held` or negative `available` when the caller asks for
    /// it; that is intentional. The only failure is decimal-range overflow.
    ///
    /// # Errors
    ///
    /// - [`AdjustmentOverflowError::ArithmeticOverflow`] if the underlying decimal
    ///   addition or subtraction overflows the value range.
    pub fn release(&self, amount: PositionSize) -> Result<Self, AdjustmentOverflowError> {
        let available = self
            .available
            .checked_add(amount)
            .map_err(|_| AdjustmentOverflowError::ArithmeticOverflow)?;
        let held = self
            .held
            .checked_sub(amount)
            .map_err(|_| AdjustmentOverflowError::ArithmeticOverflow)?;
        Ok(Self {
            avg_entry_price: self.avg_entry_price,
            available,
            held,
            incoming: self.incoming,
            realized_pnl: self.realized_pnl,
        })
    }

    /// Subtracts `amount` from `held` without enforcing the
    /// non-negative invariant.
    ///
    /// Use this when the venue execution report is authoritative and
    /// the engine must record the fact even when the actual fill
    /// exceeds the reserved `held`. The resulting `held` may be
    /// negative; the engine accepts this as evidence of divergence
    /// between the reservation estimate and the venue truth.
    ///
    /// `amount` may carry any sign; the routine performs a plain
    /// `held - amount` and returns the result.
    ///
    /// # Errors
    ///
    /// Returns [`AdjustmentOverflowError::ArithmeticOverflow`] when
    /// the underlying decimal subtraction overflows the value range.
    pub fn apply_fill_outflow(
        &self,
        amount: PositionSize,
    ) -> Result<Self, AdjustmentOverflowError> {
        let held = self
            .held
            .checked_sub(amount)
            .map_err(|_| AdjustmentOverflowError::ArithmeticOverflow)?;
        Ok(Self {
            avg_entry_price: self.avg_entry_price,
            available: self.available,
            held,
            incoming: self.incoming,
            realized_pnl: self.realized_pnl,
        })
    }

    /// Adds `amount` to `available` without enforcing the
    /// non-negative invariant.
    ///
    /// Use this when the venue execution report is authoritative
    /// (inflow side of a fill, price-improvement savings credit-back).
    /// `amount` may carry any sign; the routine performs a plain
    /// `available + amount` and returns the result.
    ///
    /// # Errors
    ///
    /// Returns [`AdjustmentOverflowError::ArithmeticOverflow`] when
    /// the underlying decimal addition overflows the value range.
    pub fn apply_fill_inflow(&self, amount: PositionSize) -> Result<Self, AdjustmentOverflowError> {
        let available = self
            .available
            .checked_add(amount)
            .map_err(|_| AdjustmentOverflowError::ArithmeticOverflow)?;
        Ok(Self {
            avg_entry_price: self.avg_entry_price,
            available,
            held: self.held,
            incoming: self.incoming,
            realized_pnl: self.realized_pnl,
        })
    }

    /// Adds `amount` to `incoming`, projecting an acquiring leg's expected
    /// inflow alongside the existing `held` outflow leg.
    ///
    /// Used by the pre-trade reserve path (a buy's base leg, a priced sell's
    /// quote leg). `incoming` is purely informational and has no solvency gate,
    /// so this never rejects on insufficiency - the only failure is decimal-range
    /// overflow, which the pre-trade caller maps to a reject. `available` and
    /// `held` are untouched, so spendable capacity is unchanged.
    ///
    /// # Errors
    ///
    /// Returns [`AdjustmentOverflowError::ArithmeticOverflow`] when the
    /// underlying decimal addition overflows the value range.
    pub fn reserve_incoming(&self, amount: PositionSize) -> Result<Self, AdjustmentOverflowError> {
        let incoming = self
            .incoming
            .checked_add(amount)
            .map_err(|_| AdjustmentOverflowError::ArithmeticOverflow)?;
        Ok(Self {
            avg_entry_price: self.avg_entry_price,
            available: self.available,
            held: self.held,
            incoming,
            realized_pnl: self.realized_pnl,
        })
    }

    /// Subtracts `amount` from `incoming`, draining the projected inflow as a
    /// fill consumes it or a cancel releases the unfilled remainder.
    ///
    /// `amount` may carry any sign and the result may go negative when the venue
    /// fill diverges from the reservation estimate (mirroring how
    /// [`Holdings::apply_fill_outflow`] allows a negative `held`); the engine
    /// accepts this as informational divergence. `available` and `held` are
    /// untouched, so this never feeds the available credit and never changes
    /// spendable capacity. The execution path maps an overflow to an account
    /// block.
    ///
    /// # Errors
    ///
    /// Returns [`AdjustmentOverflowError::ArithmeticOverflow`] when the
    /// underlying decimal subtraction overflows the value range.
    pub fn consume_incoming(&self, amount: PositionSize) -> Result<Self, AdjustmentOverflowError> {
        let incoming = self
            .incoming
            .checked_sub(amount)
            .map_err(|_| AdjustmentOverflowError::ArithmeticOverflow)?;
        Ok(Self {
            avg_entry_price: self.avg_entry_price,
            available: self.available,
            held: self.held,
            incoming,
            realized_pnl: self.realized_pnl,
        })
    }

    /// Applies one underlying-leg fill to the average-entry-price / realized-PnL
    /// state and returns the updated holdings together with this fill's
    /// position-PnL operation result.
    ///
    /// This is signed weighted-average-cost accounting with full long/short
    /// support including flips. `signed_qty` is the signed base flow of the
    /// fill (`> 0` for a buy/inflow, `< 0` for a sell/outflow) and `price` is
    /// the fill price converted into the account currency. Only the underlying
    /// (base) leg of a fill calls this; the settlement leg never touches
    /// average price or realized PnL. The returned holdings differs from
    /// `self` only in `avg_entry_price` and `realized_pnl`; the caller applies
    /// the quantity mutation (`available` / `held`) separately, within the same
    /// slot update.
    ///
    /// Let `owned = available + held` be the net base position *before* this
    /// leg's quantity mutation, `avg` the prior average entry price, `Δ` the
    /// `signed_qty`, `p` the fill `price`, and `new_owned = owned + Δ`. The
    /// realized delta and the new average are:
    ///
    /// 1. `owned == 0` (open from flat): `new_avg = Some(p)`, realized `0`.
    /// 2. same sign as `owned` (add to position): the position-weighted average
    ///    `new_avg = (owned*avg + Δ*p) / new_owned`, realized `0`.
    /// 3. opposite sign, `|Δ| <= |owned|` (reduce/close): realized
    ///    `(p - avg) * (-Δ)`; `new_avg = avg`, or `None` when `new_owned == 0`.
    /// 4. opposite sign, `|Δ| > |owned|` (flip): realized `(p - avg) * owned`
    ///    closes the whole prior position, and the remainder opens the opposite
    ///    side at `p`, so `new_avg = Some(p)`.
    ///
    /// Tracking is optional: opening from a flat slot starts tracking with
    /// `avg_entry_price = Some(p)` and `realized_pnl = Some(0)`. A non-flat
    /// slot whose `realized_pnl` is `None` halts with
    /// [`PnlHaltReason::MissingInitialPnl`]. A reduction without an average
    /// cost basis halts with [`PnlHaltReason::MissingCostBasis`]. Force-set a
    /// new realized PnL through account adjustment to re-arm tracking.
    ///
    /// Realized PnL accumulates while tracked:
    /// `realized_pnl_new = realized_pnl + realized`. Sign sanity: a long
    /// (`owned > 0`) sold at `p > avg` yields positive PnL; a short
    /// (`owned < 0`) bought back at `p < avg` also yields positive PnL.
    ///
    /// # Errors
    ///
    /// Returns [`AdjustmentOverflowError::ArithmeticOverflow`] if any decimal
    /// multiplication, addition, subtraction, or division overflows the value
    /// range (a zero `new_owned` divisor cannot occur in case 2, which is the
    /// only branch that divides).
    pub(crate) fn realize_position_fill(
        &self,
        signed_qty: PositionSize,
        price: Price,
    ) -> Result<PositionPnlOperation, AdjustmentOverflowError> {
        let owned = self
            .available
            .checked_add(self.held)
            .map_err(|_| AdjustmentOverflowError::ArithmeticOverflow)?;
        let new_owned = owned
            .checked_add(signed_qty)
            .map_err(|_| AdjustmentOverflowError::ArithmeticOverflow)?;

        let owned_dec = owned.to_decimal();
        let delta_dec = signed_qty.to_decimal();
        let price_dec = price.to_decimal();
        let zero = Decimal::ZERO;

        let (new_avg, realized_dec) = if owned_dec == zero {
            // Case 1: opening from flat. A zero-quantity fill leaves the slot
            // flat with no average; a non-zero fill seeds the average at `p`.
            let avg = if delta_dec == zero { None } else { Some(price) };
            (avg, zero)
        } else if (owned_dec > zero) == (delta_dec > zero) {
            // Case 2: same direction, growing the position. `new_owned` is
            // non-zero (same-sign add never crosses 0).
            match self.avg_entry_price {
                // Position-weighted average against the prior basis.
                Some(avg) => {
                    let weighted_existing = owned_dec
                        .checked_mul(avg.to_decimal())
                        .ok_or(AdjustmentOverflowError::ArithmeticOverflow)?;
                    let weighted_fill = delta_dec
                        .checked_mul(price_dec)
                        .ok_or(AdjustmentOverflowError::ArithmeticOverflow)?;
                    let numerator = weighted_existing
                        .checked_add(weighted_fill)
                        .ok_or(AdjustmentOverflowError::ArithmeticOverflow)?;
                    let new_avg_dec = numerator
                        .checked_div(new_owned.to_decimal())
                        .ok_or(AdjustmentOverflowError::ArithmeticOverflow)?;
                    (Some(Price::new(new_avg_dec)), zero)
                }
                // No prior basis to weight against: stay basis-less.
                None => (None, zero),
            }
        } else {
            // Cases 3 & 4: opposite direction, reducing/closing/flipping.
            match self.avg_entry_price {
                Some(avg) => {
                    let price_minus_avg = price_dec
                        .checked_sub(avg.to_decimal())
                        .ok_or(AdjustmentOverflowError::ArithmeticOverflow)?;
                    if delta_dec.abs() <= owned_dec.abs() {
                        // Case 3: reduce or exact close. Realized over the closed
                        // quantity `-Δ` (sign-correct for both long and short).
                        // `Decimal` negation is infallible.
                        let closed_qty = -delta_dec;
                        let realized = price_minus_avg
                            .checked_mul(closed_qty)
                            .ok_or(AdjustmentOverflowError::ArithmeticOverflow)?;
                        let avg = if new_owned.is_zero() { None } else { Some(avg) };
                        (avg, realized)
                    } else {
                        // Case 4: flip. Close the whole prior `owned` (realized
                        // over `owned`), then open the opposite side at `p`.
                        let realized = price_minus_avg
                            .checked_mul(owned_dec)
                            .ok_or(AdjustmentOverflowError::ArithmeticOverflow)?;
                        (Some(price), realized)
                    }
                }
                None => {
                    if self.realized_pnl_is_halted() {
                        return Ok(PositionPnlOperation::unchanged(*self));
                    }
                    return Ok(PositionPnlOperation::updated(
                        Self {
                            realized_pnl: Some(PositionPnlState::Halted(
                                PnlHaltReason::MissingCostBasis,
                            )),
                            ..*self
                        },
                        Some(Err(PnlHaltReason::MissingCostBasis)),
                        None,
                        None,
                    ));
                }
            }
        };

        let realized_delta = Pnl::new(realized_dec);
        let (realized_pnl, outcome) = match self.realized_pnl {
            Some(PositionPnlState::Pnl(current)) => match current.checked_add(realized_delta) {
                Ok(absolute) => (
                    PositionPnlState::Pnl(absolute),
                    (!realized_delta.is_zero()).then_some(Ok(PnlOutcomeAmount {
                        delta: realized_delta,
                        absolute,
                    })),
                ),
                Err(_) => (
                    PositionPnlState::Halted(PnlHaltReason::ArithmeticOverflow),
                    Some(Err(PnlHaltReason::ArithmeticOverflow)),
                ),
            },
            None if owned.is_zero() => (PositionPnlState::Pnl(realized_delta), None),
            None => (
                PositionPnlState::Halted(PnlHaltReason::MissingInitialPnl),
                Some(Err(PnlHaltReason::MissingInitialPnl)),
            ),
            Some(PositionPnlState::Halted(reason)) => (PositionPnlState::Halted(reason), None),
        };
        Ok(PositionPnlOperation::updated(
            Self {
                avg_entry_price: new_avg,
                available: self.available,
                held: self.held,
                incoming: self.incoming,
                realized_pnl: Some(realized_pnl),
            },
            outcome,
            Some(realized_delta),
            new_avg,
        ))
    }

    /// Accrues an account-currency fee into a tracked position's realized PnL.
    ///
    /// An untracked or halted slot is unchanged. A zero delta also produces no
    /// operation result because the realized PnL value did not change.
    pub(crate) fn add_realized_pnl(&self, delta: Pnl) -> PositionPnlOperation {
        let Some(PositionPnlState::Pnl(current)) = self.realized_pnl else {
            return PositionPnlOperation::unchanged(*self);
        };
        if delta.is_zero() {
            return PositionPnlOperation::unchanged(*self);
        }
        match current.checked_add(delta) {
            Ok(absolute) => PositionPnlOperation::updated(
                Self {
                    realized_pnl: Some(PositionPnlState::Pnl(absolute)),
                    ..*self
                },
                Some(Ok(PnlOutcomeAmount { delta, absolute })),
                None,
                None,
            ),
            Err(_) => PositionPnlOperation::updated(
                Self {
                    realized_pnl: Some(PositionPnlState::Halted(PnlHaltReason::ArithmeticOverflow)),
                    ..*self
                },
                Some(Err(PnlHaltReason::ArithmeticOverflow)),
                None,
                None,
            ),
        }
    }

    /// Subtracts per-quantity deltas from the current slot in one atomic step.
    ///
    /// Intended for delta-based rollback of a prior `apply_adjustment` call:
    /// pass the deltas that were applied forward, and this method reverses them
    /// by subtracting each one from the corresponding quantity field. Applying
    /// the inverse delta (rather than restoring a snapshot) keeps concurrent
    /// changes by other threads intact for the quantity fields.
    ///
    /// Average entry price and realized PnL are intentionally left untouched
    /// here: neither is delta-reversible (the weighted-average cost is
    /// path-dependent, and a forced realized value may overwrite an untracked
    /// `None`), so the rollback path restores both absolutely from a snapshot.
    ///
    /// All three subtractions are checked; returns
    /// [`AdjustmentOverflowError::ArithmeticOverflow`] if any of them would
    /// overflow the decimal range. A caller that treats rollback as best-effort
    /// should leave the slot unchanged on error.
    pub fn apply_delta_rollback(
        &self,
        available_delta: PositionSize,
        held_delta: PositionSize,
        incoming_delta: PositionSize,
    ) -> Result<Self, AdjustmentOverflowError> {
        let available = self
            .available
            .checked_sub(available_delta)
            .map_err(|_| AdjustmentOverflowError::ArithmeticOverflow)?;
        let held = self
            .held
            .checked_sub(held_delta)
            .map_err(|_| AdjustmentOverflowError::ArithmeticOverflow)?;
        let incoming = self
            .incoming
            .checked_sub(incoming_delta)
            .map_err(|_| AdjustmentOverflowError::ArithmeticOverflow)?;
        Ok(Self {
            avg_entry_price: self.avg_entry_price,
            available,
            held,
            incoming,
            realized_pnl: self.realized_pnl,
        })
    }

    /// Applies an `AdjustmentAmount` to the chosen field.
    ///
    /// - `AdjustmentAmount::Absolute(v)` sets the field to `v`
    ///   unconditionally; negative values are permitted for
    ///   manager-initiated overrides.
    /// - `AdjustmentAmount::Delta(d)` adds `d` to the field; the
    ///   result may be negative.
    ///
    /// # Errors
    ///
    /// Returns [`AdjustmentOverflowError::ArithmeticOverflow`] when
    /// the underlying decimal addition overflows the value range
    /// (delta variant only).
    pub fn apply_adjustment(
        &self,
        target: AdjustmentTarget,
        amount: AdjustmentAmount,
    ) -> Result<Self, AdjustmentOverflowError> {
        // Start from a copy so `avg_entry_price` and `realized_pnl` carry
        // through unchanged; only the targeted quantity field is rewritten.
        let mut new = *self;
        let field = match target {
            AdjustmentTarget::Available => &mut new.available,
            AdjustmentTarget::Held => &mut new.held,
            AdjustmentTarget::Incoming => &mut new.incoming,
        };
        *field = match amount {
            AdjustmentAmount::Absolute(v) => v,
            AdjustmentAmount::Delta(d) => field
                .checked_add(d)
                .map_err(|_| AdjustmentOverflowError::ArithmeticOverflow)?,
        };
        Ok(new)
    }

    /// Sets the average entry price of the current net position.
    ///
    /// Used by the account-adjustment path when a balance operation carries an
    /// account-currency average entry price. Realized PnL is never touched
    /// here.
    pub fn with_avg_entry_price(&self, avg_entry_price: Option<Price>) -> Self {
        Self {
            avg_entry_price,
            ..*self
        }
    }

    /// Returns `true` only when the slot carries no economic state at all:
    /// every quantity is zero, realized PnL is absent or zero, and there is no
    /// average entry price.
    ///
    /// Realized PnL and a residual average entry price keep the slot alive so
    /// the online PnL accumulated from fills is never silently pruned.
    pub fn is_zero(&self) -> bool {
        self.available.is_zero()
            && self.held.is_zero()
            && self.incoming.is_zero()
            && self.realized_pnl.map_or(true, |outcome| match outcome {
                PositionPnlState::Pnl(value) => value.is_zero(),
                PositionPnlState::Halted(_) => false,
            })
            && self.avg_entry_price.is_none()
    }

    /// Returns `true` if `available` is within the given inclusive bounds.
    ///
    /// `None` on either side means that bound is unconstrained.
    pub fn available_within_bounds(
        &self,
        lower: Option<PositionSize>,
        upper: Option<PositionSize>,
    ) -> bool {
        !lower.is_some_and(|b| self.available < b) && !upper.is_some_and(|b| self.available > b)
    }

    /// Returns `true` if `held` is within the given inclusive bounds.
    ///
    /// `None` on either side means that bound is unconstrained.
    pub fn held_within_bounds(
        &self,
        lower: Option<PositionSize>,
        upper: Option<PositionSize>,
    ) -> bool {
        !lower.is_some_and(|b| self.held < b) && !upper.is_some_and(|b| self.held > b)
    }

    /// Returns `true` if `incoming` is within the given inclusive bounds.
    ///
    /// `None` on either side means that bound is unconstrained.
    pub fn incoming_within_bounds(
        &self,
        lower: Option<PositionSize>,
        upper: Option<PositionSize>,
    ) -> bool {
        !lower.is_some_and(|b| self.incoming < b) && !upper.is_some_and(|b| self.incoming > b)
    }
}

#[cfg(test)]
mod tests {
    use rust_decimal::Decimal;

    use crate::core::{PnlHaltReason, PnlOutcomeAmount};
    use crate::param::{AdjustmentAmount, Pnl, PositionSize, Price};

    use super::super::error::{AdjustmentOverflowError, HoldError};
    use super::{AdjustmentTarget, Holdings, PositionPnlState};

    fn ps(value: &str) -> PositionSize {
        PositionSize::from_str(value).expect("position size literal must be valid")
    }

    fn pnl(value: &str) -> Pnl {
        Pnl::from_str(value).expect("pnl literal must be valid")
    }

    fn px(value: &str) -> Price {
        Price::from_str(value).expect("price literal must be valid")
    }

    fn realize_position_fill(
        holdings: Holdings,
        signed_qty: PositionSize,
        price: Price,
    ) -> Result<(Holdings, Option<Pnl>), AdjustmentOverflowError> {
        let operation = holdings.realize_position_fill(signed_qty, price)?;
        let delta = operation
            .outcome()
            .and_then(Result::ok)
            .map(|amount| amount.delta);
        Ok((operation.holdings(), delta))
    }

    fn holdings(available: &str, held: &str) -> Holdings {
        Holdings::new(ps(available), ps(held))
    }

    fn max_ps() -> PositionSize {
        PositionSize::new(Decimal::MAX)
    }

    fn min_ps() -> PositionSize {
        PositionSize::new(Decimal::MIN)
    }

    #[test]
    fn zero_returns_empty_components() {
        let value = Holdings::zero();

        assert_eq!(value.available(), PositionSize::ZERO);
        assert_eq!(value.held(), PositionSize::ZERO);
        assert_eq!(value.incoming(), PositionSize::ZERO);
    }

    #[test]
    fn new_stores_explicit_components() {
        let value = Holdings::new(ps("5"), ps("3"));

        assert_eq!(value.available(), ps("5"));
        assert_eq!(value.held(), ps("3"));
        assert_eq!(value.incoming(), PositionSize::ZERO);

        assert_eq!(
            Holdings::new(PositionSize::ZERO, PositionSize::ZERO),
            Holdings::zero(),
        );
    }

    #[test]
    fn new_accepts_negative_components() {
        let value = Holdings::new(ps("-1"), ps("-2"));

        assert_eq!(value.available(), ps("-1"));
        assert_eq!(value.held(), ps("-2"));
        assert_eq!(value.incoming(), PositionSize::ZERO);
    }

    #[test]
    fn accessors_return_constructor_values() {
        let value = holdings("7", "4");

        assert_eq!(value.available(), ps("7"));
        assert_eq!(value.held(), ps("4"));
        assert_eq!(value.incoming(), PositionSize::ZERO);
    }

    #[test]
    fn try_hold_moves_available_to_held() {
        let value = holdings("10", "0");
        let updated = value.try_hold(ps("5")).expect("must hold");

        assert_eq!(updated.available(), ps("5"));
        assert_eq!(updated.held(), ps("5"));
    }

    #[test]
    fn try_hold_all_available() {
        let value = holdings("10", "0");
        let updated = value.try_hold(ps("10")).expect("must hold");

        assert_eq!(updated.available(), PositionSize::ZERO);
        assert_eq!(updated.held(), ps("10"));
    }

    #[test]
    fn try_hold_rejects_insufficient_available_without_changing_original() {
        let value = holdings("10", "0");
        let err = value.try_hold(ps("15")).expect_err("must fail");

        assert_eq!(
            err,
            HoldError::InsufficientAvailable {
                available: ps("10"),
                requested: ps("15"),
            }
        );
        assert_eq!(value, holdings("10", "0"));
    }

    #[test]
    fn try_hold_negative_amount_inverts_as_arithmetic() {
        let value = holdings("10", "5");
        let updated = value.try_hold(ps("-3")).expect("must succeed");

        assert_eq!(updated.available(), ps("13"));
        assert_eq!(updated.held(), ps("2"));
    }

    #[test]
    fn try_hold_reports_arithmetic_overflow_when_held_would_overflow() {
        let value = Holdings::new(max_ps(), max_ps());
        let err = value.try_hold(max_ps()).expect_err("must fail");

        assert_eq!(err, HoldError::ArithmeticOverflow);
    }

    #[test]
    fn try_hold_respects_negative_held() {
        // Manager set held=-2000, balance=2000; net spendable is 0.
        let value = Holdings::new(ps("2000"), ps("-2000"));
        let err = value.try_hold(ps("1")).expect_err("must reject");

        assert_eq!(
            err,
            HoldError::InsufficientAvailable {
                available: PositionSize::ZERO,
                requested: ps("1"),
            }
        );
    }

    #[test]
    fn try_hold_succeeds_when_negative_held_covered_by_available() {
        // held=-2000, available=5000 → spendable=3000.
        let value = Holdings::new(ps("5000"), ps("-2000"));

        value
            .try_hold(ps("3000"))
            .expect("must succeed within spendable");

        let err = value
            .try_hold(ps("3001"))
            .expect_err("must reject one over");
        assert_eq!(
            err,
            HoldError::InsufficientAvailable {
                available: ps("3000"),
                requested: ps("3001"),
            }
        );
    }

    #[test]
    fn try_hold_positive_held_does_not_change_spendable() {
        // positive held does not reduce spendable.
        let value = holdings("10", "5");
        value
            .try_hold(ps("10"))
            .expect("must succeed - held is positive, spendable = available");
    }

    #[test]
    fn hold_allow_negative_moves_available_to_held_within_balance() {
        let value = holdings("10", "0");
        let updated = value.hold_allow_negative(ps("5")).expect("must hold");

        assert_eq!(updated.available(), ps("5"));
        assert_eq!(updated.held(), ps("5"));
    }

    #[test]
    fn hold_allow_negative_drives_available_negative_without_rejecting() {
        let value = holdings("1000", "0");
        let updated = value.hold_allow_negative(ps("2000")).expect("must hold");

        // No solvency gate: available goes negative, held records the full hold.
        assert_eq!(updated.available(), ps("-1000"));
        assert_eq!(updated.held(), ps("2000"));
    }

    #[test]
    fn hold_allow_negative_preserves_incoming_and_position_tracking() {
        let value = holdings("10", "5")
            .with_avg_entry_price(Some(px("100")))
            .with_realized_pnl(pnl("7"))
            .reserve_incoming(ps("4"))
            .expect("seed must succeed");
        let updated = value.hold_allow_negative(ps("20")).expect("must hold");

        assert_eq!(updated.incoming(), ps("4"));
        assert_eq!(updated.avg_entry_price(), Some(px("100")));
        assert_eq!(updated.realized_pnl(), Some(pnl("7")));
    }

    #[test]
    fn hold_allow_negative_reports_arithmetic_overflow() {
        // held + amount overflows the value range even though insufficiency is
        // never enforced.
        let value = Holdings::new(max_ps(), max_ps());
        let err = value.hold_allow_negative(max_ps()).expect_err("must fail");

        assert_eq!(err, HoldError::ArithmeticOverflow);
    }

    #[test]
    fn release_moves_held_to_available() {
        let value = holdings("2", "10");
        let updated = value.release(ps("4")).expect("must release");

        assert_eq!(updated.available(), ps("6"));
        assert_eq!(updated.held(), ps("6"));
    }

    #[test]
    fn release_all_held() {
        let value = holdings("2", "10");
        let updated = value.release(ps("10")).expect("must release");

        assert_eq!(updated.available(), ps("12"));
        assert_eq!(updated.held(), PositionSize::ZERO);
    }

    #[test]
    fn release_amount_exceeding_held_drives_held_negative() {
        let value = holdings("2", "10");
        let updated = value.release(ps("15")).expect("must succeed");

        assert_eq!(updated.available(), ps("17"));
        assert_eq!(updated.held(), ps("-5"));
    }

    #[test]
    fn release_negative_amount_inverts_as_arithmetic() {
        let value = holdings("10", "5");
        let updated = value.release(ps("-3")).expect("must succeed");

        assert_eq!(updated.available(), ps("7"));
        assert_eq!(updated.held(), ps("8"));
    }

    #[test]
    fn release_reports_arithmetic_overflow_when_available_would_overflow() {
        let value = Holdings::new(max_ps(), max_ps());
        let err = value.release(max_ps()).expect_err("must fail");

        assert_eq!(err, AdjustmentOverflowError::ArithmeticOverflow);
    }

    #[test]
    fn apply_fill_outflow_subtracts_held_only() {
        let value = holdings("10", "5");
        let updated = value.apply_fill_outflow(ps("3")).expect("must subtract");

        assert_eq!(updated.available(), ps("10"));
        assert_eq!(updated.held(), ps("2"));
    }

    #[test]
    fn apply_fill_outflow_drives_held_negative_when_amount_exceeds_held() {
        let value = holdings("10", "5");
        let updated = value.apply_fill_outflow(ps("8")).expect("must subtract");

        assert_eq!(updated.available(), ps("10"));
        assert_eq!(updated.held(), ps("-3"));
    }

    #[test]
    fn apply_fill_outflow_negative_amount_adds_to_held() {
        let value = holdings("10", "5");
        let updated = value.apply_fill_outflow(ps("-3")).expect("must succeed");

        assert_eq!(updated.available(), ps("10"));
        assert_eq!(updated.held(), ps("8"));
    }

    #[test]
    fn apply_fill_outflow_reports_arithmetic_overflow() {
        // held - amount overflows when amount is very negative and
        // held is near the positive end of the value range.
        let value = Holdings::new(PositionSize::ZERO, max_ps());
        let err = value
            .apply_fill_outflow(min_ps())
            .expect_err("must overflow");

        assert_eq!(err, AdjustmentOverflowError::ArithmeticOverflow);
    }

    #[test]
    fn apply_fill_inflow_zero_amount_is_no_change() {
        let value = holdings("10", "2");
        let updated = value
            .apply_fill_inflow(PositionSize::ZERO)
            .expect("must succeed");

        assert_eq!(updated, value);
    }

    #[test]
    fn apply_fill_inflow_adds_to_available_only() {
        let value = holdings("10", "5");
        let updated = value.apply_fill_inflow(ps("3")).expect("must add");

        assert_eq!(updated.available(), ps("13"));
        assert_eq!(updated.held(), ps("5"));
    }

    #[test]
    fn apply_fill_inflow_accepts_negative_amount_driving_available_negative() {
        let value = holdings("3", "5");
        let updated = value.apply_fill_inflow(ps("-7")).expect("must add");

        assert_eq!(updated.available(), ps("-4"));
        assert_eq!(updated.held(), ps("5"));
    }

    #[test]
    fn apply_fill_inflow_reports_arithmetic_overflow() {
        let value = Holdings::new(max_ps(), PositionSize::ZERO);
        let err = value
            .apply_fill_inflow(max_ps())
            .expect_err("must overflow");

        assert_eq!(err, AdjustmentOverflowError::ArithmeticOverflow);
    }

    #[test]
    fn apply_adjustment_sets_available_absolute_values() {
        let value = holdings("5", "11");

        assert_eq!(
            value
                .apply_adjustment(
                    AdjustmentTarget::Available,
                    AdjustmentAmount::Absolute(ps("7"))
                )
                .expect("absolute must succeed")
                .available(),
            ps("7")
        );
        assert_eq!(
            value
                .apply_adjustment(
                    AdjustmentTarget::Available,
                    AdjustmentAmount::Absolute(ps("0"))
                )
                .expect("absolute must succeed")
                .available(),
            PositionSize::ZERO
        );
        assert_eq!(
            value
                .apply_adjustment(
                    AdjustmentTarget::Available,
                    AdjustmentAmount::Absolute(ps("7"))
                )
                .expect("absolute must succeed")
                .held(),
            ps("11")
        );
        let neg = value
            .apply_adjustment(
                AdjustmentTarget::Available,
                AdjustmentAmount::Absolute(ps("-1")),
            )
            .expect("absolute must succeed");
        assert_eq!(neg.available(), ps("-1"));
        assert_eq!(neg.held(), ps("11"));
    }

    #[test]
    fn apply_adjustment_sets_held_absolute_values() {
        let value = holdings("11", "5");

        assert_eq!(
            value
                .apply_adjustment(AdjustmentTarget::Held, AdjustmentAmount::Absolute(ps("7")))
                .expect("absolute must succeed")
                .held(),
            ps("7")
        );
        assert_eq!(
            value
                .apply_adjustment(AdjustmentTarget::Held, AdjustmentAmount::Absolute(ps("0")))
                .expect("absolute must succeed")
                .held(),
            PositionSize::ZERO
        );
        assert_eq!(
            value
                .apply_adjustment(AdjustmentTarget::Held, AdjustmentAmount::Absolute(ps("7")))
                .expect("absolute must succeed")
                .available(),
            ps("11")
        );
        let neg = value
            .apply_adjustment(AdjustmentTarget::Held, AdjustmentAmount::Absolute(ps("-1")))
            .expect("absolute must succeed");
        assert_eq!(neg.held(), ps("-1"));
        assert_eq!(neg.available(), ps("11"));
    }

    #[test]
    fn apply_adjustment_applies_available_deltas() {
        let value = holdings("5", "11");

        assert_eq!(
            value
                .apply_adjustment(
                    AdjustmentTarget::Available,
                    AdjustmentAmount::Delta(ps("3"))
                )
                .expect("delta must succeed"),
            holdings("8", "11")
        );
        assert_eq!(
            value
                .apply_adjustment(
                    AdjustmentTarget::Available,
                    AdjustmentAmount::Delta(ps("0"))
                )
                .expect("delta must succeed"),
            value
        );
        assert_eq!(
            value
                .apply_adjustment(
                    AdjustmentTarget::Available,
                    AdjustmentAmount::Delta(ps("-3"))
                )
                .expect("delta must succeed"),
            holdings("2", "11")
        );
        assert_eq!(
            value
                .apply_adjustment(
                    AdjustmentTarget::Available,
                    AdjustmentAmount::Delta(ps("-5"))
                )
                .expect("delta must succeed"),
            holdings("0", "11")
        );
        let neg = value
            .apply_adjustment(
                AdjustmentTarget::Available,
                AdjustmentAmount::Delta(ps("-6")),
            )
            .expect("delta must succeed");
        assert_eq!(neg.available(), ps("-1"));
        assert_eq!(neg.held(), ps("11"));
    }

    #[test]
    fn apply_adjustment_applies_held_deltas() {
        let value = holdings("11", "5");

        assert_eq!(
            value
                .apply_adjustment(AdjustmentTarget::Held, AdjustmentAmount::Delta(ps("3")))
                .expect("delta must succeed"),
            holdings("11", "8")
        );
        assert_eq!(
            value
                .apply_adjustment(AdjustmentTarget::Held, AdjustmentAmount::Delta(ps("0")))
                .expect("delta must succeed"),
            value
        );
        assert_eq!(
            value
                .apply_adjustment(AdjustmentTarget::Held, AdjustmentAmount::Delta(ps("-3")))
                .expect("delta must succeed"),
            holdings("11", "2")
        );
        assert_eq!(
            value
                .apply_adjustment(AdjustmentTarget::Held, AdjustmentAmount::Delta(ps("-5")))
                .expect("delta must succeed"),
            holdings("11", "0")
        );
        let neg = value
            .apply_adjustment(AdjustmentTarget::Held, AdjustmentAmount::Delta(ps("-6")))
            .expect("delta must succeed");
        assert_eq!(neg.held(), ps("-1"));
        assert_eq!(neg.available(), ps("11"));
    }

    #[test]
    fn apply_adjustment_reports_arithmetic_overflow_for_delta() {
        let value = Holdings::new(max_ps(), PositionSize::ZERO);
        let err = value
            .apply_adjustment(
                AdjustmentTarget::Available,
                AdjustmentAmount::Delta(max_ps()),
            )
            .expect_err("must overflow");

        assert_eq!(err, AdjustmentOverflowError::ArithmeticOverflow);
    }

    #[test]
    fn apply_adjustment_sets_incoming_absolute_values() {
        let value = holdings("5", "11");

        let set = value
            .apply_adjustment(
                AdjustmentTarget::Incoming,
                AdjustmentAmount::Absolute(ps("7")),
            )
            .expect("absolute must succeed");
        assert_eq!(set.incoming(), ps("7"));
        assert_eq!(set.available(), ps("5"));
        assert_eq!(set.held(), ps("11"));

        let zero = value
            .apply_adjustment(
                AdjustmentTarget::Incoming,
                AdjustmentAmount::Absolute(ps("0")),
            )
            .expect("absolute must succeed");
        assert_eq!(zero.incoming(), PositionSize::ZERO);

        let neg = value
            .apply_adjustment(
                AdjustmentTarget::Incoming,
                AdjustmentAmount::Absolute(ps("-3")),
            )
            .expect("absolute must succeed");
        assert_eq!(neg.incoming(), ps("-3"));
        assert_eq!(neg.available(), ps("5"));
        assert_eq!(neg.held(), ps("11"));
    }

    #[test]
    fn apply_adjustment_applies_incoming_deltas() {
        let mut base = holdings("5", "11");
        // give it a non-zero incoming to start
        base = base
            .apply_adjustment(
                AdjustmentTarget::Incoming,
                AdjustmentAmount::Absolute(ps("10")),
            )
            .expect("seed must succeed");

        assert_eq!(
            base.apply_adjustment(AdjustmentTarget::Incoming, AdjustmentAmount::Delta(ps("3")))
                .expect("delta must succeed")
                .incoming(),
            ps("13")
        );
        assert_eq!(
            base.apply_adjustment(
                AdjustmentTarget::Incoming,
                AdjustmentAmount::Delta(ps("-4"))
            )
            .expect("delta must succeed")
            .incoming(),
            ps("6")
        );
        let neg = base
            .apply_adjustment(
                AdjustmentTarget::Incoming,
                AdjustmentAmount::Delta(ps("-15")),
            )
            .expect("delta must succeed");
        assert_eq!(neg.incoming(), ps("-5"));
        assert_eq!(neg.available(), ps("5"));
        assert_eq!(neg.held(), ps("11"));
    }

    #[test]
    fn apply_adjustment_incoming_overflow_returns_error() {
        let mut value = Holdings::new(PositionSize::ZERO, PositionSize::ZERO);
        value = value
            .apply_adjustment(
                AdjustmentTarget::Incoming,
                AdjustmentAmount::Absolute(max_ps()),
            )
            .expect("seed must succeed");
        let err = value
            .apply_adjustment(
                AdjustmentTarget::Incoming,
                AdjustmentAmount::Delta(max_ps()),
            )
            .expect_err("must overflow");

        assert_eq!(err, AdjustmentOverflowError::ArithmeticOverflow);
    }

    #[test]
    fn trading_operations_do_not_touch_incoming() {
        let mut base = holdings("10", "5");
        base = base
            .apply_adjustment(
                AdjustmentTarget::Incoming,
                AdjustmentAmount::Absolute(ps("7")),
            )
            .expect("seed must succeed");

        assert_eq!(
            base.try_hold(ps("3")).expect("must hold").incoming(),
            ps("7")
        );
        assert_eq!(
            base.release(ps("2")).expect("must release").incoming(),
            ps("7")
        );
        assert_eq!(
            base.apply_fill_outflow(ps("2"))
                .expect("must outflow")
                .incoming(),
            ps("7")
        );
        assert_eq!(
            base.apply_fill_inflow(ps("2"))
                .expect("must inflow")
                .incoming(),
            ps("7")
        );
    }

    #[test]
    fn reserve_incoming_adds_only_incoming() {
        let base = holdings("10", "5")
            .with_avg_entry_price(Some(px("100")))
            .with_realized_pnl(pnl("7"));
        let updated = base.reserve_incoming(ps("3")).expect("must reserve");

        assert_eq!(updated.incoming(), ps("3"));
        assert_eq!(updated.available(), ps("10"));
        assert_eq!(updated.held(), ps("5"));
        assert_eq!(updated.avg_entry_price(), Some(px("100")));
        assert_eq!(updated.realized_pnl(), Some(pnl("7")));
    }

    #[test]
    fn reserve_incoming_accumulates() {
        let base = holdings("0", "0")
            .reserve_incoming(ps("4"))
            .expect("first reserve");
        let updated = base.reserve_incoming(ps("6")).expect("second reserve");

        assert_eq!(updated.incoming(), ps("10"));
    }

    #[test]
    fn reserve_incoming_reports_arithmetic_overflow() {
        let mut value = Holdings::zero();
        value = value.reserve_incoming(max_ps()).expect("seed must succeed");
        let err = value.reserve_incoming(max_ps()).expect_err("must overflow");

        assert_eq!(err, AdjustmentOverflowError::ArithmeticOverflow);
    }

    #[test]
    fn consume_incoming_subtracts_only_incoming() {
        let base = holdings("10", "5")
            .reserve_incoming(ps("8"))
            .expect("seed must succeed");
        let updated = base.consume_incoming(ps("3")).expect("must consume");

        assert_eq!(updated.incoming(), ps("5"));
        assert_eq!(updated.available(), ps("10"));
        assert_eq!(updated.held(), ps("5"));
    }

    #[test]
    fn consume_incoming_can_drive_incoming_negative() {
        let base = holdings("10", "5")
            .reserve_incoming(ps("2"))
            .expect("seed must succeed");
        let updated = base.consume_incoming(ps("5")).expect("must consume");

        assert_eq!(updated.incoming(), ps("-3"));
        assert_eq!(updated.available(), ps("10"));
        assert_eq!(updated.held(), ps("5"));
    }

    #[test]
    fn consume_incoming_reports_arithmetic_overflow() {
        // incoming - amount overflows when amount is very negative and incoming
        // is near the positive end of the value range.
        let mut value = Holdings::zero();
        value = value.reserve_incoming(max_ps()).expect("seed must succeed");
        let err = value.consume_incoming(min_ps()).expect_err("must overflow");

        assert_eq!(err, AdjustmentOverflowError::ArithmeticOverflow);
    }

    #[test]
    fn incoming_operations_do_not_touch_available_held_or_pnl() {
        let base = holdings("10", "5")
            .with_avg_entry_price(Some(px("100")))
            .with_realized_pnl(pnl("7"));

        let reserved = base.reserve_incoming(ps("4")).expect("must reserve");
        assert_eq!(reserved.available(), ps("10"));
        assert_eq!(reserved.held(), ps("5"));
        assert_eq!(reserved.avg_entry_price(), Some(px("100")));
        assert_eq!(reserved.realized_pnl(), Some(pnl("7")));

        let consumed = reserved.consume_incoming(ps("4")).expect("must consume");
        assert_eq!(consumed.incoming(), PositionSize::ZERO);
        assert_eq!(consumed.available(), ps("10"));
        assert_eq!(consumed.held(), ps("5"));
        assert_eq!(consumed.avg_entry_price(), Some(px("100")));
        assert_eq!(consumed.realized_pnl(), Some(pnl("7")));
    }

    #[test]
    fn try_hold_spendable_ignores_incoming() {
        // Reserved incoming must never enter spendable capacity: a slot with
        // available 10 and incoming 1000 still rejects a hold above 10.
        let base = holdings("10", "0")
            .reserve_incoming(ps("1000"))
            .expect("seed must succeed");

        base.try_hold(ps("10")).expect("must hold within available");
        let err = base
            .try_hold(ps("11"))
            .expect_err("must reject over available");
        assert_eq!(
            err,
            HoldError::InsufficientAvailable {
                available: ps("10"),
                requested: ps("11"),
            }
        );
    }

    #[test]
    fn available_within_bounds_accepts_missing_bounds() {
        assert!(holdings("5", "0").available_within_bounds(None, None));
    }

    #[test]
    fn available_within_bounds_checks_lower_inclusively() {
        assert!(holdings("5", "0").available_within_bounds(Some(ps("3")), None));
        assert!(!holdings("2", "0").available_within_bounds(Some(ps("3")), None));
        assert!(holdings("3", "0").available_within_bounds(Some(ps("3")), None));
    }

    #[test]
    fn available_within_bounds_checks_upper_inclusively() {
        assert!(holdings("5", "0").available_within_bounds(None, Some(ps("7"))));
        assert!(!holdings("8", "0").available_within_bounds(None, Some(ps("7"))));
        assert!(holdings("7", "0").available_within_bounds(None, Some(ps("7"))));
    }

    #[test]
    fn available_within_bounds_checks_both_bounds() {
        assert!(holdings("5", "0").available_within_bounds(Some(ps("3")), Some(ps("7"))));
        assert!(!holdings("2", "0").available_within_bounds(Some(ps("3")), Some(ps("7"))));
        assert!(!holdings("8", "0").available_within_bounds(Some(ps("3")), Some(ps("7"))));
    }

    #[test]
    fn available_within_bounds_handles_negative_bounds() {
        assert!(holdings("0", "0").available_within_bounds(Some(ps("-3")), None));
        assert!(!holdings("0", "0").available_within_bounds(Some(ps("1")), None));
    }

    #[test]
    fn held_within_bounds_checks_inclusively() {
        let h = holdings("0", "5");
        assert!(h.held_within_bounds(None, None));
        assert!(h.held_within_bounds(Some(ps("3")), None));
        assert!(!h.held_within_bounds(Some(ps("6")), None));
        assert!(h.held_within_bounds(Some(ps("5")), None));
        assert!(h.held_within_bounds(None, Some(ps("7"))));
        assert!(!h.held_within_bounds(None, Some(ps("4"))));
        assert!(h.held_within_bounds(None, Some(ps("5"))));
        assert!(h.held_within_bounds(Some(ps("3")), Some(ps("7"))));
        assert!(!h.held_within_bounds(Some(ps("6")), Some(ps("9"))));
    }

    #[test]
    fn incoming_within_bounds_checks_inclusively() {
        let mut base = holdings("0", "0");
        base = base
            .apply_adjustment(
                AdjustmentTarget::Incoming,
                AdjustmentAmount::Absolute(ps("5")),
            )
            .expect("seed must succeed");

        assert!(base.incoming_within_bounds(None, None));
        assert!(base.incoming_within_bounds(Some(ps("3")), None));
        assert!(!base.incoming_within_bounds(Some(ps("6")), None));
        assert!(base.incoming_within_bounds(Some(ps("5")), None));
        assert!(base.incoming_within_bounds(None, Some(ps("7"))));
        assert!(!base.incoming_within_bounds(None, Some(ps("4"))));
        assert!(base.incoming_within_bounds(None, Some(ps("5"))));
        assert!(base.incoming_within_bounds(Some(ps("3")), Some(ps("7"))));
        assert!(!base.incoming_within_bounds(Some(ps("6")), Some(ps("9"))));
    }

    #[test]
    fn holdings_is_copy() {
        let original = holdings("10", "5");
        let copied = original;

        assert_eq!(copied, original);
    }

    #[test]
    fn mutating_operations_return_new_values() {
        let original = holdings("10", "5");

        let held = original.try_hold(ps("3")).expect("must hold");
        let released = original.release(ps("2")).expect("must release");
        let outflow = original.apply_fill_outflow(ps("2")).expect("must subtract");
        let inflow = original.apply_fill_inflow(ps("2")).expect("must add");

        assert_eq!(original, holdings("10", "5"));
        assert_eq!(held, holdings("7", "8"));
        assert_eq!(released, holdings("12", "3"));
        assert_eq!(outflow, holdings("10", "3"));
        assert_eq!(inflow, holdings("12", "5"));
    }

    // ── average entry price / realized PnL ─────────────────────────────────

    #[test]
    fn new_and_zero_have_no_avg_and_untracked_pnl() {
        let zero = Holdings::zero();
        assert_eq!(zero.avg_entry_price(), None);
        assert_eq!(zero.realized_pnl(), None);

        let made = Holdings::new(ps("5"), ps("3"));
        assert_eq!(made.avg_entry_price(), None);
        assert_eq!(made.realized_pnl(), None);
    }

    #[test]
    fn realize_open_from_flat_seeds_avg_and_realizes_nothing() {
        let flat = Holdings::zero();
        let (updated, realized) =
            realize_position_fill(flat, ps("10"), px("100")).expect("must realize");

        assert_eq!(realized, None);
        assert_eq!(updated.avg_entry_price(), Some(px("100")));
        assert_eq!(updated.realized_pnl(), Some(Pnl::ZERO));
    }

    #[test]
    fn realize_open_short_from_flat_seeds_avg() {
        let flat = Holdings::zero();
        let (updated, realized) =
            realize_position_fill(flat, ps("-4"), px("50")).expect("must realize");

        assert_eq!(realized, None);
        assert_eq!(updated.avg_entry_price(), Some(px("50")));
    }

    #[test]
    fn realize_zero_qty_from_flat_keeps_avg_none() {
        let flat = Holdings::zero();
        let (updated, realized) =
            realize_position_fill(flat, PositionSize::ZERO, px("100")).expect("must realize");

        assert_eq!(realized, None);
        assert_eq!(updated.avg_entry_price(), None);
    }

    #[test]
    fn realize_add_to_long_weights_average() {
        // owned = 10 @ 100, buy 10 more @ 200 → avg = (10*100 + 10*200)/20 = 150.
        let long = Holdings::new(ps("10"), PositionSize::ZERO)
            .with_avg_entry_price(Some(px("100")))
            .with_realized_pnl(Pnl::ZERO);
        let (updated, realized) =
            realize_position_fill(long, ps("10"), px("200")).expect("must realize");

        assert_eq!(realized, None);
        assert_eq!(updated.avg_entry_price(), Some(px("150")));
    }

    #[test]
    fn realize_add_to_short_weights_average() {
        // owned = -10 @ 100, sell 10 more @ 200 → avg = (-10*100 + -10*200)/-20 = 150.
        let short = Holdings::new(ps("-10"), PositionSize::ZERO)
            .with_avg_entry_price(Some(px("100")))
            .with_realized_pnl(Pnl::ZERO);
        let (updated, realized) =
            realize_position_fill(short, ps("-10"), px("200")).expect("must realize");

        assert_eq!(realized, None);
        assert_eq!(updated.avg_entry_price(), Some(px("150")));
    }

    #[test]
    fn realize_partial_close_long_realizes_positive_when_price_above_avg() {
        // long 10 @ 100, sell 4 @ 130 → realized = (130-100)*4 = 120, avg unchanged.
        let long = Holdings::new(ps("10"), PositionSize::ZERO)
            .with_avg_entry_price(Some(px("100")))
            .with_realized_pnl(Pnl::ZERO);
        let (updated, realized) =
            realize_position_fill(long, ps("-4"), px("130")).expect("must realize");

        assert_eq!(realized, Some(pnl("120")));
        assert_eq!(updated.avg_entry_price(), Some(px("100")));
        assert_eq!(updated.realized_pnl(), Some(pnl("120")));
    }

    #[test]
    fn position_pnl_operation_reports_only_changed_pnl_or_new_halt() {
        let tracked = Holdings::new(ps("10"), PositionSize::ZERO)
            .with_avg_entry_price(Some(px("100")))
            .with_realized_pnl(pnl("50"));
        let realized = tracked
            .realize_position_fill(ps("-4"), px("130"))
            .expect("must realize");
        assert_eq!(
            realized.outcome(),
            Some(Ok(PnlOutcomeAmount {
                delta: pnl("120"),
                absolute: pnl("170"),
            }))
        );

        let halted = realized
            .holdings()
            .halt_realized_pnl_preserving_average(PnlHaltReason::MissingFx);
        assert_eq!(halted.outcome(), Some(Err(PnlHaltReason::MissingFx)));
        assert_eq!(
            halted.holdings().realized_pnl_outcome(),
            Some(PositionPnlState::Halted(PnlHaltReason::MissingFx)),
        );
        assert_eq!(halted.holdings().avg_entry_price(), Some(px("100")));
        assert!(halted.holdings().realized_pnl_is_halted());

        let repeated = halted
            .holdings()
            .halt_realized_pnl(PnlHaltReason::MissingFx);
        assert_eq!(repeated.outcome(), None);
    }

    #[test]
    fn unpriced_fill_preserves_basis_only_for_partial_reduction() {
        let tracked = Holdings::new(ps("10"), PositionSize::ZERO)
            .with_avg_entry_price(Some(px("100")))
            .with_realized_pnl(Pnl::ZERO);

        let partial = tracked
            .halt_realized_pnl_for_unpriced_fill(ps("-4"), PnlHaltReason::MissingFx)
            .expect("partial close must not overflow");
        assert_eq!(partial.holdings().avg_entry_price(), Some(px("100")));
        assert_eq!(partial.outcome(), Some(Err(PnlHaltReason::MissingFx)));

        for signed_quantity in ["5", "-10", "-15"] {
            let operation = tracked
                .halt_realized_pnl_for_unpriced_fill(ps(signed_quantity), PnlHaltReason::MissingFx)
                .expect("basis transition must not overflow");
            assert_eq!(operation.holdings().avg_entry_price(), None);
        }

        let halted_partial = Holdings::new(ps("6"), PositionSize::ZERO)
            .with_avg_entry_price(Some(px("100")))
            .halt_realized_pnl_preserving_average(PnlHaltReason::MissingFx)
            .holdings();
        let exact_close = halted_partial
            .halt_realized_pnl_for_unpriced_fill(ps("-6"), PnlHaltReason::MissingFx)
            .expect("exact close must not overflow");
        assert_eq!(exact_close.holdings().avg_entry_price(), None);
        assert_eq!(exact_close.outcome(), None);
    }

    #[test]
    fn realize_partial_close_short_realizes_positive_when_price_below_avg() {
        // short -10 @ 100, buy 4 @ 70 → realized = (70-100)*-(4) = 120, avg unchanged.
        let short = Holdings::new(ps("-10"), PositionSize::ZERO)
            .with_avg_entry_price(Some(px("100")))
            .with_realized_pnl(Pnl::ZERO);
        let (updated, realized) =
            realize_position_fill(short, ps("4"), px("70")).expect("must realize");

        assert_eq!(realized, Some(pnl("120")));
        assert_eq!(updated.avg_entry_price(), Some(px("100")));
    }

    #[test]
    fn realize_exact_close_long_resets_avg_to_none_and_keeps_pnl() {
        // long 10 @ 100, sell all 10 @ 130 → realized = 300, new_owned = 0 → avg None.
        let long = Holdings::new(ps("10"), PositionSize::ZERO)
            .with_avg_entry_price(Some(px("100")))
            .with_realized_pnl(Pnl::ZERO);
        let (updated, realized) =
            realize_position_fill(long, ps("-10"), px("130")).expect("must realize");

        assert_eq!(realized, Some(pnl("300")));
        assert_eq!(updated.avg_entry_price(), None);
        assert_eq!(updated.realized_pnl(), Some(pnl("300")));
    }

    #[test]
    fn realize_flip_long_to_short_closes_then_reopens_at_price() {
        // long 10 @ 100, sell 15 @ 130 → close 10: realized = (130-100)*10 = 300;
        // remainder opens short -5 at 130 → avg = 130.
        let long = Holdings::new(ps("10"), PositionSize::ZERO)
            .with_avg_entry_price(Some(px("100")))
            .with_realized_pnl(Pnl::ZERO);
        let (updated, realized) =
            realize_position_fill(long, ps("-15"), px("130")).expect("must realize");

        assert_eq!(realized, Some(pnl("300")));
        assert_eq!(updated.avg_entry_price(), Some(px("130")));
    }

    #[test]
    fn realize_flip_short_to_long_closes_then_reopens_at_price() {
        // short -10 @ 100, buy 15 @ 70 → close 10: realized = (70-100)*-10 = 300;
        // remainder opens long +5 at 70 → avg = 70.
        let short = Holdings::new(ps("-10"), PositionSize::ZERO)
            .with_avg_entry_price(Some(px("100")))
            .with_realized_pnl(Pnl::ZERO);
        let (updated, realized) =
            realize_position_fill(short, ps("15"), px("70")).expect("must realize");

        assert_eq!(realized, Some(pnl("300")));
        assert_eq!(updated.avg_entry_price(), Some(px("70")));
    }

    #[test]
    fn realize_partial_close_long_at_loss_is_negative() {
        // long 10 @ 100, sell 4 @ 80 → realized = (80-100)*4 = -80.
        let long = Holdings::new(ps("10"), PositionSize::ZERO)
            .with_avg_entry_price(Some(px("100")))
            .with_realized_pnl(Pnl::ZERO);
        let (_updated, realized) =
            realize_position_fill(long, ps("-4"), px("80")).expect("must realize");

        assert_eq!(realized, Some(pnl("-80")));
    }

    #[test]
    fn realize_owned_uses_available_plus_held() {
        // available 6 + held 4 = owned 10 @ 100, sell 10 @ 130 → realized 300.
        let long = Holdings::new(ps("6"), ps("4"))
            .with_avg_entry_price(Some(px("100")))
            .with_realized_pnl(Pnl::ZERO);
        let (updated, realized) =
            realize_position_fill(long, ps("-10"), px("130")).expect("must realize");

        assert_eq!(realized, Some(pnl("300")));
        assert_eq!(updated.avg_entry_price(), None);
    }

    #[test]
    fn realize_reduce_without_basis_halts_with_missing_cost_basis() {
        let basis_less = Holdings::new(ps("10"), PositionSize::ZERO);
        let operation = basis_less
            .realize_position_fill(ps("-4"), px("200"))
            .expect("must calculate");

        assert_eq!(
            operation.outcome(),
            Some(Err(PnlHaltReason::MissingCostBasis))
        );
        let updated = operation.holdings();
        assert_eq!(updated.avg_entry_price(), None);
        assert_eq!(updated.realized_pnl(), None);
    }

    #[test]
    fn realize_exact_close_without_basis_halts_with_missing_cost_basis() {
        let basis_less = Holdings::new(ps("-10"), PositionSize::ZERO);
        let operation = basis_less
            .realize_position_fill(ps("10"), px("70"))
            .expect("must calculate");

        assert_eq!(
            operation.outcome(),
            Some(Err(PnlHaltReason::MissingCostBasis))
        );
        let updated = operation.holdings();
        assert_eq!(updated.avg_entry_price(), None);
    }

    #[test]
    fn realize_add_without_initial_pnl_halts_with_missing_initial_pnl() {
        let basis_less = Holdings::new(ps("10"), PositionSize::ZERO);
        let operation = basis_less
            .realize_position_fill(ps("5"), px("200"))
            .expect("must calculate");

        assert_eq!(
            operation.outcome(),
            Some(Err(PnlHaltReason::MissingInitialPnl))
        );
        let updated = operation.holdings();
        assert_eq!(updated.avg_entry_price(), None);
    }

    #[test]
    fn realize_flip_without_basis_halts_with_missing_cost_basis() {
        let basis_less = Holdings::new(ps("10"), PositionSize::ZERO);
        let operation = basis_less
            .realize_position_fill(ps("-15"), px("130"))
            .expect("must calculate");

        assert_eq!(
            operation.outcome(),
            Some(Err(PnlHaltReason::MissingCostBasis))
        );
        let updated = operation.holdings();
        assert_eq!(updated.avg_entry_price(), None);
    }

    #[test]
    fn realize_after_rollback_to_none_halts_with_missing_initial_pnl() {
        // A slot whose realized PnL was restored to `None` by an adjustment
        // rollback (modelled via `with_realized_pnl_opt(None)`) has lost its
        // basis; a subsequent non-flat fill must short-circuit and not
        // auto-resume tracking, exactly like any other untracked slot.
        let rolled_back = Holdings::new(ps("10"), PositionSize::ZERO)
            .with_avg_entry_price(Some(px("100")))
            .with_realized_pnl_opt(None);
        let operation = rolled_back
            .realize_position_fill(ps("-4"), px("130"))
            .expect("must calculate");

        assert_eq!(
            operation.outcome(),
            Some(Err(PnlHaltReason::MissingInitialPnl))
        );
        let updated = operation.holdings();
        assert_eq!(updated.realized_pnl(), None);
        assert_eq!(updated.avg_entry_price(), Some(px("100")));
    }

    #[test]
    fn realize_accumulates_realized_pnl_across_fills() {
        let long = Holdings::new(ps("10"), PositionSize::ZERO)
            .with_avg_entry_price(Some(px("100")))
            .with_realized_pnl(pnl("50"));
        let (updated, realized) =
            realize_position_fill(long, ps("-4"), px("130")).expect("must realize");

        assert_eq!(realized, Some(pnl("120")));
        assert_eq!(updated.realized_pnl(), Some(pnl("170")));
    }

    #[test]
    fn realize_position_fill_leaves_quantities_untouched() {
        let long = Holdings::new(ps("10"), ps("2"))
            .with_avg_entry_price(Some(px("100")))
            .with_realized_pnl(Pnl::ZERO);
        let (updated, _realized) =
            realize_position_fill(long, ps("-4"), px("130")).expect("must realize");

        assert_eq!(updated.available(), ps("10"));
        assert_eq!(updated.held(), ps("2"));
        assert_eq!(updated.incoming(), PositionSize::ZERO);
    }

    #[test]
    fn realize_position_fill_reports_overflow() {
        let long = Holdings::new(max_ps(), PositionSize::ZERO)
            .with_avg_entry_price(Some(px("2")))
            .with_realized_pnl(Pnl::ZERO);
        // owned*avg overflows on the weighted-average branch.
        let err = long
            .realize_position_fill(max_ps(), px("2"))
            .expect_err("must overflow");

        assert_eq!(err, AdjustmentOverflowError::ArithmeticOverflow);
    }

    #[test]
    fn is_zero_requires_no_avg_and_zero_realized_pnl() {
        assert!(Holdings::zero().is_zero());

        // Realized PnL alone keeps the slot alive.
        let with_pnl = Holdings::zero().with_realized_pnl(pnl("5"));
        assert!(!with_pnl.is_zero());

        let with_zero_pnl = Holdings::zero().with_realized_pnl(Pnl::ZERO);
        assert!(with_zero_pnl.is_zero());

        // A residual average entry price alone keeps the slot alive.
        let with_avg = Holdings::zero().with_avg_entry_price(Some(px("100")));
        assert!(!with_avg.is_zero());
    }

    #[test]
    fn reservation_and_cancel_preserve_avg_and_pnl() {
        let base = Holdings::new(ps("10"), PositionSize::ZERO)
            .with_avg_entry_price(Some(px("100")))
            .with_realized_pnl(pnl("7"));

        let held = base.try_hold(ps("4")).expect("must hold");
        assert_eq!(held.avg_entry_price(), Some(px("100")));
        assert_eq!(held.realized_pnl(), Some(pnl("7")));

        let released = held.release(ps("4")).expect("must release");
        assert_eq!(released.avg_entry_price(), Some(px("100")));
        assert_eq!(released.realized_pnl(), Some(pnl("7")));
    }

    #[test]
    fn apply_delta_rollback_reverses_quantity_deltas() {
        // Reversing the forward quantity deltas subtracts each one from the
        // current slot, leaving concurrent contributions to other fields intact.
        let slot = Holdings::new(ps("10"), ps("2"))
            .with_avg_entry_price(Some(px("100")))
            .with_realized_pnl(pnl("90"));
        let rolled = slot
            .apply_delta_rollback(ps("3"), ps("1"), PositionSize::ZERO)
            .expect("rollback must succeed");

        assert_eq!(rolled.available(), ps("7"));
        assert_eq!(rolled.held(), ps("1"));
        assert_eq!(rolled.incoming(), PositionSize::ZERO);
        // Average and realized PnL are not delta-reversed here; the rollback
        // path restores them from a snapshot instead.
        assert_eq!(rolled.avg_entry_price(), Some(px("100")));
        assert_eq!(rolled.realized_pnl(), Some(pnl("90")));
    }

    #[test]
    fn apply_delta_rollback_leaves_avg_and_pnl_untouched() {
        let slot = Holdings::new(ps("5"), ps("0"))
            .with_avg_entry_price(Some(px("42")))
            .with_realized_pnl(pnl("42"));
        let rolled = slot
            .apply_delta_rollback(ps("3"), PositionSize::ZERO, PositionSize::ZERO)
            .expect("rollback must succeed");

        assert_eq!(rolled.available(), ps("2"));
        assert_eq!(rolled.avg_entry_price(), Some(px("42")));
        assert_eq!(rolled.realized_pnl(), Some(pnl("42")));
    }

    #[test]
    fn with_realized_pnl_opt_restores_untracked_state() {
        // A non-flat slot whose realized PnL was force-set can be returned to the
        // untracked `None` state, exactly as a snapshot rollback would.
        let tracked = Holdings::new(ps("10"), ps("0")).with_realized_pnl(pnl("5"));
        let untracked = tracked.with_realized_pnl_opt(None);
        assert_eq!(untracked.realized_pnl(), None);
        assert_eq!(untracked.available(), ps("10"));

        let retracked = untracked.with_realized_pnl_opt(Some(pnl("-3")));
        assert_eq!(retracked.realized_pnl(), Some(pnl("-3")));
    }

    #[test]
    fn halted_realized_pnl_does_not_resume_until_force_set() {
        let halt =
            Holdings::new(ps("10"), PositionSize::ZERO).halt_realized_pnl(PnlHaltReason::MissingFx);
        assert_eq!(halt.outcome(), Some(Err(PnlHaltReason::MissingFx)));
        let halted = halt.holdings();
        assert!(halted.realized_pnl_is_halted());
        assert!(!halted.is_zero());

        let (still_halted, realized) = realize_position_fill(halted, ps("-4"), px("130"))
            .expect("halted tracking must not fail");
        assert_eq!(realized, None);
        assert!(still_halted.realized_pnl_is_halted());
        assert_eq!(still_halted.realized_pnl(), None);

        let rearmed = still_halted
            .with_avg_entry_price(Some(px("100")))
            .with_realized_pnl(pnl("5"));
        assert!(!rearmed.realized_pnl_is_halted());
        let (_, realized) = realize_position_fill(rearmed, ps("-4"), px("130"))
            .expect("force-set tracking must resume");
        assert_eq!(realized, Some(pnl("120")));
    }

    #[test]
    fn with_realized_pnl_force_sets_absolute_value() {
        let slot = Holdings::new(ps("10"), ps("0")).with_realized_pnl(pnl("7"));
        assert_eq!(
            slot.with_realized_pnl(pnl("-3")).realized_pnl(),
            Some(pnl("-3"))
        );
        // Quantities and average are untouched by the force-set.
        let with_avg = slot.with_avg_entry_price(Some(px("100")));
        let forced = with_avg.with_realized_pnl(pnl("99"));
        assert_eq!(forced.realized_pnl(), Some(pnl("99")));
        assert_eq!(forced.avg_entry_price(), Some(px("100")));
        assert_eq!(forced.available(), ps("10"));
    }

    #[test]
    fn quantity_adjustments_preserve_avg_and_pnl() {
        let base = Holdings::new(ps("10"), PositionSize::ZERO)
            .with_avg_entry_price(Some(px("100")))
            .with_realized_pnl(pnl("7"));

        let adjusted = base
            .apply_adjustment(
                AdjustmentTarget::Available,
                AdjustmentAmount::Delta(ps("3")),
            )
            .expect("must adjust");
        assert_eq!(adjusted.available(), ps("13"));
        assert_eq!(adjusted.avg_entry_price(), Some(px("100")));
        assert_eq!(adjusted.realized_pnl(), Some(pnl("7")));
    }

    #[test]
    fn realize_tracked_pnl_same_side_fill_without_avg_stays_basis_less() {
        // Degenerate state: realized PnL is Some but avg_entry_price is None
        // on a non-flat slot. A same-side add must not establish a basis and
        // must contribute 0 to the delta (nothing to weight against).
        let slot = Holdings::new(ps("10"), PositionSize::ZERO).with_realized_pnl(pnl("30"));
        assert_eq!(slot.avg_entry_price(), None);

        let (updated, delta) =
            realize_position_fill(slot, ps("5"), px("200")).expect("must not overflow");

        assert_eq!(delta, None);
        assert_eq!(updated.avg_entry_price(), None);
        assert_eq!(updated.realized_pnl(), Some(pnl("30")));
    }

    #[test]
    fn realize_tracked_pnl_opposite_side_fill_without_avg_halts() {
        let slot = Holdings::new(ps("10"), PositionSize::ZERO).with_realized_pnl(pnl("30"));

        let operation = slot
            .realize_position_fill(ps("-4"), px("150"))
            .expect("must calculate");

        assert_eq!(
            operation.outcome(),
            Some(Err(PnlHaltReason::MissingCostBasis))
        );
        let updated = operation.holdings();
        assert_eq!(updated.avg_entry_price(), None);
        assert_eq!(updated.realized_pnl(), None);
    }

    #[test]
    fn realize_tracked_pnl_flip_without_avg_halts() {
        let slot = Holdings::new(ps("5"), PositionSize::ZERO).with_realized_pnl(pnl("30"));

        let operation = slot
            .realize_position_fill(ps("-10"), px("150"))
            .expect("must calculate");

        assert_eq!(
            operation.outcome(),
            Some(Err(PnlHaltReason::MissingCostBasis))
        );
        let updated = operation.holdings();
        assert_eq!(updated.avg_entry_price(), None);
        assert_eq!(updated.realized_pnl(), None);
    }
}