nautilus-hyperliquid 0.56.0

Hyperliquid integration adapter for the Nautilus trading engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
// -------------------------------------------------------------------------------------------------
//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
//  https://nautechsystems.io
//
//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
//  You may not use this file except in compliance with the License.
//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
// -------------------------------------------------------------------------------------------------

//! Parsing helpers for Hyperliquid WebSocket payloads.

use std::str::FromStr;

use anyhow::Context;
use nautilus_core::{nanos::UnixNanos, uuid::UUID4};
use nautilus_model::{
    data::{
        Bar, BarType, BookOrder, FundingRateUpdate, IndexPriceUpdate, MarkPriceUpdate,
        OrderBookDelta, OrderBookDeltas, OrderBookDepth10, QuoteTick, TradeTick,
        depth::DEPTH10_LEN,
    },
    enums::{
        AggressorSide, BookAction, LiquiditySide, OrderSide, OrderStatus, OrderType, RecordFlag,
        TimeInForce,
    },
    identifiers::{AccountId, ClientOrderId, TradeId, VenueOrderId},
    instruments::{Instrument, InstrumentAny},
    reports::{FillReport, OrderStatusReport},
    types::{Currency, Money, Price, Quantity},
};
use rust_decimal::{Decimal, prelude::FromPrimitive};

use super::messages::{
    CandleData, WsActiveAssetCtxData, WsBboData, WsBookData, WsFillData, WsOrderData, WsTradeData,
};
use crate::common::{
    enums::HyperliquidFillDirection,
    parse::{
        is_conditional_order_data, make_fill_trade_id, millis_to_nanos, parse_trigger_order_type,
    },
};

fn parse_price(
    price_str: &str,
    instrument: &InstrumentAny,
    field_name: &str,
) -> anyhow::Result<Price> {
    let decimal = Decimal::from_str(price_str)
        .with_context(|| format!("Failed to parse price from '{price_str}' for {field_name}"))?;

    Price::from_decimal_dp(decimal, instrument.price_precision())
        .with_context(|| format!("Failed to create price from '{price_str}' for {field_name}"))
}

fn parse_quantity(
    quantity_str: &str,
    instrument: &InstrumentAny,
    field_name: &str,
) -> anyhow::Result<Quantity> {
    let decimal = Decimal::from_str(quantity_str).with_context(|| {
        format!("Failed to parse quantity from '{quantity_str}' for {field_name}")
    })?;

    Quantity::from_decimal_dp(decimal.abs(), instrument.size_precision()).with_context(|| {
        format!("Failed to create quantity from '{quantity_str}' for {field_name}")
    })
}

/// Parses a WebSocket trade frame into a [`TradeTick`].
pub fn parse_ws_trade_tick(
    trade: &WsTradeData,
    instrument: &InstrumentAny,
    ts_init: UnixNanos,
) -> anyhow::Result<TradeTick> {
    let price = parse_price(&trade.px, instrument, "trade.px")?;
    let size = parse_quantity(&trade.sz, instrument, "trade.sz")?;
    let aggressor = AggressorSide::from(trade.side);
    let trade_id = TradeId::new_checked(trade.tid.to_string())
        .context("invalid trade identifier in Hyperliquid trade message")?;
    let ts_event = millis_to_nanos(trade.time)?;

    TradeTick::new_checked(
        instrument.id(),
        price,
        size,
        aggressor,
        trade_id,
        ts_event,
        ts_init,
    )
    .context("failed to construct TradeTick from Hyperliquid trade message")
}

