nautilus-hyperliquid 0.55.0

Hyperliquid 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
// -------------------------------------------------------------------------------------------------
//  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.
// -------------------------------------------------------------------------------------------------

use ahash::AHashMap;
use derive_builder::Builder;
use nautilus_model::{
    data::{
        Bar, FundingRateUpdate, IndexPriceUpdate, MarkPriceUpdate, OrderBookDeltas, QuoteTick,
        TradeTick,
    },
    reports::{FillReport, OrderStatusReport},
};
use serde::{Deserialize, Serialize};
use ustr::Ustr;

use crate::common::enums::{
    HyperliquidBarInterval, HyperliquidFillDirection, HyperliquidLiquidationMethod,
    HyperliquidOrderStatus as HyperliquidOrderStatusEnum, HyperliquidSide, HyperliquidTpSl,
    HyperliquidTwapStatus,
};

/// Represents an outbound WebSocket message from client to Hyperliquid.
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "method")]
#[serde(rename_all = "lowercase")]
pub enum HyperliquidWsRequest {
    /// Subscribe to a data feed.
    Subscribe {
        /// Subscription details.
        subscription: SubscriptionRequest,
    },
    /// Unsubscribe from a data feed.
    Unsubscribe {
        /// Subscription details to remove.
        subscription: SubscriptionRequest,
    },
    /// Post a request (info or action).
    Post {
        /// Request ID for tracking.
        id: u64,
        /// Request payload.
        request: PostRequest,
    },
    /// Ping for keepalive.
    Ping,
}

/// Represents subscription request types for WebSocket feeds.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(tag = "type")]
#[serde(rename_all = "camelCase")]
pub enum SubscriptionRequest {
    /// All mid prices across markets.
    AllMids {
        #[serde(skip_serializing_if = "Option::is_none")]
        dex: Option<String>,
    },
    /// Notifications for a user.
    Notification { user: String },
    /// Web data for frontend.
    WebData2 { user: String },
    /// Candlestick data.
    Candle {
        coin: Ustr,
        interval: HyperliquidBarInterval,
    },
    /// Level 2 order book.
    L2Book {
        coin: Ustr,
        #[serde(skip_serializing_if = "Option::is_none")]
        #[serde(rename = "nSigFigs")]
        n_sig_figs: Option<u32>,
        #[serde(skip_serializing_if = "Option::is_none")]
        mantissa: Option<u32>,
    },
    /// Trade updates.
    Trades { coin: Ustr },
    /// Order updates for a user.
    OrderUpdates { user: String },
    /// User events (fills, funding, liquidations).
    UserEvents { user: String },
    /// User fill history.
    UserFills {
        user: String,
        #[serde(skip_serializing_if = "Option::is_none")]
        #[serde(rename = "aggregateByTime")]
        aggregate_by_time: Option<bool>,
    },
    /// User funding payments.
    UserFundings { user: String },
    /// User ledger updates (non-funding).
    UserNonFundingLedgerUpdates { user: String },
    /// Active asset context (for perpetuals).
    ActiveAssetCtx { coin: Ustr },
    /// Active spot asset context.
    ActiveSpotAssetCtx { coin: Ustr },
    /// Active asset data for user.
    ActiveAssetData { user: String, coin: String },
    /// TWAP slice fills.
    UserTwapSliceFills { user: String },
    /// TWAP history.
    UserTwapHistory { user: String },
    /// Best bid/offer updates.
    Bbo { coin: Ustr },
}

/// Post request wrapper for info and action requests.
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "type")]
#[serde(rename_all = "lowercase")]
pub enum PostRequest {
    /// Info request (no signature required).
    Info { payload: serde_json::Value },
    /// Action request (requires signature).
    Action { payload: ActionPayload },
}

/// Action payload with signature.
#[derive(Debug, Clone, Serialize)]
pub struct ActionPayload {
    pub action: ActionRequest,
    pub nonce: u64,
    pub signature: SignatureData,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(rename = "vaultAddress")]
    pub vault_address: Option<String>,
}

/// Signature data.
#[derive(Debug, Clone, Serialize)]
pub struct SignatureData {
    pub r: String,
    pub s: String,
    pub v: String,
}

