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