dydx 0.3.0

dYdX v4 asynchronous client.
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
use crate::node::OrderMarketParams;
use anyhow::{anyhow as err, Error};
use bigdecimal::BigDecimal;
use chrono::{DateTime, Utc};
use cosmrs::{AccountId, Denom as CosmosDenom};
use derive_more::{Add, Deref, DerefMut, Display, Div, From, Mul, Sub};
use dydx_proto::dydxprotocol::subaccounts::SubaccountId as ProtoSubaccountId;
use rand::{rng, Rng};
use serde::{Deserialize, Deserializer, Serialize};
use serde_with::{serde_as, DisplayFromStr};
use std::collections::HashMap;
use std::convert::TryFrom;
use std::{fmt, str::FromStr};

// Shared types used by REST API, WS

/// A trader's account with a parent subaccount number.
#[derive(Deserialize, Debug, Clone, Eq, Hash, PartialOrd, Ord, PartialEq)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(any(test, feature = "strict-serde"), serde(deny_unknown_fields))]
pub struct AccountWithParentSubaccountNumber {
    /// Address.
    pub address: Address,
    /// Parent subaccount number.
    pub parent_subaccount_number: Option<ParentSubaccountNumber>,
}

/// A trader's account.
#[derive(Deserialize, Debug, Clone, Eq, Hash, PartialOrd, Ord, PartialEq)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(any(test, feature = "strict-serde"), serde(deny_unknown_fields))]
pub struct Account {
    /// Address.
    pub address: Address,
    /// Parent subaccount number.
    pub subaccount_number: Option<SubaccountNumber>,
}

/// [Address](https://dydx.exchange/crypto-learning/what-is-a-wallet-address).
#[derive(
    Default,
    Serialize,
    Deserialize,
    Debug,
    Clone,
    From,
    Display,
    PartialEq,
    Eq,
    PartialOrd,
    Ord,
    Hash,
)]
pub struct Address(String);

impl FromStr for Address {
    type Err = Error;
    fn from_str(value: &str) -> Result<Self, Error> {
        Ok(Self(
            value.parse::<AccountId>().map_err(Error::msg)?.to_string(),
        ))
    }
}

impl AsRef<str> for Address {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl From<Address> for String {
    fn from(address: Address) -> Self {
        address.0
    }
}

/// Order status.
#[derive(Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase", untagged)]
pub enum ApiOrderStatus {
    /// Order status.
    OrderStatus(OrderStatus),
    /// Best effort.
    BestEffort(BestEffortOpenedStatus),
}

/// [Time-in-Force](https://docs.dydx.xyz/types/time_in_force#time-in-force).
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum ApiTimeInForce {
    /// GTT represents Good-Til-Time, where an order will first match with existing orders on the book
    /// and any remaining size will be added to the book as a maker order, which will expire at a
    /// given expiry time.
    Gtt,
    /// FOK represents Fill-Or-KILl where it's enforced that an order will either be filled
    /// completely and immediately by maker orders on the book or canceled if the entire amount can't
    /// be filled.
    Fok,
    /// IOC represents Immediate-Or-Cancel, where it's enforced that an order only be matched with
    /// maker orders on the book. If the order has remaining size after matching with existing orders
    /// on the book, the remaining size is not placed on the book.
    Ioc,
}

/// Asset id.
#[derive(
    Serialize, Deserialize, Debug, Clone, From, Display, PartialEq, Eq, PartialOrd, Ord, Hash,
)]
pub struct AssetId(pub String);

/// Best-effort opened status.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum BestEffortOpenedStatus {
    /// Best-effort opened.
    BestEffortOpened,
}

/// Candle resolution.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum CandleResolution {
    /// 1-minute.
    #[serde(rename = "1MIN")]
    M1,
    /// 5-minutes.
    #[serde(rename = "5MINS")]
    M5,
    /// 15-minutes.
    #[serde(rename = "15MINS")]
    M15,
    /// 30-minutes.
    #[serde(rename = "30MINS")]
    M30,
    /// 1-hour.
    #[serde(rename = "1HOUR")]
    H1,
    /// 4-hours.
    #[serde(rename = "4HOURS")]
    H4,
    /// 1-day.
    #[serde(rename = "1DAY")]
    D1,
}

/// Representation of an arbitrary ID.
#[derive(Clone, Debug)]
pub struct AnyId;

