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
//! Data structures and events for positions
mod closed;
mod collateral_and_usd;

pub use closed::*;
pub use collateral_and_usd::*;

use anyhow::Result;
use cosmwasm_schema::cw_serde;
use cosmwasm_std::{Addr, Decimal256, OverflowError, StdResult};
use cw_storage_plus::{IntKey, Key, KeyDeserialize, Prefixer, PrimaryKey};
use shared::prelude::*;
use std::fmt;
use std::hash::Hash;
use std::num::ParseIntError;
use std::str::FromStr;

use super::config::Config;

/// The position itself
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug, PartialEq, Eq)]
pub struct Position {
    /// Owner of the position
    pub owner: Addr,
    /// Unique identifier for a position
    pub id: PositionId,
    /// The amount of collateral deposited by the trader to create this position.
    ///
    /// It would seem like the type here should be `NonZero<Collateral>`.
    /// However, due to updates, this isn't accurate. It's possible for someone
    /// to update a position and withdraw more collateral than the original
    /// deposit.
    pub deposit_collateral: SignedCollateralAndUsd,
    /// Active collateral for the position
    ///
    /// As a position stays open, we liquifund to realize price exposure and
    /// take fees. This is the current trader-side collateral after those steps.
    pub active_collateral: NonZero<Collateral>,
    /// Collateral owned by the liquidity pool that is locked in this position.
    pub counter_collateral: NonZero<Collateral>,
    /// This is signed, where negative represents a short and positive is a long
    pub notional_size: Signed<Notional>,
    /// When the position was created, in terms of block time.
    pub created_at: Timestamp,
    /// Price point timestamp of the crank that created this position.
    ///
    /// This field is only used since deferred execution, before that it is `None`.
    pub price_point_created_at: Option<Timestamp>,
    /// The one-time fee paid when opening or updating a position
    ///
    /// this value is the current balance, including all updates
    pub trading_fee: CollateralAndUsd,
    /// The ongoing fee paid (and earned!) between positions
    /// to incentivize keeping longs and shorts in balance
    /// which in turn reduces risk for LPs
    ///
    /// This value is the current balance, not a historical record of each payment
    pub funding_fee: SignedCollateralAndUsd,
    /// The ongoing fee paid to LPs to lock up their deposit
    /// as counter-size collateral in this position
    ///
    /// This value is the current balance, not a historical record of each payment
    pub borrow_fee: CollateralAndUsd,

    /// Total crank fees paid
    pub crank_fee: CollateralAndUsd,

    /// Cumulative amount of delta neutrality fees paid by (or received by) the position.
    ///
    /// Positive == outgoing, negative == incoming, like funding_fee.
    pub delta_neutrality_fee: SignedCollateralAndUsd,

    /// Last time the position was liquifunded.
    ///
    /// For newly opened positions, this is the same as the creation time.
    pub liquifunded_at: Timestamp,
    /// When is our next scheduled liquifunding?
    ///
    /// The crank will automatically liquifund this position once this timestamp
    /// has passed. Additionally, liquifunding may be triggered by updating the
    /// position.
    pub next_liquifunding: Timestamp,
    /// A trader specified price at which the position will be liquidated
    pub stop_loss_override: Option<PriceBaseInQuote>,
    /// Stored separately to ensure there are no rounding errors, since we need precise binary equivalence for lookups.
    pub stop_loss_override_notional: Option<Price>,
    /// The most recently calculated liquidation price
    pub liquidation_price: Option<Price>,
    /// The amount of liquidation margin set aside
    pub liquidation_margin: LiquidationMargin,
    /// The take profit value set by the trader in a message.
    /// For historical reasons, this value can be optional if the user provided a max gains price.
    #[serde(rename = "take_profit_override")]
    pub take_profit_trader: Option<TakeProfitTrader>,
    /// Derived directly from `take_profit_trader` to get the PriceNotionalInCollateral representation.
    /// This will be `None` if `take_profit_trader` is infinite.
    /// For historical reasons, this value will also be `None` if the user provided a max gains price.
    /// Stored separately to ensure there are no rounding errors, since we need precise binary equivalence for lookups.
    #[serde(rename = "take_profit_override_notional")]
    pub take_profit_trader_notional: Option<Price>,
    /// The most recently calculated price at which the trader will achieve maximum gains and take all counter collateral.
    /// This is the notional price, not the base price, to avoid rounding errors
    #[serde(rename = "take_profit_price")]
    pub take_profit_total: Option<Price>,
}

/// Liquidation margin for a position, broken down by component.
///
/// Each field represents how much collateral has been set aside for the given
/// fees, or the maximum amount the position can pay at liquifunding.
#[cw_serde]
#[derive(Default, Copy, Eq)]
pub struct LiquidationMargin {
    /// Maximum borrow fee payment.
    pub borrow: Collateral,
    /// Maximum funding payment.
    pub funding: Collateral,
    /// Maximum delta neutrality fee.
    pub delta_neutrality: Collateral,
    /// Funds set aside for a single crank fee.
    pub crank: Collateral,
    /// Funds set aside to cover additional price exposure losses from sparse price updates.
    #[serde(default)]
    pub exposure: Collateral,
}

impl LiquidationMargin {
    /// Total value of the liquidation margin fields
    pub fn total(&self) -> Result<Collateral, OverflowError> {
        ((self.borrow + self.funding)? + (self.delta_neutrality + self.crank)?)? + self.exposure
    }
}

/// Response from [QueryMsg::Positions]
#[cw_serde]
pub struct PositionsResp {
    /// Open positions
    pub positions: Vec<PositionQueryResponse>,
    /// Positions which are pending a liquidation/take profit
    ///
    /// The closed position information is not the final version of the data,
    /// the close process itself still needs to make final payments.
    pub pending_close: Vec<ClosedPosition>,
    /// Positions which have already been closed.
    pub closed: Vec<ClosedPosition>,
}

/// Query response representing current state of a position
#[cw_serde]
pub struct PositionQueryResponse {
    /// Owner
    pub owner: Addr,
    /// Unique ID
    pub id: PositionId,
    /// Direction
    pub direction_to_base: DirectionToBase,
    /// Current leverage
    ///
    /// This is impacted by fees and price exposure
    pub leverage: LeverageToBase,
    /// Leverage of the counter collateral
    pub counter_leverage: LeverageToBase,
    /// When the position was opened, block time
    pub created_at: Timestamp,
    /// Price point used for creating this position
    pub price_point_created_at: Option<Timestamp>,
    /// When the position was last liquifunded
    pub liquifunded_at: Timestamp,

    /// The one-time fee paid when opening or updating a position
    ///
    /// This value is the current balance, including all updates
    pub trading_fee_collateral: Collateral,
    /// USD expression of [Self::trading_fee_collateral] using cost-basis calculation.
    pub trading_fee_usd: Usd,
    /// The ongoing fee paid (and earned!) between positions
    /// to incentivize keeping longs and shorts in balance
    /// which in turn reduces risk for LPs
    ///
    /// This value is the current balance, not a historical record of each payment
    pub funding_fee_collateral: Signed<Collateral>,
    /// USD expression of [Self::funding_fee_collateral] using cost-basis calculation.
    pub funding_fee_usd: Signed<Usd>,
    /// The ongoing fee paid to LPs to lock up their deposit
    /// as counter-size collateral in this position
    ///
    /// This value is the current balance, not a historical record of each payment
    pub borrow_fee_collateral: Collateral,
    /// USD expression of [Self::borrow_fee_collateral] using cost-basis calculation.
    pub borrow_fee_usd: Usd,