/// Parses a WebSocket L2 order book message into [`OrderBookDeltas`].
pub fn parse_ws_order_book_deltas(
    book: &WsBookData,
    instrument: &InstrumentAny,
    ts_init: UnixNanos,
) -> anyhow::Result<OrderBookDeltas> {
    let ts_event = millis_to_nanos(book.time)?;
    let mut deltas = Vec::new();

    // Treat every book payload as a snapshot: clear existing depth and rebuild it
    deltas.push(OrderBookDelta::clear(instrument.id(), 0, ts_event, ts_init));

    for level in &book.levels[0] {
        let price = parse_price(&level.px, instrument, "book.bid.px")?;
        let size = parse_quantity(&level.sz, instrument, "book.bid.sz")?;

        if !size.is_positive() {
            continue;
        }

        let order = BookOrder::new(OrderSide::Buy, price, size, 0);

        let delta = OrderBookDelta::new(
            instrument.id(),
            BookAction::Add,
            order,
            RecordFlag::F_LAST as u8,
            0, // sequence
            ts_event,
            ts_init,
        );

        deltas.push(delta);
    }

    for level in &book.levels[1] {
        let price = parse_price(&level.px, instrument, "book.ask.px")?;
        let size = parse_quantity(&level.sz, instrument, "book.ask.sz")?;

        if !size.is_positive() {
            continue;
        }

        let order = BookOrder::new(OrderSide::Sell, price, size, 0);

        let delta = OrderBookDelta::new(
            instrument.id(),
            BookAction::Add,
            order,
            RecordFlag::F_LAST as u8,
            0, // sequence
            ts_event,
            ts_init,
        );

        deltas.push(delta);
    }

    Ok(OrderBookDeltas::new(instrument.id(), deltas))
}

/// Parses a WebSocket L2 order book snapshot into [`OrderBookDepth10`].
///
/// Hyperliquid's `l2Book` subscription emits snapshots of bid/ask levels.
/// Fills any missing levels past the venue-provided depth with zero-size
/// placeholder orders so the fixed-size `[BookOrder; 10]` arrays are
/// always fully populated.
pub fn parse_ws_order_book_depth10(
    book: &WsBookData,
    instrument: &InstrumentAny,
    ts_init: UnixNanos,
) -> anyhow::Result<OrderBookDepth10> {
    let ts_event = millis_to_nanos(book.time)?;
    let price_precision = instrument.price_precision();
    let size_precision = instrument.size_precision();

    let mut bids: [BookOrder; DEPTH10_LEN] = [BookOrder::default(); DEPTH10_LEN];
    let mut asks: [BookOrder; DEPTH10_LEN] = [BookOrder::default(); DEPTH10_LEN];
    let mut bid_counts: [u32; DEPTH10_LEN] = [0; DEPTH10_LEN];
    let mut ask_counts: [u32; DEPTH10_LEN] = [0; DEPTH10_LEN];

    let raw_bids = book.levels.first().map_or(&[][..], |v| v.as_slice());
    let raw_asks = book.levels.get(1).map_or(&[][..], |v| v.as_slice());

    for (i, level) in raw_bids.iter().take(DEPTH10_LEN).enumerate() {
        let price = parse_price(&level.px, instrument, "book.bid.px")?;
        let size = parse_quantity(&level.sz, instrument, "book.bid.sz")?;
        bids[i] = BookOrder::new(OrderSide::Buy, price, size, 0);
        bid_counts[i] = level.n;
    }

    for bid in bids.iter_mut().skip(raw_bids.len().min(DEPTH10_LEN)) {
        *bid = BookOrder::new(
            OrderSide::Buy,
            Price::zero(price_precision),
            Quantity::zero(size_precision),
            0,
        );
    }

    for (i, level) in raw_asks.iter().take(DEPTH10_LEN).enumerate() {
        let price = parse_price(&level.px, instrument, "book.ask.px")?;
        let size = parse_quantity(&level.sz, instrument, "book.ask.sz")?;
        asks[i] = BookOrder::new(OrderSide::Sell, price, size, 0);
        ask_counts[i] = level.n;
    }

    for ask in asks.iter_mut().skip(raw_asks.len().min(DEPTH10_LEN)) {
        *ask = BookOrder::new(
            OrderSide::Sell,
            Price::zero(price_precision),
            Quantity::zero(size_precision),
            0,
        );
    }

    Ok(OrderBookDepth10::new(
        instrument.id(),
        bids,
        asks,
        bid_counts,
        ask_counts,
        RecordFlag::F_SNAPSHOT as u8,
        0,
        ts_event,
        ts_init,
    ))
}

