quantoxide 0.6.1

Rust framework for developing, backtesting, and deploying Bitcoin futures trading strategies.
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
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
use std::{
    cmp::Ordering,
    collections::{BTreeMap, HashMap},
    fmt,
    num::NonZeroU64,
    panic::{self, AssertUnwindSafe},
    sync::{Arc, OnceLock},
};

use async_trait::async_trait;
use chrono::{DateTime, Utc};
use futures::FutureExt;
use uuid::Uuid;

use lnm_sdk::rest::v3::{
    error::TradeValidationError,
    models::{
        ClientId, CrossExposure, CrossLeverage, CrossQuantity, Leverage, Margin, OrderQuantity,
        Percentage, PercentageCapped, Price, SATS_PER_BTC, Trade, TradeSide, TradeSize, trade_util,
    },
};

use crate::{
    db::models::OhlcCandleRow,
    error::Result as GeneralResult,
    shared::{Lookback, MinIterationInterval},
    signal::Signal,
    util::DateTimeExt,
};

use super::error::{
    IsolatedOrderValidationError, TradeCoreError, TradeCoreResult, TradeExecutorResult,
};

impl crate::sealed::Sealed for Trade {}

/// Generic trade interface used in extension traits.
///
/// Provides shared accessors for both running and closed trades. Extended by the [`TradeRunning`]
/// and [`TradeClosed`] traits, which add lifecycle-specific functionality.
///
/// This trait is sealed and not meant to be implemented outside of `quantoxide`.
pub trait TradeCore: crate::sealed::Sealed + Send + Sync + fmt::Debug + 'static {
    /// Returns the unique identifier for this trade.
    fn id(&self) -> Uuid;

    /// Returns the side of the trade (Buy or Sell).
    fn side(&self) -> TradeSide;

    /// Returns the opening fee charged when the trade was created (in satoshis).
    fn opening_fee(&self) -> u64;

    /// Returns the closing fee that will be charged when the trade closes (in satoshis).
    fn closing_fee(&self) -> u64;

    /// Returns the maintenance margin requirement (in satoshis).
    fn maintenance_margin(&self) -> i64;

    /// Returns the quantity (notional value in USD) of the trade.
    fn quantity(&self) -> OrderQuantity;

    /// Returns the margin (collateral in satoshis) allocated to the trade.
    fn margin(&self) -> Margin;

    /// Returns the leverage multiplier applied to the trade.
    fn leverage(&self) -> Leverage;

    /// Returns the trade price.
    fn price(&self) -> Price;

    /// Returns the liquidation price at which the position will be automatically closed.
    fn liquidation(&self) -> Price;

    /// Returns the stop loss price, if set.
    fn stoploss(&self) -> Option<Price>;

    /// Returns the take profit price, if set.
    fn takeprofit(&self) -> Option<Price>;

    /// Returns the price at which the trade was closed, if applicable.
    fn exit_price(&self) -> Option<Price>;

    /// Returns the timestamp when the trade was created.
    fn created_at(&self) -> DateTime<Utc>;

    /// Returns the timestamp when the trade was filled, if applicable.
    fn filled_at(&self) -> Option<DateTime<Utc>>;

    /// Returns the timestamp when the trade was closed, if applicable.
    fn closed_at(&self) -> Option<DateTime<Utc>>;

    /// Returns `true` if the trade has been closed.
    fn closed(&self) -> bool;

    /// Returns the client-provided identifier for this trade, if set.
    fn client_id(&self) -> Option<&ClientId>;
}

impl TradeCore for Trade {
    fn id(&self) -> Uuid {
        self.id()
    }

    fn side(&self) -> TradeSide {
        self.side()
    }

    fn opening_fee(&self) -> u64 {
        self.opening_fee()
    }

    fn closing_fee(&self) -> u64 {
        self.closing_fee()
    }

    fn maintenance_margin(&self) -> i64 {
        self.maintenance_margin()
    }

    fn quantity(&self) -> OrderQuantity {
        self.quantity()
    }

    fn margin(&self) -> Margin {
        self.margin()
    }

    fn leverage(&self) -> Leverage {
        self.leverage()
    }

    fn price(&self) -> Price {
        self.price()
    }

    fn liquidation(&self) -> Price {
        self.liquidation()
    }

    fn stoploss(&self) -> Option<Price> {
        self.stoploss()
    }

    fn takeprofit(&self) -> Option<Price> {
        self.takeprofit()
    }

    fn exit_price(&self) -> Option<Price> {
        self.exit_price()
    }

    fn created_at(&self) -> DateTime<Utc> {
        self.created_at()
    }

    fn filled_at(&self) -> Option<DateTime<Utc>> {
        self.filled_at()
    }

    fn closed_at(&self) -> Option<DateTime<Utc>> {
        self.closed_at()
    }

    fn closed(&self) -> bool {
        self.closed()
    }

    fn client_id(&self) -> Option<&ClientId> {
        self.client_id()
    }
}

/// Extension trait for running trades with profit/loss and margin calculations.
///
/// Provides methods for estimating profit/loss and calculating margin adjustments for trades that
/// are currently active (running). This trait extends the [`Trade`] trait with functionality
/// specific to active positions.
///
/// This trait is sealed and not meant to be implemented outside of `quantoxide`.
///
/// # Examples
///
/// ```no_run
/// # async fn example(rest: lnm_sdk::rest::v3::RestClient) -> Result<(), Box<dyn std::error::Error>> {
/// use quantoxide::{
///     models::{Trade, TradeExecution, TradeSide, TradeSize, Leverage, Margin, Price},
///     trade::TradeRunning,
/// };
///
/// let trade: Trade = rest
///     .futures_isolated
///     .new_trade(
///         TradeSide::Buy,
///         TradeSize::from(Margin::try_from(10_000).unwrap()),
///         Leverage::try_from(10.0).unwrap(),
///         TradeExecution::Market,
///         None,
///         None,
///         None
///     )
///     .await?;
///
/// let market_price = Price::try_from(101_000.0).unwrap();
/// let estimated_pl = trade.est_pl(market_price);
/// let max_cash_in = trade.est_max_cash_in(market_price);
///
/// println!("Estimated P/L: {} sats", estimated_pl);
/// println!("Max cash-in: {} sats", max_cash_in);
/// # Ok(())
/// # }
/// ```
pub trait TradeRunning: TradeCore {
    /// Estimates the profit/loss for the trade at a given market price.
    ///
    /// Returns the estimated profit or loss in satoshis if the trade were closed at the specified
    /// market price.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn example(trade: quantoxide::models::Trade) -> Result<(), Box<dyn std::error::Error>> {
    /// // Assuming `trade` impl `TradeRunning`
    ///
    /// use quantoxide::{models::Price, trade::TradeRunning};
    ///
    /// let market_price = Price::try_from(101_000.0).unwrap();
    /// let pl = trade.est_pl(market_price);
    ///
    /// if pl > 0.0 {
    ///     println!("Profit: {} sats", pl);
    /// } else {
    ///     println!("Loss: {} sats", pl.abs());
    /// }
    /// # Ok(())
    /// # }
    /// ```
    fn est_pl(&self, market_price: Price) -> f64;

    /// Estimates the maximum additional margin that can be added to the trade.
    ///
    /// Returns the maximum amount of margin (in satoshis) that can be added to reduce leverage to
    /// the minimum level (1x). Returns 0 if the trade is already at minimum leverage.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn example(trade: lnm_sdk::rest::v3::models::Trade) -> Result<(), Box<dyn std::error::Error>> {
    /// // Assuming `trade` impl `TradeRunning`
    ///
    /// use quantoxide::trade::TradeRunning;
    ///
    /// let max_additional = trade.est_max_additional_margin();
    ///
    /// println!("Can add up to {} sats margin", max_additional);
    /// # Ok(())
    /// # }
    /// ```
    fn est_max_additional_margin(&self) -> u64 {
        if self.leverage() == Leverage::MIN {
            return 0;
        }

        let max_margin = Margin::calculate(self.quantity(), self.price(), Leverage::MIN);

        max_margin.as_u64().saturating_sub(self.margin().as_u64())
    }

    /// Estimates the maximum margin that can be withdrawn from the trade.
    ///
    /// Returns the maximum amount of margin (in satoshis) that can be withdrawn while maintaining
    /// the position at maximum leverage. Includes any extractable profit.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn example(trade: quantoxide::models::Trade) -> Result<(), Box<dyn std::error::Error>> {
    /// // Assuming `trade` impl `TradeRunning`
    ///
    /// use quantoxide::{models::Price, trade::TradeRunning};
    ///
    /// let market_price = Price::try_from(101_000.0).unwrap();
    /// let max_withdrawal = trade.est_max_cash_in(market_price);
    ///
    /// println!("Can withdraw up to {} sats", max_withdrawal);
    /// # Ok(())
    /// # }
    /// ```
    fn est_max_cash_in(&self, market_price: Price) -> u64 {
        let extractable_pl = self.est_pl(market_price).max(0.) as u64;

        let min_margin = Margin::calculate(self.quantity(), self.price(), Leverage::MAX);

        let excess_margin = self.margin().as_u64().saturating_sub(min_margin.as_u64());

        excess_margin + extractable_pl
    }