    /// Cumulative amount of crank fees paid by the position
    pub crank_fee_collateral: Collateral,
    /// USD expression of [Self::crank_fee_collateral] using cost-basis calculation.
    pub crank_fee_usd: Usd,

    /// Aggregate delta neutrality fees paid or received through position opens and upates.
    pub delta_neutrality_fee_collateral: Signed<Collateral>,
    /// USD expression of [Self::delta_neutrality_fee_collateral] using cost-basis calculation.
    pub delta_neutrality_fee_usd: Signed<Usd>,

    /// See [Position::deposit_collateral]
    pub deposit_collateral: Signed<Collateral>,
    /// USD expression of [Self::deposit_collateral] using cost-basis calculation.
    pub deposit_collateral_usd: Signed<Usd>,
    /// See [Position::active_collateral]
    pub active_collateral: NonZero<Collateral>,
    /// [Self::active_collateral] converted to USD at the current exchange rate
    pub active_collateral_usd: NonZero<Usd>,
    /// See [Position::counter_collateral]
    pub counter_collateral: NonZero<Collateral>,

    /// Unrealized PnL on this position, in terms of collateral.
    pub pnl_collateral: Signed<Collateral>,
    /// Unrealized PnL on this position, in USD, using cost-basis analysis.
    pub pnl_usd: Signed<Usd>,

    /// DNF that would be charged (positive) or received (negative) if position was closed now.
    pub dnf_on_close_collateral: Signed<Collateral>,

    /// Notional size of the position
    pub notional_size: Signed<Notional>,
    /// Notional size converted to collateral at the current price
    pub notional_size_in_collateral: Signed<Collateral>,

    /// The size of the position in terms of the base asset.
    ///
    /// Note that this is not a simple conversion from notional size. Instead,
    /// this needs to account for the off-by-one leverage that occurs in
    /// collateral-is-base markets.
    pub position_size_base: Signed<Base>,

    /// Convert [Self::position_size_base] into USD at the current exchange rate.
    pub position_size_usd: Signed<Usd>,

    /// Price at which liquidation will occur
    pub liquidation_price_base: Option<PriceBaseInQuote>,
    /// The liquidation margin set aside on this position
    pub liquidation_margin: LiquidationMargin,

    /// Maximum gains, in terms of quote, the trader can achieve
    #[deprecated(note = "Use take_profit_trader instead")]
    pub max_gains_in_quote: Option<MaxGainsInQuote>,

    /// Entry price
    pub entry_price_base: PriceBaseInQuote,

    /// When the next liquifunding is scheduled
    pub next_liquifunding: Timestamp,

    /// Stop loss price set by the trader
    pub stop_loss_override: Option<PriceBaseInQuote>,

    /// The take profit value set by the trader in a message.
    /// For historical reasons, this value can be optional if the user provided a max gains price.
    #[serde(rename = "take_profit_override")]
    pub take_profit_trader: Option<TakeProfitTrader>,
    /// The most recently calculated price at which the trader will achieve maximum gains and take all counter collateral.
    #[serde(rename = "take_profit_price_base")]
    pub take_profit_total_base: Option<PriceBaseInQuote>,
}

impl Position {
    /// Direction of the position
    pub fn direction(&self) -> DirectionToNotional {
        if self.notional_size.is_negative() {
            DirectionToNotional::Short
        } else {
            DirectionToNotional::Long
        }
    }

    /// Maximum gains for the position
    pub fn max_gains_in_quote(
        &self,
        market_type: MarketType,
        price_point: &PricePoint,
    ) -> Result<MaxGainsInQuote> {
        match market_type {
            MarketType::CollateralIsQuote => Ok(MaxGainsInQuote::Finite(
                self.counter_collateral
                    .checked_div_collateral(self.active_collateral)?,
            )),
            MarketType::CollateralIsBase => {
                let take_profit_price = self.take_profit_price_total(price_point, market_type)?;
                let take_profit_price = match take_profit_price {
                    Some(price) => price,
                    None => return Ok(MaxGainsInQuote::PosInfinity),
                };
                let take_profit_collateral = self
                    .active_collateral
                    .checked_add(self.counter_collateral.raw())?;
                let take_profit_in_notional =
                    take_profit_price.collateral_to_notional_non_zero(take_profit_collateral);
                let active_collateral_in_notional =
                    price_point.collateral_to_notional_non_zero(self.active_collateral);
                anyhow::ensure!(
                    take_profit_in_notional > active_collateral_in_notional,
                    "Max gains in quote is negative, this should not be possible.
                    Take profit: {take_profit_in_notional}.
                    Active collateral: {active_collateral_in_notional}"
                );
                let res = (take_profit_in_notional.into_decimal256()
                    - active_collateral_in_notional.into_decimal256())
                .checked_div(active_collateral_in_notional.into_decimal256())?;
                Ok(MaxGainsInQuote::Finite(
                    NonZero::new(res).context("Max gains of 0")?,
                ))
            }
        }
    }

    /// Compute the internal leverage active collateral.
    pub fn active_leverage_to_notional(
        &self,
        price_point: &PricePoint,
    ) -> SignedLeverageToNotional {
        SignedLeverageToNotional::calculate(self.notional_size, price_point, self.active_collateral)
    }

    /// Compute the internal leverage for the counter collateral.
    pub fn counter_leverage_to_notional(
        &self,
        price_point: &PricePoint,
    ) -> SignedLeverageToNotional {
        SignedLeverageToNotional::calculate(
            self.notional_size,
            price_point,
            self.counter_collateral,
        )
    }

    /// Convert the notional size into collateral at the given price point.
    pub fn notional_size_in_collateral(&self, price_point: &PricePoint) -> Signed<Collateral> {
        self.notional_size
            .map(|x| price_point.notional_to_collateral(x))
    }

    /// Calculate the size of the position in terms of the base asset.
    ///
    /// This represents what the users' perception of their position is, and
    /// needs to take into account the off-by-one leverage impact of
    /// collateral-is-base markets.
    pub fn position_size_base(
        &self,
        market_type: MarketType,
        price_point: &PricePoint,
    ) -> Result<Signed<Base>> {
        let leverage = self
            .active_leverage_to_notional(price_point)
            .into_base(market_type)?;
        let active_collateral = price_point.collateral_to_base_non_zero(self.active_collateral);
        leverage.checked_mul_base(active_collateral)
    }

    /// Calculate the PnL of this position in terms of the collateral.
    pub fn pnl_in_collateral(&self) -> Result<Signed<Collateral>> {
        self.active_collateral.into_signed() - self.deposit_collateral.collateral()
    }

    /// Calculate the PnL of this position in terms of USD.
    ///
    /// Note that this is not equivalent to converting the collateral PnL into
    /// USD, since we follow a cost basis model in this function, tracking the
    /// price of the collateral asset in terms of USD for each transaction.
    pub fn pnl_in_usd(&self, price_point: &PricePoint) -> Result<Signed<Usd>> {
        let active_collateral_in_usd =
            price_point.collateral_to_usd_non_zero(self.active_collateral);

        active_collateral_in_usd.into_signed() - self.deposit_collateral.usd()
    }