/// Client ID defined by the user to identify orders.
///
/// This value should be different for different orders.
/// To update a specific previously submitted order, the new [`Order`](dydx_proto::dydxprotocol::clob::Order) must have the same client ID, and the same [`OrderId`].
/// See also: [Replacements](https://docs.dydx.xyz/concepts/trading/limit-orderbook#replacements).
#[serde_as]
#[derive(Deserialize, Debug, Clone, Display, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ClientId(#[serde_as(as = "DisplayFromStr")] pub u32);

impl ClientId {
    /// Creates a new `ClientId` from a provided `u32`.
    pub fn new(id: u32) -> Self {
        ClientId(id)
    }

    /// Creates a random `ClientId` using the default rand::rng.
    pub fn random() -> Self {
        ClientId(rng().random())
    }

    /// Creates a random `ClientId` using a user-provided RNG.
    pub fn random_with_rng<R: Rng>(rng: &mut R) -> Self {
        ClientId(rng.random())
    }
}

impl From<u32> for ClientId {
    fn from(value: u32) -> Self {
        Self(value)
    }
}

impl From<AnyId> for ClientId {
    fn from(_: AnyId) -> Self {
        Self::random()
    }
}

/// Clob pair id.
#[serde_as]
#[derive(Deserialize, Serialize, Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ClobPairId(#[serde_as(as = "DisplayFromStr")] pub u32);

impl From<u32> for ClobPairId {
    fn from(value: u32) -> Self {
        Self(value)
    }
}

impl From<&u32> for ClobPairId {
    fn from(value: &u32) -> Self {
        ClobPairId::from(*value)
    }
}

/// Client metadata.
#[serde_as]
#[derive(Deserialize, Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ClientMetadata(#[serde_as(as = "DisplayFromStr")] pub u32);

impl From<u32> for ClientMetadata {
    fn from(value: u32) -> Self {
        Self(value)
    }
}

/// Fill id.
#[derive(Deserialize, Debug, Clone, From, Display, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct FillId(pub String);

/// Fill type.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum FillType {
    /// LIMIT is the fill type for a fill with a limit taker order.
    Limit,
    /// LIQUIDATED is for the taker side of the fill where the subaccount was liquidated.
    ///
    /// The subaccountId associated with this fill is the liquidated subaccount.
    Liquidated,
    /// LIQUIDATION is for the maker side of the fill, never used for orders.
    Liquidation,
    /// DELEVERAGED is for the subaccount that was deleveraged in a deleveraging event.
    ///
    /// The fill type will be set to taker.
    Deleveraged,
    /// OFFSETTING is for the offsetting subaccount in a deleveraging event.
    ///
    /// The fill type will be set to maker.
    Offsetting,
}

/// Block height.
#[serde_as]
#[derive(
    Serialize, Deserialize, Debug, Clone, From, Display, PartialEq, Eq, PartialOrd, Ord, Hash,
)]
pub struct Height(#[serde_as(as = "DisplayFromStr")] pub u32);

impl Height {
    /// Get the block which is n blocks ahead.
    pub fn ahead(&self, n: u32) -> Height {
        Height(self.0 + n)
    }
}

/// Liquidity position.
///
/// See also [Market Makers vs Market Takers](https://dydx.exchange/crypto-learning/market-makers-vs-market-takers).
#[derive(Deserialize, Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum Liquidity {
    /// [Taker](https://dydx.exchange/crypto-learning/glossary?#taker).
    Taker,
    /// [Maker](https://dydx.exchange/crypto-learning/glossary?#maker).
    Maker,
}

/// Perpetual market status
#[derive(Deserialize, Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PerpetualMarketStatus {
    /// Active.
    Active,
    /// Paused.
    Paused,
    /// Cancel-only.
    CancelOnly,
    /// Post-only.
    PostOnly,
    /// Initializing.
    Initializing,
    /// Final settlement.
    FinalSettlement,
}

/// Perpetual position status.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PerpetualPositionStatus {
    /// Open.
    Open,
    /// Closed.
    Closed,
    /// Liquidated.
    Liquidated,
}

/// Position.
///
/// See also [How to Short Crypto: A Beginner’s Guide](https://dydx.exchange/crypto-learning/how-to-short-crypto).
#[derive(Deserialize, Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PositionSide {
    /// Long.
    Long,
    /// Short.
    Short,
}