/// Parses a WebSocket BBO (best bid/offer) message into a [`QuoteTick`].
pub fn parse_ws_quote_tick(
    bbo: &WsBboData,
    instrument: &InstrumentAny,
    ts_init: UnixNanos,
) -> anyhow::Result<QuoteTick> {
    let bid_level = bbo.bbo[0]
        .as_ref()
        .context("BBO message missing bid level")?;
    let ask_level = bbo.bbo[1]
        .as_ref()
        .context("BBO message missing ask level")?;

    let bid_price = parse_price(&bid_level.px, instrument, "bbo.bid.px")?;
    let ask_price = parse_price(&ask_level.px, instrument, "bbo.ask.px")?;
    let bid_size = parse_quantity(&bid_level.sz, instrument, "bbo.bid.sz")?;
    let ask_size = parse_quantity(&ask_level.sz, instrument, "bbo.ask.sz")?;

    let ts_event = millis_to_nanos(bbo.time)?;

    QuoteTick::new_checked(
        instrument.id(),
        bid_price,
        ask_price,
        bid_size,
        ask_size,
        ts_event,
        ts_init,
    )
    .context("failed to construct QuoteTick from Hyperliquid BBO message")
}

/// Parses a WebSocket candle message into a [`Bar`].
pub fn parse_ws_candle(
    candle: &CandleData,
    instrument: &InstrumentAny,
    bar_type: &BarType,
    ts_init: UnixNanos,
) -> anyhow::Result<Bar> {
    let open = parse_price(&candle.o, instrument, "candle.o")?;
    let high = parse_price(&candle.h, instrument, "candle.h")?;
    let low = parse_price(&candle.l, instrument, "candle.l")?;
    let close = parse_price(&candle.c, instrument, "candle.c")?;
    let volume = parse_quantity(&candle.v, instrument, "candle.v")?;

    let ts_event = millis_to_nanos(candle.t)?;

    Ok(Bar::new(
        *bar_type, open, high, low, close, volume, ts_event, ts_init,
    ))
}

/// Parses a WebSocket order update message into an [`OrderStatusReport`].
///
/// This converts Hyperliquid order data from WebSocket into Nautilus order status reports.
/// Handles both regular and conditional orders (stop/limit-if-touched).
pub fn parse_ws_order_status_report(
    order: &WsOrderData,
    instrument: &InstrumentAny,
    account_id: AccountId,
    ts_init: UnixNanos,
) -> anyhow::Result<OrderStatusReport> {
    let instrument_id = instrument.id();
    let venue_order_id = VenueOrderId::new(order.order.oid.to_string());
    let order_side = OrderSide::from(order.order.side);

    // Determine order type based on trigger info
    let order_type = if is_conditional_order_data(
        order.order.trigger_px.as_deref(),
        order.order.tpsl.as_ref(),
    ) {
        if let (Some(is_market), Some(tpsl)) = (order.order.is_market, order.order.tpsl.as_ref()) {
            parse_trigger_order_type(is_market, tpsl)
        } else {
            OrderType::Limit // fallback
        }
    } else {
        OrderType::Limit // Regular limit order
    };

    let time_in_force = TimeInForce::Gtc;
    let order_status = OrderStatus::from(order.status);

    // orig_sz is the original order quantity, sz is the remaining quantity
    let orig_qty = parse_quantity(&order.order.orig_sz, instrument, "order.orig_sz")?;
    let remaining_qty = parse_quantity(&order.order.sz, instrument, "order.sz")?;
    let filled_qty = Quantity::from_raw(
        orig_qty.raw.saturating_sub(remaining_qty.raw),
        instrument.size_precision(),
    );

    let price = parse_price(&order.order.limit_px, instrument, "order.limitPx")?;

    let ts_accepted = millis_to_nanos(order.order.timestamp)?;
    let ts_last = millis_to_nanos(order.status_timestamp)?;

    let mut report = OrderStatusReport::new(
        account_id,
        instrument_id,
        None, // venue_order_id_modified
        venue_order_id,
        order_side,
        order_type,
        time_in_force,
        order_status,
        orig_qty, // Use original quantity, not remaining
        filled_qty,
        ts_accepted,
        ts_last,
        ts_init,
        Some(UUID4::new()),
    );

    if let Some(ref cloid) = order.order.cloid {
        report = report.with_client_order_id(ClientOrderId::new(cloid.as_str()));
    }

    report = report.with_price(price);

    if let Some(ref trigger_px_str) = order.order.trigger_px {
        let trigger_price = parse_price(trigger_px_str, instrument, "order.triggerPx")?;
        report = report.with_trigger_price(trigger_price);
    }

    Ok(report)
}