    /// Computes the liquidation margin for the position
    ///
    /// Takes the price point of the last liquifunding.
    pub fn liquidation_margin(
        &self,
        price_point: &PricePoint,
        config: &Config,
    ) -> Result<LiquidationMargin> {
        const SEC_PER_YEAR: u64 = 31_536_000;
        const MS_PER_YEAR: u64 = SEC_PER_YEAR * 1000;
        // Panicking is fine here, it's a hard-coded value
        let ms_per_year = Decimal256::from_atomics(MS_PER_YEAR, 0).unwrap();

        let duration =
            Duration::from_seconds(config.liquifunding_delay_seconds.into()).as_ms_decimal_lossy();

        let borrow_fee_max_rate =
            config.borrow_fee_rate_max_annualized.raw() * duration / ms_per_year;
        let borrow_fee_max_payment = (self
            .active_collateral
            .raw()
            .checked_add(self.counter_collateral.raw())?)
        .checked_mul_dec(borrow_fee_max_rate)?;

        let max_price = match self.direction() {
            DirectionToNotional::Long => {
                price_point.price_notional.into_decimal256()
                    + self.counter_collateral.into_decimal256()
                        / self.notional_size.abs_unsigned().into_decimal256()
            }
            DirectionToNotional::Short => {
                price_point.price_notional.into_decimal256()
                    + self.active_collateral.into_decimal256()
                        / self.notional_size.abs_unsigned().into_decimal256()
            }
        };

        let funding_max_rate = config.funding_rate_max_annualized * duration / ms_per_year;
        let funding_max_payment =
            funding_max_rate * self.notional_size.abs_unsigned().into_decimal256() * max_price;

        let slippage_max = config.delta_neutrality_fee_cap.into_decimal256()
            * self.notional_size.abs_unsigned().into_decimal256()
            * max_price;

        Ok(LiquidationMargin {
            borrow: borrow_fee_max_payment,
            funding: Collateral::from_decimal256(funding_max_payment),
            delta_neutrality: Collateral::from_decimal256(slippage_max),
            crank: price_point.usd_to_collateral(config.crank_fee_charged),
            exposure: price_point
                .notional_to_collateral(self.notional_size.abs_unsigned())
                .checked_mul_dec(config.exposure_margin_ratio)?,
        })
    }

    /// Computes the liquidation price for the position at a given spot price.
    pub fn liquidation_price(
        &self,
        price: Price,
        active_collateral: NonZero<Collateral>,
        liquidation_margin: &LiquidationMargin,
    ) -> Option<Price> {
        let liquidation_margin = liquidation_margin.total().ok()?.into_number();
        let liquidation_price = (price.into_number()
            - ((active_collateral.into_number() - liquidation_margin).ok()?
                / self.notional_size.into_number())
            .ok()?)
        .ok()?;

        Price::try_from_number(liquidation_price).ok()
    }

    /// Computes the take-profit price for the position at a given spot price.
    pub fn take_profit_price_total(
        &self,
        price_point: &PricePoint,
        market_type: MarketType,
    ) -> Result<Option<Price>> {
        let take_profit_price_raw = price_point.price_notional.into_number().checked_add(
            self.counter_collateral
                .into_number()
                .checked_div(self.notional_size.into_number())?,
        )?;

        let take_profit_price = if take_profit_price_raw.approx_eq(Number::ZERO)? {
            None
        } else {
            debug_assert!(
                take_profit_price_raw.is_positive_or_zero(),
                "There should never be a calculated take profit price which is negative. In production, this is treated as 0 to indicate infinite max gains."
            );
            Price::try_from_number(take_profit_price_raw).ok()
        };

        match take_profit_price {
            Some(price) => Ok(Some(price)),
            None =>
            match market_type {
                // Infinite max gains results in a notional take profit price of 0
                MarketType::CollateralIsBase => Ok(None),
                MarketType::CollateralIsQuote => Err(anyhow!("Calculated a take profit price of {take_profit_price_raw} in a collateral-is-quote market. Spot notional price: {}. Counter collateral: {}. Notional size: {}.", price_point.price_notional, self.counter_collateral,self.notional_size)),
            }
        }
    }

    /// Add a new delta neutrality fee to the position.
    pub fn add_delta_neutrality_fee(
        &mut self,
        amount: Signed<Collateral>,
        price_point: &PricePoint,
    ) -> Result<()> {
        self.delta_neutrality_fee
            .checked_add_assign(amount, price_point)
    }

    /// Get the price exposure for a given price movement.
    pub fn get_price_exposure(
        &self,
        start_price: Price,
        end_price: PricePoint,
    ) -> Result<Signed<Collateral>> {
        let price_delta = (end_price.price_notional.into_number() - start_price.into_number())?;
        Ok(Signed::<Collateral>::from_number(
            (price_delta * self.notional_size.into_number())?,
        ))
    }

    /// Apply a price change to this position.
    ///
    /// This will determine the exposure (positive == to trader, negative == to
    /// liquidity pool) impact and return whether the position can remain open
    /// or instructions to close it.
    pub fn settle_price_exposure(
        mut self,
        start_price: Price,
        end_price: PricePoint,
        liquidation_margin: Collateral,
    ) -> Result<(MaybeClosedPosition, Signed<Collateral>)> {
        let exposure = self.get_price_exposure(start_price, end_price)?;
        let min_exposure = liquidation_margin
            .into_signed()
            .checked_sub(self.active_collateral.into_signed())?;
        let max_exposure = self.counter_collateral.into_signed();

        Ok(if exposure <= min_exposure {
            (
                MaybeClosedPosition::Close(ClosePositionInstructions {
                    pos: self,
                    capped_exposure: min_exposure,
                    additional_losses: min_exposure
                        .checked_sub(exposure)?
                        .try_into_non_negative_value()
                        .context("Calculated additional_losses is negative")?,
                    settlement_price: end_price,
                    reason: PositionCloseReason::Liquidated(LiquidationReason::Liquidated),
                    closed_during_liquifunding: true,
                }),
                min_exposure,
            )
        } else if exposure >= max_exposure {
            (
                MaybeClosedPosition::Close(ClosePositionInstructions {
                    pos: self,
                    capped_exposure: max_exposure,
                    additional_losses: Collateral::zero(),
                    settlement_price: end_price,
                    reason: PositionCloseReason::Liquidated(LiquidationReason::MaxGains),
                    closed_during_liquifunding: true,
                }),
                max_exposure,
            )
        } else {
            self.active_collateral = self.active_collateral.checked_add_signed(exposure)?;
            self.counter_collateral = self.counter_collateral.checked_sub_signed(exposure)?;
            (MaybeClosedPosition::Open(self), exposure)
        })
    }