/// Market type.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum MarketType {
    /// [Perpetuals](https://dydx.exchange/crypto-learning/perpetuals-crypto).
    Perpetual,
    /// [Spot](https://dydx.exchange/crypto-learning/what-is-spot-trading).
    Spot,
}

/// Perpetual market type.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PerpetualMarketType {
    /// Cross.
    Cross,
    /// [Isolated](https://docs.dydx.xyz/concepts/trading/isolated-markets#isolated-markets).
    Isolated,
}

/// Order id.
#[derive(Deserialize, Debug, Clone, From, Display, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct OrderId(pub String);

/// Order status.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum OrderStatus {
    /// Opened.
    Open,
    /// Filled.
    Filled,
    /// Canceled.
    Canceled,
    /// Short term cancellations are handled best-effort, meaning they are only gossiped.
    BestEffortCanceled,
    /// Untriggered.
    Untriggered,
}

/// When the order enters the execution phase
///
/// See also [Time in force](https://docs.dydx.xyz/types/time_in_force#time-in-force).
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum OrderExecution {
    /// Leaving order execution as unspecified/empty represents the default behavior
    /// where an order will first match with existing orders on the book, and any remaining size
    /// will be added to the book as a maker order.
    Default,
    /// IOC represents Immediate-Or-Cancel, where it's enforced that an order only be matched with
    /// maker orders on the book. If the order has remaining size after matching with existing orders
    /// on the book, the remaining size is not placed on the book.
    Ioc,
    /// FOK represents Fill-Or-KILl where it's enforced that an order will either be filled
    /// completely and immediately by maker orders on the book or canceled if the entire amount can't
    /// be filled.
    Fok,
    /// Post only enforces that an order only be placed on the book as a maker order.
    /// Note this means that validators will cancel any newly-placed post only orders that would cross with other maker orders.
    PostOnly,
}

/// Order flags.
#[derive(Clone, Debug, Deserialize)]
pub enum OrderFlags {
    /// Short-term order.
    #[serde(rename = "0")]
    ShortTerm = 0,
    /// Conditional order.
    #[serde(rename = "32")]
    Conditional = 32,
    /// Long-term (stateful) order.
    #[serde(rename = "64")]
    LongTerm = 64,
}

// TODO: Consider using 12-bytes array, and deserialize from hex
/// Trade id.
#[derive(
    Serialize, Deserialize, Debug, Clone, From, Display, PartialEq, Eq, PartialOrd, Ord, Hash,
)]
pub struct TradeId(pub String);

/// Order side.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum OrderSide {
    /// Buy.
    Buy,
    /// Sell.
    Sell,
}

/// Order types.
///
/// See also [OrderType](https://docs.dydx.xyz/types/order_type#ordertype).
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum OrderType {
    /// Limit.
    Limit,
    /// Market.
    Market,
    /// Stop-limit.
    StopLimit,
    /// Stop-market.
    StopMarket,
    /// Trailing-stop.
    TrailingStop,
    /// Take-profit.
    TakeProfit,
    /// Take-profit-market.
    TakeProfitMarket,
    /// Hard-trade.
    HardTrade,
    /// Failed-hard-trade.
    FailedHardTrade,
    /// Transfer-placeholder.
    TransferPlaceholder,
}

/// Subaccount.
#[derive(Deserialize, Debug, Clone, Eq, Hash, PartialOrd, Ord, PartialEq)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(any(test, feature = "strict-serde"), serde(deny_unknown_fields))]
pub struct Subaccount {
    /// Address.
    pub address: Address,
    /// Subaccount number.
    pub number: SubaccountNumber,
}

impl Subaccount {
    /// Create a new Subaccount.
    pub fn new(address: Address, number: SubaccountNumber) -> Self {
        Self { address, number }
    }

    /// Get the parent of this Subaccount.
    pub fn parent(&self) -> ParentSubaccount {
        let number = ParentSubaccountNumber(self.number.0 % 128);
        ParentSubaccount::new(self.address.clone(), number)
    }

    /// Check if this Subaccount is a parent?
    pub fn is_parent(&self) -> bool {
        self.number.0 < 128
    }
}