/// Parses a WebSocket fill message into a [`FillReport`].
///
/// This converts Hyperliquid fill data from WebSocket user events into Nautilus fill reports.
pub fn parse_ws_fill_report(
    fill: &WsFillData,
    instrument: &InstrumentAny,
    account_id: AccountId,
    ts_init: UnixNanos,
) -> anyhow::Result<FillReport> {
    let instrument_id = instrument.id();

    if let Some(liquidation) = fill.liquidation.as_ref() {
        log::warn!(
            "Liquidation fill: {} oid={} method={:?} mark_px={} liquidated_user={}",
            instrument_id,
            fill.oid,
            liquidation.method,
            liquidation.mark_px,
            liquidation
                .liquidated_user
                .as_deref()
                .unwrap_or("<unknown>"),
        );
    } else if matches!(fill.dir, HyperliquidFillDirection::AutoDeleveraging) {
        log::warn!(
            "Auto-deleveraging fill: {instrument_id} oid={} px={} sz={}",
            fill.oid,
            fill.px,
            fill.sz,
        );
    }

    let venue_order_id = VenueOrderId::new(fill.oid.to_string());
    let trade_id = make_fill_trade_id(
        &fill.hash,
        fill.oid,
        &fill.px,
        &fill.sz,
        fill.time,
        &fill.start_position,
    );

    let order_side = OrderSide::from(fill.side);
    let last_qty = parse_quantity(&fill.sz, instrument, "fill.sz")?;
    let last_px = parse_price(&fill.px, instrument, "fill.px")?;
    let liquidity_side = if fill.crossed {
        LiquiditySide::Taker
    } else {
        LiquiditySide::Maker
    };

    let fee_amount = Decimal::from_str(&fill.fee)
        .with_context(|| format!("Failed to parse fee='{}' as decimal", fill.fee))?;

    let commission_currency = Currency::from_str(fill.fee_token.as_str())
        .with_context(|| format!("Unknown fee token '{}'", fill.fee_token))?;

    let commission = Money::from_decimal(fee_amount, commission_currency)
        .with_context(|| format!("Failed to create commission from fee='{}'", fill.fee))?;
    let ts_event = millis_to_nanos(fill.time)?;

    // No client order ID available in fill data directly
    let client_order_id = None;

    Ok(FillReport::new(
        account_id,
        instrument_id,
        venue_order_id,
        trade_id,
        order_side,
        last_qty,
        last_px,
        commission,
        liquidity_side,
        client_order_id,
        None, // venue_position_id
        ts_event,
        ts_init,
        None, // report_id
    ))
}