    /// Calculates the collateral adjustment needed to achieve a target liquidation price.
    ///
    /// Returns a positive value if margin needs to be added, or a negative value if margin can be
    /// withdrawn to reach the target liquidation price.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn example(trade: quantoxide::models::Trade) -> Result<(), Box<dyn std::error::Error>>  {
    /// // Assuming `trade` impl `TradeRunning`
    ///
    /// use quantoxide::{models::Price, trade::TradeRunning};
    ///
    /// let target_liquidation = Price::try_from(95_000.0).unwrap();
    /// let market_price = Price::try_from(100_000.0).unwrap();
    ///
    /// let delta = trade.est_collateral_delta_for_liquidation(
    ///     target_liquidation,
    ///     market_price
    /// )?;
    ///
    /// if delta > 0 {
    ///     println!("Add {} sats to reach target liquidation", delta);
    /// } else {
    ///     println!("Remove {} sats to reach target liquidation", delta.abs());
    /// }
    /// # Ok(())
    /// # }
    /// ```
    fn est_collateral_delta_for_liquidation(
        &self,
        target_liquidation: Price,
        market_price: Price,
    ) -> Result<i64, TradeValidationError> {
        trade_util::evaluate_collateral_delta_for_liquidation(
            self.side(),
            self.quantity(),
            self.margin(),
            self.price(),
            self.liquidation(),
            target_liquidation,
            market_price,
        )
    }
}

impl TradeRunning for Trade {
    fn est_pl(&self, market_price: Price) -> f64 {
        trade_util::estimate_pl(self.side(), self.quantity(), self.price(), market_price)
    }
}

/// Extension trait for closed trades.
///
/// Provides access to the final profit/loss of a trade that has been closed. This trait extends the
/// [`Trade`] trait with functionality specific to completed positions.
///
/// This trait is sealed and not meant to be implemented outside of `quantoxide`.
pub trait TradeClosed: TradeCore {
    /// Returns the realized profit/loss of the closed trade in satoshis.
    ///
    /// A positive value indicates profit, while a negative value indicates a loss.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # async fn example(closed_trade: lnm_sdk::rest::v3::models::Trade) -> Result<(), Box<dyn std::error::Error>> {
    /// use quantoxide::trade::TradeClosed;
    ///
    /// let pl = closed_trade.pl();
    ///
    /// println!("Realized P/L: {} sats", pl);
    /// # Ok(())
    /// # }
    /// ```
    fn pl(&self) -> i64;
}

impl TradeClosed for Trade {
    fn pl(&self) -> i64 {
        self.pl()
    }
}

/// A reference to a trade, containing `(creation_timestamp, trade_uuid)`.
pub type TradeReference = (DateTime<Utc>, Uuid);

/// A collection of running trades indexed by creation time and UUID, with optional trailing
/// stoploss metadata. Provides efficient lookups by trade ID and chronological iteration.
#[derive(Debug)]
pub struct RunningTradesMap<T: TradeRunning + ?Sized> {
    trades: BTreeMap<TradeReference, (Arc<T>, Option<TradeTrailingStoploss>)>,
    id_to_time: HashMap<Uuid, DateTime<Utc>>,
}

/// Type alias for a dynamically dispatched running trades map.
pub type DynRunningTradesMap = RunningTradesMap<dyn TradeRunning>;

impl<T: TradeRunning + ?Sized> RunningTradesMap<T> {
    pub(super) fn new() -> Self {
        Self {
            trades: BTreeMap::new(),
            id_to_time: HashMap::new(),
        }
    }

    /// Returns `true` if the map contains no trades.
    pub fn is_empty(&self) -> bool {
        self.trades.is_empty()
    }

    pub(super) fn add(&mut self, trade: Arc<T>, trade_tsl: Option<TradeTrailingStoploss>) {
        self.id_to_time.insert(trade.id(), trade.created_at());
        self.trades
            .insert((trade.created_at(), trade.id()), (trade, trade_tsl));
    }

    /// Returns the number of trades in the map.
    pub fn len(&self) -> usize {
        self.id_to_time.len()
    }

    /// Returns `true` if the map contains a trade with the specified ID.
    pub fn contains(&self, trade_id: &Uuid) -> bool {
        self.id_to_time.contains_key(trade_id)
    }

    /// Returns a reference to the trade and its trailing stoploss metadata for the given trade ID.
    pub fn get_by_id(&self, id: Uuid) -> Option<&(Arc<T>, Option<TradeTrailingStoploss>)> {
        self.id_to_time
            .get(&id)
            .and_then(|creation_ts| self.trades.get(&(*creation_ts, id)))
    }

    pub(super) fn get_by_id_mut(
        &mut self,
        id: Uuid,
    ) -> Option<&mut (Arc<T>, Option<TradeTrailingStoploss>)> {
        self.id_to_time
            .get(&id)
            .and_then(|creation_ts| self.trades.get_mut(&(*creation_ts, id)))
    }

    /// Returns an iterator over trade references and their data in ascending chronological order
    /// (oldest first).
    pub fn iter(
        &self,
    ) -> impl Iterator<Item = (&TradeReference, &(Arc<T>, Option<TradeTrailingStoploss>))> {
        self.trades.iter()
    }

    /// Returns an iterator over trade references in ascending chronological order (oldest first).
    pub fn keys(&self) -> impl Iterator<Item = &TradeReference> {
        self.trades.keys()
    }

    /// Returns an iterator over trades and their trailing stoploss metadata in ascending
    /// chronological order (oldest first).
    pub fn values(&self) -> impl Iterator<Item = &(Arc<T>, Option<TradeTrailingStoploss>)> {
        self.trades.values()
    }

    /// Returns an iterator over trades in descending chronological order (newest first).
    pub fn trades_desc(&self) -> impl Iterator<Item = &(Arc<T>, Option<TradeTrailingStoploss>)> {
        self.trades.iter().rev().map(|(_, trade_tuple)| trade_tuple)
    }

    pub(super) fn trades_desc_mut(
        &mut self,
    ) -> impl Iterator<Item = &mut (Arc<T>, Option<TradeTrailingStoploss>)> {
        self.trades
            .iter_mut()
            .rev()
            .map(|(_, trade_tuple)| trade_tuple)
    }
}

impl<T: TradeRunning> RunningTradesMap<T> {
    pub(super) fn into_dyn(self) -> DynRunningTradesMap {
        let dyn_trades = self
            .trades
            .into_iter()
            .map(|(key, (trade, stoploss))| {
                let dyn_trade: Arc<dyn TradeRunning> = trade;
                (key, (dyn_trade, stoploss))
            })
            .collect();

        RunningTradesMap {
            trades: dyn_trades,
            id_to_time: self.id_to_time,
        }
    }
}

impl<T: TradeRunning + ?Sized> Clone for RunningTradesMap<T> {
    fn clone(&self) -> Self {
        Self {
            trades: self.trades.clone(),
            id_to_time: self.id_to_time.clone(),
        }
    }
}

impl<'a, T: TradeRunning + ?Sized> IntoIterator for &'a RunningTradesMap<T> {
    type Item = (
        &'a TradeReference,
        &'a (Arc<T>, Option<TradeTrailingStoploss>),
    );
    type IntoIter = std::collections::btree_map::Iter<
        'a,
        TradeReference,
        (Arc<T>, Option<TradeTrailingStoploss>),
    >;

    fn into_iter(self) -> Self::IntoIter {
        self.trades.iter()
    }
}

#[derive(Debug, Clone)]
struct RunningStats {
    long_len: usize,
    long_margin: u64,
    long_quantity: u64,
    short_len: usize,
    short_margin: u64,
    short_quantity: u64,
    pl: i64,
    fees: u64,
}