impl From<Subaccount> for ProtoSubaccountId {
    fn from(subacc: Subaccount) -> Self {
        ProtoSubaccountId {
            owner: subacc.address.0,
            number: subacc.number.0,
        }
    }
}

/// Subaccount number.
#[derive(Serialize, Debug, Clone, Display, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct SubaccountNumber(pub(crate) u32);

impl<'de> Deserialize<'de> for SubaccountNumber {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct SubaccountVisitor;

        impl<'de> serde::de::Visitor<'de> for SubaccountVisitor {
            type Value = SubaccountNumber;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("a u32 or a string containing a u32")
            }

            fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                Ok(SubaccountNumber(value as u32))
            }

            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                value
                    .parse::<u32>()
                    .map(SubaccountNumber)
                    .map_err(|_| E::custom(format!("invalid u32 in string: {value}")))
            }
        }

        deserializer.deserialize_any(SubaccountVisitor)
    }
}

impl SubaccountNumber {
    /// Get the subaccount number value.
    pub fn value(&self) -> u32 {
        self.0
    }
}

impl TryFrom<u32> for SubaccountNumber {
    type Error = Error;
    fn try_from(number: u32) -> Result<Self, Error> {
        match number {
            0..=128_000 => Ok(SubaccountNumber(number)),
            _ => Err(err!("Subaccount number must be [0, 128_000]")),
        }
    }
}

impl TryFrom<&u32> for SubaccountNumber {
    type Error = Error;
    fn try_from(number: &u32) -> Result<Self, Error> {
        Self::try_from(*number)
    }
}

impl TryFrom<String> for SubaccountNumber {
    type Error = Error;
    fn try_from(number: String) -> Result<Self, Error> {
        Self::try_from(number.parse::<u32>()?)
    }
}

impl TryFrom<&str> for SubaccountNumber {
    type Error = Error;
    fn try_from(number: &str) -> Result<Self, Error> {
        Self::try_from(number.parse::<u32>()?)
    }
}

impl From<ParentSubaccountNumber> for SubaccountNumber {
    fn from(parent: ParentSubaccountNumber) -> Self {
        Self(parent.value())
    }
}

/// Parent subaccount.
///
/// A parent subaccount can have multiple positions opened and all posititions are cross-margined.
/// See also [how isolated positions are handled in dYdX](https://docs.dydx.xyz/concepts/trading/isolated-positions#isolated-positions).
#[derive(Deserialize, Debug, Clone, Eq, Hash, PartialOrd, Ord, PartialEq)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(any(test, feature = "strict-serde"), serde(deny_unknown_fields))]
pub struct ParentSubaccount {
    /// Address.
    pub address: Address,
    /// Parent subaccount number.
    pub number: ParentSubaccountNumber,
}

impl ParentSubaccount {
    /// Create a new Subaccount.
    pub fn new(address: Address, number: ParentSubaccountNumber) -> Self {
        Self { address, number }
    }
}

impl std::cmp::PartialEq<Subaccount> for ParentSubaccount {
    fn eq(&self, other: &Subaccount) -> bool {
        self.address == other.address && self.number == other.number
    }
}

/// Subaccount number.
#[derive(Serialize, Deserialize, Debug, Clone, Display, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ParentSubaccountNumber(u32);

impl ParentSubaccountNumber {
    /// Get parent subaccount number value.
    pub fn value(&self) -> u32 {
        self.0
    }
}

impl TryFrom<u32> for ParentSubaccountNumber {
    type Error = Error;
    fn try_from(number: u32) -> Result<Self, Error> {
        match number {
            0..=127 => Ok(ParentSubaccountNumber(number)),
            _ => Err(err!("Parent subaccount number must be [0, 127]")),
        }
    }
}

impl std::cmp::PartialEq<SubaccountNumber> for ParentSubaccountNumber {
    fn eq(&self, other: &SubaccountNumber) -> bool {
        self.0 == other.value()
    }
}

/// Subaccount id.
#[derive(Deserialize, Debug, Clone, From, Display, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct SubaccountId(pub String);

/// Token symbol.
#[derive(
    Serialize, Deserialize, Debug, Clone, From, Display, PartialEq, Eq, PartialOrd, Ord, Hash,
)]
pub struct Symbol(pub String);