/// Action request types.
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "type")]
#[serde(rename_all = "lowercase")]
pub enum ActionRequest {
    /// Place orders.
    Order {
        orders: Vec<OrderRequest>,
        grouping: String,
    },
    /// Cancel orders.
    Cancel { cancels: Vec<CancelRequest> },
    /// Cancel orders by client order ID.
    CancelByCloid { cancels: Vec<CancelByCloidRequest> },
    /// Modify orders.
    Modify { modifies: Vec<ModifyRequest> },
}

impl ActionRequest {
    /// Create a simple order action with default "na" grouping
    ///
    /// # Example
    /// ```ignore
    /// let action = ActionRequest::order(vec![order1, order2], "na");
    /// ```
    pub fn order(orders: Vec<OrderRequest>, grouping: impl Into<String>) -> Self {
        Self::Order {
            orders,
            grouping: grouping.into(),
        }
    }

    /// Create a cancel action for multiple orders
    ///
    /// # Example
    /// ```ignore
    /// let action = ActionRequest::cancel(vec![
    ///     CancelRequest { a: 0, o: 12345 },
    ///     CancelRequest { a: 1, o: 67890 },
    /// ]);
    /// ```
    pub fn cancel(cancels: Vec<CancelRequest>) -> Self {
        Self::Cancel { cancels }
    }

    /// Create a cancel-by-cloid action
    ///
    /// # Example
    /// ```ignore
    /// let action = ActionRequest::cancel_by_cloid(vec![
    ///     CancelByCloidRequest { asset: 0, cloid: "order-1".to_string() },
    /// ]);
    /// ```
    pub fn cancel_by_cloid(cancels: Vec<CancelByCloidRequest>) -> Self {
        Self::CancelByCloid { cancels }
    }

    /// Create a modify action for multiple orders
    ///
    /// # Example
    /// ```ignore
    /// let action = ActionRequest::modify(vec![
    ///     ModifyRequest { oid: 12345, order: new_order },
    /// ]);
    /// ```
    pub fn modify(modifies: Vec<ModifyRequest>) -> Self {
        Self::Modify { modifies }
    }
}

/// Order placement request.
#[derive(Debug, Clone, Serialize, Builder)]
pub struct OrderRequest {
    /// Asset ID.
    pub a: u32,
    /// Buy side (true = buy, false = sell).
    pub b: bool,
    /// Price.
    pub p: String,
    /// Size.
    pub s: String,
    /// Reduce only.
    pub r: bool,
    /// Order type.
    pub t: OrderTypeRequest,
    /// Client order ID (optional).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub c: Option<String>,
}

/// Order type in request format.
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "type")]
#[serde(rename_all = "lowercase")]
pub enum OrderTypeRequest {
    Limit {
        tif: TimeInForceRequest,
    },
    Trigger {
        #[serde(rename = "isMarket")]
        is_market: bool,
        #[serde(rename = "triggerPx")]
        trigger_px: String,
        tpsl: TpSlRequest,
    },
}

/// Time in force in request format.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "PascalCase")]
pub enum TimeInForceRequest {
    Alo,
    Ioc,
    Gtc,
}

/// TP/SL in request format.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum TpSlRequest {
    Tp,
    Sl,
}

/// Cancel order request.
#[derive(Debug, Clone, Serialize)]
pub struct CancelRequest {
    /// Asset ID.
    pub a: u32,
    /// Order ID.
    pub o: u64,
}

/// Cancel by client order ID request.
#[derive(Debug, Clone, Serialize)]
pub struct CancelByCloidRequest {
    /// Asset ID.
    pub asset: u32,
    /// Client order ID.
    pub cloid: String,
}

/// Modify order request.
#[derive(Debug, Clone, Serialize)]
pub struct ModifyRequest {
    /// Order ID.
    pub oid: u64,
    /// New order details.
    pub order: OrderRequest,
}

/// Subscription response data wrapper.
#[derive(Debug, Clone, Deserialize)]
pub struct SubscriptionResponseData {
    pub method: String,
    pub subscription: SubscriptionRequest,
}