/// Generic cross-margin position interface used by both live and simulated positions.
///
/// The estimated P/L, NAV, and free-margin helpers take an explicit market price because LN
/// Markets' live `CrossPosition` does not expose the reference/mark price used for its own P/L
/// fields. Passing the price explicitly keeps the estimate source clear and lets simulated and live
/// callers use the same formula.
pub trait CrossPositionCore: crate::sealed::Sealed + Send + Sync + fmt::Debug + 'static {
    /// Returns the cross account margin/collateral in satoshis.
    fn margin(&self) -> u64;

    /// Returns the configured cross account leverage.
    fn leverage(&self) -> CrossLeverage;

    /// Returns the active cross-margin exposure, if any.
    fn exposure(&self) -> CrossExposure;

    /// Returns cumulative realized cross-position profit/loss in satoshis.
    fn realized_pl(&self) -> i64;

    /// Returns session-local cross funding fees in satoshis.
    ///
    /// Positive values are net costs and negative values are net revenue.
    fn session_funding_fees(&self) -> i64;

    /// Returns cross order fees.
    fn trading_fees(&self) -> u64;

    /// Returns the signed cross position quantity in USD notional.
    ///
    /// Positive quantities correspond to long positions, negative quantities correspond to short
    /// positions, and zero corresponds to a neutral position.
    fn quantity(&self) -> i64 {
        match self.exposure() {
            CrossExposure::Neutral => 0,
            CrossExposure::Running(exposure) => {
                let quantity = exposure.quantity().as_i64();
                match exposure.side() {
                    TradeSide::Buy => quantity,
                    TradeSide::Sell => -quantity,
                }
            }
        }
    }

    /// Returns the cross position entry price, if a position is open.
    fn entry_price(&self) -> Option<Price> {
        match self.exposure() {
            CrossExposure::Neutral => None,
            CrossExposure::Running(exposure) => Some(exposure.entry_price()),
        }
    }

    /// Returns the cross position liquidation price, if a position is open.
    fn liquidation(&self) -> Option<Price> {
        match self.exposure() {
            CrossExposure::Neutral => None,
            CrossExposure::Running(exposure) => Some(exposure.liquidation()),
        }
    }

    /// Returns the current initial margin allocated to the cross position.
    fn initial_margin(&self) -> u64 {
        self.running_margin()
    }

    /// Returns the current running margin for the cross position.
    fn running_margin(&self) -> u64 {
        match self.exposure() {
            CrossExposure::Neutral => 0,
            CrossExposure::Running(exposure) => exposure.running_margin().as_u64(),
        }
    }

    /// Returns the current maintenance margin for the cross position.
    fn maintenance_margin(&self) -> u64 {
        match self.exposure() {
            CrossExposure::Neutral => 0,
            CrossExposure::Running(exposure) => exposure.maintenance_margin().as_u64(),
        }
    }

    /// Estimates current cross position running P/L at the supplied market price.
    fn est_running_pl(&self, market_price: Price) -> i64 {
        match self.exposure() {
            CrossExposure::Neutral => 0,
            CrossExposure::Running(exposure) => trade_util::estimate_pl(
                exposure.side(),
                exposure.quantity(),
                exposure.entry_price(),
                market_price,
            )
            .floor() as i64,
        }
    }

    /// Estimates the cross account net asset value at the supplied market price.
    fn est_net_value(&self, market_price: Price) -> u64 {
        self.margin()
            .saturating_add_signed(self.est_running_pl(market_price))
    }

    /// Estimates cross free margin at the supplied market price.
    ///
    /// Running margin absorbs negative P/L first. When the loss exceeds running margin, the excess
    /// loss is deducted from free margin.
    fn est_free_margin(&self, market_price: Price) -> u64 {
        let loss = self.est_running_pl(market_price).min(0).unsigned_abs();
        let excess_loss = loss.saturating_sub(self.running_margin());

        self.margin()
            .saturating_sub(self.running_margin())
            .saturating_sub(self.maintenance_margin())
            .saturating_sub(excess_loss)
    }

    /// Estimates the entry price that would result from changing this cross position to
    /// `new_side` / `new_quantity` with one market adjustment at `market_price`.
    ///
    /// Same-side increases aggregate the current entry with the added quantity. Same-side
    /// reductions follow the simulator's current accounting: profitable reductions keep the current
    /// entry and losing reductions carry the loss in the remaining entry. Reversals and flat opens
    /// use the market price as the new entry.
    fn est_entry_price_for_exposure(
        &self,
        new_side: TradeSide,
        new_quantity: CrossQuantity,
        market_price: Price,
    ) -> Option<Price> {
        let CrossExposure::Running(exposure) = self.exposure() else {
            return Some(market_price);
        };

        if exposure.side() != new_side {
            return Some(market_price);
        }

        match new_quantity.cmp(&exposure.quantity()) {
            Ordering::Greater => {
                let added_quantity = new_quantity.try_sub(exposure.quantity()).ok()?;
                Some(trade_util::aggregate_cross_entry_price(
                    exposure.quantity(),
                    exposure.entry_price(),
                    added_quantity,
                    market_price,
                ))
            }
            Ordering::Equal => Some(exposure.entry_price()),
            Ordering::Less => {
                let reduced_quantity = exposure.quantity().try_sub(new_quantity).ok()?;
                let realized_pl = trade_util::estimate_pl(
                    exposure.side(),
                    reduced_quantity,
                    exposure.entry_price(),
                    market_price,
                )
                .floor() as i64;

                if realized_pl >= 0 {
                    return Some(exposure.entry_price());
                }

                let full_position_pl = trade_util::estimate_pl(
                    exposure.side(),
                    exposure.quantity(),
                    exposure.entry_price(),
                    market_price,
                );
                let inverse_market_price = SATS_PER_BTC / market_price.as_f64();
                let carried_inverse_entry_price = match exposure.side() {
                    TradeSide::Buy => {
                        inverse_market_price + full_position_pl / new_quantity.as_f64()
                    }
                    TradeSide::Sell => {
                        inverse_market_price - full_position_pl / new_quantity.as_f64()
                    }
                };

                Some(Price::bounded(SATS_PER_BTC / carried_inverse_entry_price))
            }
        }
    }

    /// Estimates the raw cross margin that would result from changing this cross position to
    /// `new_side` / `new_quantity` with one fee-free market adjustment at `market_price`.
    ///
    /// This follows the same realized-P/L margin accounting as
    /// [`est_entry_price_for_exposure`](Self::est_entry_price_for_exposure): full reversals realize
    /// the full current P/L, profitable partial reductions realize reduced-quantity P/L into raw
    /// margin, and losing partial reductions carry the loss in the remaining entry instead of
    /// deducting it from raw margin.
    fn est_margin_for_exposure(
        &self,
        new_side: TradeSide,
        new_quantity: CrossQuantity,
        market_price: Price,
    ) -> Option<i64> {
        let current_margin = i64::try_from(self.margin()).ok()?;
        let CrossExposure::Running(exposure) = self.exposure() else {
            return Some(current_margin);
        };

        if exposure.side() != new_side {
            let realized_pl = trade_util::estimate_pl(
                exposure.side(),
                exposure.quantity(),
                exposure.entry_price(),
                market_price,
            )
            .floor() as i64;

            return current_margin.checked_add(realized_pl);
        }

        if new_quantity >= exposure.quantity() {
            return Some(current_margin);
        }

        let reduced_quantity = exposure.quantity().try_sub(new_quantity).ok()?;
        let realized_pl = trade_util::estimate_pl(
            exposure.side(),
            reduced_quantity,
            exposure.entry_price(),
            market_price,
        )
        .floor() as i64;

        if realized_pl >= 0 {
            current_margin.checked_add(realized_pl)
        } else {
            Some(current_margin)
        }
    }

    /// Estimates the market-order fee for changing this cross position to `new_side` /
    /// `new_quantity` at `market_price`.
    ///
    /// The estimate uses the absolute USD exposure delta between the current and target net
    /// positions. It returns zero when the target exposure already matches the current exposure.
    fn est_order_fee_for_exposure(
        &self,
        new_side: TradeSide,
        new_quantity: CrossQuantity,
        market_price: Price,
        fee_perc: PercentageCapped,
    ) -> Option<u64> {
        let target_quantity = match new_side {
            TradeSide::Buy => new_quantity.as_i64(),
            TradeSide::Sell => new_quantity.as_i64().checked_neg()?,
        };
        let order_quantity = target_quantity.checked_sub(self.quantity())?.unsigned_abs();

        if order_quantity == 0 {
            return Some(0);
        }

        let order_quantity = CrossQuantity::try_from(order_quantity).ok()?;
        Some(trade_util::evaluate_order_fee(
            fee_perc,
            order_quantity,
            market_price,
        ))
    }

    /// Estimates the cross collateral change needed to hold a position of `new_side` /
    /// `new_quantity` with liquidation at `new_liquidation`.
    ///
    /// The target entry, raw margin, net value, and order fee are derived as though the current
    /// exposure were adjusted with one market order at `market_price`. The returned delta is the
    /// larger of:
    ///
    /// - the net-collateral delta needed to put liquidation at `new_liquidation`, including the
    ///   target exposure's maintenance margin; and
    /// - the raw-margin delta needed to satisfy the SDK cross exposure coherence floor
    ///   (`running_margin + maintenance_margin + 1`).
    ///
    /// A positive result is collateral that must be deposited; a negative result is collateral that
    /// can be withdrawn. Returns `None` when the target liquidation is not on the liquidatable side
    /// of `market_price` or the target exposure is invalid for the account leverage. If the
    /// coherence floor dominates, depositing the returned amount makes the exposure valid but may
    /// move liquidation farther from market than `new_liquidation`.
    fn est_collateral_diff_for_exposure(
        &self,
        new_side: TradeSide,
        new_quantity: CrossQuantity,
        market_price: Price,
        new_liquidation: Price,
        fee_perc: PercentageCapped,
    ) -> Option<i64> {
        let new_entry_price =
            self.est_entry_price_for_exposure(new_side, new_quantity, market_price)?;
        let CrossExposure::Running(target_exposure) = CrossExposure::running(
            Margin::MAX.as_u64(),
            self.leverage(),
            new_side,
            new_quantity,
            new_entry_price,
        )
        .ok()?
        else {
            unreachable!("running exposure requested")
        };

        let projected_order_fee =
            self.est_order_fee_for_exposure(new_side, new_quantity, market_price, fee_perc)?;
        let projected_margin = self
            .est_margin_for_exposure(new_side, new_quantity, market_price)?
            .checked_sub(i64::try_from(projected_order_fee).ok()?)?;
        let projected_pl =
            trade_util::estimate_pl(new_side, new_quantity, new_entry_price, market_price);
        let projected_net_value = projected_margin.checked_add(projected_pl.floor() as i64)?;

        let minimum_coherent_margin = target_exposure
            .running_margin()
            .try_add(target_exposure.maintenance_margin())
            .ok()?
            .try_add(1_u64)
            .ok()?
            .as_i64();

        let coherence_delta = minimum_coherent_margin.checked_sub(projected_margin)?;

        let target_net_collateral = Margin::est_from_liquidation_price(
            new_side,
            new_quantity,
            market_price,
            new_liquidation,
        )
        .ok()?
        .try_add(target_exposure.maintenance_margin())
        .ok()?
        .as_i64();

        let liquidation_delta = target_net_collateral.checked_sub(projected_net_value)?;

        Some(liquidation_delta.max(coherence_delta))
    }

    /// Estimates the cross collateral change needed to move this position's liquidation to
    /// `new_liquidation`, keeping its current side, quantity, and entry price.
    ///
    /// Convenience wrapper over [`est_collateral_diff_for_exposure`](Self::est_collateral_diff_for_exposure)
    /// for the current running exposure and configured fee rate. Returns `None` when the position
    /// is neutral.
    fn est_collateral_diff_for_liquidation(
        &self,
        market_price: Price,
        new_liquidation: Price,
        fee_perc: PercentageCapped,
    ) -> Option<i64> {
        let CrossExposure::Running(exposure) = self.exposure() else {
            return None;
        };

        self.est_collateral_diff_for_exposure(
            exposure.side(),
            exposure.quantity(),
            market_price,
            new_liquidation,
            fee_perc,
        )
    }
}