/// Trade type.
#[derive(Deserialize, Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum TradeType {
    /// LIMIT is the trade type for a fill with a limit taker order.
    Limit,
    /// LIQUIDATED is the trade type for a fill with a liquidated taker order.
    Liquidated,
    /// DELEVERAGED is the trade type for a fill with a deleveraged taker order.
    Deleveraged,
}

/// Transfer type.
#[derive(Deserialize, Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum TransferType {
    /// Transfer-in.
    TransferIn,
    /// Transfer-out.
    TransferOut,
    /// Deposit.
    Deposit,
    /// Withdrawal.
    Withdrawal,
}

/// Ticker.
#[derive(
    Serialize, Deserialize, Debug, Clone, From, Display, PartialEq, Eq, PartialOrd, Ord, Hash,
)]
pub struct Ticker(pub String);

impl<'a> From<&'a str> for Ticker {
    fn from(value: &'a str) -> Self {
        Self(value.into())
    }
}

const USDC_DENOM: &str = "ibc/8E27BA2D5493AF5636760E354E46004562C46AB7EC0CC4C1CA14E9E20E2545B5";
const DYDX_DENOM: &str = "adydx";
const DYDX_TNT_DENOM: &str = "adv4tnt";
#[cfg(feature = "noble")]
const NOBLE_USDC_DENOM: &str = "uusdc";

/// Denom.
///
/// A more convenient type for Cosmos' [`Denom`](CosmosDenom).
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub enum Denom {
    /// USDC IBC token.
    #[serde(rename = "ibc/8E27BA2D5493AF5636760E354E46004562C46AB7EC0CC4C1CA14E9E20E2545B5")]
    Usdc,
    /// dYdX native mainnet token.
    #[serde(rename = "adydx")]
    Dydx,
    /// dYdX native testnet token.
    #[serde(rename = "adv4tnt")]
    DydxTnt,
    /// Noble USDC token.
    #[cfg(feature = "noble")]
    #[serde(rename = "uusdc")]
    NobleUsdc,
    /// Custom denom representation.
    #[serde(untagged)]
    Custom(CosmosDenom),
}

impl Denom {
    /// Gas price per atomic unit.
    /// This price is only available for `Denom`s which can be used to cover transactions gas fees.
    pub fn gas_price(&self) -> Option<BigDecimal> {
        match self {
            // Defined dYdX micro USDC per Gas unit.
            // As defined in [1](https://docs.dydx.xyz/nodes/running-node/required-node-configs#node-configs) and [2](https://github.com/dydxprotocol/v4-chain/blob/ba731b00e3163f7c3ff553b4300d564c11eaa81f/protocol/cmd/dydxprotocold/cmd/config.go#L15).
            Self::Usdc => Some(BigDecimal::new(25.into(), 3)),
            // Defined dYdX native tokens per Gas unit. Recommended to be roughly the same in value as 0.025 micro USDC.
            // As defined in [1](https://github.com/dydxprotocol/v4-chain/blob/ba731b00e3163f7c3ff553b4300d564c11eaa81f/protocol/cmd/dydxprotocold/cmd/config.go#L21).
            Self::Dydx | Self::DydxTnt => Some(BigDecimal::new(25_000_000_000u64.into(), 0)),
            #[cfg(feature = "noble")]
            Self::NobleUsdc => Some(BigDecimal::new(1.into(), 1)),
            _ => None,
        }
    }
}

impl FromStr for Denom {
    type Err = Error;
    fn from_str(value: &str) -> Result<Self, Error> {
        match value {
            USDC_DENOM => Ok(Self::Usdc),
            DYDX_DENOM => Ok(Self::Dydx),
            DYDX_TNT_DENOM => Ok(Self::DydxTnt),
            _ => Ok(Self::Custom(
                value.parse::<CosmosDenom>().map_err(Error::msg)?,
            )),
        }
    }
}

impl AsRef<str> for Denom {
    fn as_ref(&self) -> &str {
        match self {
            Self::Usdc => USDC_DENOM,
            Self::Dydx => DYDX_DENOM,
            Self::DydxTnt => DYDX_TNT_DENOM,
            #[cfg(feature = "noble")]
            Self::NobleUsdc => NOBLE_USDC_DENOM,
            Self::Custom(denom) => denom.as_ref(),
        }
    }
}

impl fmt::Display for Denom {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_ref())
    }
}

