rustrade 0.4.0

Framework for building high-performance live-trading, paper-trading and back-testing systems
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
use chrono::{DateTime, Utc};
use derive_more::Constructor;
use indexmap::IndexMap;
use rust_decimal::Decimal;
pub use rustrade_execution::order::id::PositionId;
use rustrade_execution::trade::{AssetFees, Trade, TradeId};
use rustrade_instrument::{Side, asset::AssetIndex, instrument::InstrumentIndex};
use serde::{Deserialize, Serialize};
use std::fmt::Debug;
use tracing::error;

/// Order Management System mode governing how positions are tracked.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, Serialize)]
pub enum OmsMode {
    /// At most one position per instrument. Trades that cross zero flip the
    /// position. This is the default and is backward-compatible with the
    /// original `PositionManager` behaviour.
    #[default]
    Netting,
    /// Multiple concurrent positions per instrument, each identified by a
    /// `PositionId` derived from the opening order's `ClientOrderId`.
    ///
    /// Enable via [`EngineStateBuilder::oms_mode`](crate::engine::state::builder::EngineStateBuilder::oms_mode).
    /// Note that `OmsMode` is applied uniformly to all instruments; per-instrument
    /// override is a future enhancement.
    Hedging,
}

/// Manages open positions for a single instrument.
///
/// Supports two OMS modes (configurable at construction):
/// - `Netting` (default): at most one entry; same flip/close logic as before.
/// - `Hedging`: multiple concurrent entries, keyed by `PositionId`.
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
pub struct PositionManager<AssetKey = AssetIndex, InstrumentKey = InstrumentIndex> {
    pub mode: OmsMode,
    /// All currently open positions keyed by `PositionId`.
    pub positions: IndexMap<PositionId, Position<AssetKey, InstrumentKey>>,
}

impl<AssetKey, InstrumentKey> Default for PositionManager<AssetKey, InstrumentKey> {
    fn default() -> Self {
        Self::new(OmsMode::Netting)
    }
}

impl<AssetKey, InstrumentKey> PositionManager<AssetKey, InstrumentKey> {
    /// Construct a new `PositionManager` with the given OMS mode and no open positions.
    pub fn new(mode: OmsMode) -> Self {
        // Pre-allocate capacity for 1 entry in Netting mode (the common case).
        // Hedging mode may grow beyond this, but starting at 1 avoids the
        // reallocation on the first fill for the majority of use cases.
        Self {
            mode,
            positions: IndexMap::with_capacity(1),
        }
    }
}

impl<AssetKey: Debug + Clone, InstrumentKey> PositionManager<AssetKey, InstrumentKey> {
    /// Updates the current position state based on a new trade.
    ///
    /// This method handles:
    /// - Opening a new position if none exists
    /// - Updating an existing position (increase/decrease/close)
    /// - Handling position flips (close existing & open new with any remaining trade quantity)
    ///
    /// In `Netting` mode the `PositionId` is derived deterministically as `"netting"`.
    /// In `Hedging` mode the `PositionId` is derived from `trade.order_id`.
    ///
    /// # Warning — Hedging mode callers
    ///
    /// In `OmsMode::Hedging`, this method derives the `PositionId` directly from
    /// `trade.order_id`. The engine's actual fill routing instead resolves the
    /// `PositionId` via a `ClientOrderId → PositionId` lookup table populated at
    /// order submission time (see `InstrumentState::update_from_trade`). Calling this
    /// method directly in Hedging mode bypasses that lookup and will open a spurious
    /// position slot under the exchange order ID rather than the caller's chosen
    /// `PositionId`. Prefer routing fills through `InstrumentState::update_from_trade`,
    /// or call `update_from_trade_with_id` with the already-resolved `PositionId`.
    ///
    /// # Arguments
    /// * `trade` - The trade to process
    /// * `contract_size` - Contract multiplier for derivatives (1 for spot, 100 for standard options)
    pub fn update_from_trade(
        &mut self,
        trade: &Trade<AssetKey, InstrumentKey>,
        contract_size: Decimal,
    ) -> Option<PositionExited<AssetKey, InstrumentKey>>
    where
        InstrumentKey: Debug + Clone + PartialEq,
    {
        let position_id = match self.mode {
            // Fixed key: there is at most one netting position per instrument.
            OmsMode::Netting => PositionId::NETTING,
            // Derive from the order that caused this fill.
            OmsMode::Hedging => PositionId::new(trade.order_id.0.clone()),
        };
        self.update_from_trade_with_id(trade, &position_id, contract_size)
    }

    /// Updates position state routing to a specific `PositionId`.
    ///
    /// Suitable for callers (e.g. expiry settlement) that have already resolved
    /// the correct `PositionId` and want to bypass the automatic derivation.
    ///
    /// # Arguments
    /// * `trade` - The trade to process
    /// * `position_id` - The resolved position ID to route the fill to
    /// * `contract_size` - Contract multiplier for derivatives (1 for spot, 100 for standard options)
    ///
    /// # Fee model
    ///
    /// This method does **not** apply a fee model — `trade.fees.fees` is used as-is.
    /// The caller is responsible for ensuring the fee value is correct before calling.
    /// For contract expiry settlement the caller must set fees to `Decimal::ZERO` (exchange
    /// settlement commission, if any, is not modelled and must be tracked separately).
    pub fn update_from_trade_with_id(
        &mut self,
        trade: &Trade<AssetKey, InstrumentKey>,
        position_id: &PositionId,
        contract_size: Decimal,
    ) -> Option<PositionExited<AssetKey, InstrumentKey>>
    where
        InstrumentKey: Debug + Clone + PartialEq,
    {
        // Use shift_remove (not swap_remove) to preserve relative order of positions
        // not touched by this update. Updated positions move to insertion-order tail.
        // swap_remove would reorder arbitrarily on every fill.
        let (updated, closed) = match self.positions.shift_remove(position_id) {
            Some(mut position) => {
                // Existing position already has contract_size set. Update it in case
                // the instrument definition changed (rare but possible with dynamic configs).
                position.contract_size = contract_size;
                position.update_from_trade(trade)
            }
            None => {
                // New position — set contract_size before any PnL calculations.
                let mut position = Position::from(trade);
                position.contract_size = contract_size;
                (Some(position), None)
            }
        };

        // In Hedging mode a fill that crosses zero causes a position flip: the
        // new opposite-side position is re-inserted under the same PositionId.
        // Subsequent fills routed to that ID will update the wrong-direction position.
        // Strategies must close positions explicitly rather than relying on flip semantics.
        if self.mode == OmsMode::Hedging
            && let (Some(new_pos), Some(exited)) = (&updated, &closed)
        {
            error!(
                %position_id,
                closed_side = ?exited.side,
                new_side = ?new_pos.side,
                "Hedging mode: fill crossed zero — position flipped under same PositionId. \
                 Subsequent fills routed to this ID will update the opposite-direction \
                 position silently, corrupting PnL. Strategies MUST close positions \
                 explicitly; never rely on flip semantics in Hedging mode.",
            );
        }

        // Set the PositionId on the closed PositionExited so upstream consumers
        // (e.g., StateReplicaManager) can target the correct position slot.
        let closed = closed.map(|mut e| {
            e.position_id = position_id.clone();
            e
        });

        if let Some(pos) = updated {
            self.positions.insert(position_id.clone(), pos);
        }

        closed
    }
}