    /// Convert a position into a query response, calculating price exposure impact.
    #[allow(clippy::too_many_arguments)]
    pub fn into_query_response_extrapolate_exposure(
        mut self,
        start_price: PricePoint,
        end_price: PricePoint,
        entry_price: Price,
        market_type: MarketType,
        dnf_on_close_collateral: Signed<Collateral>,
    ) -> Result<PositionOrPendingClose> {
        let exposure = self.get_price_exposure(start_price.price_notional, end_price)?;

        let is_profit = exposure.is_strictly_positive();
        let exposure = exposure.abs_unsigned();

        let is_open = if is_profit {
            match self.counter_collateral.checked_sub(exposure) {
                Ok(counter_collateral) => {
                    self.counter_collateral = counter_collateral;
                    self.active_collateral = self.active_collateral.checked_add(exposure)?;
                    true
                }
                Err(_) => false,
            }
        } else {
            match self.active_collateral.checked_sub(exposure) {
                Ok(active_collateral) => {
                    self.active_collateral = active_collateral;
                    self.counter_collateral = self.counter_collateral.checked_add(exposure)?;
                    true
                }
                Err(_) => false,
            }
        };

        if is_open {
            self.into_query_response(end_price, entry_price, market_type, dnf_on_close_collateral)
                .map(|pos| PositionOrPendingClose::Open(Box::new(pos)))
        } else {
            let direction_to_base = self.direction().into_base(market_type);
            let entry_price_base = entry_price.into_base_price(market_type);

            // Figure out the final active collateral.
            let active_collateral = if is_profit {
                self.active_collateral.raw().checked_add(exposure)?
            } else {
                Collateral::zero()
            };

            let active_collateral_usd = end_price.collateral_to_usd(active_collateral);
            Ok(PositionOrPendingClose::PendingClose(Box::new(
                ClosedPosition {
                    owner: self.owner,
                    id: self.id,
                    direction_to_base,
                    created_at: self.created_at,
                    price_point_created_at: self.price_point_created_at,
                    liquifunded_at: self.liquifunded_at,
                    trading_fee_collateral: self.trading_fee.collateral(),
                    trading_fee_usd: self.trading_fee.usd(),
                    funding_fee_collateral: self.funding_fee.collateral(),
                    funding_fee_usd: self.funding_fee.usd(),
                    borrow_fee_collateral: self.borrow_fee.collateral(),
                    borrow_fee_usd: self.borrow_fee.usd(),
                    crank_fee_collateral: self.crank_fee.collateral(),
                    crank_fee_usd: self.crank_fee.usd(),
                    deposit_collateral: self.deposit_collateral.collateral(),
                    deposit_collateral_usd: self.deposit_collateral.usd(),
                    pnl_collateral: active_collateral
                        .into_signed()
                        .checked_sub(self.deposit_collateral.collateral())?,
                    pnl_usd: active_collateral_usd
                        .into_signed()
                        .checked_sub(self.deposit_collateral.usd())?,
                    notional_size: self.notional_size,
                    entry_price_base,
                    close_time: end_price.timestamp,
                    settlement_time: end_price.timestamp,
                    reason: PositionCloseReason::Liquidated(if is_profit {
                        LiquidationReason::MaxGains
                    } else {
                        LiquidationReason::Liquidated
                    }),
                    active_collateral,
                    delta_neutrality_fee_collateral: self.delta_neutrality_fee.collateral(),
                    delta_neutrality_fee_usd: self.delta_neutrality_fee.usd(),
                    liquidation_margin: Some(self.liquidation_margin),
                },
            )))
        }
    }

    /// Convert into a query response, without calculating price exposure impact.
    pub fn into_query_response(
        self,
        end_price: PricePoint,
        entry_price: Price,
        market_type: MarketType,
        dnf_on_close_collateral: Signed<Collateral>,
    ) -> Result<PositionQueryResponse> {
        let (direction_to_base, leverage) = self
            .active_leverage_to_notional(&end_price)
            .into_base(market_type)?
            .split();
        let counter_leverage = self
            .counter_leverage_to_notional(&end_price)
            .into_base(market_type)?
            .split()
            .1;
        let pnl_collateral = self.pnl_in_collateral()?;
        let pnl_usd = self.pnl_in_usd(&end_price)?;
        let notional_size_in_collateral = self.notional_size_in_collateral(&end_price);
        let position_size_base = self.position_size_base(market_type, &end_price)?;

        let Self {
            owner,
            id,
            active_collateral,
            deposit_collateral,
            counter_collateral,
            notional_size,
            created_at,
            price_point_created_at,
            trading_fee,
            funding_fee,
            borrow_fee,
            crank_fee,
            delta_neutrality_fee,
            liquifunded_at,
            next_liquifunding,
            stop_loss_override,
            liquidation_margin,
            liquidation_price,
            stop_loss_override_notional: _,
            take_profit_trader,
            take_profit_trader_notional: _,
            take_profit_total,
        } = self;

        // TODO: remove this once the deprecated fields are fully removed
        #[allow(deprecated)]
        Ok(PositionQueryResponse {
            owner,
            id,
            created_at,
            price_point_created_at,
            liquifunded_at,
            direction_to_base,
            leverage,
            counter_leverage,
            trading_fee_collateral: trading_fee.collateral(),
            trading_fee_usd: trading_fee.usd(),
            funding_fee_collateral: funding_fee.collateral(),
            funding_fee_usd: funding_fee.usd(),
            borrow_fee_collateral: borrow_fee.collateral(),
            borrow_fee_usd: borrow_fee.usd(),
            delta_neutrality_fee_collateral: delta_neutrality_fee.collateral(),
            delta_neutrality_fee_usd: delta_neutrality_fee.usd(),
            active_collateral,
            active_collateral_usd: end_price.collateral_to_usd_non_zero(active_collateral),
            deposit_collateral: deposit_collateral.collateral(),
            deposit_collateral_usd: deposit_collateral.usd(),
            pnl_collateral,
            pnl_usd,
            dnf_on_close_collateral,
            notional_size,
            notional_size_in_collateral,
            position_size_base,
            position_size_usd: position_size_base.map(|x| end_price.base_to_usd(x)),
            counter_collateral,
            max_gains_in_quote: None,
            liquidation_price_base: liquidation_price.map(|x| x.into_base_price(market_type)),
            liquidation_margin,
            take_profit_total_base: take_profit_total.map(|x| x.into_base_price(market_type)),
            entry_price_base: entry_price.into_base_price(market_type),
            next_liquifunding,
            stop_loss_override,
            take_profit_trader,
            crank_fee_collateral: crank_fee.collateral(),
            crank_fee_usd: crank_fee.usd(),
        })
    }

    /// Attributes for a position which can be emitted in events.
    pub fn attributes(&self) -> Vec<(&'static str, String)> {
        let LiquidationMargin {
            borrow: borrow_fee_max,
            funding: funding_max,
            delta_neutrality: slippage_max,
            crank,
            exposure,
        } = &self.liquidation_margin;
        vec![
            ("pos-owner", self.owner.to_string()),
            ("pos-id", self.id.to_string()),
            ("pos-active-collateral", self.active_collateral.to_string()),
            (
                "pos-deposit-collateral",
                self.deposit_collateral.collateral().to_string(),
            ),
            (
                "pos-deposit-collateral-usd",
                self.deposit_collateral.usd().to_string(),
            ),
            ("pos-trading-fee", self.trading_fee.collateral().to_string()),
            ("pos-trading-fee-usd", self.trading_fee.usd().to_string()),
            ("pos-crank-fee", self.crank_fee.collateral().to_string()),
            ("pos-crank-fee-usd", self.crank_fee.usd().to_string()),
            (
                "pos-counter-collateral",
                self.counter_collateral.to_string(),
            ),
            ("pos-notional-size", self.notional_size.to_string()),
            ("pos-created-at", self.created_at.to_string()),
            ("pos-liquifunded-at", self.liquifunded_at.to_string()),
            ("pos-next-liquifunding", self.next_liquifunding.to_string()),
            (
                "pos-borrow-fee-liquidation-margin",
                borrow_fee_max.to_string(),
            ),
            ("pos-funding-liquidation-margin", funding_max.to_string()),
            ("pos-slippage-liquidation-margin", slippage_max.to_string()),
            ("pos-crank-liquidation-margin", crank.to_string()),
            ("pos-exposure-liquidation-margin", exposure.to_string()),
        ]
    }
}

/// PositionId
#[cw_serde]
#[derive(Copy, PartialOrd, Ord, Eq)]
pub struct PositionId(Uint64);

#[cfg(feature = "arbitrary")]
impl<'a> arbitrary::Arbitrary<'a> for PositionId {
    fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
        u64::arbitrary(u).map(PositionId::new)
    }
}

