nautilus-bitmex 0.55.0

BitMEX exchange integration adapter for the Nautilus trading engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
// -------------------------------------------------------------------------------------------------
//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
//  https://nautechsystems.io
//
//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
//  You may not use this file except in compliance with the License.
//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
// -------------------------------------------------------------------------------------------------

//! BitMEX-specific enumerations shared by HTTP and WebSocket components.

use std::borrow::Cow;

use nautilus_model::enums::{
    ContingencyType, LiquiditySide, MarketStatusAction, OrderSide, OrderSideSpecified, OrderStatus,
    OrderType, PositionSide, TimeInForce,
};
use serde::{Deserialize, Deserializer, Serialize};
use strum::{AsRefStr, Display, EnumIter, EnumString};

/// Represents the status of a BitMEX symbol.
#[derive(
    Copy,
    Clone,
    Debug,
    Display,
    PartialEq,
    Eq,
    AsRefStr,
    EnumIter,
    EnumString,
    Serialize,
    Deserialize,
)]
#[serde(rename_all = "PascalCase")]
#[cfg_attr(
    feature = "python",
    pyo3::pyclass(
        module = "nautilus_trader.core.nautilus_pyo3.bitmex",
        eq,
        eq_int,
        from_py_object,
        rename_all = "SCREAMING_SNAKE_CASE",
    )
)]
#[cfg_attr(
    feature = "python",
    pyo3_stub_gen::derive::gen_stub_pyclass_enum(module = "nautilus_trader.bitmex")
)]
pub enum BitmexSymbolStatus {
    /// Symbol is open for trading.
    Open,
    /// Symbol is closed for trading.
    Closed,
    /// Symbol is unlisted.
    Unlisted,
}

/// Represents the side of an order or trade (Buy/Sell).
#[derive(
    Copy,
    Clone,
    Debug,
    Display,
    PartialEq,
    Eq,
    AsRefStr,
    EnumIter,
    EnumString,
    Serialize,
    Deserialize,
)]
pub enum BitmexSide {
    /// Buy side of a trade or order.
    #[serde(rename = "Buy", alias = "BUY", alias = "buy")]
    Buy,
    /// Sell side of a trade or order.
    #[serde(rename = "Sell", alias = "SELL", alias = "sell")]
    Sell,
}

impl From<OrderSideSpecified> for BitmexSide {
    fn from(value: OrderSideSpecified) -> Self {
        match value {
            OrderSideSpecified::Buy => Self::Buy,
            OrderSideSpecified::Sell => Self::Sell,
        }
    }
}

impl From<BitmexSide> for OrderSide {
    fn from(side: BitmexSide) -> Self {
        match side {
            BitmexSide::Buy => Self::Buy,
            BitmexSide::Sell => Self::Sell,
        }
    }
}

/// Represents the position side for BitMEX positions.
#[derive(
    Copy,
    Clone,
    Debug,
    Display,
    PartialEq,
    Eq,
    AsRefStr,
    EnumIter,
    EnumString,
    Serialize,
    Deserialize,
)]
#[cfg_attr(
    feature = "python",
    pyo3::pyclass(
        module = "nautilus_trader.core.nautilus_pyo3.bitmex",
        eq,
        eq_int,
        from_py_object
    )
)]
#[cfg_attr(
    feature = "python",
    pyo3_stub_gen::derive::gen_stub_pyclass_enum(module = "nautilus_trader.bitmex")
)]
pub enum BitmexPositionSide {
    /// Long position.
    #[serde(rename = "LONG", alias = "Long", alias = "long")]
    Long,
    /// Short position.
    #[serde(rename = "SHORT", alias = "Short", alias = "short")]
    Short,
    /// No position.
    #[serde(rename = "FLAT", alias = "Flat", alias = "flat")]
    Flat,
}

impl From<BitmexPositionSide> for PositionSide {
    fn from(side: BitmexPositionSide) -> Self {
        match side {
            BitmexPositionSide::Long => Self::Long,
            BitmexPositionSide::Short => Self::Short,
            BitmexPositionSide::Flat => Self::Flat,
        }
    }
}

impl From<PositionSide> for BitmexPositionSide {
    fn from(side: PositionSide) -> Self {
        match side {
            PositionSide::Long => Self::Long,
            PositionSide::Short => Self::Short,
            PositionSide::Flat | PositionSide::NoPositionSide => Self::Flat,
        }
    }
}

/// Represents the available order types on BitMEX.
#[derive(
    Copy,
    Clone,
    Debug,
    Display,
    PartialEq,
    Eq,
    AsRefStr,
    EnumIter,
    EnumString,
    Serialize,
    Deserialize,
)]
pub enum BitmexOrderType {
    /// Market order, executed immediately at current market price.
    Market,
    /// Limit order, executed only at specified price or better.
    Limit,
    /// Stop Market order, triggers a market order when price reaches stop price.
    Stop,
    /// Stop Limit order, triggers a limit order when price reaches stop price.
    StopLimit,
    /// Market if touched order, triggers a market order when price reaches touch price.
    MarketIfTouched,
    /// Limit if touched order, triggers a limit order when price reaches touch price.
    LimitIfTouched,
    /// Pegged order, price automatically tracks market.
    Pegged,
}