/// Comprehensive snapshot of the current trading state including balance, running trades, and
/// performance metrics. This type provides a complete view of a trading session at a specific point
/// in time.
#[derive(Debug, Clone)]
pub struct TradingState {
    last_tick_time: DateTime<Utc>,
    balance: u64,
    market_price: Price,
    last_trade_time: Option<DateTime<Utc>>,
    running_map: DynRunningTradesMap,
    running_stats: OnceLock<RunningStats>,
    funding_fees: i64,
    realized_pl: i64,
    closed_history: Arc<ClosedTradeHistory>,
    closed_fees: u64,
    cross_position: Arc<dyn CrossPositionCore>,
}

impl TradingState {
    #[allow(clippy::too_many_arguments)]
    pub(super) fn new(
        last_tick_time: DateTime<Utc>,
        balance: u64,
        market_price: Price,
        last_trade_time: Option<DateTime<Utc>>,
        running_map: DynRunningTradesMap,
        funding_fees: i64,
        realized_pl: i64,
        closed_history: Arc<ClosedTradeHistory>,
        closed_fees: u64,
        cross_position: Arc<dyn CrossPositionCore>,
    ) -> Self {
        Self {
            last_tick_time,
            balance,
            market_price,
            last_trade_time,
            running_map,
            running_stats: OnceLock::new(),
            funding_fees,
            realized_pl,
            closed_history,
            closed_fees,
            cross_position,
        }
    }

    fn get_running_stats(&self) -> &RunningStats {
        self.running_stats.get_or_init(|| {
            let mut long_len = 0;
            let mut long_margin = 0;
            let mut long_quantity = 0;
            let mut short_len = 0;
            let mut short_margin = 0;
            let mut short_quantity = 0;
            let mut pl = 0;
            let mut fees = 0;

            for (trade, _) in self.running_map.trades_desc() {
                match trade.side() {
                    TradeSide::Buy => {
                        long_len += 1;
                        long_margin +=
                            trade.margin().as_u64() + trade.maintenance_margin().max(0) as u64;
                        long_quantity += trade.quantity().as_u64();
                    }
                    TradeSide::Sell => {
                        short_len += 1;
                        short_margin +=
                            trade.margin().as_u64() + trade.maintenance_margin().max(0) as u64;
                        short_quantity += trade.quantity().as_u64();
                    }
                }
                pl += trade.est_pl(self.market_price).floor() as i64;
                fees += trade.opening_fee();
            }

            RunningStats {
                long_len,
                long_margin,
                long_quantity,
                short_len,
                short_margin,
                short_quantity,
                pl,
                fees,
            }
        })
    }

    /// Returns the timestamp of the last market price update.
    pub fn last_tick_time(&self) -> DateTime<Utc> {
        self.last_tick_time
    }

    /// Returns the total net value including balance, locked margin, and unrealized profit/loss.
    pub fn total_net_value(&self) -> u64 {
        self.balance
            .saturating_add(self.running_margin())
            .saturating_add_signed(self.running_pl())
            .saturating_add(self.cross_position.est_net_value(self.market_price))
    }

    /// Returns the available balance (in satoshis) not locked in trades.
    pub fn balance(&self) -> u64 {
        self.balance
    }

    /// Returns the current market price used for calculating unrealized profit/loss.
    pub fn market_price(&self) -> Price {
        self.market_price
    }

    /// Returns the timestamp of the most recent trade action, if any.
    pub fn last_trade_time(&self) -> Option<DateTime<Utc>> {
        self.last_trade_time
    }

    /// Returns a reference to the map of currently running trades.
    pub fn running_map(&self) -> &DynRunningTradesMap {
        &self.running_map
    }

    /// Returns the number of running long positions.
    pub fn running_long_len(&self) -> usize {
        self.get_running_stats().long_len
    }

    /// Returns the total locked margin for long positions (in satoshis).
    pub fn running_long_margin(&self) -> u64 {
        self.get_running_stats().long_margin
    }

    /// Returns the total notional quantity for long positions (in USD).
    pub fn running_long_quantity(&self) -> u64 {
        self.get_running_stats().long_quantity
    }

    /// Returns the number of running short positions.
    pub fn running_short_len(&self) -> usize {
        self.get_running_stats().short_len
    }

    /// Returns the total locked margin for short positions (in satoshis).
    pub fn running_short_margin(&self) -> u64 {
        self.get_running_stats().short_margin
    }

    /// Returns the total notional quantity for short positions (in USD).
    pub fn running_short_quantity(&self) -> u64 {
        self.get_running_stats().short_quantity
    }

    /// Returns the total locked margin across all running positions (in satoshis).
    pub fn running_margin(&self) -> u64 {
        self.running_long_margin() + self.running_short_margin()
    }

    /// Returns the total notional quantity across all running positions (in USD).
    pub fn running_quantity(&self) -> u64 {
        self.running_long_quantity() + self.running_short_quantity()
    }

    /// Returns the total unrealized profit/loss across all running positions (in satoshis).
    pub fn running_pl(&self) -> i64 {
        self.get_running_stats().pl
    }

    /// Returns the total order fees for all running positions (in satoshis).
    pub fn running_fees(&self) -> u64 {
        self.get_running_stats().fees
    }

    /// Returns the net funding fees across all settlements (in satoshis).
    ///
    /// Positive -> net cost
    /// Negative -> net revenue
    pub fn funding_fees(&self) -> i64 {
        self.funding_fees
    }

    /// Returns the total realized profit/loss including closed trades and cashed-in profits from
    /// running trades (in satoshis).
    pub fn realized_pl(&self) -> i64 {
        self.realized_pl
    }

    /// Returns a reference to the closed trade history.
    pub fn closed_history(&self) -> &Arc<ClosedTradeHistory> {
        &self.closed_history
    }

    /// Returns the number of closed trades.
    pub fn closed_len(&self) -> usize {
        self.closed_history.len()
    }

    /// Returns the total order fees paid for closed trades (in satoshis).
    pub fn closed_fees(&self) -> u64 {
        self.closed_fees
    }

    /// Returns the net profit/loss of closed trades after order fees (in satoshis).
    pub fn closed_net_pl(&self) -> i64 {
        self.realized_pl - self.closed_fees() as i64
    }

    /// Returns the total profit/loss combining both running and realized P/L (in satoshis).
    pub fn pl(&self) -> i64 {
        self.running_pl() + self.realized_pl
    }

    /// Returns the total order fees across both running and closed trades (in satoshis).
    pub fn fees(&self) -> u64 {
        self.running_fees() + self.closed_fees()
    }

    /// Returns the cross-margin position snapshot.
    pub fn cross_position(&self) -> &dyn CrossPositionCore {
        self.cross_position.as_ref()
    }