#[allow(clippy::derived_hash_with_manual_eq)]
impl Hash for PositionId {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.u64().hash(state);
    }
}

impl PositionId {
    /// Construct a new value from a [u64].
    pub fn new(x: u64) -> Self {
        PositionId(x.into())
    }

    /// The underlying `u64` representation.
    pub fn u64(self) -> u64 {
        self.0.u64()
    }

    /// Generate the next position ID
    ///
    /// Panics on overflow
    pub fn next(self) -> Self {
        PositionId((self.u64() + 1).into())
    }
}

impl<'a> PrimaryKey<'a> for PositionId {
    type Prefix = ();
    type SubPrefix = ();
    type Suffix = Self;
    type SuperSuffix = Self;

    fn key(&self) -> Vec<Key> {
        vec![Key::Val64(self.0.u64().to_cw_bytes())]
    }
}

impl<'a> Prefixer<'a> for PositionId {
    fn prefix(&self) -> Vec<Key> {
        vec![Key::Val64(self.0.u64().to_cw_bytes())]
    }
}

impl KeyDeserialize for PositionId {
    type Output = PositionId;

    const KEY_ELEMS: u16 = 1;

    #[inline(always)]
    fn from_vec(value: Vec<u8>) -> StdResult<Self::Output> {
        u64::from_vec(value).map(|x| PositionId(Uint64::new(x)))
    }
}

impl fmt::Display for PositionId {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl FromStr for PositionId {
    type Err = ParseIntError;
    fn from_str(src: &str) -> Result<Self, ParseIntError> {
        src.parse().map(|x| PositionId(Uint64::new(x)))
    }
}

/// Events
pub mod events {
    use super::*;
    use crate::constants::{event_key, event_val};
    use cosmwasm_std::Event;

    /// Collaterals calculated on a position.
    #[cw_serde]
    pub struct PositionCollaterals {
        /// [PositionQueryResponse::deposit_collateral]
        pub deposit_collateral: Signed<Collateral>,
        /// [PositionQueryResponse::deposit_collateral_usd]
        pub deposit_collateral_usd: Signed<Usd>,
        /// [PositionQueryResponse::active_collateral]
        pub active_collateral: NonZero<Collateral>,
        /// [PositionQueryResponse::counter_collateral]
        pub counter_collateral: NonZero<Collateral>,
    }

    /// Trading fees paid for a position
    #[cw_serde]
    pub struct PositionTradingFee {
        /// In collateral
        pub trading_fee: Collateral,
        /// In USD
        pub trading_fee_usd: Usd,
    }

    /// Returns a tuple containing (base, quote) calculated based on the market type
    pub fn calculate_base_and_quote(
        market_type: MarketType,
        price: Price,
        amount: Number,
    ) -> Result<(Number, Number)> {
        Ok(match market_type {
            MarketType::CollateralIsQuote => (amount.checked_div(price.into_number())?, amount),
            MarketType::CollateralIsBase => (amount, amount.checked_mul(price.into_number())?),
        })
    }

    /// Calculate the collaterals for a position
    pub fn calculate_position_collaterals(pos: &Position) -> Result<PositionCollaterals> {
        Ok(PositionCollaterals {
            deposit_collateral: pos.deposit_collateral.collateral(),
            deposit_collateral_usd: pos.deposit_collateral.usd(),
            active_collateral: pos.active_collateral,
            counter_collateral: pos.counter_collateral,
        })
    }

    /// All attributes for a position
    #[cw_serde]
    pub struct PositionAttributes {
        /// [Position::id]
        pub pos_id: PositionId,
        /// [Position::owner]
        pub owner: Addr,
        /// Collaterals calculated on the position
        pub collaterals: PositionCollaterals,
        /// Type of the market it was opened in
        pub market_type: MarketType,
        /// [Position::notional_size]
        pub notional_size: Signed<Notional>,
        /// [PositionQueryResponse::notional_size_in_collateral]
        pub notional_size_in_collateral: Signed<Collateral>,
        /// Calculated using the exchange rate when the event was emitted
        pub notional_size_usd: Signed<Usd>,
        /// Trading fee
        pub trading_fee: PositionTradingFee,
        /// Direction
        pub direction: DirectionToBase,
        /// Trader leverage
        pub leverage: LeverageToBase,
        /// Counter leverage
        pub counter_leverage: LeverageToBase,
        /// Stop loss price
        pub stop_loss_override: Option<PriceBaseInQuote>,
        /// Take profit price set by trader
        /// For historical reasons, this value can be optional if the user provided a max gains price.
        #[serde(rename = "take_profit_override")]
        pub take_profit_trader: Option<TakeProfitTrader>,
    }

    impl PositionAttributes {
        fn add_to_event(&self, event: &Event) -> Event {
            let mut event = event
                .clone()
                .add_attribute(event_key::POS_ID, self.pos_id.to_string())
                .add_attribute(event_key::POS_OWNER, self.owner.clone())
                .add_attribute(
                    event_key::DEPOSIT_COLLATERAL,
                    self.collaterals.deposit_collateral.to_string(),
                )
                .add_attribute(
                    event_key::DEPOSIT_COLLATERAL_USD,
                    self.collaterals.deposit_collateral_usd.to_string(),
                )
                .add_attribute(
                    event_key::ACTIVE_COLLATERAL,
                    self.collaterals.active_collateral.to_string(),
                )
                .add_attribute(
                    event_key::COUNTER_COLLATERAL,
                    self.collaterals.counter_collateral.to_string(),
                )
                .add_attribute(
                    event_key::MARKET_TYPE,
                    match self.market_type {
                        MarketType::CollateralIsQuote => event_val::NOTIONAL_BASE,
                        MarketType::CollateralIsBase => event_val::COLLATERAL_BASE,
                    },
                )
                .add_attribute(event_key::NOTIONAL_SIZE, self.notional_size.to_string())
                .add_attribute(
                    event_key::NOTIONAL_SIZE_IN_COLLATERAL,
                    self.notional_size_in_collateral.to_string(),
                )
                .add_attribute(
                    event_key::NOTIONAL_SIZE_USD,
                    self.notional_size_usd.to_string(),
                )
                .add_attribute(
                    event_key::TRADING_FEE,
                    self.trading_fee.trading_fee.to_string(),
                )
                .add_attribute(
                    event_key::TRADING_FEE_USD,
                    self.trading_fee.trading_fee_usd.to_string(),
                )
                .add_attribute(event_key::DIRECTION, self.direction.as_str())
                .add_attribute(event_key::LEVERAGE, self.leverage.to_string())
                .add_attribute(
                    event_key::COUNTER_LEVERAGE,
                    self.counter_leverage.to_string(),
                );

            if let Some(stop_loss_override) = self.stop_loss_override {
                event = event.add_attribute(
                    event_key::STOP_LOSS_OVERRIDE,
                    stop_loss_override.to_string(),
                );
            }

            if let Some(take_profit_trader) = self.take_profit_trader {
                event = event.add_attribute(
                    event_key::TAKE_PROFIT_OVERRIDE,
                    take_profit_trader.to_string(),
                );
            }

            event
        }
    }

    impl TryFrom<Event> for PositionAttributes {
        type Error = anyhow::Error;