impl TryFrom<OrderType> for BitmexOrderType {
    type Error = anyhow::Error;

    fn try_from(value: OrderType) -> Result<Self, Self::Error> {
        match value {
            OrderType::Market => Ok(Self::Market),
            OrderType::Limit => Ok(Self::Limit),
            OrderType::StopMarket => Ok(Self::Stop),
            OrderType::StopLimit => Ok(Self::StopLimit),
            OrderType::MarketIfTouched => Ok(Self::MarketIfTouched),
            OrderType::LimitIfTouched => Ok(Self::LimitIfTouched),
            OrderType::TrailingStopMarket => Ok(Self::Pegged),
            OrderType::TrailingStopLimit => Ok(Self::Pegged),
            OrderType::MarketToLimit => {
                anyhow::bail!("MarketToLimit order type is not supported by BitMEX")
            }
        }
    }
}

impl BitmexOrderType {
    /// Try to convert from Nautilus OrderType with anyhow::Result.
    ///
    /// # Errors
    ///
    /// Returns an error if the order type is MarketToLimit (not supported by BitMEX).
    pub fn try_from_order_type(value: OrderType) -> anyhow::Result<Self> {
        Self::try_from(value)
    }
}

impl From<BitmexOrderType> for OrderType {
    fn from(value: BitmexOrderType) -> Self {
        match value {
            BitmexOrderType::Market => Self::Market,
            BitmexOrderType::Limit => Self::Limit,
            BitmexOrderType::Stop => Self::StopMarket,
            BitmexOrderType::StopLimit => Self::StopLimit,
            BitmexOrderType::MarketIfTouched => Self::MarketIfTouched,
            BitmexOrderType::LimitIfTouched => Self::LimitIfTouched,
            BitmexOrderType::Pegged => Self::Limit,
        }
    }
}

/// Represents the possible states of an order throughout its lifecycle.
#[derive(
    Copy,
    Clone,
    Debug,
    Display,
    PartialEq,
    Eq,
    AsRefStr,
    EnumIter,
    EnumString,
    Serialize,
    Deserialize,
)]
pub enum BitmexOrderStatus {
    /// Order has been placed but not yet processed.
    New,
    /// Order is awaiting confirmation.
    PendingNew,
    /// Order has been partially filled.
    PartiallyFilled,
    /// Order has been completely filled.
    Filled,
    /// Order modification is in progress.
    PendingReplace,
    /// Order cancellation is pending.
    PendingCancel,
    /// Order has been canceled by user or system.
    Canceled,
    /// Order was rejected by the system.
    Rejected,
    /// Order has expired according to its time in force.
    Expired,
}

impl BitmexOrderStatus {
    /// Returns whether this status represents a terminal order state.
    pub fn is_terminal(self) -> bool {
        matches!(
            self,
            Self::Filled | Self::Canceled | Self::Rejected | Self::Expired
        )
    }
}

impl From<BitmexOrderStatus> for OrderStatus {
    fn from(value: BitmexOrderStatus) -> Self {
        match value {
            BitmexOrderStatus::New => Self::Accepted,
            BitmexOrderStatus::PendingNew => Self::Submitted,
            BitmexOrderStatus::PartiallyFilled => Self::PartiallyFilled,
            BitmexOrderStatus::Filled => Self::Filled,
            BitmexOrderStatus::PendingReplace => Self::PendingUpdate,
            BitmexOrderStatus::PendingCancel => Self::PendingCancel,
            BitmexOrderStatus::Canceled => Self::Canceled,
            BitmexOrderStatus::Rejected => Self::Rejected,
            BitmexOrderStatus::Expired => Self::Expired,
        }
    }
}

/// Specifies how long an order should remain active.
#[derive(
    Copy,
    Clone,
    Debug,
    Display,
    PartialEq,
    Eq,
    AsRefStr,
    EnumIter,
    EnumString,
    Serialize,
    Deserialize,
)]
pub enum BitmexTimeInForce {
    Day,
    GoodTillCancel,
    AtTheOpening,
    ImmediateOrCancel,
    FillOrKill,
    GoodTillCrossing,
    GoodTillDate,
    AtTheClose,
    GoodThroughCrossing,
    AtCrossing,
}

impl TryFrom<BitmexTimeInForce> for TimeInForce {
    type Error = anyhow::Error;

    fn try_from(value: BitmexTimeInForce) -> Result<Self, Self::Error> {
        match value {
            BitmexTimeInForce::Day => Ok(Self::Day),
            BitmexTimeInForce::GoodTillCancel => Ok(Self::Gtc),
            BitmexTimeInForce::GoodTillDate => Ok(Self::Gtd),
            BitmexTimeInForce::ImmediateOrCancel => Ok(Self::Ioc),
            BitmexTimeInForce::FillOrKill => Ok(Self::Fok),
            BitmexTimeInForce::AtTheOpening => Ok(Self::AtTheOpen),
            BitmexTimeInForce::AtTheClose => Ok(Self::AtTheClose),
            _ => anyhow::bail!("Unsupported BitmexTimeInForce: {value}"),
        }
    }
}