/// Inbound WebSocket message from Hyperliquid server.
#[derive(Debug, Clone, Deserialize)]
#[serde(tag = "channel")]
#[serde(rename_all = "camelCase")]
pub enum HyperliquidWsMessage {
    /// Subscription confirmation.
    SubscriptionResponse { data: SubscriptionResponseData },
    /// Post request response.
    Post { data: PostResponse },
    /// All mid prices.
    AllMids { data: AllMidsData },
    /// Notifications.
    Notification { data: NotificationData },
    /// Web data.
    WebData2 { data: serde_json::Value },
    /// Candlestick data.
    Candle { data: CandleData },
    /// Level 2 order book.
    L2Book { data: WsBookData },
    /// Trade updates.
    Trades { data: Vec<WsTradeData> },
    /// Order updates.
    OrderUpdates { data: Vec<WsOrderData> },
    /// User events.
    UserEvents { data: WsUserEventData },
    /// Generic user channel (Hyperliquid sends fills/events on this channel).
    #[serde(rename = "user")]
    User { data: WsUserEventData },
    /// User fills.
    UserFills { data: WsUserFillsData },
    /// User funding payments.
    UserFundings { data: WsUserFundingsData },
    /// User ledger updates.
    UserNonFundingLedgerUpdates { data: serde_json::Value },
    /// Active asset context.
    ActiveAssetCtx { data: WsActiveAssetCtxData },
    /// Active spot asset context (same data as ActiveAssetCtx, different channel name).
    ActiveSpotAssetCtx { data: WsActiveAssetCtxData },
    /// Active asset data.
    ActiveAssetData { data: WsActiveAssetData },
    /// TWAP slice fills.
    UserTwapSliceFills { data: WsUserTwapSliceFillsData },
    /// TWAP history.
    UserTwapHistory { data: WsUserTwapHistoryData },
    /// Best bid/offer.
    Bbo { data: WsBboData },
    /// Error response.
    Error { data: String },
    /// Pong response.
    Pong,
}

/// Post response data.
#[derive(Debug, Clone, Deserialize)]
pub struct PostResponse {
    pub id: u64,
    pub response: PostResponsePayload,
}

/// Post response payload.
#[derive(Debug, Clone, Deserialize)]
#[serde(tag = "type")]
#[serde(rename_all = "lowercase")]
pub enum PostResponsePayload {
    Info { payload: serde_json::Value },
    Action { payload: serde_json::Value },
    Error { payload: String },
}

/// All mid prices data.
#[derive(Debug, Clone, Deserialize)]
pub struct AllMidsData {
    pub mids: AHashMap<String, String>,
}

/// Notification data.
#[derive(Debug, Clone, Deserialize)]
pub struct NotificationData {
    pub notification: String,
}

/// Candlestick data.
#[derive(Debug, Clone, Deserialize)]
pub struct CandleData {
    /// Open time (millis).
    pub t: u64,
    /// Close time (millis).
    #[serde(rename = "T")]
    pub close_time: u64,
    /// Symbol.
    pub s: Ustr,
    /// Interval.
    pub i: Ustr,
    /// Open price.
    pub o: String,
    /// Close price.
    pub c: String,
    /// High price.
    pub h: String,
    /// Low price.
    pub l: String,
    /// Volume.
    pub v: String,
    /// Number of trades.
    pub n: u32,
}

/// WebSocket book data.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WsBookData {
    pub coin: Ustr,
    pub levels: [Vec<WsLevelData>; 2], // [bids, asks]
    pub time: u64,
}

/// WebSocket level data.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WsLevelData {
    /// Price.
    pub px: String,
    /// Size.
    pub sz: String,
    /// Number of orders.
    pub n: u32,
}

/// WebSocket trade data.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WsTradeData {
    pub coin: Ustr,
    pub side: HyperliquidSide,
    pub px: String,
    pub sz: String,
    pub hash: String,
    pub time: u64,
    pub tid: u64,
    pub users: [String; 2], // [buyer, seller]
}

/// WebSocket order data.
#[derive(Debug, Clone, Deserialize)]
pub struct WsOrderData {
    pub order: WsBasicOrderData,
    pub status: HyperliquidOrderStatusEnum,
    #[serde(rename = "statusTimestamp")]
    pub status_timestamp: u64,
}