/// Represents an open trading position for a specific instrument.
///
/// # Type Parameters
/// - `AssetKey`: The type representing the asset used for fees (e.g. AssetIndex, QuoteAsset, etc.)
/// - `InstrumentKey`: The type identifying the traded instrument (e.g. InstrumentIndex, etc.)
///
/// # Examples
/// ## Partially Reduce LONG Position
/// ```rust
/// use rustrade::engine::state::position::Position;
/// use rustrade_execution::order::id::{OrderId, StrategyId};
/// use rustrade_execution::trade::{AssetFees, Trade, TradeId};
/// use rustrade_instrument::asset::QuoteAsset;
/// use rustrade_instrument::instrument::name::InstrumentNameInternal;
/// use rustrade_instrument::Side;
/// use chrono::{DateTime, Utc};
/// use std::str::FromStr;
/// use rust_decimal_macros::dec;
///
/// // Create a new LONG Position from an initial Buy trade
/// let position = Position::from(&Trade {
///     id: TradeId::new("trade_1"),
///     order_id: OrderId::new("order_1"),
///     instrument: InstrumentNameInternal::new("BTC-USD"),
///     strategy: StrategyId::new("strategy_1"),
///     time_exchange: DateTime::from_str("2024-01-01T00:00:00Z").unwrap(),
///     side: Side::Buy,
///     price: dec!(50_000.0),
///     quantity: dec!(0.1),
///     fees: AssetFees::quote_fees(dec!(5.0))
/// });
/// assert_eq!(position.side, Side::Buy);
/// assert_eq!(position.quantity_abs, dec!(0.1));
///
/// // Partially reduce LONG Position from a new Sell Trade
/// let (updated_position, closed_position) = position.update_from_trade(&Trade {
///     id: TradeId::new("trade_2"),
///     order_id: OrderId::new("order_2"),
///     instrument: InstrumentNameInternal::new("BTC-USD"),
///     strategy: StrategyId::new("strategy_1"),
///     time_exchange: DateTime::from_str("2024-01-01T01:00:00Z").unwrap(),
///     side: Side::Sell,
///     price: dec!(60_000.0),
///     quantity: dec!(0.05),
///     fees: AssetFees::quote_fees(dec!(2.5))
/// });
///
/// // LONG Position is still open, but with reduced size
/// let updated_position = updated_position.unwrap();
/// assert_eq!(updated_position.quantity_abs, dec!(0.05));
/// assert_eq!(updated_position.quantity_abs_max, dec!(0.1));
/// assert_eq!(updated_position.pnl_realised, dec!(492.5));
/// assert!(closed_position.is_none());
/// ```
///
/// ## Flip Position - Close SHORT and Open LONG
/// ```rust
/// use rustrade::engine::state::position::Position;
/// use rustrade_execution::order::id::{OrderId, StrategyId};
/// use rustrade_execution::trade::{AssetFees, Trade, TradeId};
/// use rustrade_instrument::asset::QuoteAsset;
/// use rustrade_instrument::instrument::name::InstrumentNameInternal;
/// use rustrade_instrument::Side;
/// use chrono::{DateTime, Utc};
/// use std::str::FromStr;
/// use rust_decimal_macros::dec;
///
/// // Create a new SHORT Position from an initial Sell trade
/// let position = Position::from(&Trade {
///     id: TradeId::new("trade_1"),
///     order_id: OrderId::new("order_1"),
///     instrument: InstrumentNameInternal::new("BTC-USD"),
///     strategy: StrategyId::new("strategy_1"),
///     time_exchange: DateTime::from_str("2024-01-01T00:00:00Z").unwrap(),
///     side: Side::Sell,
///     price: dec!(50_000.0),
///     quantity: dec!(0.1),
///     fees: AssetFees::quote_fees(dec!(5.0))
/// });
/// assert_eq!(position.side, Side::Sell);
/// assert_eq!(position.quantity_abs, dec!(0.1));
///
/// // Close SHORT from a new Buy trade with larger quantity, flipping into a new LONG Position
/// let (new_position, closed_position) = position.update_from_trade(&Trade {
///     id: TradeId::new("trade_2"),
///     order_id: OrderId::new("order_2"),
///     instrument: InstrumentNameInternal::new("BTC-USD"),
///     strategy: StrategyId::new("strategy_1"),
///     time_exchange: DateTime::from_str("2024-01-01T01:00:00Z").unwrap(),
///     side: Side::Buy,
///     price: dec!(40_000.0),
///     quantity: dec!(0.2),
///     fees: AssetFees::quote_fees(dec!(10.0))
/// });
///
/// // Original SHORT Position closed with profit
/// let closed = closed_position.unwrap();
/// assert_eq!(closed.side, Side::Sell);
/// assert_eq!(closed.quantity_abs_max, dec!(0.1));
/// assert_eq!(closed.pnl_realised, dec!(990.0));
///
/// // New LONG Position opened with remaining quantity & proportional fees
/// let new_position = new_position.unwrap();
/// assert_eq!(new_position.side, Side::Buy);
/// assert_eq!(new_position.quantity_abs, dec!(0.1));
/// assert_eq!(new_position.price_entry_average, dec!(40_000.0));
/// assert_eq!(new_position.pnl_realised, dec!(-5.0));
/// ```
#[derive(Debug, Clone, PartialEq, PartialOrd, Deserialize, Serialize, Constructor)]
pub struct Position<AssetKey = AssetIndex, InstrumentKey = InstrumentIndex> {
    /// [`Position`] Instrument identifier (eg/ InstrumentIndex, InstrumentNameInternal, etc.).
    pub instrument: InstrumentKey,

    /// [`Position`] direction (Side::Buy => LONG, Side::Sell => SHORT).
    pub side: Side,

    /// Volume-weighted average entry price across all [`Position`] increasing [`Trade`]s.
    pub price_entry_average: Decimal,

    /// Current absolute [`Position`] quantity.
    pub quantity_abs: Decimal,

    /// Maximum absolute [`Position`] quantity reached by all entry/increase [`Trade`]s.
    pub quantity_abs_max: Decimal,

    /// Estimated unrealised PnL generated from closing the remaining [`Position`] `quantity_abs`.
    ///
    /// Note this includes estimated exit fees.
    pub pnl_unrealised: Decimal,

    /// Cumulative realised PnL from any partially closed [`Position`] `quantity_abs_max`.
    ///
    /// Note this includes fees.
    pub pnl_realised: Decimal,

    /// Cumulative fees paid when entering/increasing [`Position`] quantity.
    pub fees_enter: AssetFees<AssetKey>,

    /// Cumulative fees paid when exiting/reducing [`Position`] quantity.
    pub fees_exit: AssetFees<AssetKey>,

    /// Timestamp of [`Trade`] that triggered the initial [`Position`] entry.
    pub time_enter: DateTime<Utc>,

    /// Timestamp of most recent [`Position`] update.
    ///
    /// Note this could be an update triggered by a [`Trade`], or a `pnl_unrealised` update by a
    /// new market price.
    pub time_exchange_update: DateTime<Utc>,

    /// [`TradeId`]s of all the [`Trade`]s associated with this [`Position`].
    ///
    /// # Memory consideration
    ///
    /// This vector grows unboundedly with each partial fill. For positions with
    /// hundreds of partial fills (e.g., algorithmic averaging into a position),
    /// this can accumulate megabytes of UUID strings. Consider the memory
    /// implications for long-lived positions with high fill counts.
    pub trades: Vec<TradeId>,

    /// Contract multiplier for derivatives (options, futures, perpetuals).
    ///
    /// For spot instruments this is always `1`. For standard equity options it's typically `100`
    /// (each contract represents 100 shares). PnL calculations multiply the price-based PnL
    /// by this value to get the true dollar amount.
    ///
    /// Set by `PositionManager::update_from_trade_with_id` when opening a new position,
    /// inherited from the closing position when flipping.
    #[serde(default = "default_contract_size")]
    pub contract_size: Decimal,
}