impl TryFrom<TimeInForce> for BitmexTimeInForce {
    type Error = anyhow::Error;

    fn try_from(value: TimeInForce) -> Result<Self, Self::Error> {
        match value {
            TimeInForce::Day => Ok(Self::Day),
            TimeInForce::Gtc => Ok(Self::GoodTillCancel),
            TimeInForce::Gtd => Ok(Self::GoodTillDate),
            TimeInForce::Ioc => Ok(Self::ImmediateOrCancel),
            TimeInForce::Fok => Ok(Self::FillOrKill),
            TimeInForce::AtTheOpen => Ok(Self::AtTheOpening),
            TimeInForce::AtTheClose => Ok(Self::AtTheClose),
        }
    }
}

impl BitmexTimeInForce {
    /// Try to convert from Nautilus TimeInForce with anyhow::Result.
    ///
    /// # Errors
    ///
    /// Returns an error if the time in force is not supported by BitMEX.
    pub fn try_from_time_in_force(value: TimeInForce) -> anyhow::Result<Self> {
        Self::try_from(value)
    }
}

/// Represents the available contingency types on BitMEX.
#[derive(
    Copy,
    Clone,
    Debug,
    Display,
    PartialEq,
    Eq,
    AsRefStr,
    EnumIter,
    EnumString,
    Serialize,
    Deserialize,
)]
pub enum BitmexContingencyType {
    OneCancelsTheOther,
    OneTriggersTheOther,
    OneUpdatesTheOtherAbsolute,
    OneUpdatesTheOtherProportional,
    #[serde(rename = "")]
    Unknown, // Can be empty
}

impl From<BitmexContingencyType> for ContingencyType {
    fn from(value: BitmexContingencyType) -> Self {
        match value {
            BitmexContingencyType::OneCancelsTheOther => Self::Oco,
            BitmexContingencyType::OneTriggersTheOther => Self::Oto,
            BitmexContingencyType::OneUpdatesTheOtherProportional => Self::Ouo,
            BitmexContingencyType::OneUpdatesTheOtherAbsolute => Self::Ouo,
            BitmexContingencyType::Unknown => Self::NoContingency,
        }
    }
}

impl TryFrom<ContingencyType> for BitmexContingencyType {
    type Error = anyhow::Error;

    fn try_from(value: ContingencyType) -> Result<Self, Self::Error> {
        match value {
            ContingencyType::NoContingency => Ok(Self::Unknown),
            ContingencyType::Oco => Ok(Self::OneCancelsTheOther),
            ContingencyType::Oto => Ok(Self::OneTriggersTheOther),
            ContingencyType::Ouo => anyhow::bail!("OUO contingency type not supported by BitMEX"),
        }
    }
}

/// Represents the available peg price types on BitMEX.
#[derive(
    Copy,
    Clone,
    Debug,
    Display,
    PartialEq,
    Eq,
    AsRefStr,
    EnumIter,
    EnumString,
    Serialize,
    Deserialize,
)]
pub enum BitmexPegPriceType {
    LastPeg,
    OpeningPeg,
    MidPricePeg,
    MarketPeg,
    PrimaryPeg,
    PegToVWAP,
    TrailingStopPeg,
    PegToLimitPrice,
    ShortSaleMinPricePeg,
    #[serde(rename = "")]
    Unknown, // Can be empty
}

/// Represents the available execution instruments on BitMEX.
#[derive(
    Copy,
    Clone,
    Debug,
    Display,
    PartialEq,
    Eq,
    AsRefStr,
    EnumIter,
    EnumString,
    Serialize,
    Deserialize,
)]
pub enum BitmexExecInstruction {
    ParticipateDoNotInitiate,
    AllOrNone,
    MarkPrice,
    IndexPrice,
    LastPrice,
    Close,
    ReduceOnly,
    Fixed,
    #[serde(rename = "")]
    Unknown, // Can be empty
}

impl BitmexExecInstruction {
    /// Joins execution instructions into the comma-separated string expected by BitMEX.
    pub fn join(instructions: &[Self]) -> String {
        instructions
            .iter()
            .map(ToString::to_string)
            .collect::<Vec<_>>()
            .join(",")
    }
}

/// Represents the type of execution that generated a trade.
#[derive(Clone, Debug, Display, PartialEq, Eq, AsRefStr, EnumIter, EnumString, Serialize)]
pub enum BitmexExecType {
    /// New order placed.
    New,
    /// Normal trade execution.
    Trade,
    /// Order canceled.
    Canceled,
    /// Cancel request rejected.
    CancelReject,
    /// Order replaced.
    Replaced,
    /// Order rejected.
    Rejected,
    /// Order amendment rejected.
    AmendReject,
    /// Funding rate execution.
    Funding,
    /// Settlement execution.
    Settlement,
    /// Order suspended.
    Suspended,
    /// Order released.
    Released,
    /// Insurance payment.
    Insurance,
    /// Rebalance.
    Rebalance,
    /// Liquidation execution.
    Liquidation,
    /// Bankruptcy execution.
    Bankruptcy,
    /// Trial fill (testnet only).
    TrialFill,
    /// Stop/trigger order activated by system.
    TriggeredOrActivatedBySystem,
    /// Unknown execution type (not yet supported).
    #[strum(disabled)]
    Unknown(String),
}