/// Basic order data.
#[derive(Debug, Clone, Deserialize)]
pub struct WsBasicOrderData {
    pub coin: Ustr,
    pub side: HyperliquidSide,
    #[serde(rename = "limitPx")]
    pub limit_px: String,
    pub sz: String,
    pub oid: u64,
    pub timestamp: u64,
    #[serde(rename = "origSz")]
    pub orig_sz: String,
    pub cloid: Option<String>,
    /// Trigger price for conditional orders (stop/take-profit).
    #[serde(rename = "triggerPx")]
    pub trigger_px: Option<String>,
    /// Whether this is a market or limit trigger order.
    #[serde(rename = "isMarket")]
    pub is_market: Option<bool>,
    /// Take-profit or stop-loss indicator.
    pub tpsl: Option<HyperliquidTpSl>,
    /// Whether the trigger has been activated.
    #[serde(rename = "triggerActivated")]
    pub trigger_activated: Option<bool>,
    /// Trailing stop parameters if applicable.
    #[serde(rename = "trailingStop")]
    pub trailing_stop: Option<WsTrailingStopData>,
}

/// Trailing stop offset type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum TrailingOffsetType {
    /// Price offset.
    Price,
    /// Percentage offset.
    Percentage,
    /// Basis points offset.
    BasisPoints,
}

impl TrailingOffsetType {
    /// Format the offset value with the appropriate unit.
    pub fn format_offset(&self, offset: &str) -> String {
        match self {
            Self::Price => offset.to_string(),
            Self::Percentage => format!("{offset}%"),
            Self::BasisPoints => format!("{offset} bps"),
        }
    }
}

/// Trailing stop data from WebSocket.
#[derive(Debug, Clone, Deserialize)]
pub struct WsTrailingStopData {
    /// Trailing offset value.
    pub offset: String,
    /// Offset type.
    #[serde(rename = "offsetType")]
    pub offset_type: TrailingOffsetType,
    /// Current callback price (highest/lowest price reached).
    #[serde(rename = "callbackPrice")]
    pub callback_price: Option<String>,
}

/// WebSocket user event data.
#[derive(Debug, Clone, Deserialize)]
#[serde(untagged)]
pub enum WsUserEventData {
    Fills {
        fills: Vec<WsFillData>,
    },
    Funding {
        funding: WsUserFundingData,
    },
    Liquidation {
        liquidation: WsLiquidationData,
    },
    NonUserCancel {
        #[serde(rename = "nonUserCancel")]
        non_user_cancel: Vec<WsNonUserCancelData>,
    },
    /// Trigger order activated (moved from pending to active).
    TriggerActivated {
        #[serde(rename = "triggerActivated")]
        trigger_activated: WsTriggerActivatedData,
    },
    /// Trigger order executed (trigger price reached, order placed).
    TriggerTriggered {
        #[serde(rename = "triggerTriggered")]
        trigger_triggered: WsTriggerTriggeredData,
    },
}

/// WebSocket fill data.
#[derive(Debug, Clone, Deserialize)]
pub struct WsFillData {
    pub coin: Ustr,
    pub px: String,
    pub sz: String,
    pub side: HyperliquidSide,
    pub time: u64,
    #[serde(rename = "startPosition")]
    pub start_position: String,
    pub dir: HyperliquidFillDirection,
    #[serde(rename = "closedPnl")]
    pub closed_pnl: String,
    pub hash: String,
    pub oid: u64,
    pub crossed: bool,
    pub fee: String,
    pub tid: u64,
    #[serde(default)]
    pub liquidation: Option<FillLiquidationData>,
    #[serde(rename = "feeToken")]
    pub fee_token: Ustr,
    #[serde(rename = "builderFee")]
    pub builder_fee: Option<String>,
    /// Client order ID (hex string with 0x prefix).
    pub cloid: Option<String>,
    /// TWAP order ID if this fill is part of a TWAP order.
    #[serde(rename = "twapId")]
    pub twap_id: Option<serde_json::Value>,
}

/// Fill liquidation data.
#[derive(Debug, Clone, Deserialize)]
pub struct FillLiquidationData {
    #[serde(rename = "liquidatedUser")]
    pub liquidated_user: Option<String>,
    #[serde(rename = "markPx")]
    pub mark_px: f64,
    pub method: HyperliquidLiquidationMethod,
}