/// Parses a WebSocket ActiveAssetCtx message into mark price, index price, and funding rate updates.
///
/// This converts Hyperliquid asset context data into Nautilus price and funding rate updates.
/// Returns a tuple of (`MarkPriceUpdate`, `Option<IndexPriceUpdate>`, `Option<FundingRateUpdate>`).
/// Index price and funding rate are only present for perpetual contracts.
pub fn parse_ws_asset_context(
    ctx: &WsActiveAssetCtxData,
    instrument: &InstrumentAny,
    ts_init: UnixNanos,
) -> anyhow::Result<(
    MarkPriceUpdate,
    Option<IndexPriceUpdate>,
    Option<FundingRateUpdate>,
)> {
    let instrument_id = instrument.id();

    match ctx {
        WsActiveAssetCtxData::Perp { coin: _, ctx } => {
            let mark_px_f64 = ctx
                .shared
                .mark_px
                .parse::<f64>()
                .context("Failed to parse mark_px as f64")?;
            let mark_price = parse_f64_price(mark_px_f64, instrument, "ctx.mark_px")?;
            let mark_price_update =
                MarkPriceUpdate::new(instrument_id, mark_price, ts_init, ts_init);

            let oracle_px_f64 = ctx
                .oracle_px
                .parse::<f64>()
                .context("Failed to parse oracle_px as f64")?;
            let index_price = parse_f64_price(oracle_px_f64, instrument, "ctx.oracle_px")?;
            let index_price_update =
                IndexPriceUpdate::new(instrument_id, index_price, ts_init, ts_init);

            let funding_f64 = ctx
                .funding
                .parse::<f64>()
                .context("Failed to parse funding as f64")?;
            let funding_rate_decimal = Decimal::from_f64(funding_f64)
                .context("Failed to convert funding rate to Decimal")?;
            let funding_rate_update = FundingRateUpdate::new(
                instrument_id,
                funding_rate_decimal,
                Some(60), // Hyperliquid exchanges funding hourly
                None,     // Hyperliquid doesn't provide next funding time in this message
                ts_init,
                ts_init,
            );

            Ok((
                mark_price_update,
                Some(index_price_update),
                Some(funding_rate_update),
            ))
        }
        WsActiveAssetCtxData::Spot { coin: _, ctx } => {
            let mark_px_f64 = ctx
                .shared
                .mark_px
                .parse::<f64>()
                .context("Failed to parse mark_px as f64")?;
            let mark_price = parse_f64_price(mark_px_f64, instrument, "ctx.mark_px")?;
            let mark_price_update =
                MarkPriceUpdate::new(instrument_id, mark_price, ts_init, ts_init);

            Ok((mark_price_update, None, None))
        }
    }
}

fn parse_f64_price(
    price: f64,
    instrument: &InstrumentAny,
    field_name: &str,
) -> anyhow::Result<Price> {
    if !price.is_finite() {
        anyhow::bail!("Invalid price value for {field_name}: {price} (must be finite)");
    }
    Ok(Price::new(price, instrument.price_precision()))
}

#[cfg(test)]
mod tests {
    use nautilus_model::{
        identifiers::{InstrumentId, Symbol, Venue},
        instruments::CryptoPerpetual,
        types::currency::Currency,
    };
    use rstest::rstest;
    use ustr::Ustr;

    use super::*;
    use crate::{
        common::enums::{
            HyperliquidFillDirection, HyperliquidLiquidationMethod,
            HyperliquidOrderStatus as HyperliquidOrderStatusEnum, HyperliquidSide,
        },
        websocket::messages::{
            FillLiquidationData, PerpsAssetCtx, SharedAssetCtx, SpotAssetCtx, WsBasicOrderData,
            WsBookData, WsLevelData,
        },
    };

    fn create_test_instrument() -> InstrumentAny {
        let instrument_id = InstrumentId::new(Symbol::new("BTC-PERP"), Venue::new("HYPERLIQUID"));

        InstrumentAny::CryptoPerpetual(CryptoPerpetual::new(
            instrument_id,
            Symbol::new("BTC-PERP"),
            Currency::from("BTC"),
            Currency::from("USDC"),
            Currency::from("USDC"),
            false, // is_inverse
            2,     // price_precision
            3,     // size_precision
            Price::from("0.01"),
            Quantity::from("0.001"),
            None, // multiplier
            None, // lot_size
            None, // max_quantity
            None, // min_quantity
            None, // max_notional
            None, // min_notional
            None, // max_price
            None, // min_price
            None, // margin_init
            None, // margin_maint
            None, // maker_fee
            None, // taker_fee
            None, // info
            UnixNanos::default(),
            UnixNanos::default(),
        ))
    }