        fn try_from(evt: Event) -> anyhow::Result<Self> {
            Ok(Self {
                pos_id: PositionId::new(evt.u64_attr(event_key::POS_ID)?),
                owner: evt.unchecked_addr_attr(event_key::POS_OWNER)?,
                collaterals: PositionCollaterals {
                    deposit_collateral: evt.number_attr(event_key::DEPOSIT_COLLATERAL)?,
                    deposit_collateral_usd: evt.number_attr(event_key::DEPOSIT_COLLATERAL_USD)?,
                    active_collateral: evt.non_zero_attr(event_key::ACTIVE_COLLATERAL)?,
                    counter_collateral: evt.non_zero_attr(event_key::COUNTER_COLLATERAL)?,
                },
                market_type: evt.map_attr_result(event_key::MARKET_TYPE, |s| match s {
                    event_val::NOTIONAL_BASE => Ok(MarketType::CollateralIsQuote),
                    event_val::COLLATERAL_BASE => Ok(MarketType::CollateralIsBase),
                    _ => Err(PerpError::unimplemented().into()),
                })?,
                notional_size: evt.number_attr(event_key::NOTIONAL_SIZE)?,
                notional_size_in_collateral: evt
                    .number_attr(event_key::NOTIONAL_SIZE_IN_COLLATERAL)?,
                notional_size_usd: evt.number_attr(event_key::NOTIONAL_SIZE_USD)?,
                trading_fee: PositionTradingFee {
                    trading_fee: evt.decimal_attr(event_key::TRADING_FEE)?,
                    trading_fee_usd: evt.decimal_attr(event_key::TRADING_FEE_USD)?,
                },
                direction: evt.direction_attr(event_key::DIRECTION)?,
                leverage: evt.leverage_to_base_attr(event_key::LEVERAGE)?,
                counter_leverage: evt.leverage_to_base_attr(event_key::COUNTER_LEVERAGE)?,
                stop_loss_override: match evt.try_number_attr(event_key::STOP_LOSS_OVERRIDE)? {
                    None => None,
                    Some(stop_loss_override) => {
                        Some(PriceBaseInQuote::try_from_number(stop_loss_override)?)
                    }
                },
                take_profit_trader: evt
                    .try_map_attr(event_key::TAKE_PROFIT_OVERRIDE, |s| {
                        TakeProfitTrader::try_from(s)
                    })
                    .transpose()?,
            })
        }
    }

    /// A position was closed
    #[derive(Debug, Clone)]
    pub struct PositionCloseEvent {
        /// Details on the closed position
        pub closed_position: ClosedPosition,
    }

    impl TryFrom<PositionCloseEvent> for Event {
        type Error = anyhow::Error;

        fn try_from(
            PositionCloseEvent {
                closed_position:
                    ClosedPosition {
                        owner,
                        id,
                        direction_to_base,
                        created_at,
                        price_point_created_at,
                        liquifunded_at,
                        trading_fee_collateral,
                        trading_fee_usd,
                        funding_fee_collateral,
                        funding_fee_usd,
                        borrow_fee_collateral,
                        borrow_fee_usd,
                        crank_fee_collateral,
                        crank_fee_usd,
                        delta_neutrality_fee_collateral,
                        delta_neutrality_fee_usd,
                        deposit_collateral,
                        deposit_collateral_usd,
                        active_collateral,
                        pnl_collateral,
                        pnl_usd,
                        notional_size,
                        entry_price_base,
                        close_time,
                        settlement_time,
                        reason,
                        liquidation_margin,
                    },
            }: PositionCloseEvent,
        ) -> anyhow::Result<Self> {
            let mut event = Event::new(event_key::POSITION_CLOSE)
                .add_attribute(event_key::POS_OWNER, owner.to_string())
                .add_attribute(event_key::POS_ID, id.to_string())
                .add_attribute(event_key::DIRECTION, direction_to_base.as_str())
                .add_attribute(event_key::CREATED_AT, created_at.to_string())
                .add_attribute(event_key::LIQUIFUNDED_AT, liquifunded_at.to_string())
                .add_attribute(event_key::TRADING_FEE, trading_fee_collateral.to_string())
                .add_attribute(event_key::TRADING_FEE_USD, trading_fee_usd.to_string())
                .add_attribute(event_key::FUNDING_FEE, funding_fee_collateral.to_string())
                .add_attribute(event_key::FUNDING_FEE_USD, funding_fee_usd.to_string())
                .add_attribute(event_key::BORROW_FEE, borrow_fee_collateral.to_string())
                .add_attribute(event_key::BORROW_FEE_USD, borrow_fee_usd.to_string())
                .add_attribute(
                    event_key::DELTA_NEUTRALITY_FEE,
                    delta_neutrality_fee_collateral.to_string(),
                )
                .add_attribute(
                    event_key::DELTA_NEUTRALITY_FEE_USD,
                    delta_neutrality_fee_usd.to_string(),
                )
                .add_attribute(event_key::CRANK_FEE, crank_fee_collateral.to_string())
                .add_attribute(event_key::CRANK_FEE_USD, crank_fee_usd.to_string())
                .add_attribute(
                    event_key::DEPOSIT_COLLATERAL,
                    deposit_collateral.to_string(),
                )
                .add_attribute(
                    event_key::DEPOSIT_COLLATERAL_USD,
                    deposit_collateral_usd.to_string(),
                )
                .add_attribute(event_key::PNL, pnl_collateral.to_string())
                .add_attribute(event_key::PNL_USD, pnl_usd.to_string())
                .add_attribute(event_key::NOTIONAL_SIZE, notional_size.to_string())
                .add_attribute(event_key::ENTRY_PRICE, entry_price_base.to_string())
                .add_attribute(event_key::CLOSED_AT, close_time.to_string())
                .add_attribute(event_key::SETTLED_AT, settlement_time.to_string())
                .add_attribute(
                    event_key::CLOSE_REASON,
                    match reason {
                        PositionCloseReason::Liquidated(LiquidationReason::Liquidated) => {
                            event_val::LIQUIDATED
                        }
                        PositionCloseReason::Liquidated(LiquidationReason::MaxGains) => {
                            event_val::MAX_GAINS
                        }
                        PositionCloseReason::Liquidated(LiquidationReason::StopLoss) => {
                            event_val::STOP_LOSS
                        }
                        PositionCloseReason::Liquidated(LiquidationReason::TakeProfit) => {
                            event_val::TAKE_PROFIT
                        }
                        PositionCloseReason::Direct => event_val::DIRECT,
                    },
                )
                .add_attribute(event_key::ACTIVE_COLLATERAL, active_collateral.to_string());
            if let Some(x) = price_point_created_at {
                event = event.add_attribute(event_key::PRICE_POINT_CREATED_AT, x.to_string());
            }
            if let Some(x) = liquidation_margin {
                event = event
                    .add_attribute(event_key::LIQUIDATION_MARGIN_BORROW, x.borrow.to_string())
                    .add_attribute(event_key::LIQUIDATION_MARGIN_FUNDING, x.funding.to_string())
                    .add_attribute(
                        event_key::LIQUIDATION_MARGIN_DNF,
                        x.delta_neutrality.to_string(),
                    )
                    .add_attribute(event_key::LIQUIDATION_MARGIN_CRANK, x.crank.to_string())
                    .add_attribute(
                        event_key::LIQUIDATION_MARGIN_EXPOSURE,
                        x.exposure.to_string(),
                    )
                    .add_attribute(event_key::LIQUIDATION_MARGIN_TOTAL, x.total()?.to_string());
            }

            Ok(event)
        }
    }
    impl TryFrom<Event> for PositionCloseEvent {
        type Error = anyhow::Error;