impl TryFrom<Denom> for CosmosDenom {
    type Error = Error;
    fn try_from(value: Denom) -> Result<Self, Self::Error> {
        value.as_ref().parse().map_err(Self::Error::msg)
    }
}

/// Parent subaccount response.
#[derive(Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(any(test, feature = "strict-serde"), serde(deny_unknown_fields))]
pub struct ParentSubaccountResponseObject {
    /// Address.
    pub address: Address,
    /// Subaccount number.
    pub parent_subaccount_number: SubaccountNumber,
    /// Equity.
    pub equity: BigDecimal,
    /// Free collateral.
    pub free_collateral: BigDecimal,
    /// Associated child subaccounts.
    pub child_subaccounts: Vec<SubaccountResponseObject>,
}

/// Subaccount response.
#[derive(Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(any(test, feature = "strict-serde"), serde(deny_unknown_fields))]
pub struct SubaccountResponseObject {
    /// Address.
    pub address: Address,
    /// Subaccount number.
    pub subaccount_number: SubaccountNumber,
    /// Equity.
    pub equity: BigDecimal,
    /// Free collateral.
    pub free_collateral: BigDecimal,
    /// Opened perpetual positions.
    pub open_perpetual_positions: PerpetualPositionsMap,
    /// Asset positions.
    pub asset_positions: AssetPositionsMap,
    /// Is margin enabled?
    pub margin_enabled: bool,
    /// Updated at height.
    pub updated_at_height: Height,
    /// Latest processed block height.
    pub latest_processed_block_height: Height,
}

/// Asset position response.
#[derive(Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(any(test, feature = "strict-serde"), serde(deny_unknown_fields))]
pub struct AssetPositionResponseObject {
    /// Token symbol.
    pub symbol: Symbol,
    /// Position.
    pub side: PositionSide,
    /// Size.
    pub size: Quantity,
    /// Subaccount number.
    pub subaccount_number: SubaccountNumber,
    /// Asset id.
    pub asset_id: AssetId,
}

/// Perpetual position response.
#[derive(Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(any(test, feature = "strict-serde"), serde(deny_unknown_fields))]
pub struct PerpetualPositionResponseObject {
    /// Market ticker.
    pub market: Ticker,
    /// Position status.
    pub status: PerpetualPositionStatus,
    /// Position.
    pub side: PositionSide,
    /// Size.
    pub size: Quantity,
    /// Maximum size.
    pub max_size: Quantity,
    /// Entry price.
    pub entry_price: Price,
    /// Actual PnL.
    pub realized_pnl: BigDecimal,
    /// Time(UTC).
    pub created_at: DateTime<Utc>,
    /// Block height.
    pub created_at_height: Height,
    /// Sum at open.
    pub sum_open: BigDecimal,
    /// Sum at close.
    pub sum_close: BigDecimal,
    /// Net funding.
    pub net_funding: BigDecimal,
    /// Potential PnL.
    pub unrealized_pnl: BigDecimal,
    /// Time(UTC).
    pub closed_at: Option<DateTime<Utc>>,
    /// Exit price.
    pub exit_price: Option<Price>,
    /// Subaccount number.
    pub subaccount_number: SubaccountNumber,
}

/// Asset positions.
pub type AssetPositionsMap = HashMap<Ticker, AssetPositionResponseObject>;

/// Perpetual positions.
pub type PerpetualPositionsMap = HashMap<Ticker, PerpetualPositionResponseObject>;

/// Price.
#[derive(
    Add,
    Deserialize,
    Debug,
    Clone,
    Div,
    Display,
    Deref,
    DerefMut,
    PartialEq,
    Eq,
    Mul,
    PartialOrd,
    Ord,
    Hash,
    Sub,
)]
#[serde(transparent)]
pub struct Price(pub BigDecimal);

impl<T> From<T> for Price
where
    T: Into<BigDecimal>,
{
    fn from(value: T) -> Self {
        Self(value.into())
    }
}

impl FromStr for Price {
    type Err = bigdecimal::ParseBigDecimalError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        s.parse().map(Self)
    }
}

/// Quantity.
#[derive(
    Add,
    Deserialize,
    Debug,
    Clone,
    Div,
    Display,
    Deref,
    DerefMut,
    PartialEq,
    Eq,
    Mul,
    PartialOrd,
    Ord,
    Hash,
    Sub,
)]
#[serde(transparent)]
pub struct Quantity(pub BigDecimal);