fn default_contract_size() -> Decimal {
    Decimal::ONE
}

impl<AssetKey, InstrumentKey> Position<AssetKey, InstrumentKey> {
    /// Updates the [`Position`] state based on a new [`Trade`].
    ///
    /// This method handles various scenarios:
    /// - Increasing an existing [`Position`] (same [`Side`] [`Trade`]).
    /// - Reducing an existing [`Position`] (opposite [`Side`], partially closing some quantity).
    /// - Closing a [`Position`] exactly (opposite [`Side`], fully closing quantity).
    /// - Flipping a [`Position`] - closing and opening a new [`Position`] on the opposite [`Side`].
    ///
    /// # Arguments
    /// * `trade` - The new trade to process
    ///
    /// # Returns
    /// A tuple containing:
    /// - `Option<Position>`: The updated [`Position`], unless it was exactly closed.
    /// - `Option<PositionExited>`: The closed [`PositionExited`], if the [`Position`] was closed.
    pub fn update_from_trade(
        mut self,
        trade: &Trade<AssetKey, InstrumentKey>,
    ) -> (
        Option<Self>,
        Option<PositionExited<AssetKey, InstrumentKey>>,
    )
    where
        AssetKey: Debug + Clone,
        InstrumentKey: Debug + Clone + PartialEq,
    {
        // Sanity check
        if self.instrument != trade.instrument {
            error!(
                position = ?self,
                trade = ?trade,
                "Position tried to be updated from a Trade for a different Instrument - ignoring"
            );
            return (Some(self), None);
        }

        // Add TradeId to current Position
        self.trades.push(trade.id.clone());

        use Side::*;
        match (self.side, trade.side) {
            // Increase LONG/SHORT Position
            (Buy, Buy) | (Sell, Sell) => {
                self.update_price_entry_average(trade);
                self.quantity_abs += trade.quantity.abs();
                if self.quantity_abs > self.quantity_abs_max {
                    self.quantity_abs_max = self.quantity_abs;
                }
                // Use fees_quote when computable; falls back to raw fees.fees only for
                // third-party fee assets (e.g., BNB) where the indexer cannot derive a
                // quote-equivalent. Downstream is responsible for applying a converted
                // fee impact when accurate quote-denominated P&L is required for those
                // assets (see `AssetFees::fees_quote` doc).
                self.pnl_realised -= trade.fees.fees_quote.unwrap_or(trade.fees.fees);
                self.fees_enter.fees += trade.fees.fees;
                self.fees_enter.fees_quote =
                    match (self.fees_enter.fees_quote, trade.fees.fees_quote) {
                        (Some(a), Some(b)) => Some(a + b),
                        _ => None,
                    };
                self.time_exchange_update = trade.time_exchange;
                self.update_pnl_unrealised(trade.price);

                (Some(self), None)
            }
            // Reduce LONG/SHORT Position
            (Buy, Sell) | (Sell, Buy) if self.quantity_abs > trade.quantity.abs() => {
                // Use quote-equivalent fee for P&L; fall back to raw fees.fees for
                // third-party fee assets (caller must layer their own conversion).
                let closed_fee_quote = trade.fees.fees_quote.unwrap_or(trade.fees.fees);
                self.update_pnl_realised(trade.quantity, trade.price, closed_fee_quote);

                // Update remaining Position state
                self.quantity_abs -= trade.quantity.abs();
                self.fees_exit.fees += trade.fees.fees;
                self.fees_exit.fees_quote = match (self.fees_exit.fees_quote, trade.fees.fees_quote)
                {
                    (Some(a), Some(b)) => Some(a + b),
                    _ => None,
                };
                self.time_exchange_update = trade.time_exchange;

                // Update pnl_unrealised for remaining Position
                self.update_pnl_unrealised(trade.price);

                (Some(self), None)
            }
            // Close LONG/SHORT Position (exactly)
            (Buy, Sell) | (Sell, Buy) if self.quantity_abs == trade.quantity.abs() => {
                self.quantity_abs -= trade.quantity.abs();
                self.fees_exit.fees += trade.fees.fees;
                self.fees_exit.fees_quote = match (self.fees_exit.fees_quote, trade.fees.fees_quote)
                {
                    (Some(a), Some(b)) => Some(a + b),
                    _ => None,
                };
                self.time_exchange_update = trade.time_exchange;
                let closed_fee_quote = trade.fees.fees_quote.unwrap_or(trade.fees.fees);
                self.update_pnl_realised(trade.quantity, trade.price, closed_fee_quote);
                self.update_pnl_unrealised(trade.price);

                (None, Some(PositionExited::from(self)))
            }

            // Close LONG/SHORT Position & open SHORT/LONG with remaining trade.quantity
            (Buy, Sell) | (Sell, Buy) if self.quantity_abs < trade.quantity.abs() => {
                // Trade flips Position, so generate theoretical initial Trade for next Position
                let next_position_quantity = trade.quantity.abs() - self.quantity_abs;
                let next_position_fee_enter =
                    trade.fees.fees * (next_position_quantity / trade.quantity.abs());
                let next_position_trade = Trade {
                    id: trade.id.clone(),
                    order_id: trade.order_id.clone(),
                    instrument: trade.instrument.clone(),
                    strategy: trade.strategy.clone(),
                    time_exchange: trade.time_exchange,
                    side: trade.side,
                    price: trade.price,
                    quantity: next_position_quantity,
                    fees: AssetFees {
                        asset: trade.fees.asset.clone(),
                        fees: next_position_fee_enter,
                        fees_quote: trade
                            .fees
                            .fees_quote
                            .map(|fq| fq * (next_position_quantity / trade.quantity.abs())),
                    },
                };

                // Update closing Position with appropriate ratio of fees for theoretical quantity
                let fee_exit = trade.fees.fees * (self.quantity_abs / trade.quantity.abs());
                let fee_exit_quote = trade
                    .fees
                    .fees_quote
                    .map(|fq| fq * (self.quantity_abs / trade.quantity.abs()));
                self.fees_exit.fees += fee_exit;
                self.fees_exit.fees_quote = match (self.fees_exit.fees_quote, fee_exit_quote) {
                    (Some(a), Some(b)) => Some(a + b),
                    _ => None,
                };
                self.time_exchange_update = trade.time_exchange;
                self.update_pnl_realised(
                    self.quantity_abs,
                    trade.price,
                    fee_exit_quote.unwrap_or(fee_exit),
                );
                self.quantity_abs = Decimal::ZERO;
                self.update_pnl_unrealised(trade.price);

                // Propagate contract_size from closing position to the new flipped position
                let mut next_position = Self::from(&next_position_trade);
                next_position.contract_size = self.contract_size;

                (Some(next_position), Some(PositionExited::from(self)))
            }
            _ => unreachable!("match expression guard statements cover all cases"),
        }
    }

    /// Updates the volume-weighted average entry price of the [`Position`].
    ///
    /// Internally uses the logic defined in [`calculate_price_entry_average`].
    fn update_price_entry_average(&mut self, trade: &Trade<AssetKey, InstrumentKey>) {
        self.price_entry_average = calculate_price_entry_average(
            self.price_entry_average,
            self.quantity_abs,
            trade.price,
            trade.quantity.abs(),
        );
    }