    #[rstest]
    fn test_parse_ws_order_status_report_basic() {
        let instrument = create_test_instrument();
        let account_id = AccountId::new("HYPERLIQUID-001");
        let ts_init = UnixNanos::default();

        let order_data = WsOrderData {
            order: WsBasicOrderData {
                coin: Ustr::from("BTC"),
                side: HyperliquidSide::Buy,
                limit_px: "50000.0".to_string(),
                sz: "0.5".to_string(),
                oid: 12345,
                timestamp: 1704470400000,
                orig_sz: "1.0".to_string(),
                cloid: Some("test-order-1".to_string()),
                trigger_px: None,
                is_market: None,
                tpsl: None,
                trigger_activated: None,
                trailing_stop: None,
            },
            status: HyperliquidOrderStatusEnum::Open,
            status_timestamp: 1704470400000,
        };

        let result = parse_ws_order_status_report(&order_data, &instrument, account_id, ts_init);
        assert!(result.is_ok());

        let report = result.unwrap();
        assert_eq!(report.order_side, OrderSide::Buy);
        assert_eq!(report.order_type, OrderType::Limit);
        assert_eq!(report.order_status, OrderStatus::Accepted);
    }

    #[rstest]
    fn test_parse_ws_fill_report_basic() {
        let instrument = create_test_instrument();
        let account_id = AccountId::new("HYPERLIQUID-001");
        let ts_init = UnixNanos::default();

        let fill_data = WsFillData {
            coin: Ustr::from("BTC"),
            px: "50000.0".to_string(),
            sz: "0.1".to_string(),
            side: HyperliquidSide::Buy,
            time: 1704470400000,
            start_position: "0.0".to_string(),
            dir: HyperliquidFillDirection::OpenLong,
            closed_pnl: "0.0".to_string(),
            hash: "0xabc123".to_string(),
            oid: 12345,
            crossed: true,
            fee: "0.05".to_string(),
            tid: 98765,
            liquidation: None,
            fee_token: Ustr::from("USDC"),
            builder_fee: None,
            cloid: Some("0xd211f1c27288259290850338d22132a0".to_string()),
            twap_id: None,
        };

        let result = parse_ws_fill_report(&fill_data, &instrument, account_id, ts_init);
        assert!(result.is_ok());

        let report = result.unwrap();
        assert_eq!(report.order_side, OrderSide::Buy);
        assert_eq!(report.liquidity_side, LiquiditySide::Taker);
    }

    #[rstest]
    fn test_parse_ws_fill_report_with_liquidation() {
        let instrument = create_test_instrument();
        let account_id = AccountId::new("HYPERLIQUID-001");
        let ts_init = UnixNanos::default();

        let fill_data = WsFillData {
            coin: Ustr::from("BTC"),
            px: "50000.0".to_string(),
            sz: "0.1".to_string(),
            side: HyperliquidSide::Sell,
            time: 1704470400000,
            start_position: "0.1".to_string(),
            dir: HyperliquidFillDirection::CloseLong,
            closed_pnl: "-25.0".to_string(),
            hash: "0xdef456".to_string(),
            oid: 54321,
            crossed: true,
            fee: "0.0".to_string(),
            tid: 12345,
            liquidation: Some(FillLiquidationData {
                liquidated_user: Some("0xuser".to_string()),
                mark_px: 50_000.0,
                method: HyperliquidLiquidationMethod::Market,
            }),
            fee_token: Ustr::from("USDC"),
            builder_fee: None,
            cloid: None,
            twap_id: None,
        };

        let report = parse_ws_fill_report(&fill_data, &instrument, account_id, ts_init).unwrap();

        // The fill is still emitted through the standard path; the liquidation
        // metadata is logged for observability rather than encoded on the report.
        assert_eq!(report.order_side, OrderSide::Sell);
        assert_eq!(report.liquidity_side, LiquiditySide::Taker);
        assert_eq!(report.venue_order_id.to_string(), "54321");
    }