impl<T> From<T> for Quantity
where
    T: Into<BigDecimal>,
{
    fn from(value: T) -> Self {
        Self(value.into())
    }
}

impl FromStr for Quantity {
    type Err = bigdecimal::ParseBigDecimalError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        s.parse().map(Self)
    }
}

/// Orderbook price level.
#[derive(Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(any(test, feature = "strict-serde"), serde(deny_unknown_fields))]
pub struct OrderbookResponsePriceLevel {
    /// Price.
    pub price: Price,
    /// Size.
    pub size: Quantity,
}

/// Orderbook response.
#[derive(Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(any(test, feature = "strict-serde"), serde(deny_unknown_fields))]
pub struct OrderBookResponseObject {
    /// Bids.
    pub bids: Vec<OrderbookResponsePriceLevel>,
    /// Asks.
    pub asks: Vec<OrderbookResponsePriceLevel>,
}

/// Order response.
#[derive(Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(any(test, feature = "strict-serde"), serde(deny_unknown_fields))]
pub struct OrderResponseObject {
    /// Client id.
    pub client_id: ClientId,
    /// Client metadata.
    pub client_metadata: ClientMetadata,
    /// Clob pair id.
    pub clob_pair_id: ClobPairId,
    /// Block height.
    pub created_at_height: Option<Height>,
    /// Block height.
    pub good_til_block: Option<Height>,
    /// Time(UTC).
    pub good_til_block_time: Option<DateTime<Utc>>,
    /// Id.
    pub id: OrderId,
    /// Order flags.
    pub order_flags: OrderFlags,
    /// Post-only.
    pub post_only: bool,
    /// Price.
    pub price: Price,
    /// Reduce-only.
    pub reduce_only: bool,
    /// Side (buy/sell).
    pub side: OrderSide,
    /// Size.
    pub size: Quantity,
    /// Order status.
    pub status: ApiOrderStatus,
    /// Subaccount id.
    pub subaccount_id: SubaccountId,
    /// Subaccount number.
    pub subaccount_number: SubaccountNumber,
    /// Market ticker.
    pub ticker: Ticker,
    /// Time-in-force.
    pub time_in_force: ApiTimeInForce,
    /// Total filled.
    pub total_filled: BigDecimal,
    /// Order type.
    #[serde(rename = "type")]
    pub order_type: OrderType,
    /// Time(UTC).
    pub updated_at: Option<DateTime<Utc>>,
    /// Block height.
    pub updated_at_height: Option<Height>,
    /// Trigger price.
    pub trigger_price: Option<Price>,
    /// Fee ppm.
    pub fee_ppm: Option<BigDecimal>,
    /// Builder address..
    pub builder_address: Option<Address>,
    /// Order router address.
    pub order_router_address: Option<Address>,
    /// Duration.
    pub duration: Option<BigDecimal>,
    /// Interval.
    pub interval: Option<BigDecimal>,
    /// Price tolerance.
    pub price_tolerance: Option<BigDecimal>,
}

/// Trade response.
#[derive(Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(any(test, feature = "strict-serde"), serde(deny_unknown_fields))]
pub struct TradeResponse {
    /// Trades.
    pub trades: Vec<TradeResponseObject>,
}

/// Trade.
#[derive(Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(any(test, feature = "strict-serde"), serde(deny_unknown_fields))]
pub struct TradeResponseObject {
    /// Trade id.
    pub id: TradeId,
    /// Block height.
    pub created_at_height: Height,
    /// Time(UTC).
    pub created_at: DateTime<Utc>,
    /// Side (buy/sell).
    pub side: OrderSide,
    /// Price.
    pub price: Price,
    /// Size.
    pub size: Quantity,
    /// Trade type.
    #[serde(rename = "type")]
    pub trade_type: TradeType,
}

/// Perpetual markets.
#[derive(Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(any(test, feature = "strict-serde"), serde(deny_unknown_fields))]
pub struct PerpetualMarketResponse {
    /// Perpetual markets.
    pub markets: HashMap<Ticker, PerpetualMarket>,
}