/// WebSocket user funding data.
#[derive(Debug, Clone, Deserialize)]
pub struct WsUserFundingData {
    pub time: u64,
    pub coin: Ustr,
    pub usdc: String,
    pub szi: String,
    #[serde(rename = "fundingRate")]
    pub funding_rate: String,
}

/// WebSocket liquidation data.
#[derive(Debug, Clone, Deserialize)]
pub struct WsLiquidationData {
    pub lid: u64,
    pub liquidator: String,
    pub liquidated_user: String,
    pub liquidated_ntl_pos: String,
    pub liquidated_account_value: String,
}

/// WebSocket non-user cancel data.
#[derive(Debug, Clone, Deserialize)]
pub struct WsNonUserCancelData {
    pub coin: Ustr,
    pub oid: u64,
}

/// Trigger order activated event data.
#[derive(Debug, Clone, Deserialize)]
pub struct WsTriggerActivatedData {
    pub coin: Ustr,
    pub oid: u64,
    pub time: u64,
    #[serde(rename = "triggerPx")]
    pub trigger_px: String,
    pub tpsl: HyperliquidTpSl,
}

/// Trigger order triggered event data.
#[derive(Debug, Clone, Deserialize)]
pub struct WsTriggerTriggeredData {
    pub coin: Ustr,
    pub oid: u64,
    pub time: u64,
    #[serde(rename = "triggerPx")]
    pub trigger_px: String,
    #[serde(rename = "marketPx")]
    pub market_px: String,
    pub tpsl: HyperliquidTpSl,
    /// Order ID of the resulting market/limit order after trigger.
    #[serde(rename = "resultingOid")]
    pub resulting_oid: Option<u64>,
}

/// WebSocket user fills data.
#[derive(Debug, Clone, Deserialize)]
pub struct WsUserFillsData {
    #[serde(rename = "isSnapshot")]
    pub is_snapshot: Option<bool>,
    pub user: String,
    pub fills: Vec<WsFillData>,
}

/// WebSocket user fundings data.
#[derive(Debug, Clone, Deserialize)]
pub struct WsUserFundingsData {
    #[serde(rename = "isSnapshot")]
    pub is_snapshot: Option<bool>,
    pub user: String,
    pub fundings: Vec<WsUserFundingData>,
}

/// WebSocket active asset context data.
#[derive(Debug, Clone, Deserialize)]
#[serde(untagged)]
pub enum WsActiveAssetCtxData {
    Perp { coin: Ustr, ctx: PerpsAssetCtx },
    Spot { coin: Ustr, ctx: SpotAssetCtx },
}

/// Shared asset context fields.
#[derive(Debug, Clone, Deserialize)]
pub struct SharedAssetCtx {
    #[serde(rename = "dayNtlVlm")]
    pub day_ntl_vlm: String,
    #[serde(rename = "prevDayPx")]
    pub prev_day_px: String,
    #[serde(rename = "markPx")]
    pub mark_px: String,
    #[serde(rename = "midPx")]
    pub mid_px: Option<String>,
    #[serde(rename = "impactPxs")]
    pub impact_pxs: Option<Vec<String>>,
    #[serde(rename = "dayBaseVlm")]
    pub day_base_vlm: Option<String>,
}

/// Perps asset context.
#[derive(Debug, Clone, Deserialize)]
pub struct PerpsAssetCtx {
    #[serde(flatten)]
    pub shared: SharedAssetCtx,
    pub funding: String,
    #[serde(rename = "openInterest")]
    pub open_interest: String,
    #[serde(rename = "oraclePx")]
    pub oracle_px: String,
    pub premium: Option<String>,
}

/// Spot asset context.
#[derive(Debug, Clone, Deserialize)]
pub struct SpotAssetCtx {
    #[serde(flatten)]
    pub shared: SharedAssetCtx,
    #[serde(rename = "circulatingSupply")]
    pub circulating_supply: String,
}

/// WebSocket active asset data.
#[derive(Debug, Clone, Deserialize)]
pub struct WsActiveAssetData {
    pub user: String,
    pub coin: Ustr,
    pub leverage: LeverageData,
    #[serde(rename = "maxTradeSzs")]
    pub max_trade_szs: [f64; 2],
    #[serde(rename = "availableToTrade")]
    pub available_to_trade: [f64; 2],
}