    #[rstest]
    fn test_parse_ws_order_book_deltas_snapshot_behavior() {
        let instrument = create_test_instrument();
        let ts_init = UnixNanos::default();

        let book = WsBookData {
            coin: Ustr::from("BTC"),
            levels: [
                vec![WsLevelData {
                    px: "50000.0".to_string(),
                    sz: "1.0".to_string(),
                    n: 1,
                }],
                vec![WsLevelData {
                    px: "50001.0".to_string(),
                    sz: "2.0".to_string(),
                    n: 1,
                }],
            ],
            time: 1_704_470_400_000,
        };

        let deltas = parse_ws_order_book_deltas(&book, &instrument, ts_init).unwrap();

        assert_eq!(deltas.deltas.len(), 3); // clear + bid + ask
        assert_eq!(deltas.deltas[0].action, BookAction::Clear);

        let bid_delta = &deltas.deltas[1];
        assert_eq!(bid_delta.action, BookAction::Add);
        assert_eq!(bid_delta.order.side, OrderSide::Buy);
        assert!(bid_delta.order.size.is_positive());
        assert_eq!(bid_delta.order.order_id, 0);

        let ask_delta = &deltas.deltas[2];
        assert_eq!(ask_delta.action, BookAction::Add);
        assert_eq!(ask_delta.order.side, OrderSide::Sell);
        assert!(ask_delta.order.size.is_positive());
        assert_eq!(ask_delta.order.order_id, 0);
    }

    #[rstest]
    fn test_parse_ws_order_book_depth10_pads_sparse_book() {
        let instrument = create_test_instrument();
        let ts_init = UnixNanos::default();

        // 3 bids, 2 asks — Depth10 must pad the remaining 7/8 slots with zero orders
        let book = WsBookData {
            coin: Ustr::from("BTC"),
            levels: [
                vec![
                    WsLevelData {
                        px: "100.00".to_string(),
                        sz: "1.0".to_string(),
                        n: 2,
                    },
                    WsLevelData {
                        px: "99.99".to_string(),
                        sz: "2.0".to_string(),
                        n: 3,
                    },
                    WsLevelData {
                        px: "99.98".to_string(),
                        sz: "3.0".to_string(),
                        n: 1,
                    },
                ],
                vec![
                    WsLevelData {
                        px: "100.01".to_string(),
                        sz: "1.5".to_string(),
                        n: 1,
                    },
                    WsLevelData {
                        px: "100.02".to_string(),
                        sz: "2.5".to_string(),
                        n: 4,
                    },
                ],
            ],
            time: 1_704_470_400_000,
        };

        let depth = parse_ws_order_book_depth10(&book, &instrument, ts_init).unwrap();

        assert_eq!(depth.instrument_id, instrument.id());
        assert_eq!(depth.bids.len(), 10);
        assert_eq!(depth.asks.len(), 10);

        assert_eq!(depth.bids[0].price.as_f64(), 100.00);
        assert_eq!(depth.bids[0].side, OrderSide::Buy);
        assert_eq!(depth.bid_counts[0], 2);
        assert_eq!(depth.bids[2].price.as_f64(), 99.98);
        assert_eq!(depth.bid_counts[2], 1);

        // Padded bid slots
        for i in 3..10 {
            assert_eq!(depth.bids[i].side, OrderSide::Buy);
            assert!(depth.bids[i].size.is_zero());
            assert_eq!(depth.bid_counts[i], 0);
        }

        assert_eq!(depth.asks[0].price.as_f64(), 100.01);
        assert_eq!(depth.asks[0].side, OrderSide::Sell);
        assert_eq!(depth.ask_counts[0], 1);
        assert_eq!(depth.asks[1].price.as_f64(), 100.02);
        assert_eq!(depth.ask_counts[1], 4);

        for i in 2..10 {
            assert_eq!(depth.asks[i].side, OrderSide::Sell);
            assert!(depth.asks[i].size.is_zero());
            assert_eq!(depth.ask_counts[i], 0);
        }

        // Snapshot flag set
        assert_eq!(depth.flags, RecordFlag::F_SNAPSHOT as u8);
        assert_eq!(
            depth.ts_event,
            UnixNanos::from(1_704_470_400_000 * 1_000_000)
        );
    }