impl<'de> Deserialize<'de> for BitmexExecType {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;

        match s.as_str() {
            "New" => Ok(Self::New),
            "Trade" => Ok(Self::Trade),
            "Canceled" => Ok(Self::Canceled),
            "CancelReject" => Ok(Self::CancelReject),
            "Replaced" => Ok(Self::Replaced),
            "Rejected" => Ok(Self::Rejected),
            "AmendReject" => Ok(Self::AmendReject),
            "Funding" => Ok(Self::Funding),
            "Settlement" => Ok(Self::Settlement),
            "Suspended" => Ok(Self::Suspended),
            "Released" => Ok(Self::Released),
            "Insurance" => Ok(Self::Insurance),
            "Rebalance" => Ok(Self::Rebalance),
            "Liquidation" => Ok(Self::Liquidation),
            "Bankruptcy" => Ok(Self::Bankruptcy),
            "TrialFill" => Ok(Self::TrialFill),
            "TriggeredOrActivatedBySystem" => Ok(Self::TriggeredOrActivatedBySystem),
            other => Ok(Self::Unknown(other.to_string())),
        }
    }
}

/// Indicates whether the execution was maker or taker.
#[derive(
    Copy,
    Clone,
    Debug,
    Display,
    PartialEq,
    Eq,
    AsRefStr,
    EnumIter,
    EnumString,
    Serialize,
    Deserialize,
)]
pub enum BitmexLiquidityIndicator {
    /// Provided liquidity to the order book (maker).
    /// BitMEX returns "Added" in REST API responses and "AddedLiquidity" in WebSocket messages.
    #[serde(rename = "Added")]
    #[serde(alias = "AddedLiquidity")]
    Maker,
    /// Took liquidity from the order book (taker).
    /// BitMEX returns "Removed" in REST API responses and "RemovedLiquidity" in WebSocket messages.
    #[serde(rename = "Removed")]
    #[serde(alias = "RemovedLiquidity")]
    Taker,
}

impl From<BitmexLiquidityIndicator> for LiquiditySide {
    fn from(value: BitmexLiquidityIndicator) -> Self {
        match value {
            BitmexLiquidityIndicator::Maker => Self::Maker,
            BitmexLiquidityIndicator::Taker => Self::Taker,
        }
    }
}

/// Represents BitMEX instrument types (CFI codes).
///
/// The CFI (Classification of Financial Instruments) code is a 6-character code
/// following ISO 10962 standard that classifies financial instruments.
///
/// See: <https://support.bitmex.com/hc/en-gb/articles/6299296145565-What-are-the-Typ-Values-for-Instrument-endpoint>
#[derive(
    Copy,
    Clone,
    Debug,
    Display,
    PartialEq,
    Eq,
    AsRefStr,
    EnumIter,
    EnumString,
    Serialize,
    Deserialize,
)]
#[serde(rename_all = "UPPERCASE")]
pub enum BitmexInstrumentType {
    /// Legacy futures (settled).
    #[serde(rename = "FXXXS")]
    LegacyFutures,

    /// Legacy futures (settled, variant).
    #[serde(rename = "FXXXN")]
    LegacyFuturesN,

    /// Futures spreads (settled).
    #[serde(rename = "FMXXS")]
    FuturesSpreads,

    /// Prediction Markets (non-standardized financial future on index, cash settled).
    /// CFI code FFICSX - traders predict outcomes of events.
    #[serde(rename = "FFICSX")]
    PredictionMarket,

    /// Stock-based Perpetual Contracts (e.g., SPY, equity derivatives).
    /// CFI code FFSCSX - financial future on stocks, cash settled.
    #[serde(rename = "FFSCSX")]
    StockPerpetual,

    /// Perpetual Contracts (crypto).
    #[serde(rename = "FFWCSX")]
    PerpetualContract,

    /// Perpetual Contracts (FX underliers).
    #[serde(rename = "FFWCSF")]
    PerpetualContractFx,

    /// Futures (calendar futures, cash settled).
    #[serde(rename = "FFCCSX")]
    Futures,

    /// Spot trading pairs.
    #[serde(rename = "IFXXXP")]
    Spot,

    /// Call options (European, cash settled).
    #[serde(rename = "OCECCS")]
    CallOption,

    /// Put options (European, cash settled).
    #[serde(rename = "OPECCS")]
    PutOption,

    /// Swap rate contracts (yield products).
    #[serde(rename = "SRMCSX")]
    SwapRate,

    /// Reference basket contracts.
    #[serde(rename = "RCSXXX")]
    ReferenceBasket,

    /// BitMEX Basket Index.
    #[serde(rename = "MRBXXX")]
    BasketIndex,