    /// Returns a formatted string containing a comprehensive summary of the trading state including
    /// timing information, balances, positions, and metrics.
    pub fn summary(&self) -> String {
        let mut result = String::new();

        let last_trade_str = self
            .last_trade_time()
            .map_or("-".to_string(), |t| t.format_local_short());

        let tick_str = self.last_tick_time().format_local_short();
        let w = tick_str.len().max(last_trade_str.len());
        result.push_str("Timestamps:\n");
        result.push_str(&format!("  Tick:       {:>w$}\n", tick_str));
        result.push_str(&format!("  Last trade: {:>w$}\n\n", last_trade_str));

        result.push_str(&format!("Price: {:.1} USD\n\n", self.market_price));

        // Net Asset Value
        let price = self.market_price.as_f64();
        let nav_sats = self.total_net_value().to_string();
        let nav_usd = format!(
            "{:.2}",
            self.total_net_value() as f64 * price / SATS_PER_BTC
        );
        let w = nav_sats.len().max(nav_usd.len());
        result.push_str(&format!("Net Asset Value: {:>w$} sats\n", nav_sats));
        result.push_str(&format!("                 {:>w$} USD\n\n", nav_usd));

        // Available balance
        let bal_sats = self.balance.to_string();
        let bal_usd = format!("{:.2}", self.balance as f64 * price / SATS_PER_BTC);
        let w = bal_sats.len().max(bal_usd.len());
        result.push_str(&format!("Available balance: {:>w$} sats\n", bal_sats));
        result.push_str(&format!("                   {:>w$} USD\n\n", bal_usd));

        // Cross
        let cross_position = self.cross_position();
        let cross_margin = cross_position.margin().to_string();
        let cross_free_margin = cross_position
            .est_free_margin(self.market_price)
            .to_string();
        let mut cross_rows = Vec::new();

        if let CrossExposure::Running(exposure) = cross_position.exposure() {
            cross_rows.extend([
                ("Side:", exposure.side().to_string(), ""),
                (
                    "Quantity:",
                    exposure.quantity().as_u64().to_string(),
                    " USD",
                ),
                (
                    "Running P/L:",
                    cross_position.est_running_pl(self.market_price).to_string(),
                    " sats",
                ),
            ]);
        }

        cross_rows.extend([
            (
                "Funding fees:",
                cross_position.session_funding_fees().to_string(),
                " sats",
            ),
            (
                "Realized P/L:",
                cross_position.realized_pl().to_string(),
                " sats",
            ),
            (
                "Order fees:",
                cross_position.trading_fees().to_string(),
                " sats",
            ),
        ]);

        let label_width = cross_rows
            .iter()
            .map(|(label, _, _)| label.len())
            .max()
            .unwrap_or(0);
        let margin_label_width = label_width.saturating_sub(2);
        let w = cross_rows
            .iter()
            .map(|(_, value, _)| value.len())
            .chain([cross_margin.len(), cross_free_margin.len()])
            .max()
            .unwrap_or(0);
        result.push_str("Cross:\n");
        result.push_str("  Margin:\n");
        result.push_str(&format!(
            "    {:<margin_label_width$} {cross_margin:>w$} sats\n",
            "Total:"
        ));
        result.push_str(&format!(
            "    {:<margin_label_width$} {cross_free_margin:>w$} sats\n",
            "Free:"
        ));
        for (label, value, suffix) in cross_rows {
            result.push_str(&format!("  {label:<label_width$} {value:>w$}{suffix}\n"));
        }
        result.push('\n');

        result.push_str("Isolated:\n");

        // Isolated - Running Positions (aligned across Long and Short)
        let running_long_rows = [
            ("      Trades:", self.running_long_len().to_string(), ""),
            (
                "      Margin:",
                self.running_long_margin().to_string(),
                " sats",
            ),
            (
                "      Quantity:",
                self.running_long_quantity().to_string(),
                " USD",
            ),
        ];
        let running_short_rows = [
            ("      Trades:", self.running_short_len().to_string(), ""),
            (
                "      Margin:",
                self.running_short_margin().to_string(),
                " sats",
            ),
            (
                "      Quantity:",
                self.running_short_quantity().to_string(),
                " USD",
            ),
        ];
        let running_metric_rows = [
            ("    P/L:", self.running_pl().to_string(), " sats"),
            ("    Order fees:", self.running_fees().to_string(), " sats"),
            ("    Margin:", self.running_margin().to_string(), " sats"),
        ];
        let realized_rows = [
            ("  Funding fees:", self.funding_fees.to_string(), " sats"),
            ("  Realized P/L:", self.realized_pl.to_string(), " sats"),
        ];
        let closed_rows = [
            ("    Trades:", self.closed_len().to_string(), ""),
            ("    Order fees:", self.closed_fees.to_string(), " sats"),
        ];
        let isolated_label_width = running_long_rows
            .iter()
            .chain(running_short_rows.iter())
            .chain(running_metric_rows.iter())
            .chain(realized_rows.iter())
            .chain(closed_rows.iter())
            .map(|(label, _, _)| label.len())
            .max()
            .unwrap_or(0);
        let w = running_long_rows
            .iter()
            .chain(running_short_rows.iter())
            .chain(running_metric_rows.iter())
            .chain(realized_rows.iter())
            .chain(closed_rows.iter())
            .map(|(_, value, _)| value.len())
            .max()
            .unwrap_or(0);

        result.push_str("  Running Positions:\n");
        result.push_str("    Long:\n");
        for (label, value, suffix) in running_long_rows {
            result.push_str(&format!(
                "{label:<isolated_label_width$} {value:>w$}{suffix}\n"
            ));
        }
        result.push_str("    Short:\n");
        for (label, value, suffix) in running_short_rows {
            result.push_str(&format!(
                "{label:<isolated_label_width$} {value:>w$}{suffix}\n"
            ));
        }

        // Isolated - Running Metrics
        result.push_str("  Running Metrics:\n");
        for (label, value, suffix) in running_metric_rows {
            result.push_str(&format!(
                "{label:<isolated_label_width$} {value:>w$}{suffix}\n"
            ));
        }

        // Isolated - Funding / Realized
        for (label, value, suffix) in realized_rows {
            result.push_str(&format!(
                "{label:<isolated_label_width$} {value:>w$}{suffix}\n"
            ));
        }

        // Isolated - Closed
        result.push_str("  Closed:\n");
        for (label, value, suffix) in closed_rows {
            result.push_str(&format!(
                "{label:<isolated_label_width$} {value:>w$}{suffix}\n"
            ));
        }
        result.push('\n');

        result
    }

    /// Returns a formatted table displaying the cross-margin position snapshot.
    pub fn cross_position_table(&self) -> String {
        let cross_position = self.cross_position();
        let market_price = self.market_price();
        let side = cross_position
            .exposure()
            .as_running_params()
            .map_or_else(|| "Neutral".to_string(), |(side, _, _)| side.to_string());
        let price_or_na = |price: Option<Price>| {
            price.map_or_else(|| "N/A".to_string(), |price| format!("{price:.1}"))
        };
        let entry = price_or_na(cross_position.entry_price());
        let liquidation = price_or_na(cross_position.liquidation());

        format!(
            "{:>7} | {:>11} | {:>11} | {:>11} | {:>8} | {:>11} | {:>11} | {:>11}\n{}\n{:>7} | {:>11} | {:>11} | {:>11} | {:>8} | {:>11} | {:>11} | {:>11}",
            "side",
            "quantity",
            "entry",
            "liquidation",
            "leverage",
            "margin",
            "P/L",
            "order fees",
            "-".repeat(102),
            side,
            cross_position.quantity().unsigned_abs(),
            entry,
            liquidation,
            cross_position.leverage().as_u64(),
            cross_position.margin(),
            cross_position.est_running_pl(market_price),
            cross_position.trading_fees(),
        )
    }

    /// Returns a formatted table displaying all running trades with their details including price,
    /// leverage, margin, profit/loss, and order fees.
    pub fn running_trades_table(&self) -> String {
        if self.running_map.is_empty() {
            return "No running trades.".to_string();
        }

        let mut table = String::new();

        table.push_str(&format!(
            "{:>14} | {:>5} | {:>11} | {:>11} | {:>11} | {:>11} | {:>5} | {:>11} | {:>8} | {:>11} | {:>11} | {:>11}",
            "creation time",
            "side",
            "quantity",
            "price",
            "liquidation",
            "stoploss",
            "TSL",
            "takeprofit",
            "leverage",
            "margin",
            "P/L",
            "order fees"
        ));

        table.push_str(&format!("\n{}", "-".repeat(153)));

        for (trade, tsl) in self.running_map.trades_desc() {
            let creation_time = trade
                .created_at()
                .with_timezone(&chrono::Local)
                .format("%y-%m-%d %H:%M");
            let stoploss_str = trade
                .stoploss()
                .map_or("N/A".to_string(), |sl| format!("{:.1}", sl));
            let tsl_str = tsl.map_or("N/A".to_string(), |tsl| format!("{:.1}%", tsl.as_f64()));
            let takeprofit_str = trade
                .takeprofit()
                .map_or("N/A".to_string(), |sl| format!("{:.1}", sl));
            let total_margin = trade.margin().as_i64() + trade.maintenance_margin().max(0);
            let pl = trade.est_pl(self.market_price).floor() as i64;
            let total_fees = trade.opening_fee() + trade.closing_fee();

            table.push_str(&format!(
                "\n{:>14} | {:>5} | {:>11} | {:>11.1} | {:>11.1} | {:>11} | {:>5} | {:>11} | {:>8.2} | {:>11} | {:>11} | {:>11}",
                creation_time,
                trade.side(),
                trade.quantity(),
                trade.price(),
                trade.liquidation(),
                stoploss_str,
                tsl_str,
                takeprofit_str,
                trade.leverage(),
                total_margin,
                pl,
                total_fees
            ));
        }

        table
    }
}

impl fmt::Display for TradingState {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "TradingState:")?;
        for line in self.summary().lines() {
            write!(f, "\n  {line}")?;
        }
        Ok(())
    }
}

/// A chronologically ordered collection of closed trades. Stores completed trades indexed by
/// creation time and UUID. Uses dynamic dispatch to support heterogeneous trade types.
pub struct ClosedTradeHistory {
    trades: BTreeMap<(DateTime<Utc>, Uuid), Arc<dyn TradeClosed>>,
    /// Maps UUID to creation timestamp for O(1) lookups by trade ID.
    id_to_time: HashMap<Uuid, DateTime<Utc>>,
}

impl ClosedTradeHistory {
    /// Creates a new empty closed trade history.
    pub fn new() -> Self {
        Self {
            trades: BTreeMap::new(),
            id_to_time: HashMap::new(),
        }
    }

    /// Adds a closed trade (as Arc) to the history. Returns an error if the trade is not properly
    /// closed.
    pub(super) fn add(&mut self, trade: Arc<dyn TradeClosed>) -> TradeCoreResult<()> {
        if !trade.closed() || trade.exit_price().is_none() || trade.closed_at().is_none() {
            return Err(TradeCoreError::TradeNotClosed {
                trade_id: trade.id(),
            });
        }

        let id = trade.id();
        let created_at = trade.created_at();
        self.trades.insert((created_at, id), trade);
        self.id_to_time.insert(id, created_at);
        Ok(())
    }

    /// Returns a reference to the trade with the given UUID, if it exists.
    pub fn get_by_id(&self, id: Uuid) -> Option<&Arc<dyn TradeClosed>> {
        let creation_ts = self.id_to_time.get(&id)?;
        self.trades.get(&(*creation_ts, id))
    }

