quantoxide 0.5.5

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
use std::{
    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::api_v3::{
    error::TradeValidationError,
    models::{
        ClientId, Leverage, Margin, Percentage, PercentageCapped, Price, Quantity, 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::{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) -> Quantity;

    /// 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) -> Quantity {
        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::api_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::api_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::api_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,
}

/// 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,
}

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,
    ) -> 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,
        }
    }

    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())
    }

    /// 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 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 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 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 fees across both running and closed trades (in satoshis).
    pub fn fees(&self) -> u64 {
        self.running_fees() + self.closed_fees()
    }

    /// 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));

        // Running Positions (aligned across Long and Short)
        let lt = self.running_long_len().to_string();
        let lm = self.running_long_margin().to_string();
        let lq = self.running_long_quantity().to_string();
        let st = self.running_short_len().to_string();
        let sm = self.running_short_margin().to_string();
        let sq = self.running_short_quantity().to_string();
        let w = [&lt, &lm, &lq, &st, &sm, &sq]
            .iter()
            .map(|s| s.len())
            .max()
            .unwrap_or(0);
        result.push_str("Running Positions:\n");
        result.push_str("  Long:\n");
        result.push_str(&format!("    Trades:   {:>w$}\n", lt));
        result.push_str(&format!("    Margin:   {:>w$} sats\n", lm));
        result.push_str(&format!("    Quantity: {:>w$} USD\n", lq));
        result.push_str("  Short:\n");
        result.push_str(&format!("    Trades:   {:>w$}\n", st));
        result.push_str(&format!("    Margin:   {:>w$} sats\n", sm));
        result.push_str(&format!("    Quantity: {:>w$} USD\n\n", sq));

        // Running Metrics
        let rpl = self.running_pl().to_string();
        let rf = self.running_fees().to_string();
        let rm = self.running_margin().to_string();
        let w = rpl.len().max(rf.len()).max(rm.len());
        result.push_str("Running Metrics:\n");
        result.push_str(&format!("  P/L:    {:>w$} sats\n", rpl));
        result.push_str(&format!("  Fees:   {:>w$} sats\n", rf));
        result.push_str(&format!("  Margin: {:>w$} sats\n\n", rm));

        // Funding / Realized
        let ff = self.funding_fees.to_string();
        let rp = self.realized_pl.to_string();
        let w = ff.len().max(rp.len());
        result.push_str(&format!("Funding fees: {:>w$} sats\n", ff));
        result.push_str(&format!("Realized P/L: {:>w$} sats\n\n", rp));

        // Closed
        let ct = self.closed_len().to_string();
        let cf = self.closed_fees.to_string();
        let w = ct.len().max(cf.len());
        result.push_str("Closed:\n");
        result.push_str(&format!("  Trades: {:>w$}\n", ct));
        result.push_str(&format!("  Fees:   {:>w$} sats", cf));

        result
    }

    /// Returns a formatted table displaying all running trades with their details including price,
    /// leverage, margin, profit/loss, and 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",
            "pl",
            "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 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",
            "fees",
            "net_pl"
        ));

        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()
    }
}

/// Trait for executing trading operations including opening/closing positions and managing margin.
/// Implementors provide the core trading functionality for both backtesting and live trading.
#[async_trait]
pub trait TradeExecutor: Send + Sync {
    /// Opens a new long position with the specified size, leverage, and optional risk management
    /// parameters. Returns the UUID of the created trade.
    async fn open_long(
        &self,
        size: TradeSize,
        leverage: Leverage,
        stoploss: Option<Stoploss>,
        takeprofit: Option<Price>,
        client_id: Option<ClientId>,
    ) -> TradeExecutorResult<Uuid>;

    /// Opens a new short position with the specified size, leverage, and optional risk management
    /// parameters. Returns the UUID of the created trade.
    async fn open_short(
        &self,
        size: TradeSize,
        leverage: Leverage,
        stoploss: Option<Stoploss>,
        takeprofit: Option<Price>,
        client_id: Option<ClientId>,
    ) -> TradeExecutorResult<Uuid>;

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

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

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

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

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

    /// Closes all open positions (both long and short). Returns the UUIDs of the closed trades.
    async fn close_all(&self) -> TradeExecutorResult<Vec<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 open, close, or modify
/// positions. 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()
            }
        }
    }
}