    /// BitMEX Crypto Index.
    #[serde(rename = "MRCXXX")]
    CryptoIndex,

    /// BitMEX FX Index.
    #[serde(rename = "MRFXXX")]
    FxIndex,

    /// BitMEX Lending/Premium Index.
    #[serde(rename = "MRRXXX")]
    LendingIndex,

    /// BitMEX Volatility Index.
    #[serde(rename = "MRIXXX")]
    VolatilityIndex,

    /// BitMEX Stock/Securities Index.
    #[serde(rename = "MRSXXX")]
    StockIndex,

    /// BitMEX Yield/Dividend Index.
    #[serde(rename = "MRVDXX")]
    YieldIndex,
}

/// Represents the different types of instrument subscriptions available on BitMEX.
#[derive(Clone, Debug, Display, PartialEq, Eq, AsRefStr, EnumIter, EnumString, Serialize)]
pub enum BitmexProductType {
    /// All instruments AND indices.
    #[serde(rename = "instrument")]
    All,

    /// All instruments, but no indices.
    #[serde(rename = "CONTRACTS")]
    Contracts,

    /// All indices, but no tradeable instruments.
    #[serde(rename = "INDICES")]
    Indices,

    /// Only derivative instruments, and no indices.
    #[serde(rename = "DERIVATIVES")]
    Derivatives,

    /// Only spot instruments, and no indices.
    #[serde(rename = "SPOT")]
    Spot,

    /// Specific instrument subscription (e.g., "instrument:XBTUSD").
    #[serde(rename = "instrument")]
    #[serde(untagged)]
    Specific(String),
}

impl BitmexProductType {
    /// Converts the product type to its websocket subscription string.
    #[must_use]
    pub fn to_subscription(&self) -> Cow<'static, str> {
        match self {
            Self::All => Cow::Borrowed("instrument"),
            Self::Specific(symbol) => Cow::Owned(format!("instrument:{symbol}")),
            Self::Contracts => Cow::Borrowed("CONTRACTS"),
            Self::Indices => Cow::Borrowed("INDICES"),
            Self::Derivatives => Cow::Borrowed("DERIVATIVES"),
            Self::Spot => Cow::Borrowed("SPOT"),
        }
    }
}

impl<'de> Deserialize<'de> for BitmexProductType {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;

        match s.as_str() {
            "instrument" => Ok(Self::All),
            "CONTRACTS" => Ok(Self::Contracts),
            "INDICES" => Ok(Self::Indices),
            "DERIVATIVES" => Ok(Self::Derivatives),
            "SPOT" => Ok(Self::Spot),
            s if s.starts_with("instrument:") => {
                let symbol = s.strip_prefix("instrument:").unwrap();
                Ok(Self::Specific(symbol.to_string()))
            }
            _ => Err(serde::de::Error::custom(format!(
                "Invalid product type: {s}"
            ))),
        }
    }
}

/// Represents the tick direction of the last trade.
#[derive(
    Copy,
    Clone,
    Debug,
    Display,
    PartialEq,
    Eq,
    AsRefStr,
    EnumIter,
    EnumString,
    Serialize,
    Deserialize,
)]
pub enum BitmexTickDirection {
    /// Price increased on last trade.
    PlusTick,
    /// Price decreased on last trade.
    MinusTick,
    /// Price unchanged, but previous tick was plus.
    ZeroPlusTick,
    /// Price unchanged, but previous tick was minus.
    ZeroMinusTick,
}

/// Represents the state of an instrument.
#[derive(
    Clone,
    Copy,
    Debug,
    Display,
    PartialEq,
    Eq,
    AsRefStr,
    EnumIter,
    EnumString,
    Serialize,
    Deserialize,
)]
pub enum BitmexInstrumentState {
    /// Instrument is open for trading.
    Open,
    /// Instrument is closed for trading.
    Closed,
    /// Instrument is unlisted.
    Unlisted,
    /// Instrument is settled.
    Settled,
    /// Instrument is delisted.
    Delisted,
}

impl From<&BitmexInstrumentState> for MarketStatusAction {
    fn from(state: &BitmexInstrumentState) -> Self {
        match state {
            BitmexInstrumentState::Open => Self::Trading,
            BitmexInstrumentState::Closed => Self::Close,
            BitmexInstrumentState::Settled => Self::Close,
            BitmexInstrumentState::Unlisted => Self::NotAvailableForTrading,
            BitmexInstrumentState::Delisted => Self::NotAvailableForTrading,
        }
    }
}

/// Represents the fair price calculation method.
#[derive(
    Clone, Debug, Display, PartialEq, Eq, AsRefStr, EnumIter, EnumString, Serialize, Deserialize,
)]
pub enum BitmexFairMethod {
    /// Funding rate based.
    FundingRate,
    /// Impact mid price.
    ImpactMidPrice,
    /// Last price.
    LastPrice,
}