    /// Returns `true` if the history contains no trades.
    pub fn is_empty(&self) -> bool {
        self.trades.is_empty()
    }

    /// Returns the number of closed trades in the history.
    pub fn len(&self) -> usize {
        self.trades.len()
    }

    /// Returns an iterator over trades in ascending chronological order (oldest first).
    pub fn iter(&self) -> impl Iterator<Item = &Arc<dyn TradeClosed>> {
        self.trades.values()
    }

    /// Returns an iterator over trades in descending chronological order (newest first).
    pub fn iter_desc(&self) -> impl Iterator<Item = &Arc<dyn TradeClosed>> {
        self.trades.values().rev()
    }

    /// Returns a formatted table displaying all closed trades with their entry/exit details,
    /// profit/loss, and order fees.
    pub fn to_table(&self) -> String {
        if self.trades.is_empty() {
            return "No closed trades.".to_string();
        }

        let mut table = String::new();

        table.push_str(&format!(
            "{:>14} | {:>5} | {:>11} | {:>11} | {:>11} | {:>11} | {:>14} | {:>11} | {:>11} | {:>11}",
            "creation time",
            "side",
            "quantity",
            "margin",
            "price",
            "exit price",
            "exit time",
            "pl",
            "order fees",
            "net P/L"
        ));

        table.push_str(&format!("\n{}", "-".repeat(137)));

        for trade in self.trades.values().rev() {
            let creation_time = trade
                .created_at()
                .with_timezone(&chrono::Local)
                .format("%y-%m-%d %H:%M");

            // Should never panic due to `add` validation
            let exit_price = trade
                .exit_price()
                .expect("`closed` trade must have `exit_price`");
            let exit_time = trade
                .closed_at()
                .expect("`closed` trade must have `closed_at`")
                .with_timezone(&chrono::Local)
                .format("%y-%m-%d %H:%M");

            let pl = trade.pl();
            let total_fees = trade.opening_fee() + trade.closing_fee();
            let net_pl = pl - total_fees as i64;

            table.push_str(&format!(
                "\n{:>14} | {:>5} | {:>11} | {:>11} | {:>11} | {:>11} | {:>14} | {:>11} | {:>11} | {:>11}",
                creation_time,
                trade.side(),
                trade.quantity(),
                trade.margin(),
                trade.price(),
                exit_price,
                exit_time,
                pl,
                total_fees,
                net_pl
            ));
        }

        table
    }
}

impl Clone for ClosedTradeHistory {
    fn clone(&self) -> Self {
        Self {
            trades: self.trades.clone(),
            id_to_time: self.id_to_time.clone(),
        }
    }
}

impl Default for ClosedTradeHistory {
    fn default() -> Self {
        Self::new()
    }
}

impl fmt::Debug for ClosedTradeHistory {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ClosedTradeHistory")
            .field("len", &self.trades.len())
            .finish()
    }
}

/// Stoploss configuration specifying either a fixed price level or a trailing percentage.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Stoploss {
    /// Fixed stoploss at a specific price.
    Fixed(Price),
    /// Trailing stoploss that follows the market price by a percentage.
    Trailing(PercentageCapped),
}

impl Stoploss {
    pub(super) fn evaluate(
        &self,
        tsl_step_size: PercentageCapped,
        side: TradeSide,
        market_price: Price,
    ) -> TradeCoreResult<(Price, Option<TradeTrailingStoploss>)> {
        match self {
            Self::Fixed(price) => Ok((*price, None)),
            Self::Trailing(tsl) => {
                if tsl_step_size > *tsl {
                    return Err(TradeCoreError::InvalidStoplossSmallerThanTrailingStepSize {
                        tsl: *tsl,
                        tsl_step_size,
                    });
                }

                let initial_stoploss_price = match side {
                    TradeSide::Buy => market_price.apply_discount(*tsl).map_err(|e| {
                        TradeCoreError::InvalidPriceApplyDiscount {
                            price: market_price,
                            discount: *tsl,
                            e,
                        }
                    })?,
                    TradeSide::Sell => market_price.apply_gain((*tsl).into()).map_err(|e| {
                        TradeCoreError::InvalidPriceApplyGain {
                            price: market_price,
                            gain: (*tsl).into(),
                            e,
                        }
                    })?,
                };

                Ok((initial_stoploss_price, Some(TradeTrailingStoploss(*tsl))))
            }
        }
    }

    /// Creates a fixed stoploss at the specified price.
    pub fn fixed(stoploss_price: Price) -> Self {
        Self::Fixed(stoploss_price)
    }

    /// Creates a trailing stoploss with the specified percentage.
    pub fn trailing(stoploss_perc: PercentageCapped) -> Self {
        Self::Trailing(stoploss_perc)
    }
}

impl From<Price> for Stoploss {
    fn from(value: Price) -> Self {
        Self::Fixed(value)
    }
}

impl From<PercentageCapped> for Stoploss {
    fn from(value: PercentageCapped) -> Self {
        Self::Trailing(value)
    }
}

/// Metadata for a trailing stoploss that has been validated and applied to a trade. Wraps a
/// percentage value that determines how the stoploss follows market price movements.
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
pub struct TradeTrailingStoploss(PercentageCapped);

impl TradeTrailingStoploss {
    pub(crate) fn prev_validated(tsl: PercentageCapped) -> Self {
        Self(tsl)
    }

    /// Returns the trailing stoploss percentage as an f64 value.
    pub fn as_f64(self) -> f64 {
        self.0.as_f64()
    }
}

impl From<TradeTrailingStoploss> for f64 {
    fn from(value: TradeTrailingStoploss) -> Self {
        value.0.as_f64()
    }
}

impl From<TradeTrailingStoploss> for PercentageCapped {
    fn from(value: TradeTrailingStoploss) -> Self {
        value.0
    }
}

impl From<TradeTrailingStoploss> for Percentage {
    fn from(value: TradeTrailingStoploss) -> Self {
        value.0.into()
    }
}

/// Validated request for a market isolated-margin order.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IsolatedOrderRequest {
    side: TradeSide,
    size: TradeSize,
    leverage: Leverage,
    stoploss: Option<Stoploss>,
    takeprofit: Option<Price>,
    client_id: Option<ClientId>,
}

impl IsolatedOrderRequest {
    /// Creates an isolated-margin market order request from its required fields.
    pub fn market(side: TradeSide, size: TradeSize, leverage: Leverage) -> Self {
        Self {
            side,
            size,
            leverage,
            stoploss: None,
            takeprofit: None,
            client_id: None,
        }
    }

    /// Sets a stoploss on the request.
    pub fn with_stoploss(
        mut self,
        stoploss: Stoploss,
    ) -> Result<Self, IsolatedOrderValidationError> {
        Self::validate_fixed_risk_ordering(self.side, Some(&stoploss), self.takeprofit)?;
        self.stoploss = Some(stoploss);

        Ok(self)
    }

    /// Sets a takeprofit on the request.
    pub fn with_takeprofit(
        mut self,
        takeprofit: Price,
    ) -> Result<Self, IsolatedOrderValidationError> {
        Self::validate_fixed_risk_ordering(self.side, self.stoploss.as_ref(), Some(takeprofit))?;
        self.takeprofit = Some(takeprofit);

        Ok(self)
    }

    /// Sets a client ID on the request.
    pub fn with_client_id(mut self, client_id: ClientId) -> Self {
        self.client_id = Some(client_id);
        self
    }

    fn validate_fixed_risk_ordering(
        side: TradeSide,
        stoploss: Option<&Stoploss>,
        takeprofit: Option<Price>,
    ) -> Result<(), IsolatedOrderValidationError> {
        let (Some(Stoploss::Fixed(stoploss)), Some(takeprofit)) = (stoploss, takeprofit) else {
            return Ok(());
        };

        let valid = match side {
            TradeSide::Buy => *stoploss < takeprofit,
            TradeSide::Sell => *stoploss > takeprofit,
        };

        if !valid {
            return Err(IsolatedOrderValidationError::InvalidRiskBounds {
                side,
                stoploss: *stoploss,
                takeprofit,
            });
        }

        Ok(())
    }

    /// Returns the order side.
    pub fn side(&self) -> TradeSide {
        self.side
    }

    /// Returns the requested isolated trade size.
    pub fn size(&self) -> TradeSize {
        self.size
    }

    /// Returns the requested isolated trade leverage.
    pub fn leverage(&self) -> Leverage {
        self.leverage
    }

    /// Returns the requested stoploss, if any.
    pub fn stoploss(&self) -> Option<&Stoploss> {
        self.stoploss.as_ref()
    }

    /// Returns the requested takeprofit, if any.
    pub fn takeprofit(&self) -> Option<Price> {
        self.takeprofit
    }

    /// Returns the requested client ID, if any.
    pub fn client_id(&self) -> Option<&ClientId> {
        self.client_id.as_ref()
    }

    pub(crate) fn into_isolated_order_parts(
        self,
    ) -> (
        TradeSide,
        TradeSize,
        Leverage,
        Option<Stoploss>,
        Option<Price>,
        Option<ClientId>,
    ) {
        (
            self.side,
            self.size,
            self.leverage,
            self.stoploss,
            self.takeprofit,
            self.client_id,
        )
    }
}

/// Validated request for a cross-margin market order.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CrossOrderRequest {
    side: TradeSide,
    quantity: OrderQuantity,
    client_id: Option<ClientId>,
}