/// Leverage data.
#[derive(Debug, Clone, Deserialize)]
pub struct LeverageData {
    pub value: f64,
    pub type_: String,
}

/// WebSocket TWAP slice fills data.
#[derive(Debug, Clone, Deserialize)]
pub struct WsUserTwapSliceFillsData {
    #[serde(rename = "isSnapshot")]
    pub is_snapshot: Option<bool>,
    pub user: String,
    #[serde(rename = "twapSliceFills")]
    pub twap_slice_fills: Vec<WsTwapSliceFillData>,
}

/// TWAP slice fill data.
#[derive(Debug, Clone, Deserialize)]
pub struct WsTwapSliceFillData {
    pub fill: WsFillData,
    #[serde(rename = "twapId")]
    pub twap_id: u64,
}

/// WebSocket TWAP history data.
#[derive(Debug, Clone, Deserialize)]
pub struct WsUserTwapHistoryData {
    #[serde(rename = "isSnapshot")]
    pub is_snapshot: Option<bool>,
    pub user: String,
    pub history: Vec<WsTwapHistoryData>,
}

/// TWAP history data.
#[derive(Debug, Clone, Deserialize)]
pub struct WsTwapHistoryData {
    pub state: TwapStateData,
    pub status: TwapStatusData,
    pub time: u64,
}

/// TWAP state data.
#[derive(Debug, Clone, Deserialize)]
pub struct TwapStateData {
    pub coin: Ustr,
    pub user: String,
    pub side: HyperliquidSide,
    pub sz: f64,
    #[serde(rename = "executedSz")]
    pub executed_sz: f64,
    #[serde(rename = "executedNtl")]
    pub executed_ntl: f64,
    pub minutes: u32,
    #[serde(rename = "reduceOnly")]
    pub reduce_only: bool,
    pub randomize: bool,
    pub timestamp: u64,
}

/// TWAP status data.
#[derive(Debug, Clone, Deserialize)]
pub struct TwapStatusData {
    pub status: HyperliquidTwapStatus,
    pub description: String,
}