/// Represents the mark price calculation method.
#[derive(
    Clone, Debug, Display, PartialEq, Eq, AsRefStr, EnumIter, EnumString, Serialize, Deserialize,
)]
pub enum BitmexMarkMethod {
    /// Fair price.
    FairPrice,
    /// Fair price for stock-based perpetuals.
    FairPriceStox,
    /// Last price.
    LastPrice,
    /// Last price for pre-launch instruments.
    LastPricePreLaunch,
    /// Composite index.
    CompositeIndex,
}

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

    use super::*;

    #[rstest]
    fn test_bitmex_side_deserialization() {
        // Test all case variations
        assert_eq!(
            serde_json::from_str::<BitmexSide>(r#""Buy""#).unwrap(),
            BitmexSide::Buy
        );
        assert_eq!(
            serde_json::from_str::<BitmexSide>(r#""BUY""#).unwrap(),
            BitmexSide::Buy
        );
        assert_eq!(
            serde_json::from_str::<BitmexSide>(r#""buy""#).unwrap(),
            BitmexSide::Buy
        );
        assert_eq!(
            serde_json::from_str::<BitmexSide>(r#""Sell""#).unwrap(),
            BitmexSide::Sell
        );
        assert_eq!(
            serde_json::from_str::<BitmexSide>(r#""SELL""#).unwrap(),
            BitmexSide::Sell
        );
        assert_eq!(
            serde_json::from_str::<BitmexSide>(r#""sell""#).unwrap(),
            BitmexSide::Sell
        );
    }

    #[rstest]
    fn test_bitmex_order_type_deserialization() {
        assert_eq!(
            serde_json::from_str::<BitmexOrderType>(r#""Market""#).unwrap(),
            BitmexOrderType::Market
        );
        assert_eq!(
            serde_json::from_str::<BitmexOrderType>(r#""Limit""#).unwrap(),
            BitmexOrderType::Limit
        );
        assert_eq!(
            serde_json::from_str::<BitmexOrderType>(r#""Stop""#).unwrap(),
            BitmexOrderType::Stop
        );
        assert_eq!(
            serde_json::from_str::<BitmexOrderType>(r#""StopLimit""#).unwrap(),
            BitmexOrderType::StopLimit
        );
        assert_eq!(
            serde_json::from_str::<BitmexOrderType>(r#""MarketIfTouched""#).unwrap(),
            BitmexOrderType::MarketIfTouched
        );
        assert_eq!(
            serde_json::from_str::<BitmexOrderType>(r#""LimitIfTouched""#).unwrap(),
            BitmexOrderType::LimitIfTouched
        );
        assert_eq!(
            serde_json::from_str::<BitmexOrderType>(r#""Pegged""#).unwrap(),
            BitmexOrderType::Pegged
        );
    }

    #[rstest]
    fn test_instrument_type_serialization() {
        // Tradeable instruments
        assert_eq!(
            serde_json::to_string(&BitmexInstrumentType::PerpetualContract).unwrap(),
            r#""FFWCSX""#
        );
        assert_eq!(
            serde_json::to_string(&BitmexInstrumentType::PerpetualContractFx).unwrap(),
            r#""FFWCSF""#
        );
        assert_eq!(
            serde_json::to_string(&BitmexInstrumentType::StockPerpetual).unwrap(),
            r#""FFSCSX""#
        );
        assert_eq!(
            serde_json::to_string(&BitmexInstrumentType::Spot).unwrap(),
            r#""IFXXXP""#
        );
        assert_eq!(
            serde_json::to_string(&BitmexInstrumentType::Futures).unwrap(),
            r#""FFCCSX""#
        );
        assert_eq!(
            serde_json::to_string(&BitmexInstrumentType::PredictionMarket).unwrap(),
            r#""FFICSX""#
        );
        assert_eq!(
            serde_json::to_string(&BitmexInstrumentType::CallOption).unwrap(),
            r#""OCECCS""#
        );
        assert_eq!(
            serde_json::to_string(&BitmexInstrumentType::PutOption).unwrap(),
            r#""OPECCS""#
        );
        assert_eq!(
            serde_json::to_string(&BitmexInstrumentType::SwapRate).unwrap(),
            r#""SRMCSX""#
        );

        // Legacy instruments
        assert_eq!(
            serde_json::to_string(&BitmexInstrumentType::LegacyFutures).unwrap(),
            r#""FXXXS""#
        );
        assert_eq!(
            serde_json::to_string(&BitmexInstrumentType::LegacyFuturesN).unwrap(),
            r#""FXXXN""#
        );
        assert_eq!(
            serde_json::to_string(&BitmexInstrumentType::FuturesSpreads).unwrap(),
            r#""FMXXS""#
        );
        assert_eq!(
            serde_json::to_string(&BitmexInstrumentType::ReferenceBasket).unwrap(),
            r#""RCSXXX""#
        );

        // Index types
        assert_eq!(
            serde_json::to_string(&BitmexInstrumentType::BasketIndex).unwrap(),
            r#""MRBXXX""#
        );
        assert_eq!(
            serde_json::to_string(&BitmexInstrumentType::CryptoIndex).unwrap(),
            r#""MRCXXX""#
        );
        assert_eq!(
            serde_json::to_string(&BitmexInstrumentType::FxIndex).unwrap(),
            r#""MRFXXX""#
        );
        assert_eq!(
            serde_json::to_string(&BitmexInstrumentType::LendingIndex).unwrap(),
            r#""MRRXXX""#
        );
        assert_eq!(
            serde_json::to_string(&BitmexInstrumentType::VolatilityIndex).unwrap(),
            r#""MRIXXX""#
        );
        assert_eq!(
            serde_json::to_string(&BitmexInstrumentType::StockIndex).unwrap(),
            r#""MRSXXX""#
        );
        assert_eq!(
            serde_json::to_string(&BitmexInstrumentType::YieldIndex).unwrap(),
            r#""MRVDXX""#
        );
    }

    #[rstest]
    fn test_instrument_type_deserialization() {
        // Tradeable instruments
        assert_eq!(
            serde_json::from_str::<BitmexInstrumentType>(r#""FFWCSX""#).unwrap(),
            BitmexInstrumentType::PerpetualContract
        );
        assert_eq!(
            serde_json::from_str::<BitmexInstrumentType>(r#""FFWCSF""#).unwrap(),
            BitmexInstrumentType::PerpetualContractFx
        );
        assert_eq!(
            serde_json::from_str::<BitmexInstrumentType>(r#""FFSCSX""#).unwrap(),
            BitmexInstrumentType::StockPerpetual
        );
        assert_eq!(
            serde_json::from_str::<BitmexInstrumentType>(r#""IFXXXP""#).unwrap(),
            BitmexInstrumentType::Spot
        );
        assert_eq!(
            serde_json::from_str::<BitmexInstrumentType>(r#""FFCCSX""#).unwrap(),
            BitmexInstrumentType::Futures
        );
        assert_eq!(
            serde_json::from_str::<BitmexInstrumentType>(r#""FFICSX""#).unwrap(),
            BitmexInstrumentType::PredictionMarket
        );
        assert_eq!(
            serde_json::from_str::<BitmexInstrumentType>(r#""OCECCS""#).unwrap(),
            BitmexInstrumentType::CallOption
        );
        assert_eq!(
            serde_json::from_str::<BitmexInstrumentType>(r#""OPECCS""#).unwrap(),
            BitmexInstrumentType::PutOption
        );
        assert_eq!(
            serde_json::from_str::<BitmexInstrumentType>(r#""SRMCSX""#).unwrap(),
            BitmexInstrumentType::SwapRate
        );

        // Legacy instruments
        assert_eq!(
            serde_json::from_str::<BitmexInstrumentType>(r#""FXXXS""#).unwrap(),
            BitmexInstrumentType::LegacyFutures
        );
        assert_eq!(
            serde_json::from_str::<BitmexInstrumentType>(r#""FXXXN""#).unwrap(),
            BitmexInstrumentType::LegacyFuturesN
        );
        assert_eq!(
            serde_json::from_str::<BitmexInstrumentType>(r#""FMXXS""#).unwrap(),
            BitmexInstrumentType::FuturesSpreads
        );
        assert_eq!(
            serde_json::from_str::<BitmexInstrumentType>(r#""RCSXXX""#).unwrap(),
            BitmexInstrumentType::ReferenceBasket
        );

        // Index types
        assert_eq!(
            serde_json::from_str::<BitmexInstrumentType>(r#""MRBXXX""#).unwrap(),
            BitmexInstrumentType::BasketIndex
        );
        assert_eq!(
            serde_json::from_str::<BitmexInstrumentType>(r#""MRCXXX""#).unwrap(),
            BitmexInstrumentType::CryptoIndex
        );
        assert_eq!(
            serde_json::from_str::<BitmexInstrumentType>(r#""MRFXXX""#).unwrap(),
            BitmexInstrumentType::FxIndex
        );
        assert_eq!(
            serde_json::from_str::<BitmexInstrumentType>(r#""MRRXXX""#).unwrap(),
            BitmexInstrumentType::LendingIndex
        );
        assert_eq!(
            serde_json::from_str::<BitmexInstrumentType>(r#""MRIXXX""#).unwrap(),
            BitmexInstrumentType::VolatilityIndex
        );
        assert_eq!(
            serde_json::from_str::<BitmexInstrumentType>(r#""MRSXXX""#).unwrap(),
            BitmexInstrumentType::StockIndex
        );
        assert_eq!(
            serde_json::from_str::<BitmexInstrumentType>(r#""MRVDXX""#).unwrap(),
            BitmexInstrumentType::YieldIndex
        );

        // Error case
        assert!(serde_json::from_str::<BitmexInstrumentType>(r#""INVALID""#).is_err());
    }

    #[rstest]
    fn test_subscription_strings() {
        assert_eq!(BitmexProductType::All.to_subscription(), "instrument");
        assert_eq!(
            BitmexProductType::Specific("XBTUSD".to_string()).to_subscription(),
            "instrument:XBTUSD"
        );
        assert_eq!(BitmexProductType::Contracts.to_subscription(), "CONTRACTS");
        assert_eq!(BitmexProductType::Indices.to_subscription(), "INDICES");
        assert_eq!(
            BitmexProductType::Derivatives.to_subscription(),
            "DERIVATIVES"
        );
        assert_eq!(BitmexProductType::Spot.to_subscription(), "SPOT");
    }

    #[rstest]
    fn test_serialization() {
        // Test serialization
        assert_eq!(
            serde_json::to_string(&BitmexProductType::All).unwrap(),
            r#""instrument""#
        );
        assert_eq!(
            serde_json::to_string(&BitmexProductType::Specific("XBTUSD".to_string())).unwrap(),
            r#""XBTUSD""#
        );
        assert_eq!(
            serde_json::to_string(&BitmexProductType::Contracts).unwrap(),
            r#""CONTRACTS""#
        );
    }

    #[rstest]
    fn test_deserialization() {
        assert_eq!(
            serde_json::from_str::<BitmexProductType>(r#""instrument""#).unwrap(),
            BitmexProductType::All
        );
        assert_eq!(
            serde_json::from_str::<BitmexProductType>(r#""instrument:XBTUSD""#).unwrap(),
            BitmexProductType::Specific("XBTUSD".to_string())
        );
        assert_eq!(
            serde_json::from_str::<BitmexProductType>(r#""CONTRACTS""#).unwrap(),
            BitmexProductType::Contracts
        );
    }

    #[rstest]
    fn test_error_cases() {
        assert!(serde_json::from_str::<BitmexProductType>(r#""invalid_type""#).is_err());
        assert!(serde_json::from_str::<BitmexProductType>("123").is_err());
        assert!(serde_json::from_str::<BitmexProductType>("{}").is_err());
    }

    #[rstest]
    fn test_order_side_from_specified() {
        assert_eq!(BitmexSide::from(OrderSideSpecified::Buy), BitmexSide::Buy);
        assert_eq!(BitmexSide::from(OrderSideSpecified::Sell), BitmexSide::Sell);
    }

    #[rstest]
    fn test_order_type_try_from() {
        // Valid conversions
        assert_eq!(
            BitmexOrderType::try_from(OrderType::Market).unwrap(),
            BitmexOrderType::Market
        );
        assert_eq!(
            BitmexOrderType::try_from(OrderType::Limit).unwrap(),
            BitmexOrderType::Limit
        );

        // MarketToLimit should fail
        let result = BitmexOrderType::try_from(OrderType::MarketToLimit);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("not supported"));
    }

    #[rstest]
    fn test_time_in_force_conversions() {
        // BitMEX to Nautilus (all supported variants)
        assert_eq!(
            TimeInForce::try_from(BitmexTimeInForce::Day).unwrap(),
            TimeInForce::Day
        );
        assert_eq!(
            TimeInForce::try_from(BitmexTimeInForce::GoodTillCancel).unwrap(),
            TimeInForce::Gtc
        );
        assert_eq!(
            TimeInForce::try_from(BitmexTimeInForce::ImmediateOrCancel).unwrap(),
            TimeInForce::Ioc
        );

        // Unsupported BitMEX variants should fail
        let result = TimeInForce::try_from(BitmexTimeInForce::GoodTillCrossing);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("Unsupported"));

        // Nautilus to BitMEX (all supported variants)
        assert_eq!(
            BitmexTimeInForce::try_from(TimeInForce::Day).unwrap(),
            BitmexTimeInForce::Day
        );
        assert_eq!(
            BitmexTimeInForce::try_from(TimeInForce::Gtc).unwrap(),
            BitmexTimeInForce::GoodTillCancel
        );
        assert_eq!(
            BitmexTimeInForce::try_from(TimeInForce::Fok).unwrap(),
            BitmexTimeInForce::FillOrKill
        );
    }

    #[rstest]
    fn test_helper_methods() {
        // Test try_from_order_type helper
        let result = BitmexOrderType::try_from_order_type(OrderType::Limit);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), BitmexOrderType::Limit);

        let result = BitmexOrderType::try_from_order_type(OrderType::MarketToLimit);
        assert!(result.is_err());

        // Test try_from_time_in_force helper
        let result = BitmexTimeInForce::try_from_time_in_force(TimeInForce::Ioc);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), BitmexTimeInForce::ImmediateOrCancel);
    }

    #[rstest]
    #[case(BitmexInstrumentState::Open, MarketStatusAction::Trading)]
    #[case(BitmexInstrumentState::Closed, MarketStatusAction::Close)]
    #[case(BitmexInstrumentState::Settled, MarketStatusAction::Close)]
    #[case(
        BitmexInstrumentState::Unlisted,
        MarketStatusAction::NotAvailableForTrading
    )]
    #[case(
        BitmexInstrumentState::Delisted,
        MarketStatusAction::NotAvailableForTrading
    )]
    fn test_bitmex_instrument_state_to_market_status_action(
        #[case] state: BitmexInstrumentState,
        #[case] expected: MarketStatusAction,
    ) {
        assert_eq!(MarketStatusAction::from(&state), expected);
    }
}