impl CrossOrderRequest {
    /// Creates a cross-margin market order request from its required fields.
    pub fn market(side: TradeSide, quantity: OrderQuantity) -> Self {
        Self {
            side,
            quantity,
            client_id: None,
        }
    }

    /// Sets a client ID on the request.
    pub fn with_client_id(mut self, client_id: ClientId) -> Self {
        self.client_id = Some(client_id);
        self
    }

    /// Returns the order side.
    pub fn side(&self) -> TradeSide {
        self.side
    }

    /// Returns the requested cross-margin order quantity.
    pub fn quantity(&self) -> OrderQuantity {
        self.quantity
    }

    /// Returns the requested client ID, if any.
    pub fn client_id(&self) -> Option<&ClientId> {
        self.client_id.as_ref()
    }

    pub(crate) fn into_cross_order_parts(self) -> (TradeSide, OrderQuantity, Option<ClientId>) {
        (self.side, self.quantity, self.client_id)
    }
}

/// Trait for executing trading operations with explicit isolated and cross-margin namespaces.
/// Implementors provide the core trading functionality for both backtesting and live trading.
#[async_trait]
pub trait TradeExecutor: Send + Sync {
    /// Places a validated isolated-margin market order.
    async fn isolated_order(&self, request: IsolatedOrderRequest) -> TradeExecutorResult<Uuid>;

    /// Places an isolated-margin market long order.
    async fn isolated_order_market_long(
        &self,
        size: TradeSize,
        leverage: Leverage,
        stoploss: Option<Stoploss>,
        takeprofit: Option<Price>,
        client_id: Option<ClientId>,
    ) -> TradeExecutorResult<Uuid> {
        let mut request = IsolatedOrderRequest::market(TradeSide::Buy, size, leverage);
        if let Some(stoploss) = stoploss {
            request = request.with_stoploss(stoploss)?;
        }
        if let Some(takeprofit) = takeprofit {
            request = request.with_takeprofit(takeprofit)?;
        }
        if let Some(client_id) = client_id {
            request = request.with_client_id(client_id);
        }

        self.isolated_order(request).await
    }

    /// Places an isolated-margin market short order.
    async fn isolated_order_market_short(
        &self,
        size: TradeSize,
        leverage: Leverage,
        stoploss: Option<Stoploss>,
        takeprofit: Option<Price>,
        client_id: Option<ClientId>,
    ) -> TradeExecutorResult<Uuid> {
        let mut request = IsolatedOrderRequest::market(TradeSide::Sell, size, leverage);
        if let Some(stoploss) = stoploss {
            request = request.with_stoploss(stoploss)?;
        }
        if let Some(takeprofit) = takeprofit {
            request = request.with_takeprofit(takeprofit)?;
        }
        if let Some(client_id) = client_id {
            request = request.with_client_id(client_id);
        }

        self.isolated_order(request).await
    }

    /// Adds margin to an existing isolated trade, reducing its leverage.
    async fn isolated_trade_add_margin(
        &self,
        trade_id: Uuid,
        amount: NonZeroU64,
    ) -> TradeExecutorResult<()>;

    /// Withdraws profit and/or margin from a running isolated trade without closing the position.
    async fn isolated_trade_cash_in(
        &self,
        trade_id: Uuid,
        amount: NonZeroU64,
    ) -> TradeExecutorResult<()>;

    /// Closes a specific isolated trade by its ID.
    async fn isolated_order_close(&self, trade_id: Uuid) -> TradeExecutorResult<()>;

    /// Closes all isolated long positions. Returns the UUIDs of the closed trades.
    async fn isolated_order_close_longs(&self) -> TradeExecutorResult<Vec<Uuid>>;

    /// Closes all isolated short positions. Returns the UUIDs of the closed trades.
    async fn isolated_order_close_shorts(&self) -> TradeExecutorResult<Vec<Uuid>>;

    /// Closes all isolated positions. Returns the UUIDs of the closed trades.
    async fn isolated_order_close_all(&self) -> TradeExecutorResult<Vec<Uuid>>;

    /// Transfers satoshis from isolated/free balance into the cross-margin account and returns the
    /// updated cross position.
    async fn cross_deposit(
        &self,
        amount: NonZeroU64,
    ) -> TradeExecutorResult<Arc<dyn CrossPositionCore>>;

    /// Transfers satoshis from the cross-margin account back to isolated/free balance and returns
    /// the updated cross position.
    async fn cross_withdraw(
        &self,
        amount: NonZeroU64,
    ) -> TradeExecutorResult<Arc<dyn CrossPositionCore>>;

    /// Sets the account-level cross-margin leverage and returns the updated cross position.
    async fn cross_set_leverage(
        &self,
        leverage: CrossLeverage,
    ) -> TradeExecutorResult<Arc<dyn CrossPositionCore>>;

    /// Places a validated cross-margin market order and returns the cross-order UUID.
    async fn cross_order(&self, request: CrossOrderRequest) -> TradeExecutorResult<Uuid>;

    /// Places a cross-margin market long order and returns the cross-order UUID.
    async fn cross_order_market_long(&self, quantity: OrderQuantity) -> TradeExecutorResult<Uuid> {
        self.cross_order(CrossOrderRequest::market(TradeSide::Buy, quantity))
            .await
    }

    /// Places a cross-margin market short order and returns the cross-order UUID.
    async fn cross_order_market_short(&self, quantity: OrderQuantity) -> TradeExecutorResult<Uuid> {
        self.cross_order(CrossOrderRequest::market(TradeSide::Sell, quantity))
            .await
    }

    /// Closes the full cross-margin position, returning the closing cross-order UUID when a
    /// position was open.
    async fn cross_order_close_position(&self) -> TradeExecutorResult<Option<Uuid>>;

    /// Returns the current trading state including balance, positions, and metrics.
    async fn trading_state(&self) -> TradeExecutorResult<TradingState>;
}

/// Trait for processing trading signals and making trading decisions.
///
/// Signal operators receive evaluated signals and determine when to place orders, close positions,
/// or modify margin. The type parameter `S` represents the signal type that this operator handles.
///
/// # Type Parameter
///
/// * `S` - The signal type this operator processes. This should match the signal type produced by
///   the evaluators being used.
#[async_trait]
pub trait SignalOperator<S: Signal>: Send + Sync {
    /// Sets the trade executor that should be used to execute trading operations.
    fn set_trade_executor(&mut self, trade_executor: Arc<dyn TradeExecutor>) -> GeneralResult<()>;

    /// Processes a trading signal and executes trading actions via the [`TradeExecutor`] that was
    /// set.
    async fn process_signal(&self, signal: &S) -> GeneralResult<()>;
}

pub(crate) struct WrappedSignalOperator<S: Signal>(Box<dyn SignalOperator<S>>);

impl<S: Signal> WrappedSignalOperator<S> {
    pub fn set_trade_executor(
        &mut self,
        trade_executor: Arc<dyn TradeExecutor>,
    ) -> TradeCoreResult<()> {
        panic::catch_unwind(AssertUnwindSafe(|| {
            self.0.set_trade_executor(trade_executor)
        }))
        .map_err(|e| TradeCoreError::SignalOperatorSetTradeExecutorPanicked(e.into()))?
        .map_err(|e| TradeCoreError::SignalOperatorSetTradeExecutorError(e.to_string()))
    }

    pub async fn process_signal(&self, signal: &S) -> TradeCoreResult<()> {
        FutureExt::catch_unwind(AssertUnwindSafe(self.0.process_signal(signal)))
            .await
            .map_err(|e| TradeCoreError::SignalOperatorProcessSignalPanicked(e.into()))?
            .map_err(|e| TradeCoreError::SignalOperatorProcessSignalError(e.to_string()))
    }
}

impl<S: Signal> From<Box<dyn SignalOperator<S>>> for WrappedSignalOperator<S> {
    fn from(value: Box<dyn SignalOperator<S>>) -> Self {
        Self(value)
    }
}

/// Placeholder signal type for raw operators that don't use signals.
#[derive(Debug, Clone, Copy)]
pub struct Raw;

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

/// Trait for implementing direct trading logic without intermediate signal generation. Raw operators
/// receive candlestick data and make trading decisions directly, providing more flexible control
/// over the trading strategy implementation.
#[async_trait]
pub trait RawOperator: Send + Sync {
    /// Sets the trade executor that should be used to execute trading operations.
    fn set_trade_executor(&mut self, trade_executor: Arc<dyn TradeExecutor>) -> GeneralResult<()>;

    /// Returns the lookback configuration for this operator, or `None` if no historical candle
    /// data is required.
    fn lookback(&self) -> Option<Lookback>;

    /// Returns the minimum interval between successive iterations of the operator.
    fn min_iteration_interval(&self) -> MinIterationInterval;

    /// Processes candlestick data and executes trading actions via the [`TradeExecutor`] that was
    /// set. Called periodically according to the minimum iteration interval.
    async fn iterate(&self, candles: &[OhlcCandleRow]) -> GeneralResult<()>;
}

pub(super) struct WrappedRawOperator(Box<dyn RawOperator>);

impl WrappedRawOperator {
    pub fn set_trade_executor(
        &mut self,
        trade_executor: Arc<dyn TradeExecutor>,
    ) -> TradeCoreResult<()> {
        panic::catch_unwind(AssertUnwindSafe(|| {
            self.0.set_trade_executor(trade_executor)
        }))
        .map_err(|e| TradeCoreError::RawOperatorSetTradeExecutorPanicked(e.into()))?
        .map_err(|e| TradeCoreError::RawOperatorSetTradeExecutorError(e.to_string()))
    }