/// Perpetual market.
#[derive(Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(any(test, feature = "strict-serde"), serde(deny_unknown_fields))]
pub struct PerpetualMarket {
    /// Clob pair id.
    pub clob_pair_id: ClobPairId,
    /// Market ticker.
    pub ticker: Ticker,
    /// Market status
    pub status: PerpetualMarketStatus,
    /// Oracle price.
    pub oracle_price: Option<Price>,
    /// 24-h price change.
    #[serde(rename = "priceChange24H")]
    pub price_change_24h: BigDecimal,
    /// 24-h volume.
    #[serde(rename = "volume24H")]
    pub volume_24h: Quantity,
    /// 24-h number of trades.
    #[serde(rename = "trades24H")]
    pub trades_24h: u64,
    /// Next funding rate.
    pub next_funding_rate: BigDecimal,
    /// Initial margin fraction.
    pub initial_margin_fraction: BigDecimal,
    /// Maintenance margin fraction.
    pub maintenance_margin_fraction: BigDecimal,
    /// Open interest.
    pub open_interest: BigDecimal,
    /// Atomic resolution
    pub atomic_resolution: i32,
    /// Quantum conversion exponent.
    pub quantum_conversion_exponent: i32,
    /// Tick size.
    pub tick_size: BigDecimal,
    /// Step size.
    pub step_size: BigDecimal,
    /// Step base quantums.
    pub step_base_quantums: u64,
    /// Subticks per tick.
    pub subticks_per_tick: u32,
    /// Market type.
    pub market_type: PerpetualMarketType,
    /// Open interest lower capitalization.
    pub open_interest_lower_cap: Option<BigDecimal>,
    /// Open interest upper capitalization.
    pub open_interest_upper_cap: Option<BigDecimal>,
    /// Base open interest.
    pub base_open_interest: BigDecimal,
    /// Default funding rate 1H.
    #[serde(rename = "defaultFundingRate1H")]
    pub default_funding_rate_1h: Option<BigDecimal>,
}

impl PerpetualMarket {
    /// Creates a [`OrderMarketParams`], capable of performing price and size quantizations and other
    /// operations based on market data.
    /// These quantizations are required for `Order` placement.
    pub fn order_params(&self) -> OrderMarketParams {
        OrderMarketParams {
            atomic_resolution: self.atomic_resolution,
            clob_pair_id: self.clob_pair_id.clone(),
            oracle_price: self.oracle_price.clone(),
            quantum_conversion_exponent: self.quantum_conversion_exponent,
            step_base_quantums: self.step_base_quantums,
            subticks_per_tick: self.subticks_per_tick,
        }
    }
}

/// Candle response.
#[derive(Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(any(test, feature = "strict-serde"), serde(deny_unknown_fields))]
pub struct CandleResponse {
    /// List of candles.
    pub candles: Vec<CandleResponseObject>,
}

/// Candle response.
#[derive(Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(any(test, feature = "strict-serde"), serde(deny_unknown_fields))]
pub struct CandleResponseObject {
    /// Time(UTC).
    pub started_at: DateTime<Utc>,
    /// Market ticker.
    pub ticker: Ticker,
    /// Candle resolution.
    pub resolution: CandleResolution,
    /// Low price volume.
    pub low: Price,
    /// High price volume.
    pub high: Price,
    /// Token price at open.
    pub open: Price,
    /// Token price at close.
    pub close: Price,
    /// Base token volume.
    pub base_token_volume: Quantity,
    /// USD volume.
    pub usd_volume: Quantity,
    /// Number of trades.
    pub trades: u64,
    /// Starting open interest.
    pub starting_open_interest: BigDecimal,
    /// Orderbook mid price open.
    pub orderbook_mid_price_open: Option<Price>,
    /// Orderbook mid price close.
    pub orderbook_mid_price_close: Option<Price>,
}

/// Block height parsed by Indexer.
#[derive(Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(any(test, feature = "strict-serde"), serde(deny_unknown_fields))]
pub struct HeightResponse {
    /// Block height.
    pub height: Height,
    /// Time (UTC).
    pub time: DateTime<Utc>,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn denom_parse() {
        // Test if hardcoded denom is parsed correctly
        let _usdc = Denom::Usdc.to_string().parse::<Denom>().unwrap();
        let _dydx = Denom::Dydx.to_string().parse::<Denom>().unwrap();
        let _dydx_tnt = Denom::DydxTnt.to_string().parse::<Denom>().unwrap();
        let _custom: Denom = "uusdc".parse().unwrap();
    }
}