        fn try_from(evt: Event) -> anyhow::Result<Self> {
            let closed_position = ClosedPosition {
                close_time: evt.timestamp_attr(event_key::CLOSED_AT)?,
                settlement_time: evt.timestamp_attr(event_key::SETTLED_AT)?,
                reason: evt.map_attr_result(event_key::CLOSE_REASON, |s| match s {
                    event_val::LIQUIDATED => Ok(PositionCloseReason::Liquidated(
                        LiquidationReason::Liquidated,
                    )),
                    event_val::MAX_GAINS => {
                        Ok(PositionCloseReason::Liquidated(LiquidationReason::MaxGains))
                    }
                    event_val::STOP_LOSS => {
                        Ok(PositionCloseReason::Liquidated(LiquidationReason::StopLoss))
                    }
                    event_val::TAKE_PROFIT => Ok(PositionCloseReason::Liquidated(
                        LiquidationReason::TakeProfit,
                    )),
                    event_val::DIRECT => Ok(PositionCloseReason::Direct),
                    _ => Err(PerpError::unimplemented().into()),
                })?,
                owner: evt.unchecked_addr_attr(event_key::POS_OWNER)?,
                id: PositionId::new(evt.u64_attr(event_key::POS_ID)?),
                direction_to_base: evt.direction_attr(event_key::DIRECTION)?,
                created_at: evt.timestamp_attr(event_key::CREATED_AT)?,
                price_point_created_at: evt
                    .try_timestamp_attr(event_key::PRICE_POINT_CREATED_AT)?,
                liquifunded_at: evt.timestamp_attr(event_key::LIQUIFUNDED_AT)?,
                trading_fee_collateral: evt.decimal_attr(event_key::TRADING_FEE)?,
                trading_fee_usd: evt.decimal_attr(event_key::TRADING_FEE_USD)?,
                funding_fee_collateral: evt.number_attr(event_key::FUNDING_FEE)?,
                funding_fee_usd: evt.number_attr(event_key::FUNDING_FEE_USD)?,
                borrow_fee_collateral: evt.decimal_attr(event_key::BORROW_FEE)?,
                borrow_fee_usd: evt.decimal_attr(event_key::BORROW_FEE_USD)?,
                crank_fee_collateral: evt.decimal_attr(event_key::CRANK_FEE)?,
                crank_fee_usd: evt.decimal_attr(event_key::CRANK_FEE_USD)?,
                delta_neutrality_fee_collateral: evt
                    .number_attr(event_key::DELTA_NEUTRALITY_FEE)?,
                delta_neutrality_fee_usd: evt.number_attr(event_key::DELTA_NEUTRALITY_FEE_USD)?,
                deposit_collateral: evt.number_attr(event_key::DEPOSIT_COLLATERAL)?,
                deposit_collateral_usd: evt
                    // For migrations, this data wasn't always present
                    .try_number_attr(event_key::DEPOSIT_COLLATERAL_USD)?
                    .unwrap_or_default(),
                pnl_collateral: evt.number_attr(event_key::PNL)?,
                pnl_usd: evt.number_attr(event_key::PNL_USD)?,
                notional_size: evt.number_attr(event_key::NOTIONAL_SIZE)?,
                entry_price_base: PriceBaseInQuote::try_from_number(
                    evt.number_attr(event_key::ENTRY_PRICE)?,
                )?,
                active_collateral: evt.decimal_attr(event_key::ACTIVE_COLLATERAL)?,
                liquidation_margin: match (
                    evt.try_decimal_attr::<Collateral>(event_key::LIQUIDATION_MARGIN_BORROW)?,
                    evt.try_decimal_attr::<Collateral>(event_key::LIQUIDATION_MARGIN_FUNDING)?,
                    evt.try_decimal_attr::<Collateral>(event_key::LIQUIDATION_MARGIN_DNF)?,
                    evt.try_decimal_attr::<Collateral>(event_key::LIQUIDATION_MARGIN_CRANK)?,
                    evt.try_decimal_attr::<Collateral>(event_key::LIQUIDATION_MARGIN_EXPOSURE)?,
                ) {
                    (
                        Some(borrow),
                        Some(funding),
                        Some(delta_neutrality),
                        Some(crank),
                        Some(exposure),
                    ) => Some(LiquidationMargin {
                        borrow,
                        funding,
                        delta_neutrality,
                        crank,
                        exposure,
                    }),
                    _ => None,
                },
            };
            Ok(PositionCloseEvent { closed_position })
        }
    }

    /// A position was opened
    pub struct PositionOpenEvent {
        /// Details of the position
        pub position_attributes: PositionAttributes,
        /// When it was opened, block time
        pub created_at: Timestamp,
        /// Price point used for creating this
        pub price_point_created_at: Timestamp,
    }

    impl From<PositionOpenEvent> for Event {
        fn from(src: PositionOpenEvent) -> Self {
            let event = Event::new(event_key::POSITION_OPEN)
                .add_attribute(event_key::CREATED_AT, src.created_at.to_string());

            src.position_attributes.add_to_event(&event)
        }
    }
    impl TryFrom<Event> for PositionOpenEvent {
        type Error = anyhow::Error;

        fn try_from(evt: Event) -> anyhow::Result<Self> {
            Ok(Self {
                created_at: evt.timestamp_attr(event_key::CREATED_AT)?,
                price_point_created_at: evt.timestamp_attr(event_key::PRICE_POINT_CREATED_AT)?,
                position_attributes: evt.try_into()?,
            })
        }
    }

    /// Event when a position has been updated
    #[cw_serde]
    pub struct PositionUpdateEvent {
        /// Attributes about the position
        pub position_attributes: PositionAttributes,
        /// Amount of collateral added or removed to the position
        pub deposit_collateral_delta: Signed<Collateral>,
        /// [Self::deposit_collateral_delta] converted to USD at the current price.
        pub deposit_collateral_delta_usd: Signed<Usd>,
        /// Change to active collateral
        pub active_collateral_delta: Signed<Collateral>,
        /// [Self::active_collateral_delta] converted to USD at the current price.
        pub active_collateral_delta_usd: Signed<Usd>,
        /// Change to counter collateral
        pub counter_collateral_delta: Signed<Collateral>,
        /// [Self::counter_collateral_delta] converted to USD at the current price.
        pub counter_collateral_delta_usd: Signed<Usd>,
        /// Change in trader leverage
        pub leverage_delta: Signed<Decimal256>,
        /// Change in counter collateral leverage
        pub counter_leverage_delta: Signed<Decimal256>,
        /// Change in the notional size
        pub notional_size_delta: Signed<Notional>,
        /// [Self::notional_size_delta] converted to USD at the current price.
        pub notional_size_delta_usd: Signed<Usd>,
        /// The change in notional size from the absolute value
        ///
        /// not the absolute value of delta itself
        /// e.g. from -10 to -15 will be 5, because it's the delta of 15-10
        /// but -15 to -10 will be -5, because it's the delta of 10-15
        pub notional_size_abs_delta: Signed<Notional>,
        /// [Self::notional_size_abs_delta] converted to USD at the current price.
        pub notional_size_abs_delta_usd: Signed<Usd>,
        /// Additional trading fee paid
        pub trading_fee_delta: Collateral,
        /// [Self::trading_fee_delta] converted to USD at the current price.
        pub trading_fee_delta_usd: Usd,
        /// Additional delta neutrality fee paid (or received)
        pub delta_neutrality_fee_delta: Signed<Collateral>,
        /// [Self::delta_neutrality_fee_delta] converted to USD at the current price.
        pub delta_neutrality_fee_delta_usd: Signed<Usd>,
        /// When the update occurred
        pub updated_at: Timestamp,
    }

