Skip to main content

nautilus_hyperliquid/websocket/
messages.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16use std::borrow::Cow;
17
18use ahash::AHashMap;
19use derive_builder::Builder;
20#[cfg(test)]
21use nautilus_core::string::secret::REDACTED;
22use nautilus_core::{
23    serialization::{
24        decimal, deserialize_decimal, deserialize_decimal_from_str,
25        deserialize_optional_decimal_from_str, serialize_decimal_as_str,
26    },
27    string::secret::SecretString,
28};
29use nautilus_model::{
30    data::{
31        Bar, Data, FundingRateUpdate, IndexPriceUpdate, MarkPriceUpdate, OrderBookDeltas,
32        OrderBookDepth, QuoteTick, TradeTick,
33    },
34    identifiers::InstrumentId,
35    reports::{FillReport, OrderStatusReport},
36};
37use rust_decimal::Decimal;
38use serde::{Deserialize, Deserializer, Serialize, de::Error};
39use serde_json::value::RawValue;
40use ustr::Ustr;
41
42use crate::{
43    common::{
44        enums::{
45            HyperliquidBarInterval, HyperliquidFillDirection, HyperliquidLiquidationMethod,
46            HyperliquidOrderStatus as HyperliquidOrderStatusEnum, HyperliquidSide,
47            HyperliquidTimeInForce, HyperliquidTpSl, HyperliquidTwapStatus,
48        },
49        parse::is_false_or_none,
50    },
51    http::models::{
52        ClearinghouseState, HyperliquidExchangeAction, HyperliquidExchangeRequest, LeverageInfo,
53        SpotClearinghouseState,
54    },
55};
56
57/// Represents an outbound WebSocket message from client to Hyperliquid.
58#[derive(Debug, Clone, Serialize)]
59#[serde(tag = "method")]
60#[serde(rename_all = "lowercase")]
61pub enum HyperliquidWsRequest {
62    /// Subscribe to a data feed.
63    Subscribe {
64        /// Subscription details.
65        subscription: SubscriptionRequest,
66    },
67    /// Unsubscribe from a data feed.
68    Unsubscribe {
69        /// Subscription details to remove.
70        subscription: SubscriptionRequest,
71    },
72    /// Post a request (info or action).
73    Post {
74        /// Request ID for tracking.
75        id: u64,
76        /// Request payload.
77        request: PostRequest,
78    },
79    /// Ping for keepalive.
80    Ping,
81}
82
83/// Represents subscription request types for WebSocket feeds.
84#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
85#[serde(tag = "type")]
86#[serde(rename_all = "camelCase")]
87pub enum SubscriptionRequest {
88    /// All mid prices across markets.
89    AllMids {
90        #[serde(skip_serializing_if = "Option::is_none")]
91        dex: Option<String>,
92    },
93    /// Aggregate asset contexts across all perp dexes.
94    AllDexsAssetCtxs,
95    /// Notifications for a user.
96    Notification { user: String },
97    /// Web data for frontend.
98    WebData2 { user: String },
99    /// Candlestick data.
100    Candle {
101        coin: Ustr,
102        interval: HyperliquidBarInterval,
103    },
104    /// Level 2 order book.
105    L2Book {
106        coin: Ustr,
107        #[serde(skip_serializing_if = "Option::is_none")]
108        #[serde(rename = "nSigFigs")]
109        n_sig_figs: Option<u32>,
110        #[serde(skip_serializing_if = "Option::is_none")]
111        mantissa: Option<u32>,
112    },
113    /// Trade updates.
114    Trades { coin: Ustr },
115    /// Order updates for a user.
116    OrderUpdates { user: String },
117    /// User events (fills, funding, liquidations).
118    UserEvents { user: String },
119    /// User fill history.
120    UserFills {
121        user: String,
122        #[serde(skip_serializing_if = "Option::is_none")]
123        #[serde(rename = "aggregateByTime")]
124        aggregate_by_time: Option<bool>,
125    },
126    /// User funding payments.
127    UserFundings { user: String },
128    /// User ledger updates (non-funding).
129    UserNonFundingLedgerUpdates { user: String },
130    /// Active asset context (for perpetuals).
131    ActiveAssetCtx { coin: Ustr },
132    /// Active spot asset context.
133    ActiveSpotAssetCtx { coin: Ustr },
134    /// Active asset data for user.
135    ActiveAssetData { user: String, coin: String },
136    /// TWAP slice fills.
137    UserTwapSliceFills { user: String },
138    /// TWAP history.
139    UserTwapHistory { user: String },
140    /// Best bid/offer updates.
141    Bbo { coin: Ustr },
142    /// Default perp dex account state.
143    ClearinghouseState { user: String },
144    /// Spot balances and holds.
145    SpotState {
146        user: String,
147        #[serde(default, rename = "isPortfolioMargin")]
148        is_portfolio_margin: bool,
149    },
150}
151
152/// Post request wrapper for info and action requests.
153#[derive(Debug, Clone, Serialize)]
154#[serde(tag = "type")]
155#[serde(rename_all = "lowercase")]
156pub enum PostRequest {
157    /// Info request (no signature required).
158    Info { payload: serde_json::Value },
159    /// Action request (requires signature).
160    Action {
161        payload: HyperliquidExchangeRequest<HyperliquidExchangeAction>,
162    },
163}
164
165/// Action payload with signature.
166#[derive(Debug, Clone, Serialize)]
167pub struct ActionPayload {
168    pub action: ActionRequest,
169    pub nonce: u64,
170    pub signature: SignatureData,
171    #[serde(skip_serializing_if = "Option::is_none")]
172    #[serde(rename = "vaultAddress")]
173    pub vault_address: Option<String>,
174}
175
176/// Signature data.
177#[derive(Debug, Clone, Serialize)]
178pub struct SignatureData {
179    pub r: SecretString,
180    pub s: SecretString,
181    pub v: SecretString,
182}
183
184/// Action request types.
185///
186/// Fast-cancel flags are serialized only when true.
187#[derive(Debug, Clone, Serialize)]
188#[serde(tag = "type")]
189#[serde(rename_all = "lowercase")]
190pub enum ActionRequest {
191    /// Place orders.
192    Order {
193        orders: Vec<OrderRequest>,
194        grouping: String,
195    },
196    /// Cancel orders.
197    Cancel {
198        cancels: Vec<CancelRequest>,
199        #[serde(rename = "f", skip_serializing_if = "is_false_or_none")]
200        fast: Option<bool>,
201    },
202    /// Cancel orders by client order ID.
203    CancelByCloid {
204        cancels: Vec<CancelByCloidRequest>,
205        #[serde(rename = "f", skip_serializing_if = "is_false_or_none")]
206        fast: Option<bool>,
207    },
208    /// Modify orders.
209    Modify { modifies: Vec<ModifyRequest> },
210}
211
212impl ActionRequest {
213    /// Create a simple order action with default "na" grouping
214    ///
215    /// # Example
216    /// ```ignore
217    /// let action = ActionRequest::order(vec![order1, order2], "na");
218    /// ```
219    pub fn order(orders: Vec<OrderRequest>, grouping: impl Into<String>) -> Self {
220        Self::Order {
221            orders,
222            grouping: grouping.into(),
223        }
224    }
225
226    /// Create a cancel action for multiple orders
227    ///
228    /// # Example
229    /// ```ignore
230    /// let action = ActionRequest::cancel(vec![
231    ///     CancelRequest { a: 0, o: 12345 },
232    ///     CancelRequest { a: 1, o: 67890 },
233    /// ]);
234    /// ```
235    pub fn cancel(cancels: Vec<CancelRequest>) -> Self {
236        Self::Cancel {
237            cancels,
238            fast: None,
239        }
240    }
241
242    /// Create a cancel-by-cloid action
243    ///
244    /// # Example
245    /// ```ignore
246    /// let action = ActionRequest::cancel_by_cloid(vec![
247    ///     CancelByCloidRequest { asset: 0, cloid: "order-1".to_string() },
248    /// ]);
249    /// ```
250    pub fn cancel_by_cloid(cancels: Vec<CancelByCloidRequest>) -> Self {
251        Self::CancelByCloid {
252            cancels,
253            fast: None,
254        }
255    }
256
257    /// Create a modify action for multiple orders
258    ///
259    /// # Example
260    /// ```ignore
261    /// let action = ActionRequest::modify(vec![
262    ///     ModifyRequest { oid: 12345, order: new_order },
263    /// ]);
264    /// ```
265    pub fn modify(modifies: Vec<ModifyRequest>) -> Self {
266        Self::Modify { modifies }
267    }
268}
269
270/// Order placement request.
271#[derive(Debug, Clone, Serialize, Builder)]
272pub struct OrderRequest {
273    /// Asset ID.
274    pub a: u32,
275    /// Buy side (true = buy, false = sell).
276    pub b: bool,
277    /// Price.
278    pub p: String,
279    /// Size.
280    pub s: String,
281    /// Reduce only.
282    pub r: bool,
283    /// Order type.
284    pub t: OrderTypeRequest,
285    /// Client order ID (optional).
286    #[serde(skip_serializing_if = "Option::is_none")]
287    pub c: Option<String>,
288}
289
290/// Order type in request format.
291#[derive(Debug, Clone, Serialize)]
292#[serde(tag = "type")]
293#[serde(rename_all = "lowercase")]
294pub enum OrderTypeRequest {
295    Limit {
296        tif: TimeInForceRequest,
297    },
298    Trigger {
299        #[serde(rename = "isMarket")]
300        is_market: bool,
301        #[serde(rename = "triggerPx")]
302        trigger_px: String,
303        tpsl: TpSlRequest,
304    },
305}
306
307/// Time in force in request format.
308#[derive(Debug, Clone, Serialize)]
309#[serde(rename_all = "PascalCase")]
310pub enum TimeInForceRequest {
311    Alo,
312    Ioc,
313    Gtc,
314}
315
316/// TP/SL in request format.
317#[derive(Debug, Clone, Serialize)]
318#[serde(rename_all = "lowercase")]
319pub enum TpSlRequest {
320    Tp,
321    Sl,
322}
323
324/// Cancel order request.
325#[derive(Debug, Clone, Serialize)]
326pub struct CancelRequest {
327    /// Asset ID.
328    pub a: u32,
329    /// Order ID.
330    pub o: u64,
331}
332
333/// Cancel by client order ID request.
334#[derive(Debug, Clone, Serialize)]
335pub struct CancelByCloidRequest {
336    /// Asset ID.
337    pub asset: u32,
338    /// Client order ID.
339    pub cloid: String,
340}
341
342/// Modify order request.
343#[derive(Debug, Clone, Serialize)]
344pub struct ModifyRequest {
345    /// Order ID.
346    pub oid: u64,
347    /// New order details.
348    pub order: OrderRequest,
349}
350
351/// Subscription response data wrapper.
352#[derive(Debug, Clone, Deserialize)]
353pub struct SubscriptionResponseData {
354    pub method: String,
355    pub subscription: SubscriptionRequest,
356}
357
358/// Inbound WebSocket message from Hyperliquid server.
359#[derive(Debug, Clone, Deserialize)]
360#[serde(remote = "Self", tag = "channel")]
361#[serde(rename_all = "camelCase")]
362pub enum HyperliquidWsMessage {
363    /// Subscription confirmation.
364    SubscriptionResponse { data: SubscriptionResponseData },
365    /// Post request response.
366    Post { data: PostResponse },
367    /// All mid prices.
368    AllMids { data: AllMidsData },
369    /// Aggregate asset contexts across all perp dexes.
370    AllDexsAssetCtxs { data: WsAllDexsAssetCtxsData },
371    /// Notifications.
372    Notification { data: NotificationData },
373    /// Web data.
374    WebData2 { data: serde_json::Value },
375    /// Candlestick data.
376    Candle { data: CandleData },
377    /// Level 2 order book.
378    L2Book { data: WsBookData },
379    /// Trade updates.
380    Trades { data: Vec<WsTradeData> },
381    /// Order updates.
382    OrderUpdates { data: Vec<WsOrderData> },
383    /// User events.
384    UserEvents { data: WsUserEventData },
385    /// Generic user channel (Hyperliquid sends fills/events on this channel).
386    #[serde(rename = "user")]
387    User { data: WsUserEventData },
388    /// User fills.
389    UserFills { data: WsUserFillsData },
390    /// User funding payments.
391    UserFundings { data: WsUserFundingsData },
392    /// User ledger updates.
393    UserNonFundingLedgerUpdates { data: serde_json::Value },
394    /// Active asset context.
395    ActiveAssetCtx { data: WsActiveAssetCtxData },
396    /// Active spot asset context (same data as ActiveAssetCtx, different channel name).
397    ActiveSpotAssetCtx { data: WsActiveAssetCtxData },
398    /// Active asset data.
399    ActiveAssetData { data: WsActiveAssetData },
400    /// TWAP slice fills.
401    UserTwapSliceFills { data: WsUserTwapSliceFillsData },
402    /// TWAP history.
403    UserTwapHistory { data: WsUserTwapHistoryData },
404    /// Best bid/offer.
405    Bbo { data: WsBboData },
406    /// Error response.
407    Error { data: String },
408    /// Pong response.
409    Pong,
410    /// Default perp dex account state.
411    ClearinghouseState { data: WsClearinghouseState },
412    /// Spot balances and holds.
413    SpotState { data: WsSpotState },
414}
415
416impl<'de> Deserialize<'de> for HyperliquidWsMessage {
417    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
418        let raw = Box::<RawValue>::deserialize(deserializer)?;
419        decode_ws_message(raw.get()).map_err(D::Error::custom)
420    }
421}
422
423pub(crate) fn decode_ws_message(text: &str) -> serde_json::Result<HyperliquidWsMessage> {
424    let header: WsMessageHeader = serde_json::from_str(text)?;
425
426    // Tagged enum buffering loses raw numeric tokens; parse active asset data directly
427    if header.channel == "activeAssetData" {
428        let message: WsActiveAssetDataMessage = serde_json::from_str(text)?;
429        return Ok(HyperliquidWsMessage::ActiveAssetData { data: message.data });
430    }
431
432    HyperliquidWsMessage::deserialize(&mut serde_json::Deserializer::from_str(text))
433}
434
435#[derive(Deserialize)]
436struct WsMessageHeader<'a> {
437    #[serde(borrow)]
438    channel: Cow<'a, str>,
439}
440
441#[derive(Deserialize)]
442struct WsActiveAssetDataMessage {
443    data: WsActiveAssetData,
444}
445
446/// Perp account snapshot from the clearinghouse state channel.
447#[derive(Debug, Clone, Deserialize)]
448#[serde(rename_all = "camelCase")]
449pub struct WsClearinghouseState {
450    #[serde(deserialize_with = "deserialize_clearinghouse_state")]
451    pub clearinghouse_state: ClearinghouseState,
452}
453
454fn deserialize_clearinghouse_state<'de, D: Deserializer<'de>>(
455    deserializer: D,
456) -> Result<ClearinghouseState, D::Error> {
457    let state = ClearinghouseState::deserialize(deserializer)?;
458    if state.cross_margin_summary.is_none() {
459        return Err(D::Error::missing_field("crossMarginSummary"));
460    }
461
462    if state.withdrawable.is_none() {
463        return Err(D::Error::missing_field("withdrawable"));
464    }
465
466    Ok(state)
467}
468
469/// Spot account snapshot from the spot state channel.
470#[derive(Debug, Clone, Deserialize)]
471#[serde(rename_all = "camelCase")]
472pub struct WsSpotState {
473    #[serde(deserialize_with = "deserialize_spot_state")]
474    pub spot_state: SpotClearinghouseState,
475}
476
477fn deserialize_spot_state<'de, D: Deserializer<'de>>(
478    deserializer: D,
479) -> Result<SpotClearinghouseState, D::Error> {
480    let value = serde_json::Value::deserialize(deserializer)?;
481    if value.get("balances").is_none() {
482        return Err(D::Error::missing_field("balances"));
483    }
484
485    serde_json::from_value(value).map_err(D::Error::custom)
486}
487
488/// Post response data.
489#[derive(Debug, Clone, Deserialize)]
490pub struct PostResponse {
491    pub id: u64,
492    pub response: PostResponsePayload,
493}
494
495/// Post response payload.
496#[derive(Debug, Clone, Deserialize)]
497#[serde(tag = "type")]
498#[serde(rename_all = "lowercase")]
499pub enum PostResponsePayload {
500    Info { payload: serde_json::Value },
501    Action { payload: serde_json::Value },
502    Error { payload: String },
503}
504
505/// All mid prices data.
506#[derive(Debug, Clone, Deserialize)]
507pub struct AllMidsData {
508    pub mids: AHashMap<Ustr, String>,
509}
510
511/// `allDexsAssetCtxs` data payload.
512#[derive(Debug, Clone, Deserialize)]
513pub struct WsAllDexsAssetCtxsData {
514    pub ctxs: Vec<(String, Vec<PerpsAssetCtx>)>,
515}
516
517/// Notification data.
518#[derive(Debug, Clone, Deserialize)]
519pub struct NotificationData {
520    pub notification: String,
521}
522
523/// Candlestick data.
524#[derive(Debug, Clone, Deserialize)]
525pub struct CandleData {
526    /// Open time (millis).
527    pub t: u64,
528    /// Close time (millis).
529    #[serde(rename = "T")]
530    pub close_time: u64,
531    /// Symbol.
532    pub s: Ustr,
533    /// Interval.
534    pub i: Ustr,
535    /// Open price.
536    #[serde(deserialize_with = "deserialize_decimal_from_str")]
537    pub o: Decimal,
538    /// Close price.
539    #[serde(deserialize_with = "deserialize_decimal_from_str")]
540    pub c: Decimal,
541    /// High price.
542    #[serde(deserialize_with = "deserialize_decimal_from_str")]
543    pub h: Decimal,
544    /// Low price.
545    #[serde(deserialize_with = "deserialize_decimal_from_str")]
546    pub l: Decimal,
547    /// Volume.
548    #[serde(deserialize_with = "deserialize_decimal_from_str")]
549    pub v: Decimal,
550    /// Number of trades.
551    pub n: u32,
552}
553
554/// WebSocket book data.
555#[derive(Debug, Clone, Serialize, Deserialize)]
556pub struct WsBookData {
557    pub coin: Ustr,
558    pub levels: [Vec<WsLevelData>; 2], // [bids, asks]
559    pub time: u64,
560}
561
562/// WebSocket level data.
563#[derive(Debug, Clone, Serialize, Deserialize)]
564pub struct WsLevelData {
565    /// Price.
566    #[serde(
567        deserialize_with = "deserialize_decimal_from_str",
568        serialize_with = "serialize_decimal_as_str"
569    )]
570    pub px: Decimal,
571    /// Size.
572    #[serde(
573        deserialize_with = "deserialize_decimal_from_str",
574        serialize_with = "serialize_decimal_as_str"
575    )]
576    pub sz: Decimal,
577    /// Number of orders.
578    pub n: u32,
579}
580
581/// WebSocket trade data.
582#[derive(Debug, Clone, Serialize, Deserialize)]
583pub struct WsTradeData {
584    pub coin: Ustr,
585    pub side: HyperliquidSide,
586    #[serde(
587        deserialize_with = "deserialize_decimal_from_str",
588        serialize_with = "serialize_decimal_as_str"
589    )]
590    pub px: Decimal,
591    #[serde(
592        deserialize_with = "deserialize_decimal_from_str",
593        serialize_with = "serialize_decimal_as_str"
594    )]
595    pub sz: Decimal,
596    pub hash: String,
597    pub time: u64,
598    pub tid: u64,
599    pub users: [String; 2], // [buyer, seller]
600}
601
602/// WebSocket order data.
603#[derive(Debug, Clone, Deserialize)]
604pub struct WsOrderData {
605    pub order: WsBasicOrderData,
606    pub status: HyperliquidOrderStatusEnum,
607    #[serde(rename = "statusTimestamp")]
608    pub status_timestamp: u64,
609}
610
611/// Basic order data.
612#[derive(Debug, Clone, Deserialize)]
613pub struct WsBasicOrderData {
614    pub coin: Ustr,
615    pub side: HyperliquidSide,
616    #[serde(rename = "limitPx", deserialize_with = "deserialize_decimal_from_str")]
617    pub limit_px: Decimal,
618    #[serde(deserialize_with = "deserialize_decimal_from_str")]
619    pub sz: Decimal,
620    pub oid: u64,
621    pub timestamp: u64,
622    #[serde(rename = "origSz", deserialize_with = "deserialize_decimal_from_str")]
623    pub orig_sz: Decimal,
624    pub cloid: Option<String>,
625    pub tif: Option<HyperliquidTimeInForce>,
626    #[serde(rename = "reduceOnly")]
627    pub reduce_only: Option<bool>,
628    /// Trigger price for conditional orders (stop/take-profit).
629    #[serde(
630        rename = "triggerPx",
631        default,
632        deserialize_with = "deserialize_optional_decimal_from_str"
633    )]
634    pub trigger_px: Option<Decimal>,
635    /// Whether this is a market or limit trigger order.
636    #[serde(rename = "isMarket")]
637    pub is_market: Option<bool>,
638    /// Take-profit or stop-loss indicator.
639    pub tpsl: Option<HyperliquidTpSl>,
640    /// Whether the trigger has been activated.
641    #[serde(rename = "triggerActivated")]
642    pub trigger_activated: Option<bool>,
643    /// Trailing stop parameters if applicable.
644    #[serde(rename = "trailingStop")]
645    pub trailing_stop: Option<WsTrailingStopData>,
646    /// Venue order type label (for example `"Stop Market"`), present on REST order rows
647    /// such as `frontendOpenOrders`, which omit `tpsl` and `isMarket`.
648    #[serde(rename = "orderType", default)]
649    pub order_type: Option<String>,
650}
651
652/// Trailing stop offset type.
653#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
654#[serde(rename_all = "camelCase")]
655pub enum TrailingOffsetType {
656    /// Price offset.
657    Price,
658    /// Percentage offset.
659    Percentage,
660    /// Basis points offset.
661    BasisPoints,
662}
663
664impl TrailingOffsetType {
665    /// Format the offset value with the appropriate unit.
666    pub fn format_offset(&self, offset: &str) -> String {
667        match self {
668            Self::Price => offset.to_string(),
669            Self::Percentage => format!("{offset}%"),
670            Self::BasisPoints => format!("{offset} bps"),
671        }
672    }
673}
674
675/// Trailing stop data from WebSocket.
676#[derive(Debug, Clone, Deserialize)]
677pub struct WsTrailingStopData {
678    /// Trailing offset value.
679    #[serde(deserialize_with = "deserialize_decimal_from_str")]
680    pub offset: Decimal,
681    /// Offset type.
682    #[serde(rename = "offsetType")]
683    pub offset_type: TrailingOffsetType,
684    /// Current callback price (highest/lowest price reached).
685    #[serde(
686        rename = "callbackPrice",
687        default,
688        deserialize_with = "deserialize_optional_decimal_from_str"
689    )]
690    pub callback_price: Option<Decimal>,
691}
692
693/// WebSocket user event data.
694#[derive(Debug, Clone, Deserialize)]
695#[serde(untagged)]
696pub enum WsUserEventData {
697    Fills {
698        fills: Vec<WsFillData>,
699    },
700    Funding {
701        funding: WsUserFundingData,
702    },
703    Liquidation {
704        liquidation: WsLiquidationData,
705    },
706    NonUserCancel {
707        #[serde(rename = "nonUserCancel")]
708        non_user_cancel: Vec<WsNonUserCancelData>,
709    },
710    /// Trigger order activated (moved from pending to active).
711    TriggerActivated {
712        #[serde(rename = "triggerActivated")]
713        trigger_activated: WsTriggerActivatedData,
714    },
715    /// Trigger order executed (trigger price reached, order placed).
716    TriggerTriggered {
717        #[serde(rename = "triggerTriggered")]
718        trigger_triggered: WsTriggerTriggeredData,
719    },
720}
721
722/// WebSocket fill data.
723#[derive(Debug, Clone, Deserialize)]
724pub struct WsFillData {
725    pub coin: Ustr,
726    #[serde(deserialize_with = "deserialize_decimal_from_str")]
727    pub px: Decimal,
728    #[serde(deserialize_with = "deserialize_decimal_from_str")]
729    pub sz: Decimal,
730    pub side: HyperliquidSide,
731    pub time: u64,
732    #[serde(
733        rename = "startPosition",
734        deserialize_with = "deserialize_decimal_from_str"
735    )]
736    pub start_position: Decimal,
737    pub dir: HyperliquidFillDirection,
738    #[serde(
739        rename = "closedPnl",
740        deserialize_with = "deserialize_decimal_from_str"
741    )]
742    pub closed_pnl: Decimal,
743    pub hash: String,
744    pub oid: u64,
745    pub crossed: bool,
746    #[serde(deserialize_with = "deserialize_decimal_from_str")]
747    pub fee: Decimal,
748    pub tid: u64,
749    #[serde(default)]
750    pub liquidation: Option<FillLiquidationData>,
751    #[serde(rename = "feeToken")]
752    pub fee_token: Ustr,
753    #[serde(
754        rename = "builderFee",
755        default,
756        deserialize_with = "deserialize_optional_decimal_from_str"
757    )]
758    pub builder_fee: Option<Decimal>,
759    /// Client order ID (hex string with 0x prefix).
760    pub cloid: Option<String>,
761    /// TWAP order ID if this fill is part of a TWAP order.
762    #[serde(rename = "twapId")]
763    pub twap_id: Option<serde_json::Value>,
764}
765
766/// Fill liquidation data.
767#[derive(Debug, Clone, Deserialize)]
768pub struct FillLiquidationData {
769    #[serde(rename = "liquidatedUser")]
770    pub liquidated_user: Option<String>,
771    #[serde(rename = "markPx", deserialize_with = "deserialize_decimal_from_str")]
772    pub mark_px: Decimal,
773    pub method: HyperliquidLiquidationMethod,
774}
775
776/// WebSocket user funding data.
777#[derive(Debug, Clone, Deserialize)]
778pub struct WsUserFundingData {
779    pub time: u64,
780    pub coin: Ustr,
781    #[serde(deserialize_with = "deserialize_decimal_from_str")]
782    pub usdc: Decimal,
783    #[serde(deserialize_with = "deserialize_decimal_from_str")]
784    pub szi: Decimal,
785    #[serde(
786        rename = "fundingRate",
787        deserialize_with = "deserialize_decimal_from_str"
788    )]
789    pub funding_rate: Decimal,
790}
791
792/// WebSocket liquidation data.
793#[derive(Debug, Clone, Deserialize)]
794pub struct WsLiquidationData {
795    pub lid: u64,
796    pub liquidator: String,
797    pub liquidated_user: String,
798    #[serde(deserialize_with = "deserialize_decimal_from_str")]
799    pub liquidated_ntl_pos: Decimal,
800    #[serde(deserialize_with = "deserialize_decimal_from_str")]
801    pub liquidated_account_value: Decimal,
802}
803
804/// WebSocket non-user cancel data.
805#[derive(Debug, Clone, Deserialize)]
806pub struct WsNonUserCancelData {
807    pub coin: Ustr,
808    pub oid: u64,
809}
810
811/// Trigger order activated event data.
812#[derive(Debug, Clone, Deserialize)]
813pub struct WsTriggerActivatedData {
814    pub coin: Ustr,
815    pub oid: u64,
816    pub time: u64,
817    #[serde(
818        rename = "triggerPx",
819        deserialize_with = "deserialize_decimal_from_str"
820    )]
821    pub trigger_px: Decimal,
822    pub tpsl: HyperliquidTpSl,
823}
824
825/// Trigger order triggered event data.
826#[derive(Debug, Clone, Deserialize)]
827pub struct WsTriggerTriggeredData {
828    pub coin: Ustr,
829    pub oid: u64,
830    pub time: u64,
831    #[serde(
832        rename = "triggerPx",
833        deserialize_with = "deserialize_decimal_from_str"
834    )]
835    pub trigger_px: Decimal,
836    #[serde(rename = "marketPx", deserialize_with = "deserialize_decimal_from_str")]
837    pub market_px: Decimal,
838    pub tpsl: HyperliquidTpSl,
839    /// Order ID of the resulting market/limit order after trigger.
840    #[serde(rename = "resultingOid")]
841    pub resulting_oid: Option<u64>,
842}
843
844/// WebSocket user fills data.
845#[derive(Debug, Clone, Deserialize)]
846pub struct WsUserFillsData {
847    #[serde(rename = "isSnapshot")]
848    pub is_snapshot: Option<bool>,
849    pub user: String,
850    pub fills: Vec<WsFillData>,
851}
852
853/// WebSocket user fundings data.
854#[derive(Debug, Clone, Deserialize)]
855pub struct WsUserFundingsData {
856    #[serde(rename = "isSnapshot")]
857    pub is_snapshot: Option<bool>,
858    pub user: String,
859    pub fundings: Vec<WsUserFundingData>,
860}
861
862/// WebSocket active asset context data.
863#[derive(Debug, Clone, Deserialize)]
864#[serde(untagged)]
865pub enum WsActiveAssetCtxData {
866    Perp { coin: Ustr, ctx: PerpsAssetCtx },
867    Spot { coin: Ustr, ctx: SpotAssetCtx },
868}
869
870/// Shared asset context fields.
871#[derive(Debug, Clone, Deserialize)]
872pub struct SharedAssetCtx {
873    #[serde(
874        rename = "dayNtlVlm",
875        deserialize_with = "deserialize_decimal_from_str"
876    )]
877    pub day_ntl_vlm: Decimal,
878    #[serde(
879        rename = "prevDayPx",
880        deserialize_with = "deserialize_decimal_from_str"
881    )]
882    pub prev_day_px: Decimal,
883    #[serde(rename = "markPx", deserialize_with = "deserialize_decimal_from_str")]
884    pub mark_px: Decimal,
885    #[serde(
886        rename = "midPx",
887        default,
888        deserialize_with = "deserialize_optional_decimal_from_str"
889    )]
890    pub mid_px: Option<Decimal>,
891    #[serde(rename = "impactPxs")]
892    pub impact_pxs: Option<Vec<Decimal>>,
893    #[serde(
894        rename = "dayBaseVlm",
895        default,
896        deserialize_with = "deserialize_optional_decimal_from_str"
897    )]
898    pub day_base_vlm: Option<Decimal>,
899}
900
901/// Perps asset context.
902#[derive(Debug, Clone, Deserialize)]
903pub struct PerpsAssetCtx {
904    #[serde(flatten)]
905    pub shared: SharedAssetCtx,
906    #[serde(deserialize_with = "deserialize_decimal_from_str")]
907    pub funding: Decimal,
908    #[serde(
909        rename = "openInterest",
910        deserialize_with = "deserialize_decimal_from_str"
911    )]
912    pub open_interest: Decimal,
913    #[serde(rename = "oraclePx", deserialize_with = "deserialize_decimal_from_str")]
914    pub oracle_px: Decimal,
915    #[serde(default, deserialize_with = "deserialize_optional_decimal_from_str")]
916    pub premium: Option<Decimal>,
917}
918
919/// Spot asset context.
920#[derive(Debug, Clone, Deserialize)]
921pub struct SpotAssetCtx {
922    #[serde(flatten)]
923    pub shared: SharedAssetCtx,
924    #[serde(
925        rename = "circulatingSupply",
926        deserialize_with = "deserialize_decimal_from_str"
927    )]
928    pub circulating_supply: Decimal,
929}
930
931/// WebSocket active asset data.
932#[derive(Debug, Clone, Deserialize)]
933pub struct WsActiveAssetData {
934    pub user: String,
935    pub coin: Ustr,
936    pub leverage: LeverageInfo,
937    #[serde(rename = "maxTradeSzs", deserialize_with = "deserialize_trade_limits")]
938    pub max_trade_szs: [Decimal; 2],
939    #[serde(
940        rename = "availableToTrade",
941        deserialize_with = "deserialize_trade_limits"
942    )]
943    pub available_to_trade: [Decimal; 2],
944}
945
946fn deserialize_trade_limits<'de, D: Deserializer<'de>>(
947    deserializer: D,
948) -> Result<[Decimal; 2], D::Error> {
949    <[DecimalToken; 2]>::deserialize(deserializer).map(|values| values.map(|value| value.0))
950}
951
952#[derive(Deserialize)]
953struct DecimalToken(#[serde(deserialize_with = "decimal::deserialize_json")] Decimal);
954
955/// WebSocket TWAP slice fills data.
956#[derive(Debug, Clone, Deserialize)]
957pub struct WsUserTwapSliceFillsData {
958    #[serde(rename = "isSnapshot")]
959    pub is_snapshot: Option<bool>,
960    pub user: String,
961    #[serde(rename = "twapSliceFills")]
962    pub twap_slice_fills: Vec<WsTwapSliceFillData>,
963}
964
965/// TWAP slice fill data.
966#[derive(Debug, Clone, Deserialize)]
967pub struct WsTwapSliceFillData {
968    pub fill: WsFillData,
969    #[serde(rename = "twapId")]
970    pub twap_id: u64,
971}
972
973/// WebSocket TWAP history data.
974#[derive(Debug, Clone, Deserialize)]
975pub struct WsUserTwapHistoryData {
976    #[serde(rename = "isSnapshot")]
977    pub is_snapshot: Option<bool>,
978    pub user: String,
979    pub history: Vec<WsTwapHistoryData>,
980}
981
982/// TWAP history data.
983#[derive(Debug, Clone, Deserialize)]
984pub struct WsTwapHistoryData {
985    pub state: TwapStateData,
986    pub status: TwapStatusData,
987    pub time: u64,
988    #[serde(default, rename = "twapId")]
989    pub twap_id: Option<u64>,
990}
991
992/// TWAP state data.
993#[derive(Debug, Clone, Deserialize)]
994pub struct TwapStateData {
995    pub coin: Ustr,
996    pub user: String,
997    pub side: HyperliquidSide,
998    /// Venue may send a JSON string or number.
999    #[serde(deserialize_with = "deserialize_decimal")]
1000    pub sz: Decimal,
1001    #[serde(rename = "executedSz", deserialize_with = "deserialize_decimal")]
1002    pub executed_sz: Decimal,
1003    #[serde(rename = "executedNtl", deserialize_with = "deserialize_decimal")]
1004    pub executed_ntl: Decimal,
1005    pub minutes: u32,
1006    #[serde(rename = "reduceOnly")]
1007    pub reduce_only: bool,
1008    pub randomize: bool,
1009    pub timestamp: u64,
1010}
1011
1012/// TWAP status data.
1013#[derive(Debug, Clone, Deserialize)]
1014pub struct TwapStatusData {
1015    pub status: HyperliquidTwapStatus,
1016    /// Present when `status` is `error`; otherwise often omitted.
1017    #[serde(default)]
1018    pub description: String,
1019}
1020
1021/// WebSocket BBO data.
1022#[derive(Debug, Clone, Deserialize)]
1023pub struct WsBboData {
1024    pub coin: Ustr,
1025    pub time: u64,
1026    pub bbo: [Option<WsLevelData>; 2], // [bid, ask]
1027}
1028
1029#[cfg(test)]
1030mod tests {
1031    use rstest::rstest;
1032    use rust_decimal_macros::dec;
1033    use serde_json;
1034
1035    use super::*;
1036    use crate::common::enums::HyperliquidLeverageType;
1037
1038    #[rstest]
1039    fn test_clearinghouse_state_accepts_zero_balances() {
1040        let mut frame: serde_json::Value =
1041            serde_json::from_str(include_str!("../../test_data/ws_account_states.json")).unwrap();
1042        let state = &mut frame["perp"]["data"]["clearinghouseState"];
1043        state["withdrawable"] = serde_json::json!("0");
1044        for field in [
1045            "accountValue",
1046            "totalNtlPos",
1047            "totalRawUsd",
1048            "totalMarginUsed",
1049        ] {
1050            state["crossMarginSummary"][field] = serde_json::json!("0");
1051        }
1052
1053        let message = decode_ws_message(&frame["perp"].to_string()).unwrap();
1054
1055        let HyperliquidWsMessage::ClearinghouseState { data } = message else {
1056            panic!("expected clearinghouse state");
1057        };
1058
1059        let summary = data.clearinghouse_state.cross_margin_summary.unwrap();
1060
1061        assert_eq!(data.clearinghouse_state.withdrawable, Some(Decimal::ZERO));
1062        assert_eq!(summary.account_value, Decimal::ZERO);
1063        assert_eq!(summary.total_ntl_pos, Decimal::ZERO);
1064        assert_eq!(summary.total_raw_usd, Decimal::ZERO);
1065        assert_eq!(summary.total_margin_used, Decimal::ZERO);
1066    }
1067
1068    #[rstest]
1069    fn test_cancel_action_serialization(
1070        #[values(None, Some(false), Some(true))] fast: Option<bool>,
1071        #[values(false, true)] by_cloid: bool,
1072    ) {
1073        let (action, name) = if by_cloid {
1074            (
1075                ActionRequest::CancelByCloid {
1076                    cancels: vec![CancelByCloidRequest {
1077                        asset: 7,
1078                        cloid: "0x0123456789abcdef0123456789abcdef".to_string(),
1079                    }],
1080                    fast,
1081                },
1082                "ws_cancel_by_cloid",
1083            )
1084        } else {
1085            (
1086                ActionRequest::Cancel {
1087                    cancels: vec![CancelRequest { a: 7, o: 12345 }],
1088                    fast,
1089                },
1090                "cancel",
1091            )
1092        };
1093
1094        let fixtures: serde_json::Value =
1095            serde_json::from_str(include_str!("../../test_data/cancel_actions.json")).unwrap();
1096        let expected = &fixtures[name][if fast == Some(true) { "fast" } else { "normal" }];
1097        let json = serde_json::to_value(&action).unwrap();
1098        let msgpack = rmp_serde::to_vec_named(&action).unwrap();
1099
1100        assert_eq!(json, expected["json"]);
1101        assert_eq!(
1102            nautilus_core::hex::encode(msgpack),
1103            expected["msgpack"].as_str().unwrap()
1104        );
1105    }
1106
1107    #[rstest]
1108    #[case("cross", HyperliquidLeverageType::Cross)]
1109    #[case("isolated", HyperliquidLeverageType::Isolated)]
1110    fn test_ws_active_asset_data_preserves_decimals(
1111        #[case] leverage_type: &str,
1112        #[case] expected_type: HyperliquidLeverageType,
1113        #[values("number", "string", "scientific")] encoding: &str,
1114        #[values(false, true)] serde_entry: bool,
1115        #[values(false, true)] channel_last: bool,
1116    ) {
1117        let max_trade_szs = [
1118            dec!(9007199254740993.01),
1119            dec!(0.0000000000000000000000000001),
1120        ];
1121        let available_to_trade = [
1122            dec!(0.1234567890123456789012345678),
1123            dec!(1234567890.1234567890123456789),
1124        ];
1125        let mut json = include_str!("../../test_data/ws_active_asset_data_decimal.json")
1126            .replace("\"cross\"", &format!("\"{leverage_type}\""));
1127
1128        if encoding != "number" {
1129            for value in max_trade_szs.into_iter().chain(available_to_trade) {
1130                let text = value.to_string();
1131
1132                let encoded = match encoding {
1133                    "string" => format!("\"{text}\""),
1134                    "scientific" => format!("{text}e0"),
1135                    _ => unreachable!(),
1136                };
1137
1138                json = json.replace(&text, &encoded);
1139            }
1140        }
1141
1142        if channel_last {
1143            json = json
1144                .replace("  \"channel\": \"activeAssetData\",\n", "")
1145                .trim_end()
1146                .strip_suffix('}')
1147                .unwrap()
1148                .to_string()
1149                + ",\"channel\":\"activeAssetData\"}";
1150        }
1151
1152        let msg = if serde_entry {
1153            serde_json::from_str::<HyperliquidWsMessage>(&json).unwrap()
1154        } else {
1155            decode_ws_message(&json).unwrap()
1156        };
1157
1158        let HyperliquidWsMessage::ActiveAssetData { data } = msg else {
1159            panic!("Expected ActiveAssetData message");
1160        };
1161
1162        assert_eq!(data.user, "0x0000000000000000000000000000000000000001");
1163        assert_eq!(data.coin, "BTC");
1164        assert_eq!(data.leverage.leverage_type, expected_type);
1165        assert_eq!(data.leverage.value, 7);
1166        assert_eq!(data.max_trade_szs, max_trade_szs);
1167        assert_eq!(data.available_to_trade, available_to_trade);
1168    }
1169
1170    #[rstest]
1171    #[case(
1172        "[1]",
1173        serde_json::error::Category::Data,
1174        "invalid length 1, expected an array of length 2"
1175    )]
1176    #[case(
1177        "[1, 2, 3]",
1178        serde_json::error::Category::Syntax,
1179        "trailing characters"
1180    )]
1181    #[case(
1182        "[null, 2]",
1183        serde_json::error::Category::Data,
1184        "invalid decimal significand"
1185    )]
1186    #[case(
1187        "[\"not-a-number\", 2]",
1188        serde_json::error::Category::Data,
1189        "invalid decimal exponent"
1190    )]
1191    #[case(
1192        "[\"\", 2]",
1193        serde_json::error::Category::Data,
1194        "invalid decimal significand"
1195    )]
1196    #[case(
1197        "[true, 2]",
1198        serde_json::error::Category::Data,
1199        "invalid decimal exponent"
1200    )]
1201    #[case(
1202        "[{}, 2]",
1203        serde_json::error::Category::Data,
1204        "invalid decimal significand"
1205    )]
1206    #[case(
1207        "[0.00000000000000000000000000001, 2]",
1208        serde_json::error::Category::Data,
1209        "Number has a high precision that can not be represented."
1210    )]
1211    fn test_ws_active_asset_data_rejects_invalid_trade_limits(
1212        #[values("maxTradeSzs", "availableToTrade")] field: &str,
1213        #[case] values: &str,
1214        #[case] category: serde_json::error::Category,
1215        #[case] expected: &str,
1216    ) {
1217        let mut json =
1218            include_str!("../../test_data/ws_active_asset_data_decimal.json").to_string();
1219        let key = format!("\"{field}\": ");
1220        let start = json.find(&key).unwrap() + key.len();
1221        let end = start + json[start..].find(']').unwrap() + 1;
1222        json.replace_range(start..end, values);
1223        let error = decode_ws_message(&json).unwrap_err();
1224
1225        assert_eq!(error.classify(), category);
1226        assert_eq!(
1227            error.to_string().split(" at line ").next().unwrap(),
1228            expected
1229        );
1230    }
1231
1232    #[rstest]
1233    #[case(r#"{"channel":"pong"}"#)]
1234    #[case(r#"{"channel":"p\u006fng"}"#)]
1235    fn test_decode_ws_message_pong(#[case] json: &str) {
1236        let message = decode_ws_message(json).unwrap();
1237
1238        assert!(matches!(message, HyperliquidWsMessage::Pong));
1239    }
1240
1241    #[rstest]
1242    #[case("{}", "missing field `channel`")]
1243    #[case(r#"{"channel":"activeAssetData"}"#, "missing field `data`")]
1244    #[case(
1245        r#"{"channel":"pong","channel":"activeAssetData"}"#,
1246        "duplicate field `channel`"
1247    )]
1248    fn test_decode_ws_message_rejects_invalid_envelope(#[case] json: &str, #[case] expected: &str) {
1249        let error = decode_ws_message(json).unwrap_err();
1250
1251        assert_eq!(error.classify(), serde_json::error::Category::Data);
1252        assert_eq!(
1253            error.to_string().split(" at line ").next().unwrap(),
1254            expected
1255        );
1256    }
1257
1258    #[rstest]
1259    fn test_ws_active_asset_ctx_preserves_decimals() {
1260        let json = include_str!("../../test_data/ws_active_asset_ctx_decimal.json");
1261        let msg: HyperliquidWsMessage = serde_json::from_str(json).unwrap();
1262
1263        let HyperliquidWsMessage::ActiveAssetCtx {
1264            data: WsActiveAssetCtxData::Perp { coin, ctx },
1265        } = msg
1266        else {
1267            panic!("Expected perpetual ActiveAssetCtx message");
1268        };
1269
1270        assert_eq!(coin, "BTC");
1271        assert_eq!(ctx.shared.day_ntl_vlm, dec!(1234567890.1234567890123456789));
1272        assert_eq!(ctx.shared.prev_day_px, dec!(49000.12345678901234567890123));
1273        assert_eq!(ctx.shared.mark_px, dec!(50000.12345678901234567890123));
1274        assert_eq!(ctx.shared.mid_px, Some(dec!(50001.12345678901234567890123)));
1275        assert_eq!(
1276            ctx.shared.impact_pxs,
1277            Some(vec![
1278                dec!(50002.12345678901234567890123),
1279                dec!(50003.12345678901234567890123),
1280            ])
1281        );
1282        assert_eq!(
1283            ctx.shared.day_base_vlm,
1284            Some(dec!(12345.12345678901234567890123))
1285        );
1286        assert_eq!(ctx.funding, dec!(-0.0000000000000000000000000001));
1287        assert_eq!(ctx.open_interest, dec!(9007199254740993.01));
1288        assert_eq!(ctx.oracle_px, dec!(50004.12345678901234567890123));
1289        assert_eq!(ctx.premium, Some(dec!(0.0000000000000000000000000002)));
1290    }
1291
1292    #[rstest]
1293    #[case(true)]
1294    #[case(false)]
1295    fn test_ws_active_asset_ctx_optional_decimals(#[case] explicit_null: bool) {
1296        let mut json: serde_json::Value = serde_json::from_str(include_str!(
1297            "../../test_data/ws_active_asset_ctx_decimal.json"
1298        ))
1299        .unwrap();
1300        let ctx = json["data"]["ctx"].as_object_mut().unwrap();
1301
1302        for field in ["midPx", "impactPxs", "dayBaseVlm", "premium"] {
1303            if explicit_null {
1304                ctx.insert(field.to_string(), serde_json::Value::Null);
1305            } else {
1306                ctx.remove(field);
1307            }
1308        }
1309
1310        let msg: HyperliquidWsMessage = serde_json::from_value(json).unwrap();
1311
1312        let HyperliquidWsMessage::ActiveAssetCtx {
1313            data: WsActiveAssetCtxData::Perp { ctx, .. },
1314        } = msg
1315        else {
1316            panic!("Expected perpetual ActiveAssetCtx message");
1317        };
1318
1319        assert_eq!(ctx.shared.mid_px, None);
1320        assert_eq!(ctx.shared.impact_pxs, None);
1321        assert_eq!(ctx.shared.day_base_vlm, None);
1322        assert_eq!(ctx.premium, None);
1323    }
1324
1325    #[rstest]
1326    fn test_ws_active_spot_asset_ctx_preserves_decimals() {
1327        let json = include_str!("../../test_data/ws_active_spot_asset_ctx_decimal.json");
1328        let msg: HyperliquidWsMessage = serde_json::from_str(json).unwrap();
1329
1330        let HyperliquidWsMessage::ActiveSpotAssetCtx {
1331            data: WsActiveAssetCtxData::Spot { coin, ctx },
1332        } = msg
1333        else {
1334            panic!("Expected spot ActiveAssetCtx message");
1335        };
1336
1337        assert_eq!(coin, "@107");
1338        assert_eq!(ctx.shared.day_ntl_vlm, dec!(1234567890.1234567890123456789));
1339        assert_eq!(ctx.shared.prev_day_px, dec!(31.12345678901234567890123456));
1340        assert_eq!(ctx.shared.mark_px, dec!(32.12345678901234567890123456));
1341        assert_eq!(ctx.shared.mid_px, None);
1342        assert_eq!(ctx.shared.impact_pxs, None);
1343        assert_eq!(ctx.shared.day_base_vlm, None);
1344        assert_eq!(ctx.circulating_supply, dec!(9007199254740993.01));
1345    }
1346
1347    #[rstest]
1348    fn test_signature_data_serialization_and_debug_redaction() {
1349        let signature = SignatureData {
1350            r: SecretString::from("0xsignature-r"),
1351            s: SecretString::from("0xsignature-s"),
1352            v: SecretString::from("0x1b"),
1353        };
1354        let wire = serde_json::to_value(&signature).unwrap();
1355        let debug = format!("{signature:?}");
1356
1357        assert_eq!(wire["r"], "0xsignature-r");
1358        assert_eq!(wire["s"], "0xsignature-s");
1359        assert_eq!(wire["v"], "0x1b");
1360        assert_eq!(debug.matches(REDACTED).count(), 3);
1361        assert!(!debug.contains("0xsignature-r"));
1362        assert!(!debug.contains("0xsignature-s"));
1363        assert!(!debug.contains("0x1b"));
1364    }
1365
1366    #[rstest]
1367    fn test_subscription_request_serialization() {
1368        let sub = SubscriptionRequest::L2Book {
1369            coin: Ustr::from("BTC"),
1370            n_sig_figs: Some(5),
1371            mantissa: None,
1372        };
1373
1374        let json = serde_json::to_string(&sub).unwrap();
1375        assert!(json.contains(r#""type":"l2Book""#));
1376        assert!(json.contains(r#""coin":"BTC""#));
1377    }
1378
1379    #[rstest]
1380    fn test_hyperliquid_ws_request_serialization() {
1381        let req = HyperliquidWsRequest::Subscribe {
1382            subscription: SubscriptionRequest::Trades {
1383                coin: Ustr::from("ETH"),
1384            },
1385        };
1386
1387        let json = serde_json::to_string(&req).unwrap();
1388        assert!(json.contains(r#""method":"subscribe""#));
1389        assert!(json.contains(r#""type":"trades""#));
1390    }
1391
1392    #[rstest]
1393    fn test_order_request_serialization() {
1394        let order = OrderRequest {
1395            a: 0,    // BTC asset ID
1396            b: true, // buy
1397            p: "50000.0".to_string(),
1398            s: "0.1".to_string(),
1399            r: false,
1400            t: OrderTypeRequest::Limit {
1401                tif: TimeInForceRequest::Gtc,
1402            },
1403            c: Some("client-123".to_string()),
1404        };
1405
1406        let json = serde_json::to_string(&order).unwrap();
1407        assert!(json.contains(r#""a":0"#));
1408        assert!(json.contains(r#""b":true"#));
1409        assert!(json.contains(r#""p":"50000.0""#));
1410    }
1411
1412    #[rstest]
1413    fn test_ws_trade_data_deserialization() {
1414        let json = r#"{
1415            "coin": "BTC",
1416            "side": "B",
1417            "px": "50000.0",
1418            "sz": "0.1",
1419            "hash": "0x123",
1420            "time": 1234567890,
1421            "tid": 12345,
1422            "users": ["0xabc", "0xdef"]
1423        }"#;
1424
1425        let trade: WsTradeData = serde_json::from_str(json).unwrap();
1426        assert_eq!(trade.coin, "BTC");
1427        assert_eq!(trade.side, HyperliquidSide::Buy);
1428        assert_eq!(trade.px, dec!(50000.0));
1429    }
1430
1431    #[rstest]
1432    fn test_ws_book_data_deserialization() {
1433        let json = r#"{
1434            "coin": "ETH",
1435            "levels": [
1436                [{"px": "3000.0", "sz": "1.0", "n": 1}],
1437                [{"px": "3001.0", "sz": "2.0", "n": 2}]
1438            ],
1439            "time": 1234567890
1440        }"#;
1441
1442        let book: WsBookData = serde_json::from_str(json).unwrap();
1443        assert_eq!(book.coin, "ETH");
1444        assert_eq!(book.levels[0].len(), 1);
1445        assert_eq!(book.levels[1].len(), 1);
1446    }
1447
1448    #[rstest]
1449    fn test_ws_trailing_stop_data_deserialization() {
1450        let json = r#"{
1451            "offset": "100.0",
1452            "offsetType": "price",
1453            "callbackPrice": "50000.0"
1454        }"#;
1455
1456        let data: WsTrailingStopData = serde_json::from_str(json).unwrap();
1457        assert_eq!(data.offset, dec!(100.0));
1458        assert_eq!(data.offset_type, TrailingOffsetType::Price);
1459        assert_eq!(data.callback_price.unwrap(), dec!(50000.0));
1460    }
1461
1462    #[rstest]
1463    fn test_ws_trigger_activated_data_deserialization() {
1464        let json = r#"{
1465            "coin": "BTC",
1466            "oid": 12345,
1467            "time": 1704470400000,
1468            "triggerPx": "50000.0",
1469            "tpsl": "sl"
1470        }"#;
1471
1472        let data: WsTriggerActivatedData = serde_json::from_str(json).unwrap();
1473        assert_eq!(data.coin, Ustr::from("BTC"));
1474        assert_eq!(data.oid, 12345);
1475        assert_eq!(data.trigger_px, dec!(50000.0));
1476        assert_eq!(data.tpsl, HyperliquidTpSl::Sl);
1477        assert_eq!(data.time, 1704470400000);
1478    }
1479
1480    #[rstest]
1481    fn test_ws_trigger_triggered_data_deserialization() {
1482        let json = r#"{
1483            "coin": "ETH",
1484            "oid": 67890,
1485            "time": 1704470500000,
1486            "triggerPx": "3000.0",
1487            "marketPx": "3001.0",
1488            "tpsl": "tp",
1489            "resultingOid": 99999
1490        }"#;
1491
1492        let data: WsTriggerTriggeredData = serde_json::from_str(json).unwrap();
1493        assert_eq!(data.coin, Ustr::from("ETH"));
1494        assert_eq!(data.oid, 67890);
1495        assert_eq!(data.trigger_px, dec!(3000.0));
1496        assert_eq!(data.market_px, dec!(3001.0));
1497        assert_eq!(data.tpsl, HyperliquidTpSl::Tp);
1498        assert_eq!(data.resulting_oid, Some(99999));
1499    }
1500
1501    #[rstest]
1502    fn test_ws_fill_data_deserialization_with_cloid_and_twap() {
1503        let json = r#"{
1504            "coin": "@107",
1505            "px": "31.737",
1506            "sz": "0.31",
1507            "side": "B",
1508            "time": 1769920606068,
1509            "startPosition": "0.0",
1510            "dir": "Buy",
1511            "closedPnl": "0.0",
1512            "hash": "0xc731e7561e5334a0c8ab043472ce7d01d400ff3bb95653726afa92a8dd570e8b",
1513            "oid": 308086083674,
1514            "crossed": true,
1515            "fee": "0.00021699",
1516            "tid": 812806034449156,
1517            "cloid": "0xd211f1c27288259290850338d22132a0",
1518            "feeToken": "HYPE",
1519            "twapId": null
1520        }"#;
1521
1522        let fill: WsFillData = serde_json::from_str(json).unwrap();
1523        assert_eq!(fill.coin, "@107");
1524        assert_eq!(fill.px, dec!(31.737));
1525        assert_eq!(fill.sz, dec!(0.31));
1526        assert_eq!(fill.side, HyperliquidSide::Buy);
1527        assert_eq!(fill.oid, 308086083674);
1528        assert!(fill.crossed);
1529        assert_eq!(fill.fee, dec!(0.00021699));
1530        assert_eq!(fill.fee_token, "HYPE");
1531        assert_eq!(
1532            fill.cloid,
1533            Some("0xd211f1c27288259290850338d22132a0".to_string())
1534        );
1535        assert!(fill.twap_id.is_none() || fill.twap_id == Some(serde_json::Value::Null));
1536    }
1537
1538    #[rstest]
1539    fn test_ws_user_fills_message_deserialization() {
1540        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}]}}"#;
1541
1542        let msg: HyperliquidWsMessage = serde_json::from_str(json).unwrap();
1543
1544        match msg {
1545            HyperliquidWsMessage::User { data } => match data {
1546                WsUserEventData::Fills { fills } => {
1547                    assert_eq!(fills.len(), 1);
1548                    let fill = &fills[0];
1549                    assert_eq!(fill.coin, "@107");
1550                    assert_eq!(fill.px, dec!(31.737));
1551                    assert_eq!(
1552                        fill.cloid,
1553                        Some("0xd211f1c27288259290850338d22132a0".to_string())
1554                    );
1555                }
1556                _ => panic!("Expected Fills variant"),
1557            },
1558            _ => panic!("Expected User channel message"),
1559        }
1560    }
1561
1562    #[rstest]
1563    fn test_ws_user_fills_message_with_builder_fee() {
1564        // Real message from production that was failing
1565        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}]}}"#;
1566
1567        let msg: HyperliquidWsMessage = serde_json::from_str(json).unwrap();
1568
1569        match msg {
1570            HyperliquidWsMessage::User { data } => match data {
1571                WsUserEventData::Fills { fills } => {
1572                    assert_eq!(fills.len(), 1);
1573                    let fill = &fills[0];
1574                    assert_eq!(fill.coin, "BTC");
1575                    assert_eq!(fill.px, dec!(79146.0));
1576                    assert_eq!(fill.side, HyperliquidSide::Sell);
1577                    assert_eq!(fill.builder_fee, Some(dec!(0.007914)));
1578                    assert_eq!(fill.fee_token, "USDC");
1579                }
1580                _ => panic!("Expected Fills variant"),
1581            },
1582            _ => panic!("Expected User channel message"),
1583        }
1584    }
1585
1586    #[rstest]
1587    fn test_ws_user_fills_message_with_liquidation() {
1588        // Real message from production that failed to parse: the liquidation
1589        // block carries `markPx` as a quoted string like every other decimal.
1590        let json = include_str!("../../test_data/ws_user_fill_liquidation.json");
1591
1592        let msg: HyperliquidWsMessage = serde_json::from_str(json).unwrap();
1593
1594        match msg {
1595            HyperliquidWsMessage::User { data } => match data {
1596                WsUserEventData::Fills { fills } => {
1597                    assert_eq!(fills.len(), 1);
1598                    let fill = &fills[0];
1599                    let liquidation = fill.liquidation.as_ref().expect("expected liquidation");
1600                    assert_eq!(fill.coin, "BTC");
1601                    assert_eq!(fill.side, HyperliquidSide::Sell);
1602                    assert_eq!(liquidation.mark_px, dec!(66607.0));
1603                    assert_eq!(liquidation.method, HyperliquidLiquidationMethod::Market);
1604                    assert_eq!(
1605                        liquidation.liquidated_user.as_deref(),
1606                        Some("0x360878d351f05975e25f1807a27895e1e5e004fb"),
1607                    );
1608                }
1609                _ => panic!("Expected Fills variant"),
1610            },
1611            _ => panic!("Expected User channel message"),
1612        }
1613    }
1614
1615    #[rstest]
1616    fn test_ws_trade_data_round_trips_decimals_as_strings() {
1617        // Deserializing into Decimal then serializing must reproduce the
1618        // string wire form (with scale preserved), not emit a JSON number.
1619        let json = r#"{"coin":"BTC","side":"B","px":"66653.0","sz":"0.001","hash":"0xabc","time":1,"tid":2,"users":["0xa","0xb"]}"#;
1620
1621        let trade: WsTradeData = serde_json::from_str(json).unwrap();
1622        assert_eq!(trade.px, dec!(66653.0));
1623        assert_eq!(trade.sz, dec!(0.001));
1624
1625        let value = serde_json::to_value(&trade).unwrap();
1626        assert_eq!(value["px"], serde_json::Value::from("66653.0"));
1627        assert_eq!(value["sz"], serde_json::Value::from("0.001"));
1628    }
1629}
1630
1631/// Nautilus WebSocket message wrapper for routing to execution engine.
1632///
1633/// Wraps parsed messages from the handler.
1634///
1635/// All parsing happens in the handler layer, with parsed Nautilus domain objects.
1636/// passed through to the Python layer.
1637#[derive(Debug, Clone)]
1638pub enum NautilusWsMessage {
1639    /// Execution reports (order status and fills).
1640    ExecutionReports(Vec<ExecutionReport>),
1641    /// Parsed trade ticks.
1642    Trades(Vec<TradeTick>),
1643    /// Parsed quote tick (from BBO).
1644    Quote(QuoteTick),
1645    /// Parsed order book deltas.
1646    Deltas(OrderBookDeltas),
1647    /// Parsed order book depth-10 snapshot.
1648    Depth(Box<OrderBookDepth>),
1649    /// An order book frame that failed to parse, leaving the instrument's book out of sync.
1650    BookInvalid(InstrumentId),
1651    /// Parsed candle/bar.
1652    Candle(Bar),
1653    /// Mark price update.
1654    MarkPrice(MarkPriceUpdate),
1655    /// Index price update.
1656    IndexPrice(IndexPriceUpdate),
1657    /// Funding rate update.
1658    FundingRate(FundingRateUpdate),
1659    /// Custom data (e.g. allMids).
1660    CustomData(Data),
1661    /// Error occurred.
1662    Error(String),
1663    /// WebSocket reconnected.
1664    Reconnected,
1665    /// Default perp dex account state.
1666    ClearinghouseState(ClearinghouseState),
1667    /// Spot balances and holds.
1668    SpotState(SpotClearinghouseState),
1669}
1670
1671/// Execution report wrapper for order status and fill reports.
1672///
1673/// This enum allows both order status updates and fill reports.
1674/// to be sent through the execution engine.
1675#[derive(Debug, Clone)]
1676#[allow(
1677    clippy::large_enum_variant,
1678    reason = "the variant size gap only crosses the threshold when high-precision widens the raw types"
1679)]
1680pub enum ExecutionReport {
1681    /// Order status report.
1682    Order(OrderStatusReport),
1683    /// Fill report.
1684    Fill(FillReport),
1685}