    /// Update [`Position::pnl_unrealised`](Position) with the estimated PnL from closing
    /// the [`Position`] at the provided price.
    ///
    /// Note that this could be called with a recent [`Trade`] price, or a price generated from
    /// a model based on public market data.
    pub fn update_pnl_unrealised(&mut self, price: Decimal) {
        self.pnl_unrealised = calculate_pnl_unrealised(
            self.side,
            self.price_entry_average,
            self.quantity_abs,
            self.quantity_abs_max,
            self.fees_enter.fees,
            price,
            self.contract_size,
        );
    }

    /// Updates the [`Position`] `pnl_realised` from a closed portion of the [`Position`] quantity.
    pub fn update_pnl_realised(
        &mut self,
        closed_quantity: Decimal,
        closed_price: Decimal,
        closed_fee: Decimal,
    ) {
        // Update total Position pnl_realised with closed quantity PnL
        self.pnl_realised += calculate_pnl_realised(
            self.side,
            self.price_entry_average,
            closed_quantity,
            closed_price,
            closed_fee,
            self.contract_size,
        );
    }
}

impl<AssetKey, InstrumentKey> From<&Trade<AssetKey, InstrumentKey>>
    for Position<AssetKey, InstrumentKey>
where
    AssetKey: Clone,
    InstrumentKey: Clone,
{
    fn from(trade: &Trade<AssetKey, InstrumentKey>) -> Self {
        let mut trades = Vec::with_capacity(2);
        trades.push(trade.id.clone());
        Self {
            instrument: trade.instrument.clone(),
            side: trade.side,
            price_entry_average: trade.price,
            quantity_abs: trade.quantity.abs(),
            quantity_abs_max: trade.quantity.abs(),
            pnl_unrealised: Decimal::ZERO,
            pnl_realised: -trade.fees.fees_quote.unwrap_or(trade.fees.fees),
            fees_enter: trade.fees.clone(),
            fees_exit: AssetFees::new(trade.fees.asset.clone(), Decimal::ZERO, Some(Decimal::ZERO)),
            time_enter: trade.time_exchange,
            time_exchange_update: trade.time_exchange,
            trades,
            // Default to 1; PositionManager::update_from_trade_with_id assigns the
            // correct value via direct field assignment after creation.
            contract_size: Decimal::ONE,
        }
    }
}

/// Represents a fully closed trading [`Position`] for a specific instrument.
///
/// Contains the final state and history of a [`Position`] that has been completely closed.
///
/// # Type Parameters
/// - `AssetKey`: The type representing the asset used for fees (e.g. AssetIndex, QuoteAsset, etc.)
/// - `InstrumentKey`: The type identifying the traded instrument (e.g. InstrumentIndex, etc.)
#[derive(
    Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize, Constructor,
)]
pub struct PositionExited<AssetKey, InstrumentKey = InstrumentIndex> {
    /// The `PositionId` that identified this position in the `PositionManager`.
    ///
    /// In `OmsMode::Netting` this is always [`PositionId::NETTING`].
    /// In `OmsMode::Hedging` this matches the `PositionId` from the opening order's
    /// `RequestOpen::position_id`, enabling the `StateReplicaManager` to do targeted
    /// per-position removal rather than clearing all positions at once.
    #[serde(default)]
    pub position_id: PositionId,

    /// Closed [`Position`] Instrument identifier (eg/ InstrumentIndex, InstrumentNameInternal, etc.).
    pub instrument: InstrumentKey,

    /// Closed [`Position`] direction (Side::Buy => LONG, Side::Sell => SHORT).
    pub side: Side,

    /// Volume-weighted average entry price across all [`Position`] increasing [`Trade`]s.
    pub price_entry_average: Decimal,

    /// Maximum absolute [`Position`] quantity reached by all entry/increase [`Trade`]s.
    pub quantity_abs_max: Decimal,

    /// Cumulative realised PnL from closing the full [`Position`] `quantity_abs_max`.
    ///
    /// Note this includes fees.
    pub pnl_realised: Decimal,

    /// Cumulative fees paid when entering the [`Position`].
    pub fees_enter: AssetFees<AssetKey>,

    /// Cumulative fees paid when exiting the [`Position`].
    pub fees_exit: AssetFees<AssetKey>,

    /// Timestamp of [`Trade`] that triggered the initial [`Position`] entry.
    pub time_enter: DateTime<Utc>,

    /// Timestamp of [`Trade`] that triggered the closing of the [`Position`].
    pub time_exit: DateTime<Utc>,

    /// [`TradeId`]s of all the [`Trade`]s associated with the closed [`Position`].
    pub trades: Vec<TradeId>,
}

impl<AssetKey, InstrumentKey> From<Position<AssetKey, InstrumentKey>>
    for PositionExited<AssetKey, InstrumentKey>
{
    fn from(value: Position<AssetKey, InstrumentKey>) -> Self {
        Self {
            position_id: PositionId::default(),
            instrument: value.instrument,
            side: value.side,
            price_entry_average: value.price_entry_average,
            quantity_abs_max: value.quantity_abs_max,
            pnl_realised: value.pnl_realised,
            fees_enter: value.fees_enter,
            fees_exit: value.fees_exit,
            time_enter: value.time_enter,
            time_exit: value.time_exchange_update,
            trades: value.trades,
        }
    }
}

/// Calculates the volume-weighted average entry price when adding a [`Trade`] data to existing
/// [`Position`] data.
///
/// This function uses the formula: <br>
/// (current_value + trade_value) / (current_quantity + trade_quantity)
///
/// # Arguments
/// * `current_price_entry_average` - The current average entry price of the position
/// * `current_quantity_abs` - The current absolute quantity of the position
/// * `trade_price` - The price of the new trade
/// * `trade_quantity_abs` - The absolute quantity of the new trade
fn calculate_price_entry_average(
    current_price_entry_average: Decimal,
    current_quantity_abs: Decimal,
    trade_price: Decimal,
    trade_quantity_abs: Decimal,
) -> Decimal {
    if current_quantity_abs.is_zero() && trade_quantity_abs.is_zero() {
        return Decimal::ZERO;
    }

    let current_value = current_price_entry_average * current_quantity_abs;
    let trade_value = trade_price * trade_quantity_abs;

    (current_value + trade_value) / (current_quantity_abs + trade_quantity_abs)
}

/// Calculate the estimated unrealised PnL from closing a [`Position`] `quantity_abs` at the
/// provided price.
///
/// The `contract_size` multiplier converts price-based PnL to actual dollar PnL for derivatives.
/// For spot instruments, pass `Decimal::ONE`.
pub fn calculate_pnl_unrealised(
    position_side: Side,
    price_entry_average: Decimal,
    quantity_abs: Decimal,
    quantity_abs_max: Decimal,
    fees_enter: Decimal,
    price: Decimal,
    contract_size: Decimal,
) -> Decimal {
    let approx_exit_fees =
        approximate_remaining_exit_fees(quantity_abs, quantity_abs_max, fees_enter);

    let value_quote_current = quantity_abs * price * contract_size;
    let value_quote_entry = quantity_abs * price_entry_average * contract_size;

    match position_side {
        Side::Buy => value_quote_current - value_quote_entry - approx_exit_fees,
        Side::Sell => value_quote_entry - value_quote_current - approx_exit_fees,
    }
}

/// Approximate the exit fees from closing a [`Position`] with `quantity_abs`.
///
/// The `fees_enter` value was the fee cost to enter a [`Position`] of `quantity_abs_max`,
/// therefore this 'fee per quantity' ratio can be used to approximate the exit fees required to
/// close a `quantity_abs` [`Position`].
fn approximate_remaining_exit_fees(
    quantity_abs: Decimal,
    quantity_abs_max: Decimal,
    fees_enter: Decimal,
) -> Decimal {
    if quantity_abs_max.is_zero() {
        return Decimal::ZERO;
    }
    (quantity_abs / quantity_abs_max) * fees_enter
}