    impl From<PositionUpdateEvent> for Event {
        fn from(
            PositionUpdateEvent {
                position_attributes,
                deposit_collateral_delta,
                deposit_collateral_delta_usd,
                active_collateral_delta,
                active_collateral_delta_usd,
                counter_collateral_delta,
                counter_collateral_delta_usd,
                leverage_delta,
                counter_leverage_delta,
                notional_size_delta,
                notional_size_delta_usd,
                notional_size_abs_delta,
                notional_size_abs_delta_usd,
                trading_fee_delta,
                trading_fee_delta_usd,
                delta_neutrality_fee_delta,
                delta_neutrality_fee_delta_usd,
                updated_at,
            }: PositionUpdateEvent,
        ) -> Self {
            let event = Event::new(event_key::POSITION_UPDATE)
                .add_attribute(event_key::UPDATED_AT, updated_at.to_string())
                .add_attribute(
                    event_key::DEPOSIT_COLLATERAL_DELTA,
                    deposit_collateral_delta.to_string(),
                )
                .add_attribute(
                    event_key::DEPOSIT_COLLATERAL_DELTA_USD,
                    deposit_collateral_delta_usd.to_string(),
                )
                .add_attribute(
                    event_key::ACTIVE_COLLATERAL_DELTA,
                    active_collateral_delta.to_string(),
                )
                .add_attribute(
                    event_key::ACTIVE_COLLATERAL_DELTA_USD,
                    active_collateral_delta_usd.to_string(),
                )
                .add_attribute(
                    event_key::COUNTER_COLLATERAL_DELTA,
                    counter_collateral_delta.to_string(),
                )
                .add_attribute(
                    event_key::COUNTER_COLLATERAL_DELTA_USD,
                    counter_collateral_delta_usd.to_string(),
                )
                .add_attribute(event_key::LEVERAGE_DELTA, leverage_delta.to_string())
                .add_attribute(
                    event_key::COUNTER_LEVERAGE_DELTA,
                    counter_leverage_delta.to_string(),
                )
                .add_attribute(
                    event_key::NOTIONAL_SIZE_DELTA,
                    notional_size_delta.to_string(),
                )
                .add_attribute(
                    event_key::NOTIONAL_SIZE_DELTA_USD,
                    notional_size_delta_usd.to_string(),
                )
                .add_attribute(
                    event_key::NOTIONAL_SIZE_ABS_DELTA,
                    notional_size_abs_delta.to_string(),
                )
                .add_attribute(
                    event_key::NOTIONAL_SIZE_ABS_DELTA_USD,
                    notional_size_abs_delta_usd.to_string(),
                )
                .add_attribute(event_key::TRADING_FEE_DELTA, trading_fee_delta.to_string())
                .add_attribute(
                    event_key::TRADING_FEE_DELTA_USD,
                    trading_fee_delta_usd.to_string(),
                )
                .add_attribute(
                    event_key::DELTA_NEUTRALITY_FEE_DELTA,
                    delta_neutrality_fee_delta.to_string(),
                )
                .add_attribute(
                    event_key::DELTA_NEUTRALITY_FEE_DELTA_USD,
                    delta_neutrality_fee_delta_usd.to_string(),
                );

            position_attributes.add_to_event(&event)
        }
    }

    impl TryFrom<Event> for PositionUpdateEvent {
        type Error = anyhow::Error;

        fn try_from(evt: Event) -> anyhow::Result<Self> {
            Ok(Self {
                updated_at: evt.timestamp_attr(event_key::UPDATED_AT)?,
                deposit_collateral_delta: evt.number_attr(event_key::DEPOSIT_COLLATERAL_DELTA)?,
                deposit_collateral_delta_usd: evt
                    .number_attr(event_key::DEPOSIT_COLLATERAL_DELTA_USD)?,
                active_collateral_delta: evt.number_attr(event_key::ACTIVE_COLLATERAL_DELTA)?,
                active_collateral_delta_usd: evt
                    .number_attr(event_key::ACTIVE_COLLATERAL_DELTA_USD)?,
                counter_collateral_delta: evt.number_attr(event_key::COUNTER_COLLATERAL_DELTA)?,
                counter_collateral_delta_usd: evt
                    .number_attr(event_key::COUNTER_COLLATERAL_DELTA_USD)?,
                leverage_delta: evt.number_attr(event_key::LEVERAGE_DELTA)?,
                counter_leverage_delta: evt.number_attr(event_key::COUNTER_LEVERAGE_DELTA)?,
                notional_size_delta: evt.number_attr(event_key::NOTIONAL_SIZE_DELTA)?,
                notional_size_delta_usd: evt.number_attr(event_key::NOTIONAL_SIZE_DELTA_USD)?,
                notional_size_abs_delta: evt.number_attr(event_key::NOTIONAL_SIZE_ABS_DELTA)?,
                notional_size_abs_delta_usd: evt
                    .number_attr(event_key::NOTIONAL_SIZE_ABS_DELTA_USD)?,
                trading_fee_delta: evt.decimal_attr(event_key::TRADING_FEE_DELTA)?,
                trading_fee_delta_usd: evt.decimal_attr(event_key::TRADING_FEE_DELTA_USD)?,
                delta_neutrality_fee_delta: evt
                    .number_attr(event_key::DELTA_NEUTRALITY_FEE_DELTA)?,
                delta_neutrality_fee_delta_usd: evt
                    .number_attr(event_key::DELTA_NEUTRALITY_FEE_DELTA_USD)?,
                position_attributes: evt.try_into()?,
            })
        }
    }

    /// Emitted each time a position is saved
    #[derive(Clone, Copy, PartialEq, Eq, Debug)]
    pub struct PositionSaveEvent {
        /// ID of the position
        pub id: PositionId,
        /// Reason the position was saved
        pub reason: PositionSaveReason,
    }

    /// Why was a position saved?
    #[derive(Clone, Copy, PartialEq, Eq, Debug)]
    pub enum PositionSaveReason {
        /// Newly opened position via market order
        OpenMarket,
        /// Update to an existing position
        Update,
        /// The crank processed this position for liquifunding
        Crank,
        /// A limit order was executed
        ExecuteLimitOrder,
        /// User attempted to set a trigger price on an existing position
        SetTrigger,
    }

    impl PositionSaveReason {
        /// Get the [CongestionReason] for this value.
        ///
        /// If this user action can result in a congestion error message,
        /// provide the [CongestionReason] value. If [None], then this
        /// [PositionSaveReason] cannot be blocked because of congestion.
        pub fn into_congestion_reason(self) -> Option<CongestionReason> {
            match self {
                PositionSaveReason::OpenMarket => Some(CongestionReason::OpenMarket),
                PositionSaveReason::Update => Some(CongestionReason::Update),
                PositionSaveReason::Crank => None,
                PositionSaveReason::ExecuteLimitOrder => None,
                PositionSaveReason::SetTrigger => Some(CongestionReason::SetTrigger),
            }
        }

        /// Represent as a string
        pub fn as_str(self) -> &'static str {
            match self {
                PositionSaveReason::OpenMarket => "open",
                PositionSaveReason::Update => "update",
                PositionSaveReason::Crank => "crank",
                PositionSaveReason::ExecuteLimitOrder => "limit-order",
                PositionSaveReason::SetTrigger => "set-trigger",
            }
        }
    }

    impl From<PositionSaveEvent> for Event {
        fn from(PositionSaveEvent { id, reason }: PositionSaveEvent) -> Self {
            Event::new("position-save")
                .add_attribute("id", id.0)
                .add_attribute("reason", reason.as_str())
        }
    }
}