    pub fn lookback(&self) -> TradeCoreResult<Option<Lookback>> {
        let lookback = panic::catch_unwind(AssertUnwindSafe(|| self.0.lookback()))
            .map_err(|e| TradeCoreError::RawOperatorLookbackPanicked(e.into()))?;
        Ok(lookback)
    }

    pub fn min_iteration_interval(&self) -> TradeCoreResult<MinIterationInterval> {
        let interval = panic::catch_unwind(AssertUnwindSafe(|| self.0.min_iteration_interval()))
            .map_err(|e| TradeCoreError::RawOperatorMinIterationIntervalPanicked(e.into()))?;
        Ok(interval)
    }

    pub async fn iterate(&self, candles: &[OhlcCandleRow]) -> TradeCoreResult<()> {
        FutureExt::catch_unwind(AssertUnwindSafe(self.0.iterate(candles)))
            .await
            .map_err(|e| TradeCoreError::RawOperatorIteratePanicked(e.into()))?
            .map_err(|e| TradeCoreError::RawOperatorIterateError(e.to_string()))
    }
}

impl From<Box<dyn RawOperator>> for WrappedRawOperator {
    fn from(value: Box<dyn RawOperator>) -> Self {
        Self(value)
    }
}

pub(super) trait TradeRunningExt: TradeRunning {
    /// Calculates the price that must be reached to trigger a trailing stoploss update.
    ///
    /// For the stoploss to only trail in the favorable direction (UP for longs, DOWN for shorts),
    /// we must use division rather than multiplication in the trigger formula.
    ///
    /// For longs, when the trigger fires we calculate: `new_sl = trigger_price × (1 - tsl)`
    /// We want to guarantee: `new_sl >= curr_sl × (1 + step)`
    ///
    /// Solving for the trigger price:
    ///   `trigger_price × (1 - tsl) >= curr_sl × (1 + step)`
    ///   `trigger_price >= curr_sl × (1 + step) / (1 - tsl)`
    ///
    /// Note: We must use division `/ (1 - tsl)` rather than the simpler multiplication
    /// `× (1 + tsl)`, in order to guarantee that `new_sl >= next_stoploss`. Rounding errors
    /// from other methods may compound over updates, causing the stoploss to drift and
    /// potentially cross the liquidation price.
    fn next_stoploss_update_trigger(
        &self,
        tsl_step_size: PercentageCapped,
        trade_tsl: TradeTrailingStoploss,
    ) -> TradeCoreResult<Price> {
        let tsl = trade_tsl.into();
        if tsl_step_size > tsl {
            return Err(TradeCoreError::InvalidStoplossSmallerThanTrailingStepSize {
                tsl,
                tsl_step_size,
            });
        }

        let curr_stoploss =
            self.stoploss()
                .ok_or_else(|| TradeCoreError::NoNextTriggerTradeStoplossNotSet {
                    trade_id: self.id(),
                })?;

        let price_trigger = match self.side() {
            TradeSide::Buy => {
                let next_stoploss =
                    curr_stoploss
                        .apply_gain(tsl_step_size.into())
                        .map_err(|e| TradeCoreError::InvalidPriceApplyGain {
                            price: curr_stoploss,
                            gain: tsl_step_size.into(),
                            e,
                        })?;
                let tsl_factor = 1.0 - trade_tsl.as_f64() / 100.0;
                let trigger_price = next_stoploss.as_f64() / tsl_factor;
                Price::round_up(trigger_price).map_err(|e| {
                    TradeCoreError::InvalidPriceRounding {
                        price: trigger_price,
                        e,
                    }
                })?
            }
            TradeSide::Sell => {
                let next_stoploss = curr_stoploss.apply_discount(tsl_step_size).map_err(|e| {
                    TradeCoreError::InvalidPriceApplyDiscount {
                        price: curr_stoploss,
                        discount: tsl_step_size,
                        e,
                    }
                })?;
                let tsl_factor = 1.0 + trade_tsl.as_f64() / 100.0;
                let trigger_price = next_stoploss.as_f64() / tsl_factor;
                Price::round_down(trigger_price).map_err(|e| {
                    TradeCoreError::InvalidPriceRounding {
                        price: trigger_price,
                        e,
                    }
                })?
            }
        };

        Ok(price_trigger)
    }

    fn eval_trigger_bounds(
        &self,
        tsl_step_size: PercentageCapped,
        trade_tsl: Option<TradeTrailingStoploss>,
    ) -> TradeCoreResult<(Price, Price)> {
        let next_stoploss_update_trigger = trade_tsl
            .map(|tsl| self.next_stoploss_update_trigger(tsl_step_size, tsl))
            .transpose()?;

        match self.side() {
            TradeSide::Buy => {
                let lower_bound = self.stoploss().unwrap_or(self.liquidation());
                let takeprofit_trigger = self.takeprofit().unwrap_or(Price::MAX);
                let upper_bound =
                    takeprofit_trigger.min(next_stoploss_update_trigger.unwrap_or(Price::MAX));

                Ok((lower_bound, upper_bound))
            }
            TradeSide::Sell => {
                let takeprofit_trigger = self.takeprofit().unwrap_or(Price::MIN);
                let lower_bound =
                    takeprofit_trigger.max(next_stoploss_update_trigger.unwrap_or(Price::MIN));
                let upper_bound = self.stoploss().unwrap_or(self.liquidation());

                Ok((lower_bound, upper_bound))
            }
        }
    }

    fn was_closed_on_range(&self, range_min: f64, range_max: f64) -> bool {
        match self.side() {
            TradeSide::Buy => {
                let stoploss_reached = self
                    .stoploss()
                    .is_some_and(|stoploss| range_min <= stoploss.as_f64());
                let liquidation_reached = range_min <= self.liquidation().as_f64();
                let takeprofit_reached = self
                    .takeprofit()
                    .is_some_and(|takeprofit| range_max >= takeprofit.as_f64());

                stoploss_reached || liquidation_reached || takeprofit_reached
            }
            TradeSide::Sell => {
                let stoploss_reached = self
                    .stoploss()
                    .is_some_and(|stoploss| range_max >= stoploss.as_f64());
                let liquidation_reached = range_max >= self.liquidation().as_f64();
                let takeprofit_reached = self
                    .takeprofit()
                    .is_some_and(|takeprofit| range_min <= takeprofit.as_f64());

                stoploss_reached || liquidation_reached || takeprofit_reached
            }
        }
    }

    fn eval_new_stoploss_on_range(
        &self,
        tsl_step_size: PercentageCapped,
        trade_tsl: TradeTrailingStoploss,
        range_min: f64,
        range_max: f64,
    ) -> TradeCoreResult<Option<Price>> {
        let next_stoploss_update_trigger = self
            .next_stoploss_update_trigger(tsl_step_size, trade_tsl)?
            .as_f64();

        let new_stoploss = match self.side() {
            TradeSide::Buy => {
                if range_max >= next_stoploss_update_trigger {
                    let new_stoploss = Price::round(range_max).map_err(|e| {
                        TradeCoreError::InvalidPriceRounding {
                            price: range_max,
                            e,
                        }
                    })?;
                    let new_stoploss =
                        new_stoploss.apply_discount(trade_tsl.into()).map_err(|e| {
                            TradeCoreError::InvalidPriceApplyDiscount {
                                price: new_stoploss,
                                discount: trade_tsl.into(),
                                e,
                            }
                        })?;

                    Some(new_stoploss)
                } else {
                    None
                }
            }
            TradeSide::Sell => {
                if range_min <= next_stoploss_update_trigger {
                    let new_stoploss = Price::round(range_min).map_err(|e| {
                        TradeCoreError::InvalidPriceRounding {
                            price: range_min,
                            e,
                        }
                    })?;
                    let new_stoploss = new_stoploss.apply_gain(trade_tsl.into()).map_err(|e| {
                        TradeCoreError::InvalidPriceApplyGain {
                            price: new_stoploss,
                            gain: trade_tsl.into(),
                            e,
                        }
                    })?;

                    Some(new_stoploss)
                } else {
                    None
                }
            }
        };

        // Skip no-op updates: rounding can collapse `new_sl` back to `curr_sl`
        let new_stoploss = new_stoploss.filter(|new_sl| Some(*new_sl) != self.stoploss());

        Ok(new_stoploss)
    }
}

// Implement `TradeRunningExt` for any type that implements `TradeRunning`
impl<T: TradeRunning + ?Sized> TradeRunningExt for T {}

#[derive(Debug, Clone)]
pub(super) enum PriceTrigger {
    NotSet,
    Set { min: Price, max: Price },
}

impl PriceTrigger {
    pub fn new() -> Self {
        Self::NotSet
    }

    pub fn update<T: TradeRunningExt + ?Sized>(
        &mut self,
        tsl_step_size: PercentageCapped,
        trade: &T,
        trade_tsl: Option<TradeTrailingStoploss>,
    ) -> TradeCoreResult<()> {
        let (mut new_min, mut new_max) = trade.eval_trigger_bounds(tsl_step_size, trade_tsl)?;

        if let PriceTrigger::Set { min, max } = *self {
            new_min = new_min.max(min);
            new_max = new_max.min(max);
        }

        *self = PriceTrigger::Set {
            min: new_min,
            max: new_max,
        };

        Ok(())
    }

    pub fn was_reached(&self, market_price: f64) -> bool {
        match self {
            PriceTrigger::NotSet => false,
            PriceTrigger::Set { min, max } => {
                market_price <= min.as_f64() || market_price >= max.as_f64()
            }
        }
    }
}