/// WebSocket BBO data.
#[derive(Debug, Clone, Deserialize)]
pub struct WsBboData {
    pub coin: Ustr,
    pub time: u64,
    pub bbo: [Option<WsLevelData>; 2], // [bid, ask]
}

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

    use super::*;

    #[rstest]
    fn test_subscription_request_serialization() {
        let sub = SubscriptionRequest::L2Book {
            coin: Ustr::from("BTC"),
            n_sig_figs: Some(5),
            mantissa: None,
        };

        let json = serde_json::to_string(&sub).unwrap();
        assert!(json.contains(r#""type":"l2Book""#));
        assert!(json.contains(r#""coin":"BTC""#));
    }

    #[rstest]
    fn test_hyperliquid_ws_request_serialization() {
        let req = HyperliquidWsRequest::Subscribe {
            subscription: SubscriptionRequest::Trades {
                coin: Ustr::from("ETH"),
            },
        };

        let json = serde_json::to_string(&req).unwrap();
        assert!(json.contains(r#""method":"subscribe""#));
        assert!(json.contains(r#""type":"trades""#));
    }

    #[rstest]
    fn test_order_request_serialization() {
        let order = OrderRequest {
            a: 0,    // BTC asset ID
            b: true, // buy
            p: "50000.0".to_string(),
            s: "0.1".to_string(),
            r: false,
            t: OrderTypeRequest::Limit {
                tif: TimeInForceRequest::Gtc,
            },
            c: Some("client-123".to_string()),
        };

        let json = serde_json::to_string(&order).unwrap();
        assert!(json.contains(r#""a":0"#));
        assert!(json.contains(r#""b":true"#));
        assert!(json.contains(r#""p":"50000.0""#));
    }

    #[rstest]
    fn test_ws_trade_data_deserialization() {
        let json = r#"{
            "coin": "BTC",
            "side": "B",
            "px": "50000.0",
            "sz": "0.1",
            "hash": "0x123",
            "time": 1234567890,
            "tid": 12345,
            "users": ["0xabc", "0xdef"]
        }"#;

        let trade: WsTradeData = serde_json::from_str(json).unwrap();
        assert_eq!(trade.coin, "BTC");
        assert_eq!(trade.side, HyperliquidSide::Buy);
        assert_eq!(trade.px, "50000.0");
    }

    #[rstest]
    fn test_ws_book_data_deserialization() {
        let json = r#"{
            "coin": "ETH",
            "levels": [
                [{"px": "3000.0", "sz": "1.0", "n": 1}],
                [{"px": "3001.0", "sz": "2.0", "n": 2}]
            ],
            "time": 1234567890
        }"#;

        let book: WsBookData = serde_json::from_str(json).unwrap();
        assert_eq!(book.coin, "ETH");
        assert_eq!(book.levels[0].len(), 1);
        assert_eq!(book.levels[1].len(), 1);
    }

    #[rstest]
    fn test_ws_trailing_stop_data_deserialization() {
        let json = r#"{
            "offset": "100.0",
            "offsetType": "price",
            "callbackPrice": "50000.0"
        }"#;

        let data: WsTrailingStopData = serde_json::from_str(json).unwrap();
        assert_eq!(data.offset, "100.0");
        assert_eq!(data.offset_type, TrailingOffsetType::Price);
        assert_eq!(data.callback_price.unwrap(), "50000.0");
    }

    #[rstest]
    fn test_ws_trigger_activated_data_deserialization() {
        let json = r#"{
            "coin": "BTC",
            "oid": 12345,
            "time": 1704470400000,
            "triggerPx": "50000.0",
            "tpsl": "sl"
        }"#;

        let data: WsTriggerActivatedData = serde_json::from_str(json).unwrap();
        assert_eq!(data.coin, Ustr::from("BTC"));
        assert_eq!(data.oid, 12345);
        assert_eq!(data.trigger_px, "50000.0");
        assert_eq!(data.tpsl, HyperliquidTpSl::Sl);
        assert_eq!(data.time, 1704470400000);
    }

    #[rstest]
    fn test_ws_trigger_triggered_data_deserialization() {
        let json = r#"{
            "coin": "ETH",
            "oid": 67890,
            "time": 1704470500000,
            "triggerPx": "3000.0",
            "marketPx": "3001.0",
            "tpsl": "tp",
            "resultingOid": 99999
        }"#;

        let data: WsTriggerTriggeredData = serde_json::from_str(json).unwrap();
        assert_eq!(data.coin, Ustr::from("ETH"));
        assert_eq!(data.oid, 67890);
        assert_eq!(data.trigger_px, "3000.0");
        assert_eq!(data.market_px, "3001.0");
        assert_eq!(data.tpsl, HyperliquidTpSl::Tp);
        assert_eq!(data.resulting_oid, Some(99999));
    }

    #[rstest]
    fn test_ws_fill_data_deserialization_with_cloid_and_twap() {
        let json = r#"{
            "coin": "@107",
            "px": "31.737",
            "sz": "0.31",
            "side": "B",
            "time": 1769920606068,
            "startPosition": "0.0",
            "dir": "Buy",
            "closedPnl": "0.0",
            "hash": "0xc731e7561e5334a0c8ab043472ce7d01d400ff3bb95653726afa92a8dd570e8b",
            "oid": 308086083674,
            "crossed": true,
            "fee": "0.00021699",
            "tid": 812806034449156,
            "cloid": "0xd211f1c27288259290850338d22132a0",
            "feeToken": "HYPE",
            "twapId": null
        }"#;

        let fill: WsFillData = serde_json::from_str(json).unwrap();
        assert_eq!(fill.coin, "@107");
        assert_eq!(fill.px, "31.737");
        assert_eq!(fill.sz, "0.31");
        assert_eq!(fill.side, HyperliquidSide::Buy);
        assert_eq!(fill.oid, 308086083674);
        assert!(fill.crossed);
        assert_eq!(fill.fee, "0.00021699");
        assert_eq!(fill.fee_token, "HYPE");
        assert_eq!(
            fill.cloid,
            Some("0xd211f1c27288259290850338d22132a0".to_string())
        );
        assert!(fill.twap_id.is_none() || fill.twap_id == Some(serde_json::Value::Null));
    }

    #[rstest]
    fn test_ws_user_fills_message_deserialization() {
        let json = r#"{"channel":"user","data":{"fills":[{"coin":"@107","px":"31.737","sz":"0.31","side":"B","time":1769920606068,"startPosition":"0.0","dir":"Buy","closedPnl":"0.0","hash":"0xc731e7561e5334a0c8ab043472ce7d01d400ff3bb95653726afa92a8dd570e8b","oid":308086083674,"crossed":true,"fee":"0.00021699","tid":812806034449156,"cloid":"0xd211f1c27288259290850338d22132a0","feeToken":"HYPE","twapId":null}]}}"#;

        let msg: HyperliquidWsMessage = serde_json::from_str(json).unwrap();

        match msg {
            HyperliquidWsMessage::User { data } => match data {
                WsUserEventData::Fills { fills } => {
                    assert_eq!(fills.len(), 1);
                    let fill = &fills[0];
                    assert_eq!(fill.coin, "@107");
                    assert_eq!(fill.px, "31.737");
                    assert_eq!(
                        fill.cloid,
                        Some("0xd211f1c27288259290850338d22132a0".to_string())
                    );
                }
                _ => panic!("Expected Fills variant"),
            },
            _ => panic!("Expected User channel message"),
        }
    }

    #[rstest]
    fn test_ws_user_fills_message_with_builder_fee() {
        // Real message from production that was failing
        let json = r#"{"channel":"user","data":{"fills":[{"coin":"BTC","px":"79146.0","sz":"0.001","side":"A","time":1769940855551,"startPosition":"0.00093","dir":"Long > Short","closedPnl":"0.046128","hash":"0x5f8b9c337a197c4061050434769793020e020019151c9b1203544786391d562b","oid":308254271324,"crossed":false,"fee":"0.019785","builderFee":"0.007914","tid":404237815023429,"cloid":"0x50663504b0f4fedea00080176229d94f","feeToken":"USDC","twapId":null}]}}"#;

        let msg: HyperliquidWsMessage = serde_json::from_str(json).unwrap();

        match msg {
            HyperliquidWsMessage::User { data } => match data {
                WsUserEventData::Fills { fills } => {
                    assert_eq!(fills.len(), 1);
                    let fill = &fills[0];
                    assert_eq!(fill.coin, "BTC");
                    assert_eq!(fill.px, "79146.0");
                    assert_eq!(fill.side, HyperliquidSide::Sell);
                    assert_eq!(fill.builder_fee, Some("0.007914".to_string()));
                    assert_eq!(fill.fee_token, "USDC");
                }
                _ => panic!("Expected Fills variant"),
            },
            _ => panic!("Expected User channel message"),
        }
    }
}

/// Nautilus WebSocket message wrapper for routing to execution engine.
///
/// Wraps parsed messages from the handler.
///
/// All parsing happens in the handler layer, with parsed Nautilus domain objects.
/// passed through to the Python layer.
#[derive(Debug, Clone)]
pub enum NautilusWsMessage {
    /// Execution reports (order status and fills).
    ExecutionReports(Vec<ExecutionReport>),
    /// Parsed trade ticks.
    Trades(Vec<TradeTick>),
    /// Parsed quote tick (from BBO).
    Quote(QuoteTick),
    /// Parsed order book deltas.
    Deltas(OrderBookDeltas),
    /// Parsed candle/bar.
    Candle(Bar),
    /// Mark price update.
    MarkPrice(MarkPriceUpdate),
    /// Index price update.
    IndexPrice(IndexPriceUpdate),
    /// Funding rate update.
    FundingRate(FundingRateUpdate),
    /// Error occurred.
    Error(String),
    /// WebSocket reconnected.
    Reconnected,
}

/// Execution report wrapper for order status and fill reports.
///
/// This enum allows both order status updates and fill reports.
/// to be sent through the execution engine.
#[derive(Debug, Clone)]
#[allow(clippy::large_enum_variant)]
pub enum ExecutionReport {
    /// Order status report.
    Order(OrderStatusReport),
    /// Fill report.
    Fill(FillReport),
}