/// Calculate the realised PnL generated from closing the provided [`Position`] quantity, at the
/// specified price and closing fee.
///
/// The `contract_size` multiplier converts price-based PnL to actual dollar PnL for derivatives.
/// For spot instruments, pass `Decimal::ONE`. For standard equity options (100 shares/contract),
/// pass `Decimal::from(100)`.
pub fn calculate_pnl_realised(
    position_side: Side,
    price_entry_average: Decimal,
    closed_quantity: Decimal,
    closed_price: Decimal,
    closed_fee: Decimal,
    contract_size: Decimal,
) -> Decimal {
    let close_quantity = closed_quantity.abs();
    let value_quote_closed = close_quantity * closed_price * contract_size;
    let value_quote_entry = close_quantity * price_entry_average * contract_size;

    match position_side {
        Side::Buy => value_quote_closed - value_quote_entry - closed_fee,
        Side::Sell => value_quote_entry - value_quote_closed - closed_fee,
    }
}

/// Calculate the PnL returns.
///
/// Returns = pnl_realised / cost_of_investment
///
/// See docs: <https://www.investopedia.com/articles/basics/10/guide-to-calculating-roi.asp>
pub fn calculate_pnl_return(
    pnl_realised: Decimal,
    price_entry_average: Decimal,
    quantity_abs_max: Decimal,
) -> Decimal {
    if price_entry_average.is_zero() || quantity_abs_max.is_zero() {
        return Decimal::ZERO;
    }
    pnl_realised / (price_entry_average * quantity_abs_max)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_utils::{time_plus_days, trade};
    use rust_decimal_macros::dec;
    use rustrade_instrument::{asset::QuoteAsset, instrument::name::InstrumentNameInternal};

    #[test]
    fn test_position_update_from_trade() {
        struct TestCase {
            initial_trade: Trade<QuoteAsset, InstrumentNameInternal>,
            update_trade: Trade<QuoteAsset, InstrumentNameInternal>,
            expected_position: Option<Position<QuoteAsset, InstrumentNameInternal>>,
            expected_position_exited: Option<PositionExited<QuoteAsset, InstrumentNameInternal>>,
        }

        let base_time = DateTime::<Utc>::MIN_UTC;

        let cases = vec![
            // TC0: Increase long position
            TestCase {
                initial_trade: trade(base_time, Side::Buy, 100.0, 1.0, 10.0),
                update_trade: trade(time_plus_days(base_time, 1), Side::Buy, 120.0, 1.0, 10.0),
                expected_position: Some(Position {
                    instrument: InstrumentNameInternal::new("instrument"),
                    side: Side::Buy,
                    price_entry_average: dec!(110.0),
                    quantity_abs: dec!(2.0),
                    quantity_abs_max: dec!(2.0),
                    pnl_unrealised: dec!(0.0),
                    pnl_realised: dec!(-20.0), // Sum of fees
                    fees_enter: AssetFees {
                        asset: QuoteAsset,
                        fees: dec!(20.0),
                        fees_quote: Some(dec!(20.0)),
                    },
                    fees_exit: AssetFees {
                        asset: QuoteAsset,
                        fees: dec!(0.0),
                        fees_quote: Some(dec!(0.0)),
                    },
                    time_enter: base_time,
                    time_exchange_update: time_plus_days(base_time, 1),
                    trades: vec![TradeId::new("trade_id"), TradeId::new("trade_id")],
                    contract_size: Decimal::ONE,
                }),
                expected_position_exited: None,
            },
            // TC1: Partial reduce long position
            TestCase {
                initial_trade: trade(base_time, Side::Buy, 100.0, 2.0, 10.0),
                update_trade: trade(time_plus_days(base_time, 1), Side::Sell, 150.0, 0.5, 5.0),
                expected_position: Some(Position {
                    instrument: InstrumentNameInternal::new("instrument"),
                    side: Side::Buy,
                    price_entry_average: dec!(100.0), // update_trade is Sell, so unchanged
                    quantity_abs: dec!(1.5),
                    quantity_abs_max: dec!(2.0),
                    pnl_unrealised: dec!(67.5), // (150-100)*(2.0-0.5) - approx_exit_fees (1.5/2 * 10)
                    pnl_realised: dec!(10.0),   // (150-100)*0.5 - 15_fees
                    fees_enter: AssetFees {
                        asset: QuoteAsset,
                        fees: dec!(10.0),
                        fees_quote: Some(dec!(10.0)),
                    },
                    fees_exit: AssetFees {
                        asset: QuoteAsset,
                        fees: dec!(5.0),
                        fees_quote: Some(dec!(5.0)),
                    },
                    time_enter: base_time,
                    time_exchange_update: time_plus_days(base_time, 1),
                    trades: vec![TradeId::new("trade_id"), TradeId::new("trade_id")],
                    contract_size: Decimal::ONE,
                }),
                expected_position_exited: None,
            },
            // TC2: Exact position close, in profit
            TestCase {
                initial_trade: trade(base_time, Side::Buy, 100.0, 1.0, 10.0),
                update_trade: trade(time_plus_days(base_time, 1), Side::Sell, 150.0, 1.0, 10.0),
                expected_position: None,
                expected_position_exited: Some(PositionExited {
                    position_id: PositionId::NETTING,
                    instrument: InstrumentNameInternal::new("instrument"),
                    side: Side::Buy,
                    price_entry_average: dec!(100.0),
                    quantity_abs_max: dec!(1.0),
                    pnl_realised: dec!(30.0), // (150-100)*1 - 20 (total fees)
                    fees_enter: AssetFees {
                        asset: QuoteAsset,
                        fees: dec!(10.0),
                        fees_quote: Some(dec!(10.0)),
                    },
                    fees_exit: AssetFees {
                        asset: QuoteAsset,
                        fees: dec!(10.0),
                        fees_quote: Some(dec!(10.0)),
                    },
                    time_enter: base_time,
                    time_exit: time_plus_days(base_time, 1),
                    trades: vec![TradeId::new("trade_id"), TradeId::new("trade_id")],
                }),
            },
            // TC3: Position flip (close and open new)
            TestCase {
                initial_trade: trade(base_time, Side::Buy, 100.0, 1.0, 10.0),
                update_trade: trade(time_plus_days(base_time, 1), Side::Sell, 150.0, 2.0, 20.0),
                expected_position: Some(Position {
                    instrument: InstrumentNameInternal::new("instrument"),
                    side: Side::Sell,
                    price_entry_average: dec!(150.0),
                    quantity_abs: dec!(1.0),
                    quantity_abs_max: dec!(1.0),
                    pnl_unrealised: dec!(0.0),
                    pnl_realised: dec!(-10.0), // Entry fees for new position (2-1)*(1/2)*20
                    fees_enter: AssetFees {
                        asset: QuoteAsset,
                        fees: dec!(10.0),
                        fees_quote: Some(dec!(10.0)),
                    },
                    fees_exit: AssetFees {
                        asset: QuoteAsset,
                        fees: dec!(0.0),
                        fees_quote: Some(dec!(0.0)),
                    },
                    time_enter: time_plus_days(base_time, 1),
                    time_exchange_update: time_plus_days(base_time, 1),
                    trades: vec![TradeId::new("trade_id")],
                    contract_size: Decimal::ONE,
                }),
                expected_position_exited: Some(PositionExited {
                    position_id: PositionId::NETTING,
                    instrument: InstrumentNameInternal::new("instrument"),
                    side: Side::Buy,
                    price_entry_average: dec!(100.0),
                    quantity_abs_max: dec!(1.0),
                    pnl_realised: dec!(30.0), // (150-100)*1 - 20 (total fees)
                    fees_enter: AssetFees {
                        asset: QuoteAsset,
                        fees: dec!(10.0),
                        fees_quote: Some(dec!(10.0)),
                    },
                    fees_exit: AssetFees {
                        asset: QuoteAsset,
                        fees: dec!(10.0),
                        fees_quote: Some(dec!(10.0)),
                    },
                    time_enter: base_time,
                    time_exit: time_plus_days(base_time, 1),
                    trades: vec![TradeId::new("trade_id"), TradeId::new("trade_id")],
                }),
            },
            // TC4: Increase short position
            TestCase {
                initial_trade: trade(base_time, Side::Sell, 100.0, 1.0, 10.0),
                update_trade: trade(base_time, Side::Sell, 80.0, 1.0, 10.0),
                expected_position: Some(Position {
                    instrument: InstrumentNameInternal::new("instrument"),
                    side: Side::Sell,
                    price_entry_average: dec!(90.0), // (100*1 + 80*1)/(1 + 1)
                    quantity_abs: dec!(2.0),
                    quantity_abs_max: dec!(2.0),
                    pnl_unrealised: dec!(0.0), // (90-80)*2 - approx_exit_fees(2/2 * 20)
                    pnl_realised: dec!(-20.0), // Sum of entry fees
                    fees_enter: AssetFees {
                        asset: QuoteAsset,
                        fees: dec!(20.0),
                        fees_quote: Some(dec!(20.0)),
                    },
                    fees_exit: AssetFees {
                        asset: QuoteAsset,
                        fees: dec!(0.0),
                        fees_quote: Some(dec!(0.0)),
                    },
                    time_enter: base_time,
                    time_exchange_update: base_time,
                    trades: vec![TradeId::new("trade_id"), TradeId::new("trade_id")],
                    contract_size: Decimal::ONE,
                }),
                expected_position_exited: None,
            },
            // TC5: Partial reduce short position
            TestCase {
                initial_trade: trade(base_time, Side::Sell, 100.0, 2.0, 10.0),
                update_trade: trade(base_time, Side::Buy, 80.0, 0.5, 5.0),
                expected_position: Some(Position {
                    instrument: InstrumentNameInternal::new("instrument"),
                    side: Side::Sell,
                    price_entry_average: dec!(100.0), // update_trade is Buy, so unchanged
                    quantity_abs: dec!(1.5),
                    quantity_abs_max: dec!(2.0),
                    pnl_unrealised: dec!(22.5), // (100-80)*1.5 - approx_exit_fees(1.5/2 * 10)
                    pnl_realised: dec!(-5.0),   // 10_fee_entry - (100-80)*0.5 - 5_fee_exit
                    fees_enter: AssetFees {
                        asset: QuoteAsset,
                        fees: dec!(10.0),
                        fees_quote: Some(dec!(10.0)),
                    },
                    fees_exit: AssetFees {
                        asset: QuoteAsset,
                        fees: dec!(5.0),
                        fees_quote: Some(dec!(5.0)),
                    },
                    time_enter: base_time,
                    time_exchange_update: base_time,
                    trades: vec![TradeId::new("trade_id"), TradeId::new("trade_id")],
                    contract_size: Decimal::ONE,
                }),
                expected_position_exited: None,
            },
            // TC6: Exact short position close
            TestCase {
                initial_trade: trade(base_time, Side::Sell, 100.0, 1.0, 10.0),
                update_trade: trade(base_time, Side::Buy, 80.0, 1.0, 10.0),
                expected_position: None,
                expected_position_exited: Some(PositionExited {
                    position_id: PositionId::NETTING,
                    instrument: InstrumentNameInternal::new("instrument"),
                    side: Side::Sell,
                    price_entry_average: dec!(100.0),
                    quantity_abs_max: dec!(1.0),
                    pnl_realised: dec!(0.0), // (100-80)*1 - 20 (total fees)
                    fees_enter: AssetFees {
                        asset: QuoteAsset,
                        fees: dec!(10.0),
                        fees_quote: Some(dec!(10.0)),
                    },
                    fees_exit: AssetFees {
                        asset: QuoteAsset,
                        fees: dec!(10.0),
                        fees_quote: Some(dec!(10.0)),
                    },
                    time_enter: base_time,
                    time_exit: base_time,
                    trades: vec![TradeId::new("trade_id"), TradeId::new("trade_id")],
                }),
            },
            // TC7: Short position flip (close and open long)
            TestCase {
                initial_trade: trade(base_time, Side::Sell, 100.0, 1.0, 10.0),
                update_trade: trade(base_time, Side::Buy, 80.0, 2.0, 20.0),
                expected_position: Some(Position {
                    instrument: InstrumentNameInternal::new("instrument"),
                    side: Side::Buy,
                    price_entry_average: dec!(80.0),
                    quantity_abs: dec!(1.0),
                    quantity_abs_max: dec!(1.0),
                    pnl_unrealised: dec!(0.0),
                    pnl_realised: dec!(-10.0), // Entry fees for new position
                    fees_enter: AssetFees {
                        asset: QuoteAsset,
                        fees: dec!(10.0),
                        fees_quote: Some(dec!(10.0)),
                    },
                    fees_exit: AssetFees {
                        asset: QuoteAsset,
                        fees: dec!(0.0),
                        fees_quote: Some(dec!(0.0)),
                    },
                    time_enter: base_time,
                    time_exchange_update: base_time,
                    trades: vec![TradeId::new("trade_id")],
                    contract_size: Decimal::ONE,
                }),
                expected_position_exited: Some(PositionExited {
                    position_id: PositionId::NETTING,
                    instrument: InstrumentNameInternal::new("instrument"),
                    side: Side::Sell,
                    price_entry_average: dec!(100.0),
                    quantity_abs_max: dec!(1.0),
                    pnl_realised: dec!(0.0), // (100-80)*1 - 20 (total fees)
                    fees_enter: AssetFees {
                        asset: QuoteAsset,
                        fees: dec!(10.0),
                        fees_quote: Some(dec!(10.0)),
                    },
                    fees_exit: AssetFees {
                        asset: QuoteAsset,
                        fees: dec!(10.0),
                        fees_quote: Some(dec!(10.0)),
                    },
                    time_enter: base_time,
                    time_exit: base_time,
                    trades: vec![TradeId::new("trade_id"), TradeId::new("trade_id")],
                }),
            },
        ];

        for (index, test) in cases.into_iter().enumerate() {
            let position = Position::from(&test.initial_trade);
            let (updated_position, exited_position) =
                position.update_from_trade(&test.update_trade);

            assert_eq!(updated_position, test.expected_position, "TC{index} failed");
            assert_eq!(
                exited_position, test.expected_position_exited,
                "TC{index} failed"
            );
        }
    }

    #[test]
    fn test_calculate_price_entry_average() {
        struct TestCase {
            current_price_entry_average: Decimal,
            current_quantity_abs: Decimal,
            trade_price: Decimal,
            trade_quantity_abs: Decimal,
            expected: Decimal,
        }

        let cases = vec![
            // TC0: equal contribution
            TestCase {
                current_price_entry_average: dec!(100.0),
                current_quantity_abs: dec!(2.0),
                trade_price: dec!(200.0),
                trade_quantity_abs: dec!(2.0),
                expected: dec!(150.0),
            },
            // TC1: trade larger contribution
            TestCase {
                current_price_entry_average: dec!(100.0),
                current_quantity_abs: dec!(2.0),
                trade_price: dec!(200.0),
                trade_quantity_abs: dec!(4.0),
                expected: dec!(166.66666666666666666666666667),
            },
            // TC2: current larger contribution
            TestCase {
                current_price_entry_average: dec!(100.0),
                current_quantity_abs: dec!(20.0),
                trade_price: dec!(200.0),
                trade_quantity_abs: dec!(1.0),
                expected: dec!(104.76190476190476190476190476),
            },
            // TC3: zero current quantity, so expect trade price
            TestCase {
                current_price_entry_average: dec!(100.0),
                current_quantity_abs: dec!(0.0),
                trade_price: dec!(200.0),
                trade_quantity_abs: dec!(4.0),
                expected: dec!(200.0),
            },
            // TC4: zero trade quantity, so expect current price
            TestCase {
                current_price_entry_average: dec!(100.0),
                current_quantity_abs: dec!(10.0),
                trade_price: dec!(0.0),
                trade_quantity_abs: dec!(0.0),
                expected: dec!(100.0),
            },
            // TC5: both zero quantities
            TestCase {
                current_price_entry_average: dec!(100.0),
                current_quantity_abs: dec!(0.0),
                trade_price: dec!(200.0),
                trade_quantity_abs: dec!(0.0),
                expected: dec!(0.0),
            },
        ];

        for (index, test) in cases.into_iter().enumerate() {
            let actual = calculate_price_entry_average(
                test.current_price_entry_average,
                test.current_quantity_abs,
                test.trade_price,
                test.trade_quantity_abs,
            );

            assert_eq!(actual, test.expected, "TC{} failed", index)
        }
    }

    #[test]
    fn test_calculate_pnl_unrealised() {
        struct TestCase {
            position_side: Side,
            price_entry_average: Decimal,
            quantity_abs: Decimal,
            quantity_abs_max: Decimal,
            fees_enter: Decimal,
            price: Decimal,
            expected: Decimal,
        }

        let cases = vec![
            // TC0: LONG position in profit
            TestCase {
                position_side: Side::Buy,
                price_entry_average: dec!(100.0),
                quantity_abs: dec!(1.0),
                quantity_abs_max: dec!(1.0),
                fees_enter: dec!(10.0),
                price: dec!(150.0),
                expected: dec!(40.0), // (150-100)*1 - 10
            },
            // TC1: LONG position at loss
            TestCase {
                position_side: Side::Buy,
                price_entry_average: dec!(100.0),
                quantity_abs: dec!(1.0),
                quantity_abs_max: dec!(1.0),
                fees_enter: dec!(10.0),
                price: dec!(80.0),
                expected: dec!(-30.0), // (80-100)*1 - 10
            },
            // TC2: SHORT position in profit
            TestCase {
                position_side: Side::Sell,
                price_entry_average: dec!(100.0),
                quantity_abs: dec!(1.0),
                quantity_abs_max: dec!(1.0),
                fees_enter: dec!(10.0),
                price: dec!(80.0),
                expected: dec!(10.0), // (100-80)*1 - 10
            },
            // TC3: SHORT position at loss
            TestCase {
                position_side: Side::Sell,
                price_entry_average: dec!(100.0),
                quantity_abs: dec!(1.0),
                quantity_abs_max: dec!(1.0),
                fees_enter: dec!(10.0),
                price: dec!(150.0),
                expected: dec!(-60.0), // (100-150)*1 - 10
            },
            // TC4: Partial position remaining (half closed)
            TestCase {
                position_side: Side::Buy,
                price_entry_average: dec!(100.0),
                quantity_abs: dec!(0.5),
                quantity_abs_max: dec!(1.0),
                fees_enter: dec!(10.0),
                price: dec!(150.0),
                expected: dec!(20.0), // (150-100)*0.5 - (0.5/1.0)*10
            },
            // TC5: Zero quantity position
            TestCase {
                position_side: Side::Buy,
                price_entry_average: dec!(100.0),
                quantity_abs: dec!(0.0),
                quantity_abs_max: dec!(1.0),
                fees_enter: dec!(10.0),
                price: dec!(150.0),
                expected: dec!(0.0),
            },
        ];

        for (index, test) in cases.into_iter().enumerate() {
            // Spot instrument: contract_size = 1
            let actual = calculate_pnl_unrealised(
                test.position_side,
                test.price_entry_average,
                test.quantity_abs,
                test.quantity_abs_max,
                test.fees_enter,
                test.price,
                Decimal::ONE,
            );

            assert_eq!(actual, test.expected, "TC{} failed", index);
        }
    }

    #[test]
    fn test_calculate_pnl_unrealised_with_contract_size() {
        // Standard equity option: contract_size = 100
        // Long 1 call bought at $10/share, current price $15/share, $1 entry fee
        // Unrealised PnL = (15 - 10) * 1 * 100 - 1 = 499
        let pnl = calculate_pnl_unrealised(
            Side::Buy,
            dec!(10.0),  // entry price per share
            dec!(1.0),   // 1 contract
            dec!(1.0),   // max quantity (for fee approximation)
            dec!(1.0),   // $1 entry fee
            dec!(15.0),  // current price per share
            dec!(100.0), // 100 shares per contract
        );
        assert_eq!(pnl, dec!(499.0));

        // Short 2 puts sold at $5/share, current price $3/share, $2 entry fee
        // Unrealised PnL = (5 - 3) * 2 * 100 - 2 = 398
        let pnl = calculate_pnl_unrealised(
            Side::Sell,
            dec!(5.0),   // entry price per share
            dec!(2.0),   // 2 contracts
            dec!(2.0),   // max quantity
            dec!(2.0),   // $2 entry fee
            dec!(3.0),   // current price per share
            dec!(100.0), // 100 shares per contract
        );
        assert_eq!(pnl, dec!(398.0));
    }

    #[test]
    fn test_approximate_remaining_exit_fees() {
        struct TestCase {
            quantity_abs: Decimal,
            quantity_abs_max: Decimal,
            fees_enter: Decimal,
            expected: Decimal,
        }

        let cases = vec![
            // TC0: Full position - expect full fees
            TestCase {
                quantity_abs: dec!(1.0),
                quantity_abs_max: dec!(1.0),
                fees_enter: dec!(10.0),
                expected: dec!(10.0),
            },
            // TC1: Half position - expect half fees
            TestCase {
                quantity_abs: dec!(0.5),
                quantity_abs_max: dec!(1.0),
                fees_enter: dec!(10.0),
                expected: dec!(5.0),
            },
            // TC2: Zero position - expect zero fees
            TestCase {
                quantity_abs: dec!(0.0),
                quantity_abs_max: dec!(1.0),
                fees_enter: dec!(10.0),
                expected: dec!(0.0),
            },
            // TC3: Larger current quantity than max (edge case)
            TestCase {
                quantity_abs: dec!(2.0),
                quantity_abs_max: dec!(1.0),
                fees_enter: dec!(10.0),
                expected: dec!(20.0),
            },
            // TC4: Zero max quantity — guard against divide-by-zero
            TestCase {
                quantity_abs: dec!(1.0),
                quantity_abs_max: dec!(0.0),
                fees_enter: dec!(10.0),
                expected: dec!(0.0),
            },
        ];

        for (index, test) in cases.into_iter().enumerate() {
            let actual = approximate_remaining_exit_fees(
                test.quantity_abs,
                test.quantity_abs_max,
                test.fees_enter,
            );

            assert_eq!(actual, test.expected, "TC{} failed", index);
        }
    }

    #[test]
    fn test_calculate_pnl_realised() {
        struct TestCase {
            side: Side,
            price_entry_average: Decimal,
            closed_quantity: Decimal,
            closed_price: Decimal,
            closed_fee: Decimal,
            expected: Decimal,
        }

        let cases = vec![
            // TC0: LONG in profit w/ fee deduction
            TestCase {
                side: Side::Buy,
                price_entry_average: dec!(100.0),
                closed_quantity: dec!(10.0),
                closed_price: dec!(150.0),
                closed_fee: dec!(5.0),
                expected: dec!(495.0),
            },
            // TC1: LONG in profit w/o fee deduction
            TestCase {
                side: Side::Buy,
                price_entry_average: dec!(100.0),
                closed_quantity: dec!(10.0),
                closed_price: dec!(150.0),
                closed_fee: dec!(0.0),
                expected: dec!(500.0),
            },
            // TC2: LONG in profit w/ fee rebate
            TestCase {
                side: Side::Buy,
                price_entry_average: dec!(100.0),
                closed_quantity: dec!(10.0),
                closed_price: dec!(150.0),
                closed_fee: dec!(-5.0),
                expected: dec!(505.0),
            },
            // TC3: LONG in loss w/ fee deduction
            TestCase {
                side: Side::Buy,
                price_entry_average: dec!(100.0),
                closed_quantity: dec!(10.0),
                closed_price: dec!(50.0),
                closed_fee: dec!(5.0),
                expected: dec!(-505.0),
            },
            // TC4: LONG in loss w/o fee deduction
            TestCase {
                side: Side::Buy,
                price_entry_average: dec!(100.0),
                closed_quantity: dec!(10.0),
                closed_price: dec!(50.0),
                closed_fee: dec!(0.0),
                expected: dec!(-500.0),
            },
            // TC5: LONG in loss w/ fee rebate
            TestCase {
                side: Side::Buy,
                price_entry_average: dec!(100.0),
                closed_quantity: dec!(10.0),
                closed_price: dec!(50.0),
                closed_fee: dec!(-5.0),
                expected: dec!(-495.0),
            },
            // TC6: SHORT in profit w/ fee deduction
            TestCase {
                side: Side::Sell,
                price_entry_average: dec!(100.0),
                closed_quantity: dec!(10.0),
                closed_price: dec!(50.0),
                closed_fee: dec!(5.0),
                expected: dec!(495.0),
            },
            // TC7: SHORT in profit w/o fee deduction
            TestCase {
                side: Side::Sell,
                price_entry_average: dec!(100.0),
                closed_quantity: dec!(10.0),
                closed_price: dec!(50.0),
                closed_fee: dec!(0.0),
                expected: dec!(500.0),
            },
            // TC8: SHORT in profit w/ fee rebate
            TestCase {
                side: Side::Sell,
                price_entry_average: dec!(100.0),
                closed_quantity: dec!(10.0),
                closed_price: dec!(50.0),
                closed_fee: dec!(-5.0),
                expected: dec!(505.0),
            },
            // TC9: SHORT in loss w/ fee deduction
            TestCase {
                side: Side::Sell,
                price_entry_average: dec!(100.0),
                closed_quantity: dec!(10.0),
                closed_price: dec!(150.0),
                closed_fee: dec!(5.0),
                expected: dec!(-505.0),
            },
            // TC10: SHORT in loss w/o fee deduction
            TestCase {
                side: Side::Sell,
                price_entry_average: dec!(100.0),
                closed_quantity: dec!(10.0),
                closed_price: dec!(150.0),
                closed_fee: dec!(0.0),
                expected: dec!(-500.0),
            },
            // TC10: SHORT in loss w/ fee rebate
            TestCase {
                side: Side::Sell,
                price_entry_average: dec!(100.0),
                closed_quantity: dec!(10.0),
                closed_price: dec!(150.0),
                closed_fee: dec!(-5.0),
                expected: dec!(-495.0),
            },
        ];

        for (index, test) in cases.into_iter().enumerate() {
            // Spot instrument: contract_size = 1
            let actual = calculate_pnl_realised(
                test.side,
                test.price_entry_average,
                test.closed_quantity,
                test.closed_price,
                test.closed_fee,
                Decimal::ONE,
            );

            assert_eq!(actual, test.expected, "TC{} failed", index);
        }
    }

    #[test]
    fn test_calculate_pnl_realised_with_contract_size() {
        // Standard equity option: contract_size = 100
        // Buy 1 call at $10/share, sell at $15/share, $1 fee
        // PnL = (15 - 10) * 1 * 100 - 1 = 499
        let pnl = calculate_pnl_realised(
            Side::Buy,
            dec!(10.0),  // entry price per share
            dec!(1.0),   // 1 contract
            dec!(15.0),  // exit price per share
            dec!(1.0),   // $1 fee
            dec!(100.0), // 100 shares per contract
        );
        assert_eq!(pnl, dec!(499.0));

        // SHORT option scenario: sell 2 puts at $5/share, buy back at $3/share, $2 fee
        // PnL = (5 - 3) * 2 * 100 - 2 = 398
        let pnl = calculate_pnl_realised(
            Side::Sell,
            dec!(5.0),   // entry price per share
            dec!(2.0),   // 2 contracts
            dec!(3.0),   // exit price per share
            dec!(2.0),   // $2 fee
            dec!(100.0), // 100 shares per contract
        );
        assert_eq!(pnl, dec!(398.0));
    }

    #[test]
    fn test_calculate_pnl_return() {
        struct TestCase {
            pnl_realised: Decimal,
            price_entry_average: Decimal,
            quantity_abs_max: Decimal,
            expected: Decimal,
        }

        let cases = vec![
            // TC0: Break even (0% return)
            TestCase {
                pnl_realised: dec!(0.0),
                price_entry_average: dec!(100.0),
                quantity_abs_max: dec!(1.0),
                expected: dec!(0.0),
            },
            // TC1: 100% return
            TestCase {
                pnl_realised: dec!(100.0),
                price_entry_average: dec!(100.0),
                quantity_abs_max: dec!(1.0),
                expected: dec!(1.0),
            },
            // TC2: -50% return
            TestCase {
                pnl_realised: dec!(-50.0),
                price_entry_average: dec!(100.0),
                quantity_abs_max: dec!(1.0),
                expected: dec!(-0.5),
            },
            // TC3: Complex case with larger position
            TestCase {
                pnl_realised: dec!(500.0),
                price_entry_average: dec!(100.0),
                quantity_abs_max: dec!(10.0),
                expected: dec!(0.5), // 500/(100*10)
            },
            // TC4: Zero entry price — guard against divide-by-zero
            TestCase {
                pnl_realised: dec!(100.0),
                price_entry_average: dec!(0.0),
                quantity_abs_max: dec!(1.0),
                expected: dec!(0.0),
            },
            // TC5: Zero max quantity — guard against divide-by-zero
            TestCase {
                pnl_realised: dec!(100.0),
                price_entry_average: dec!(100.0),
                quantity_abs_max: dec!(0.0),
                expected: dec!(0.0),
            },
        ];

        for (index, test) in cases.into_iter().enumerate() {
            let actual = calculate_pnl_return(
                test.pnl_realised,
                test.price_entry_average,
                test.quantity_abs_max,
            );

            assert_eq!(actual, test.expected, "TC{} failed", index);
        }
    }
}