    #[rstest]
    fn test_parse_ws_order_book_depth10_truncates_beyond_10() {
        let instrument = create_test_instrument();
        let ts_init = UnixNanos::default();

        let mk_levels = |base: f64, n: usize| -> Vec<WsLevelData> {
            (0..n)
                .map(|i| WsLevelData {
                    px: format!("{:.2}", base - i as f64 * 0.01),
                    sz: "1.0".to_string(),
                    n: 1,
                })
                .collect()
        };

        let book = WsBookData {
            coin: Ustr::from("BTC"),
            levels: [mk_levels(100.00, 15), mk_levels(100.50, 12)],
            time: 1_704_470_400_000,
        };

        let depth = parse_ws_order_book_depth10(&book, &instrument, ts_init).unwrap();

        // Only first 10 on each side retained
        for i in 0..10 {
            assert!(
                !depth.bids[i].size.is_zero(),
                "bid slot {i} unexpectedly empty"
            );
            assert!(
                !depth.asks[i].size.is_zero(),
                "ask slot {i} unexpectedly empty"
            );
        }
    }

    #[rstest]
    fn test_parse_ws_asset_context_perp() {
        let instrument = create_test_instrument();
        let ts_init = UnixNanos::default();

        let ctx_data = WsActiveAssetCtxData::Perp {
            coin: Ustr::from("BTC"),
            ctx: PerpsAssetCtx {
                shared: SharedAssetCtx {
                    day_ntl_vlm: "1000000.0".to_string(),
                    prev_day_px: "49000.0".to_string(),
                    mark_px: "50000.0".to_string(),
                    mid_px: Some("50001.0".to_string()),
                    impact_pxs: Some(vec!["50000.0".to_string(), "50002.0".to_string()]),
                    day_base_vlm: Some("100.0".to_string()),
                },
                funding: "0.0001".to_string(),
                open_interest: "100000.0".to_string(),
                oracle_px: "50005.0".to_string(),
                premium: Some("-0.0001".to_string()),
            },
        };

        let result = parse_ws_asset_context(&ctx_data, &instrument, ts_init);
        assert!(result.is_ok());

        let (mark_price, index_price, funding_rate) = result.unwrap();

        assert_eq!(mark_price.instrument_id, instrument.id());
        assert_eq!(mark_price.value.as_f64(), 50_000.0);

        assert!(index_price.is_some());
        let index = index_price.unwrap();
        assert_eq!(index.instrument_id, instrument.id());
        assert_eq!(index.value.as_f64(), 50_005.0);

        assert!(funding_rate.is_some());
        let funding = funding_rate.unwrap();
        assert_eq!(funding.instrument_id, instrument.id());
        assert_eq!(funding.rate.to_string(), "0.0001");
        assert_eq!(funding.interval, Some(60));
    }

    #[rstest]
    fn test_parse_ws_asset_context_spot() {
        let instrument = create_test_instrument();
        let ts_init = UnixNanos::default();

        let ctx_data = WsActiveAssetCtxData::Spot {
            coin: Ustr::from("BTC"),
            ctx: SpotAssetCtx {
                shared: SharedAssetCtx {
                    day_ntl_vlm: "1000000.0".to_string(),
                    prev_day_px: "49000.0".to_string(),
                    mark_px: "50000.0".to_string(),
                    mid_px: Some("50001.0".to_string()),
                    impact_pxs: Some(vec!["50000.0".to_string(), "50002.0".to_string()]),
                    day_base_vlm: Some("100.0".to_string()),
                },
                circulating_supply: "19000000.0".to_string(),
            },
        };

        let result = parse_ws_asset_context(&ctx_data, &instrument, ts_init);
        assert!(result.is_ok());

        let (mark_price, index_price, funding_rate) = result.unwrap();

        assert_eq!(mark_price.instrument_id, instrument.id());
        assert_eq!(mark_price.value.as_f64(), 50_000.0);
        assert!(index_price.is_none());
        assert!(funding_rate.is_none());
    }
}