Skip to main content

nautilus_deribit/websocket/
parse.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
16//! Parsing functions for converting Deribit WebSocket messages to Nautilus domain types.
17
18use ahash::AHashMap;
19use anyhow::Context;
20use jiff::{Span, Timestamp, tz::Offset};
21use nautilus_core::{
22    UUID4, UnixNanos, datetime::NANOSECONDS_IN_MILLISECOND,
23    serialization::deserialize_decimal_token_borrowed,
24};
25use nautilus_model::{
26    data::{
27        Bar, BarType, BookOrder, Data, FundingRateUpdate, IndexPriceUpdate, MarkPriceUpdate,
28        OrderBookDelta, OrderBookDeltas, OrderBookDepth, QuoteTick, TradeTick,
29        bar::BarSpecification, option_chain::OptionGreeks,
30    },
31    enums::{
32        AggregationSource, AggressorSide, BarAggregation, BookAction, GreeksConvention,
33        LiquiditySide, OrderSide, OrderStatus, OrderType, PositionSide, PriceType, RecordFlag,
34        TimeInForce,
35    },
36    events::{OrderAccepted, OrderCanceled, OrderExpired, OrderUpdated},
37    identifiers::{
38        AccountId, ClientOrderId, InstrumentId, StrategyId, TradeId, TraderId, VenueOrderId,
39    },
40    instruments::{Instrument, InstrumentAny},
41    reports::{FillReport, OrderStatusReport, PositionStatusReport},
42    types::{Currency, Money, Price, Quantity},
43};
44use rust_decimal::{Decimal, prelude::ToPrimitive};
45use serde_json::value::RawValue;
46use ustr::Ustr;
47
48use super::{
49    enums::{DeribitBookAction, DeribitBookMsgType},
50    messages::{
51        DeribitBookMsg, DeribitChartMsg, DeribitOrderMsg, DeribitPerpetualMsg, DeribitQuoteMsg,
52        DeribitTickerMsg, DeribitTradeMsg, DeribitUserTradeMsg,
53    },
54};
55use crate::{common::parse::build_public_trade_id, http::models::DeribitPosition};
56
57fn next_8_utc(from_ns: UnixNanos) -> anyhow::Result<UnixNanos> {
58    let from_secs = from_ns.as_u64() / 1_000_000_000;
59    let timestamp = Timestamp::from_second(i64::try_from(from_secs)?)?;
60    let dt = Offset::UTC.to_datetime(timestamp);
61    let date = if dt.hour() < 8 {
62        dt.date()
63    } else {
64        dt.date().checked_add(Span::new().days(1))?
65    };
66    let next_8 = Offset::UTC.to_timestamp(date.at(8, 0, 0, 0))?;
67    let nanos = u64::try_from(next_8.as_nanosecond())
68        .context("GTD expiry timestamp out of UnixNanos range")?;
69    Ok(UnixNanos::from(nanos))
70}
71
72/// Parses a Deribit trade message into a Nautilus `TradeTick`.
73///
74/// # Errors
75///
76/// Returns an error if the trade cannot be parsed.
77pub fn parse_trade_msg(
78    msg: &DeribitTradeMsg,
79    instrument: &InstrumentAny,
80    ts_init: UnixNanos,
81) -> anyhow::Result<TradeTick> {
82    let instrument_id = instrument.id();
83    let price_precision = instrument.price_precision();
84    let size_precision = instrument.size_precision();
85
86    let price = Price::from_decimal_dp(msg.price, price_precision)?;
87    let size = Quantity::from_decimal_dp(msg.amount.abs(), size_precision)?;
88
89    let aggressor_side = match msg.direction.as_str() {
90        "buy" => AggressorSide::Buy,
91        "sell" => AggressorSide::Sell,
92        _ => AggressorSide::NoAggressor,
93    };
94
95    let trade_id = build_public_trade_id(
96        &msg.trade_id,
97        msg.block_rfq_id,
98        msg.block_trade_id.as_deref(),
99        msg.combo_id.as_deref(),
100    );
101    let ts_event = UnixNanos::new(msg.timestamp * NANOSECONDS_IN_MILLISECOND);
102
103    TradeTick::new_checked(
104        instrument_id,
105        price,
106        size,
107        aggressor_side,
108        trade_id,
109        ts_event,
110        ts_init,
111    )
112}
113
114/// Parses a vector of Deribit trade messages into Nautilus `Data` items.
115pub fn parse_trades_data(
116    trades: &[DeribitTradeMsg],
117    instruments_cache: &AHashMap<Ustr, InstrumentAny>,
118    ts_init: UnixNanos,
119) -> Vec<Data> {
120    trades
121        .iter()
122        .filter_map(|msg| {
123            instruments_cache
124                .get(&msg.instrument_name)
125                .and_then(|inst| parse_trade_msg(msg, inst, ts_init).ok())
126                .map(Data::Trade)
127        })
128        .collect()
129}
130
131fn parse_snapshot_level(
132    level: &[&RawValue],
133    index: usize,
134    side: &str,
135    instrument_name: &str,
136) -> Option<(Decimal, Decimal)> {
137    let (price_index, amount_index) = if level.len() >= 3 {
138        (1, 2)
139    } else if level.len() >= 2 {
140        (0, 1)
141    } else {
142        log::warn!(
143            "Invalid {side} format at index {index} for {instrument_name}: expected 2-3 elements, was {}",
144            level.len()
145        );
146        return None;
147    };
148
149    let price_val = deserialize_decimal_token_borrowed(level[price_index])
150        .ok()
151        .or_else(|| {
152            log::warn!(
153                "Failed to parse {side} price at index {index} for {instrument_name}: {level:?}"
154            );
155            None
156        })?;
157
158    let amount_val = deserialize_decimal_token_borrowed(level[amount_index])
159        .ok()
160        .or_else(|| {
161            log::warn!(
162                "Failed to parse {side} amount at index {index} for {instrument_name}: {level:?}"
163            );
164            None
165        })?;
166
167    if price_val <= Decimal::ZERO {
168        log::warn!(
169            "Invalid {side} price {price_val} at index {index} for {instrument_name}: {level:?}"
170        );
171        return None;
172    }
173
174    Some((price_val, amount_val))
175}
176
177fn parse_delta_level(
178    level: &[&RawValue],
179    index: usize,
180    side: &str,
181    instrument_name: &str,
182) -> Option<(BookAction, Decimal, Decimal)> {
183    if level.len() < 3 {
184        log::warn!(
185            "Invalid {side} delta format at index {index} for {instrument_name}: expected 3 elements, was {}",
186            level.len()
187        );
188        return None;
189    }
190
191    let action_str = serde_json::from_str::<&str>(level[0].get())
192        .ok()
193        .or_else(|| {
194            log::warn!(
195                "Failed to parse {side} action at index {index} for {instrument_name}: {level:?}"
196            );
197            None
198        })?;
199
200    let deribit_action: DeribitBookAction = action_str.parse().ok().or_else(|| {
201        log::warn!(
202            "Unknown {side} action '{action_str}' at index {index} for {instrument_name}: {level:?}"
203        );
204        None
205    })?;
206
207    let price_val = deserialize_decimal_token_borrowed(level[1])
208        .ok()
209        .or_else(|| {
210            log::warn!(
211                "Failed to parse {side} price at index {index} for {instrument_name}: {level:?}"
212            );
213            None
214        })?;
215
216    let amount_val = deserialize_decimal_token_borrowed(level[2])
217        .ok()
218        .or_else(|| {
219            log::warn!(
220                "Failed to parse {side} amount at index {index} for {instrument_name}: {level:?}"
221            );
222            None
223        })?;
224
225    if price_val <= Decimal::ZERO {
226        log::warn!(
227            "Invalid {side} price {price_val} at index {index} for {instrument_name}: {level:?}"
228        );
229        return None;
230    }
231
232    Some((deribit_action.into(), price_val, amount_val))
233}
234
235/// Parses a Deribit order book snapshot into Nautilus `OrderBookDeltas`.
236///
237/// Skips a malformed level, and a level whose amount is not positive or rounds to zero at the
238/// instrument's size precision.
239///
240/// # Errors
241///
242/// Returns an error if a level's price or amount cannot convert to `Price` or `Quantity`, such as a
243/// value outside their range.
244pub fn parse_book_snapshot(
245    msg: &DeribitBookMsg<'_>,
246    instrument: &InstrumentAny,
247    ts_init: UnixNanos,
248) -> anyhow::Result<OrderBookDeltas> {
249    let instrument_id = instrument.id();
250    let price_precision = instrument.price_precision();
251    let size_precision = instrument.size_precision();
252    let ts_event = UnixNanos::new(msg.timestamp * NANOSECONDS_IN_MILLISECOND);
253
254    let mut deltas = Vec::new();
255
256    let has_levels = !msg.bids.is_empty() || !msg.asks.is_empty();
257
258    // All snapshot deltas get F_SNAPSHOT; CLEAR also gets F_LAST if no levels follow
259    let clear_flags = if has_levels {
260        RecordFlag::F_SNAPSHOT as u8
261    } else {
262        RecordFlag::F_SNAPSHOT as u8 | RecordFlag::F_LAST as u8
263    };
264
265    deltas.push(OrderBookDelta::new(
266        instrument_id,
267        BookAction::Clear,
268        BookOrder::default(),
269        clear_flags,
270        msg.change_id,
271        ts_event,
272        ts_init,
273    ));
274
275    let sides = [
276        (OrderSide::Buy, "bid", &msg.bids, 0),
277        (OrderSide::Sell, "ask", &msg.asks, msg.bids.len()),
278    ];
279
280    for (order_side, side, levels, order_id_offset) in sides {
281        for (i, level) in levels.iter().enumerate() {
282            let Some((price_val, amount_val)) =
283                parse_snapshot_level(level, i, side, msg.instrument_name.as_str())
284            else {
285                continue;
286            };
287
288            if amount_val <= Decimal::ZERO {
289                continue;
290            }
291
292            let price = Price::from_decimal_dp(price_val, price_precision)?;
293            let size = Quantity::from_decimal_dp(amount_val, size_precision)?;
294
295            if is_zero_at_size_precision(size, amount_val, side, i, msg.instrument_name.as_str()) {
296                continue;
297            }
298
299            deltas.push(OrderBookDelta::new_checked(
300                instrument_id,
301                BookAction::Add,
302                BookOrder::new(order_side, price, size, (order_id_offset + i) as u64),
303                RecordFlag::F_SNAPSHOT as u8,
304                msg.change_id,
305                ts_event,
306                ts_init,
307            )?);
308        }
309    }
310
311    if let Some(last) = deltas.last_mut() {
312        last.flags |= RecordFlag::F_LAST as u8;
313    }
314
315    Ok(OrderBookDeltas::new(instrument_id, deltas))
316}
317
318/// Parses a Deribit order book change (delta) into Nautilus `OrderBookDeltas`.
319///
320/// Skips a malformed level. A `new` or `change` level whose amount rounds to zero at the
321/// instrument's size precision becomes a delete.
322///
323/// # Errors
324///
325/// Returns an error if a level's price or amount cannot convert to `Price` or `Quantity`, such as a
326/// value outside their range.
327pub fn parse_book_delta(
328    msg: &DeribitBookMsg<'_>,
329    instrument: &InstrumentAny,
330    ts_init: UnixNanos,
331) -> anyhow::Result<OrderBookDeltas> {
332    let instrument_id = instrument.id();
333    let price_precision = instrument.price_precision();
334    let size_precision = instrument.size_precision();
335    let ts_event = UnixNanos::new(msg.timestamp * NANOSECONDS_IN_MILLISECOND);
336
337    let mut deltas = Vec::new();
338
339    let sides = [
340        (OrderSide::Buy, "bid", &msg.bids, 0),
341        (OrderSide::Sell, "ask", &msg.asks, msg.bids.len()),
342    ];
343
344    for (order_side, side, levels, order_id_offset) in sides {
345        for (i, level) in levels.iter().enumerate() {
346            let Some((action, price_val, amount_val)) =
347                parse_delta_level(level, i, side, msg.instrument_name.as_str())
348            else {
349                continue;
350            };
351
352            let price = Price::from_decimal_dp(price_val, price_precision)?;
353            let size = Quantity::from_decimal_dp(amount_val.abs(), size_precision)?;
354
355            let action = if action != BookAction::Delete
356                && is_zero_at_size_precision(
357                    size,
358                    amount_val,
359                    side,
360                    i,
361                    msg.instrument_name.as_str(),
362                ) {
363                BookAction::Delete
364            } else {
365                action
366            };
367
368            deltas.push(OrderBookDelta::new_checked(
369                instrument_id,
370                action,
371                BookOrder::new(order_side, price, size, (order_id_offset + i) as u64),
372                0,
373                msg.change_id,
374                ts_event,
375                ts_init,
376            )?);
377        }
378    }
379
380    // Set F_LAST flag on the last delta
381    if let Some(last) = deltas.last_mut() {
382        last.flags |= RecordFlag::F_LAST as u8;
383    }
384
385    Ok(OrderBookDeltas::new(instrument_id, deltas))
386}
387
388/// Parses a Deribit order book message (snapshot or delta) into Nautilus `OrderBookDeltas`.
389///
390/// # Errors
391///
392/// Returns an error if a level's price or amount cannot convert to `Price` or `Quantity`, such as a
393/// value outside their range.
394pub fn parse_book_msg(
395    msg: &DeribitBookMsg<'_>,
396    instrument: &InstrumentAny,
397    ts_init: UnixNanos,
398) -> anyhow::Result<OrderBookDeltas> {
399    match msg.msg_type {
400        DeribitBookMsgType::Snapshot => parse_book_snapshot(msg, instrument, ts_init),
401        DeribitBookMsgType::Change => parse_book_delta(msg, instrument, ts_init),
402    }
403}
404
405/// Parses a grouped book snapshot into depth data, with zero order counts because Deribit
406/// does not supply them. Skips levels under the same rules as [`parse_book_snapshot`].
407///
408/// # Errors
409///
410/// Returns an error if a level's price or amount cannot convert to `Price` or `Quantity`.
411pub(crate) fn parse_book_depth(
412    msg: &DeribitBookMsg<'_>,
413    instrument: &InstrumentAny,
414    ts_init: UnixNanos,
415) -> anyhow::Result<OrderBookDepth> {
416    let snapshot = parse_book_snapshot(msg, instrument, ts_init)?;
417    let (bids, asks): (Vec<_>, Vec<_>) = snapshot
418        .deltas
419        .iter()
420        .filter(|delta| delta.action == BookAction::Add)
421        .map(|delta| delta.order)
422        .partition(|order| order.side == OrderSide::Buy.into());
423    let bid_counts = vec![0; bids.len()];
424    let ask_counts = vec![0; asks.len()];
425
426    OrderBookDepth::new_checked(
427        snapshot.instrument_id,
428        bids,
429        asks,
430        bid_counts,
431        ask_counts,
432        RecordFlag::F_SNAPSHOT as u8 | RecordFlag::F_LAST as u8,
433        msg.change_id,
434        snapshot.ts_event,
435        ts_init,
436    )
437}
438
439// An amount below half the size increment rounds to zero, which a book level cannot hold, so
440// callers treat the level as absent.
441fn is_zero_at_size_precision(
442    size: Quantity,
443    amount: Decimal,
444    side: &str,
445    index: usize,
446    instrument_name: &str,
447) -> bool {
448    if size.is_positive() {
449        return false;
450    }
451
452    log::warn!(
453        "Book {side} amount {amount} at index {index} for {instrument_name} is zero at size precision {}, treating level as absent",
454        size.precision
455    );
456    true
457}
458
459/// Parses a Deribit ticker message into a Nautilus `QuoteTick`.
460///
461/// # Errors
462///
463/// Returns an error if the quote cannot be parsed or prices are missing.
464pub fn parse_ticker_to_quote(
465    msg: &DeribitTickerMsg,
466    instrument: &InstrumentAny,
467    ts_init: UnixNanos,
468) -> anyhow::Result<QuoteTick> {
469    let instrument_id = instrument.id();
470    let price_precision = instrument.price_precision();
471    let size_precision = instrument.size_precision();
472
473    let bid_price_val = msg
474        .best_bid_price
475        .context("Missing best_bid_price in ticker")?;
476    let ask_price_val = msg
477        .best_ask_price
478        .context("Missing best_ask_price in ticker")?;
479
480    let bid_price = Price::from_decimal_dp(bid_price_val, price_precision)?;
481    let ask_price = Price::from_decimal_dp(ask_price_val, price_precision)?;
482    let bid_size =
483        Quantity::from_decimal_dp(msg.best_bid_amount.unwrap_or_default(), size_precision)?;
484    let ask_size =
485        Quantity::from_decimal_dp(msg.best_ask_amount.unwrap_or_default(), size_precision)?;
486    let ts_event = UnixNanos::new(msg.timestamp * NANOSECONDS_IN_MILLISECOND);
487
488    QuoteTick::new_checked(
489        instrument_id,
490        bid_price,
491        ask_price,
492        bid_size,
493        ask_size,
494        ts_event,
495        ts_init,
496    )
497}
498
499/// Parses a Deribit quote message into a Nautilus `QuoteTick`.
500///
501/// # Errors
502///
503/// Returns an error if the quote cannot be parsed.
504pub fn parse_quote_msg(
505    msg: &DeribitQuoteMsg,
506    instrument: &InstrumentAny,
507    ts_init: UnixNanos,
508) -> anyhow::Result<QuoteTick> {
509    let instrument_id = instrument.id();
510    let price_precision = instrument.price_precision();
511    let size_precision = instrument.size_precision();
512
513    let bid_price = Price::from_decimal_dp(msg.best_bid_price, price_precision)?;
514    let ask_price = Price::from_decimal_dp(msg.best_ask_price, price_precision)?;
515    let bid_size = Quantity::from_decimal_dp(msg.best_bid_amount, size_precision)?;
516    let ask_size = Quantity::from_decimal_dp(msg.best_ask_amount, size_precision)?;
517    let ts_event = UnixNanos::new(msg.timestamp * NANOSECONDS_IN_MILLISECOND);
518
519    QuoteTick::new_checked(
520        instrument_id,
521        bid_price,
522        ask_price,
523        bid_size,
524        ask_size,
525        ts_event,
526        ts_init,
527    )
528}
529
530/// Parses a Deribit ticker message into a Nautilus `MarkPriceUpdate`.
531///
532/// # Errors
533///
534/// Returns an error if the price cannot be converted to the required precision.
535pub fn parse_ticker_to_mark_price(
536    msg: &DeribitTickerMsg,
537    instrument: &InstrumentAny,
538    ts_init: UnixNanos,
539) -> anyhow::Result<MarkPriceUpdate> {
540    let instrument_id = instrument.id();
541    let price_precision = instrument.price_precision();
542    let value = Price::from_decimal_dp(msg.mark_price, price_precision)?;
543    let ts_event = UnixNanos::new(msg.timestamp * NANOSECONDS_IN_MILLISECOND);
544
545    Ok(MarkPriceUpdate::new(
546        instrument_id,
547        value,
548        ts_event,
549        ts_init,
550    ))
551}
552
553/// Parses a Deribit ticker message into a Nautilus `IndexPriceUpdate`.
554///
555/// # Errors
556///
557/// Returns an error if the price cannot be converted to the required precision.
558pub fn parse_ticker_to_index_price(
559    msg: &DeribitTickerMsg,
560    instrument: &InstrumentAny,
561    ts_init: UnixNanos,
562) -> anyhow::Result<IndexPriceUpdate> {
563    let instrument_id = instrument.id();
564    let price_precision = instrument.price_precision();
565    let value = Price::from_decimal_dp(msg.index_price, price_precision)?;
566    let ts_event = UnixNanos::new(msg.timestamp * NANOSECONDS_IN_MILLISECOND);
567
568    Ok(IndexPriceUpdate::new(
569        instrument_id,
570        value,
571        ts_event,
572        ts_init,
573    ))
574}
575
576/// Parses a Deribit ticker message into a Nautilus `FundingRateUpdate`.
577///
578/// Returns `None` if the instrument is not a perpetual or the funding rate is not available.
579#[must_use]
580pub fn parse_ticker_to_funding_rate(
581    msg: &DeribitTickerMsg,
582    instrument: &InstrumentAny,
583    ts_init: UnixNanos,
584) -> Option<FundingRateUpdate> {
585    // current_funding is only available for perpetual instruments
586    let rate = msg.current_funding?;
587    let instrument_id = instrument.id();
588    let ts_event = UnixNanos::new(msg.timestamp * NANOSECONDS_IN_MILLISECOND);
589
590    // Deribit ticker doesn't include next_funding_time, set to None
591    Some(FundingRateUpdate::new(
592        instrument_id,
593        rate,
594        None, // Deribit exchanges funding every few seconds, instead of in set intervals like other exchanges
595        None, // next_funding_ns not available in ticker
596        ts_event,
597        ts_init,
598    ))
599}
600
601/// Parses a Deribit ticker message into a Nautilus `OptionGreeks`.
602///
603/// Returns `None` if the ticker message does not contain Greeks (non-option instrument).
604#[must_use]
605pub fn parse_ticker_to_option_greeks(
606    msg: &DeribitTickerMsg,
607    instrument: &InstrumentAny,
608    ts_init: UnixNanos,
609) -> Option<OptionGreeks> {
610    let deribit_greeks = msg.greeks.as_ref()?;
611    let instrument_id = instrument.id();
612    let ts_event = UnixNanos::new(msg.timestamp * NANOSECONDS_IN_MILLISECOND);
613    let iv_to_fraction = |iv: Decimal| iv.to_f64().map(|v| v / 100.0);
614
615    Some(OptionGreeks {
616        instrument_id,
617        convention: GreeksConvention::BlackScholes,
618        greeks: deribit_greeks.to_greek_values(),
619        mark_iv: msg.mark_iv.and_then(iv_to_fraction),
620        bid_iv: msg.bid_iv.and_then(iv_to_fraction),
621        ask_iv: msg.ask_iv.and_then(iv_to_fraction),
622        underlying_price: msg.underlying_price.and_then(|v| v.to_f64()),
623        open_interest: Some(msg.open_interest.to_f64().unwrap_or(0.0)),
624        ts_event,
625        ts_init,
626    })
627}
628
629/// Parses a Deribit perpetual channel message into a Nautilus `FundingRateUpdate`.
630///
631/// The perpetual channel (`perpetual.{instrument}.{interval}`) provides dedicated
632/// funding rate updates with the `interest` field representing the current funding rate.
633#[must_use]
634pub fn parse_perpetual_to_funding_rate(
635    msg: &DeribitPerpetualMsg,
636    instrument: &InstrumentAny,
637    ts_init: UnixNanos,
638) -> FundingRateUpdate {
639    let instrument_id = instrument.id();
640    let ts_event = UnixNanos::new(msg.timestamp * NANOSECONDS_IN_MILLISECOND);
641
642    FundingRateUpdate::new(
643        instrument_id,
644        msg.interest,
645        None, // Deribit exchanges funding every few seconds, instead of in set intervals like other exchanges
646        None, // next_funding_ns not available in perpetual channel
647        ts_event,
648        ts_init,
649    )
650}
651
652/// Converts a Deribit chart resolution and instrument to a Nautilus BarType.
653///
654/// Deribit resolutions: "1", "3", "5", "10", "15", "30", "60", "120", "180", "360", "720", "1D"
655///
656/// # Errors
657///
658/// Returns an error if the resolution string is invalid or BarType construction fails.
659pub fn resolution_to_bar_type(
660    instrument_id: InstrumentId,
661    resolution: &str,
662) -> anyhow::Result<BarType> {
663    let (step, aggregation) = match resolution {
664        "1" => (1, BarAggregation::Minute),
665        "3" => (3, BarAggregation::Minute),
666        "5" => (5, BarAggregation::Minute),
667        "10" => (10, BarAggregation::Minute),
668        "15" => (15, BarAggregation::Minute),
669        "30" => (30, BarAggregation::Minute),
670        "60" => (1, BarAggregation::Hour),
671        "120" => (2, BarAggregation::Hour),
672        "180" => (3, BarAggregation::Hour),
673        "360" => (6, BarAggregation::Hour),
674        "720" => (12, BarAggregation::Hour),
675        "1D" => (1, BarAggregation::Day),
676        _ => anyhow::bail!("Unsupported Deribit resolution: {resolution}"),
677    };
678
679    let spec = BarSpecification::new_checked(step, aggregation, PriceType::Last)
680        .context("invalid Deribit bar resolution")?;
681    Ok(BarType::new(
682        instrument_id,
683        spec,
684        AggregationSource::External,
685    ))
686}
687
688/// Parses a Deribit chart message from a WebSocket subscription into a [`Bar`].
689///
690/// Converts a single OHLCV data point from the `chart.trades.{instrument}.{resolution}` channel
691/// into a Nautilus Bar object.
692///
693/// When `use_cost_for_volume` is true, `Bar.volume` is populated from `chart_msg.cost` (USD) to
694/// match instruments whose trade `amount` is in USD (inverse perpetuals / inverse futures).
695/// Otherwise `chart_msg.volume` (base currency) is used. Callers derive this from the instrument
696/// via [`crate::common::parse::use_cost_for_bar_volume`].
697///
698/// # Errors
699///
700/// Returns an error if:
701/// - Price or volume values are invalid.
702/// - Bar construction fails validation.
703pub fn parse_chart_msg(
704    chart_msg: &DeribitChartMsg,
705    bar_type: BarType,
706    price_precision: u8,
707    size_precision: u8,
708    use_cost_for_volume: bool,
709    timestamp_on_close: bool,
710    ts_init: UnixNanos,
711) -> anyhow::Result<Bar> {
712    let open =
713        Price::from_decimal_dp(chart_msg.open, price_precision).context("Invalid open price")?;
714    let high =
715        Price::from_decimal_dp(chart_msg.high, price_precision).context("Invalid high price")?;
716    let low =
717        Price::from_decimal_dp(chart_msg.low, price_precision).context("Invalid low price")?;
718    let close =
719        Price::from_decimal_dp(chart_msg.close, price_precision).context("Invalid close price")?;
720
721    let raw_volume = if use_cost_for_volume {
722        chart_msg.cost
723    } else {
724        chart_msg.volume
725    };
726
727    let volume = Quantity::from_decimal_dp(raw_volume, size_precision).context("Invalid volume")?;
728
729    // Convert timestamp from milliseconds to nanoseconds
730    let mut ts_event = UnixNanos::from(chart_msg.tick * NANOSECONDS_IN_MILLISECOND);
731
732    // Adjust timestamp to close time if configured
733    if timestamp_on_close {
734        let interval_ns = bar_type.spec().timedelta().as_nanos();
735        let interval_ns = u64::try_from(interval_ns)
736            .context("bar interval overflowed the u64 range for nanoseconds")?;
737        let updated = ts_event
738            .as_u64()
739            .checked_add(interval_ns)
740            .context("bar timestamp overflowed when adjusting to close time")?;
741        ts_event = UnixNanos::from(updated);
742    }
743
744    Bar::new_checked(bar_type, open, high, low, close, volume, ts_event, ts_init)
745        .context("Invalid OHLC bar")
746}
747
748/// Parses a Deribit user order message into a Nautilus `OrderStatusReport`.
749///
750/// # Errors
751///
752/// Returns an error if the order data cannot be parsed.
753pub fn parse_user_order_msg(
754    msg: &DeribitOrderMsg,
755    instrument: &InstrumentAny,
756    account_id: AccountId,
757    ts_init: UnixNanos,
758) -> anyhow::Result<OrderStatusReport> {
759    let instrument_id = instrument.id();
760    let venue_order_id = VenueOrderId::new(&msg.order_id);
761
762    let order_side = match msg.direction.as_str() {
763        "buy" => OrderSide::Buy,
764        "sell" => OrderSide::Sell,
765        _ => anyhow::bail!("Unknown order direction: {}", msg.direction),
766    };
767
768    // Map Deribit order type to Nautilus
769    let order_type = parse_deribit_order_type(&msg.order_type);
770
771    // Deribit supports: good_til_cancelled, good_til_day, fill_or_kill, immediate_or_cancel
772    let time_in_force = match msg.time_in_force.as_str() {
773        "good_til_cancelled" => TimeInForce::Gtc,
774        "good_til_day" => TimeInForce::Gtd,
775        "fill_or_kill" => TimeInForce::Fok,
776        "immediate_or_cancel" => TimeInForce::Ioc,
777        other => {
778            log::warn!("Unknown time_in_force '{other}', defaulting to GTC");
779            TimeInForce::Gtc
780        }
781    };
782
783    // Map Deribit order state to Nautilus status
784    let order_status = match msg.order_state.as_str() {
785        "open" => {
786            if msg.filled_amount.is_zero() {
787                OrderStatus::Accepted
788            } else {
789                OrderStatus::PartiallyFilled
790            }
791        }
792        "filled" => OrderStatus::Filled,
793        "rejected" => OrderStatus::Rejected,
794        "cancelled" => OrderStatus::Canceled,
795        "untriggered" => OrderStatus::Accepted, // Pending trigger
796        other => {
797            log::warn!("Unknown Deribit order_state '{other}', defaulting to Accepted");
798            OrderStatus::Accepted
799        }
800    };
801
802    let price_precision = instrument.price_precision();
803    let size_precision = instrument.size_precision();
804
805    let quantity = Quantity::from_decimal_dp(msg.amount, size_precision)?;
806    let filled_qty = Quantity::from_decimal_dp(msg.filled_amount, size_precision)?;
807
808    let ts_accepted = UnixNanos::new(msg.creation_timestamp * NANOSECONDS_IN_MILLISECOND);
809    let ts_last = UnixNanos::new(msg.last_update_timestamp * NANOSECONDS_IN_MILLISECOND);
810
811    let mut report = OrderStatusReport::new(
812        account_id,
813        instrument_id,
814        None, // order_list_id
815        venue_order_id,
816        order_side.into(),
817        order_type,
818        time_in_force,
819        order_status,
820        quantity,
821        filled_qty,
822        ts_accepted,
823        ts_last,
824        ts_init,
825        Some(UUID4::new()),
826    );
827
828    // Add client order ID if present
829    if let Some(ref label) = msg.label
830        && !label.is_empty()
831    {
832        report = report.with_client_order_id(ClientOrderId::new(label));
833    }
834
835    // Add price for limit orders
836    if let Some(price_val) = msg.price
837        && !price_val.is_zero()
838    {
839        let price = Price::from_decimal_dp(price_val, price_precision)?;
840        report = report.with_price(price);
841    }
842
843    if time_in_force == TimeInForce::Gtd {
844        let expire_time = next_8_utc(ts_accepted)?;
845        report = report.with_expire_time(expire_time);
846    }
847
848    // Add average price if filled
849    if let Some(avg_price) = msg.average_price
850        && !avg_price.is_zero()
851    {
852        report = report.with_avg_px(avg_price);
853    }
854
855    // Add trigger price for stop/take orders
856    if let Some(trigger_price) = msg.trigger_price
857        && !trigger_price.is_zero()
858    {
859        let trigger = Price::from_decimal_dp(trigger_price, price_precision)?;
860        report = report.with_trigger_price(trigger);
861    }
862
863    if msg.post_only {
864        report = report.with_post_only(true);
865    }
866
867    if msg.reduce_only {
868        report = report.with_reduce_only(true);
869    }
870
871    // Add cancel/reject reason
872    if let Some(ref reason) = msg.reject_reason {
873        report = report.with_cancel_reason(reason.clone());
874    } else if let Some(ref reason) = msg.cancel_reason {
875        report = report.with_cancel_reason(reason.clone());
876    }
877
878    Ok(report)
879}
880
881#[must_use]
882pub(crate) fn parse_deribit_order_type(order_type: &str) -> OrderType {
883    match order_type {
884        "limit" => OrderType::Limit,
885        "market" => OrderType::Market,
886        "stop_limit" => OrderType::StopLimit,
887        "stop_market" => OrderType::StopMarket,
888        "take_limit" => OrderType::LimitIfTouched,
889        "take_market" => OrderType::MarketIfTouched,
890        other => {
891            log::warn!("Unknown Deribit order_type '{other}', defaulting to Limit");
892            OrderType::Limit
893        }
894    }
895}
896
897/// Parses a Deribit user trade message into a Nautilus `FillReport`.
898///
899/// # Errors
900///
901/// Returns an error if the trade data cannot be parsed.
902pub fn parse_user_trade_msg(
903    msg: &DeribitUserTradeMsg,
904    instrument: &InstrumentAny,
905    account_id: AccountId,
906    ts_init: UnixNanos,
907) -> anyhow::Result<FillReport> {
908    let instrument_id = instrument.id();
909    let venue_order_id = VenueOrderId::new(&msg.order_id);
910    let trade_id = TradeId::new(&msg.trade_id);
911
912    // Deribit marks liquidation-triggered trades with "M" (maker liquidated),
913    // "T" (taker liquidated), or "MT" (both). Absent means a normal trade.
914    if let Some(liq) = msg.liquidation.as_deref().filter(|s| !s.is_empty()) {
915        let who = match liq {
916            "M" => "maker",
917            "T" => "taker",
918            "MT" => "both",
919            _ => liq,
920        };
921        log::warn!(
922            "Liquidation trade: {} trade_id={} order_id={} liquidation_side={} direction={} amount={} price={}",
923            instrument_id,
924            msg.trade_id,
925            msg.order_id,
926            who,
927            msg.direction,
928            msg.amount,
929            msg.price,
930        );
931    }
932
933    let order_side = match msg.direction.as_str() {
934        "buy" => OrderSide::Buy,
935        "sell" => OrderSide::Sell,
936        _ => anyhow::bail!("Unknown trade direction: {}", msg.direction),
937    };
938
939    let price_precision = instrument.price_precision();
940    let size_precision = instrument.size_precision();
941
942    let last_qty = Quantity::from_decimal_dp(msg.amount, size_precision)?;
943    let last_px = Price::from_decimal_dp(msg.price, price_precision)?;
944
945    let liquidity_side = match msg.liquidity.as_str() {
946        "M" => LiquiditySide::Maker,
947        "T" => LiquiditySide::Taker,
948        _ => LiquiditySide::NoLiquiditySide,
949    };
950
951    // Get fee currency from the fee_currency field
952    let fee_currency = Currency::from(&msg.fee_currency);
953    let commission = Money::from_decimal(msg.fee, fee_currency)?;
954
955    let ts_event = UnixNanos::new(msg.timestamp * NANOSECONDS_IN_MILLISECOND);
956
957    let client_order_id = msg
958        .label
959        .as_ref()
960        .filter(|l| !l.is_empty())
961        .map(ClientOrderId::new);
962
963    Ok(FillReport::new(
964        account_id,
965        instrument_id,
966        venue_order_id,
967        trade_id,
968        order_side,
969        last_qty,
970        last_px,
971        commission,
972        liquidity_side,
973        client_order_id,
974        None, // venue_position_id
975        ts_event,
976        ts_init,
977        None, // report_id
978    ))
979}
980
981/// Parses a Deribit position into a Nautilus `PositionStatusReport`.
982///
983/// # Arguments
984/// - `position` - The Deribit position data from `/private/get_positions`
985/// - `instrument` - The corresponding Nautilus instrument
986/// - `account_id` - The account ID for the report
987/// - `ts_init` - Initialization timestamp
988///
989/// # Returns
990/// A `PositionStatusReport` representing the current position state.
991#[must_use]
992pub fn parse_position_status_report(
993    position: &DeribitPosition,
994    instrument: &InstrumentAny,
995    account_id: AccountId,
996    ts_init: UnixNanos,
997) -> PositionStatusReport {
998    let instrument_id = instrument.id();
999    let size_precision = instrument.size_precision();
1000
1001    let signed_qty = Quantity::from_decimal_dp(position.size.abs(), size_precision)
1002        .unwrap_or_else(|_| Quantity::zero(size_precision));
1003
1004    let position_side = match position.direction.as_str() {
1005        "buy" => PositionSide::Long,
1006        "sell" => PositionSide::Short,
1007        _ => PositionSide::Flat,
1008    };
1009
1010    // Use average_price directly as it's already a Decimal
1011    let avg_px_open = Some(position.average_price);
1012
1013    PositionStatusReport::new(
1014        account_id,
1015        instrument_id,
1016        position_side,
1017        signed_qty,
1018        ts_init,
1019        ts_init,
1020        Some(UUID4::new()),
1021        None, // venue_position_id
1022        avg_px_open,
1023    )
1024}
1025
1026/// Parsed order event result from a Deribit order message.
1027///
1028/// This enum represents the discrete order events that can be derived from
1029/// Deribit order state transitions.
1030#[derive(Debug, Clone)]
1031pub enum ParsedOrderEvent {
1032    /// Order was accepted by the venue.
1033    Accepted(OrderAccepted),
1034    /// Order was canceled.
1035    Canceled(OrderCanceled),
1036    /// Order expired.
1037    Expired(OrderExpired),
1038    /// Order was updated (amended).
1039    Updated(OrderUpdated),
1040    /// No event to emit (e.g., already processed or intermediate state).
1041    None,
1042}
1043
1044/// Extracts the client order ID from a Deribit order message label.
1045fn extract_client_order_id(msg: &DeribitOrderMsg) -> Option<ClientOrderId> {
1046    msg.label
1047        .as_ref()
1048        .filter(|l| !l.is_empty())
1049        .map(ClientOrderId::new)
1050}
1051
1052/// Parses a Deribit order message into an `OrderAccepted` event.
1053///
1054/// This should be called when an order transitions to "open" state for the first time
1055/// or when a buy/sell response is received successfully.
1056#[must_use]
1057pub fn parse_order_accepted(
1058    msg: &DeribitOrderMsg,
1059    instrument: &InstrumentAny,
1060    account_id: AccountId,
1061    trader_id: TraderId,
1062    strategy_id: StrategyId,
1063    ts_init: UnixNanos,
1064) -> OrderAccepted {
1065    let client_order_id =
1066        extract_client_order_id(msg).unwrap_or_else(|| ClientOrderId::new(&msg.order_id));
1067    parse_order_accepted_with_client_order_id(
1068        msg,
1069        instrument,
1070        account_id,
1071        trader_id,
1072        strategy_id,
1073        client_order_id,
1074        ts_init,
1075    )
1076}
1077
1078#[must_use]
1079pub(crate) fn parse_order_accepted_with_client_order_id(
1080    msg: &DeribitOrderMsg,
1081    instrument: &InstrumentAny,
1082    account_id: AccountId,
1083    trader_id: TraderId,
1084    strategy_id: StrategyId,
1085    client_order_id: ClientOrderId,
1086    ts_init: UnixNanos,
1087) -> OrderAccepted {
1088    let instrument_id = instrument.id();
1089    let venue_order_id = VenueOrderId::new(&msg.order_id);
1090    let ts_event = UnixNanos::new(msg.last_update_timestamp * NANOSECONDS_IN_MILLISECOND);
1091
1092    OrderAccepted::new(
1093        trader_id,
1094        strategy_id,
1095        instrument_id,
1096        client_order_id,
1097        venue_order_id,
1098        account_id,
1099        nautilus_core::UUID4::new(),
1100        ts_event,
1101        ts_init,
1102        false, // reconciliation
1103    )
1104}
1105
1106/// Parses a Deribit order message into an `OrderCanceled` event.
1107///
1108/// This should be called when an order transitions to "cancelled" state.
1109#[must_use]
1110pub fn parse_order_canceled(
1111    msg: &DeribitOrderMsg,
1112    instrument: &InstrumentAny,
1113    account_id: AccountId,
1114    trader_id: TraderId,
1115    strategy_id: StrategyId,
1116    ts_init: UnixNanos,
1117) -> OrderCanceled {
1118    let client_order_id =
1119        extract_client_order_id(msg).unwrap_or_else(|| ClientOrderId::new(&msg.order_id));
1120    parse_order_canceled_with_client_order_id(
1121        msg,
1122        instrument,
1123        account_id,
1124        trader_id,
1125        strategy_id,
1126        client_order_id,
1127        ts_init,
1128    )
1129}
1130
1131#[must_use]
1132pub(crate) fn parse_order_canceled_with_client_order_id(
1133    msg: &DeribitOrderMsg,
1134    instrument: &InstrumentAny,
1135    account_id: AccountId,
1136    trader_id: TraderId,
1137    strategy_id: StrategyId,
1138    client_order_id: ClientOrderId,
1139    ts_init: UnixNanos,
1140) -> OrderCanceled {
1141    let instrument_id = instrument.id();
1142    let venue_order_id = VenueOrderId::new(&msg.order_id);
1143    let ts_event = UnixNanos::new(msg.last_update_timestamp * NANOSECONDS_IN_MILLISECOND);
1144
1145    OrderCanceled::new(
1146        trader_id,
1147        strategy_id,
1148        instrument_id,
1149        client_order_id,
1150        nautilus_core::UUID4::new(),
1151        ts_event,
1152        ts_init,
1153        false, // reconciliation
1154        Some(venue_order_id),
1155        Some(account_id),
1156        msg.cancel_reason.as_deref().map(Ustr::from),
1157    )
1158}
1159
1160/// Parses a Deribit order message into an `OrderExpired` event.
1161///
1162/// This should be called when an order transitions to "expired" state
1163/// (e.g., GTD orders that reached their expiry time).
1164#[must_use]
1165pub fn parse_order_expired(
1166    msg: &DeribitOrderMsg,
1167    instrument: &InstrumentAny,
1168    account_id: AccountId,
1169    trader_id: TraderId,
1170    strategy_id: StrategyId,
1171    ts_init: UnixNanos,
1172) -> OrderExpired {
1173    let client_order_id =
1174        extract_client_order_id(msg).unwrap_or_else(|| ClientOrderId::new(&msg.order_id));
1175    parse_order_expired_with_client_order_id(
1176        msg,
1177        instrument,
1178        account_id,
1179        trader_id,
1180        strategy_id,
1181        client_order_id,
1182        ts_init,
1183    )
1184}
1185
1186#[must_use]
1187pub(crate) fn parse_order_expired_with_client_order_id(
1188    msg: &DeribitOrderMsg,
1189    instrument: &InstrumentAny,
1190    account_id: AccountId,
1191    trader_id: TraderId,
1192    strategy_id: StrategyId,
1193    client_order_id: ClientOrderId,
1194    ts_init: UnixNanos,
1195) -> OrderExpired {
1196    let instrument_id = instrument.id();
1197    let venue_order_id = VenueOrderId::new(&msg.order_id);
1198    let ts_event = UnixNanos::new(msg.last_update_timestamp * NANOSECONDS_IN_MILLISECOND);
1199
1200    OrderExpired::new(
1201        trader_id,
1202        strategy_id,
1203        instrument_id,
1204        client_order_id,
1205        nautilus_core::UUID4::new(),
1206        ts_event,
1207        ts_init,
1208        false, // reconciliation
1209        Some(venue_order_id),
1210        Some(account_id),
1211    )
1212}
1213
1214/// Parses a Deribit order message into an `OrderUpdated` event.
1215///
1216/// This should be called when an order is amended (price or quantity changed).
1217#[must_use]
1218pub fn parse_order_updated(
1219    msg: &DeribitOrderMsg,
1220    instrument: &InstrumentAny,
1221    account_id: AccountId,
1222    trader_id: TraderId,
1223    strategy_id: StrategyId,
1224    ts_init: UnixNanos,
1225) -> OrderUpdated {
1226    let client_order_id =
1227        extract_client_order_id(msg).unwrap_or_else(|| ClientOrderId::new(&msg.order_id));
1228    parse_order_updated_with_client_order_id(
1229        msg,
1230        instrument,
1231        account_id,
1232        trader_id,
1233        strategy_id,
1234        client_order_id,
1235        ts_init,
1236    )
1237}
1238
1239#[must_use]
1240pub(crate) fn parse_order_updated_with_client_order_id(
1241    msg: &DeribitOrderMsg,
1242    instrument: &InstrumentAny,
1243    account_id: AccountId,
1244    trader_id: TraderId,
1245    strategy_id: StrategyId,
1246    client_order_id: ClientOrderId,
1247    ts_init: UnixNanos,
1248) -> OrderUpdated {
1249    let instrument_id = instrument.id();
1250    let price_precision = instrument.price_precision();
1251    let size_precision = instrument.size_precision();
1252
1253    let venue_order_id = VenueOrderId::new(&msg.order_id);
1254    let quantity = Quantity::from_decimal_dp(msg.amount, size_precision)
1255        .unwrap_or_else(|_| Quantity::zero(size_precision));
1256    let price = msg
1257        .price
1258        .and_then(|p| Price::from_decimal_dp(p, price_precision).ok());
1259    let trigger_price = msg
1260        .trigger_price
1261        .and_then(|p| Price::from_decimal_dp(p, price_precision).ok());
1262    let ts_event = UnixNanos::new(msg.last_update_timestamp * NANOSECONDS_IN_MILLISECOND);
1263
1264    OrderUpdated::new(
1265        trader_id,
1266        strategy_id,
1267        instrument_id,
1268        client_order_id,
1269        quantity,
1270        nautilus_core::UUID4::new(),
1271        ts_event,
1272        ts_init,
1273        false, // reconciliation
1274        Some(venue_order_id),
1275        Some(account_id),
1276        price,
1277        trigger_price,
1278        None,  // protection_price
1279        false, // is_quote_quantity
1280    )
1281}
1282
1283/// Determines the appropriate order event based on the Deribit order state.
1284///
1285/// This function analyzes the order state and returns the corresponding event type.
1286/// It's used by the handler to determine which event to emit for a given order update.
1287///
1288/// # Arguments
1289/// - `order_state` - The Deribit order state string ("open", "filled", "cancelled", etc.)
1290/// - `is_new_order` - Whether this is the first time we're seeing this order
1291/// - `was_amended` - Whether this update is due to an amendment (edit) operation
1292///
1293/// # Returns
1294/// The type of event that should be emitted, or `None` if no event should be emitted.
1295#[must_use]
1296pub fn determine_order_event_type(
1297    order_state: &str,
1298    is_new_order: bool,
1299    was_amended: bool,
1300) -> OrderEventType {
1301    match order_state {
1302        "open" | "untriggered" => {
1303            if was_amended {
1304                OrderEventType::Updated
1305            } else if is_new_order {
1306                OrderEventType::Accepted
1307            } else {
1308                // Order is still open, no event needed (partial fill handled separately)
1309                OrderEventType::None
1310            }
1311        }
1312        "cancelled" => OrderEventType::Canceled,
1313        "expired" => OrderEventType::Expired,
1314        "filled" => {
1315            // Fills are handled through the user.trades channel
1316            OrderEventType::None
1317        }
1318        "rejected" => {
1319            // Rejections are handled separately via OrderRejected
1320            OrderEventType::None
1321        }
1322        other => {
1323            log::warn!("Unknown Deribit order_state '{other}' in event routing, dropping");
1324            OrderEventType::None
1325        }
1326    }
1327}
1328
1329/// Order event type to be emitted.
1330#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1331pub enum OrderEventType {
1332    /// Emit OrderAccepted event.
1333    Accepted,
1334    /// Emit OrderCanceled event.
1335    Canceled,
1336    /// Emit OrderExpired event.
1337    Expired,
1338    /// Emit OrderUpdated event.
1339    Updated,
1340    /// No event to emit.
1341    None,
1342}
1343
1344#[cfg(test)]
1345mod tests {
1346    use nautilus_model::data::greeks::OptionGreekValues;
1347    use rstest::{fixture, rstest};
1348    use rust_decimal_macros::dec;
1349    use serde::de::DeserializeOwned;
1350
1351    use super::*;
1352    use crate::{
1353        common::{
1354            parse::{parse_deribit_instrument_any, parse_portfolio_to_account_state},
1355            testing::load_test_json,
1356        },
1357        http::models::{DeribitInstrument, DeribitJsonRpcResponse},
1358        websocket::messages::{DeribitPortfolioMsg, DeribitWsMessage, parse_raw_message},
1359    };
1360
1361    /// Creates a BTC-PERPETUAL test instrument.
1362    fn test_perpetual_instrument() -> InstrumentAny {
1363        let json = load_test_json("http_get_instruments.json");
1364        let response: DeribitJsonRpcResponse<Vec<DeribitInstrument>> =
1365            serde_json::from_str(&json).unwrap();
1366        let instrument = &response.result.unwrap()[0];
1367        parse_deribit_instrument_any(instrument, UnixNanos::default(), UnixNanos::default())
1368            .unwrap()
1369            .unwrap()
1370    }
1371
1372    #[rstest]
1373    fn test_parse_trade_msg_sell() {
1374        let instrument = test_perpetual_instrument();
1375        let json = load_test_json("ws_trades.json");
1376        let response: serde_json::Value = serde_json::from_str(&json).unwrap();
1377        let trades: Vec<DeribitTradeMsg> =
1378            serde_json::from_str(&response["params"]["data"].to_string()).unwrap();
1379        let msg = &trades[0];
1380
1381        let tick = parse_trade_msg(msg, &instrument, UnixNanos::default()).unwrap();
1382
1383        assert_eq!(tick.instrument_id, instrument.id());
1384        assert_eq!(tick.price, instrument.make_price(92294.5));
1385        assert_eq!(tick.size, instrument.make_qty(10.0, None));
1386        assert_eq!(tick.aggressor_side, AggressorSide::Sell);
1387        assert_eq!(tick.trade_id.to_string(), "403691824");
1388        assert_eq!(tick.ts_event, UnixNanos::new(1_765_531_356_452_000_000));
1389    }
1390
1391    #[rstest]
1392    fn test_parse_trade_msg_buy() {
1393        let instrument = test_perpetual_instrument();
1394        let json = load_test_json("ws_trades.json");
1395        let response: serde_json::Value = serde_json::from_str(&json).unwrap();
1396        let trades: Vec<DeribitTradeMsg> =
1397            serde_json::from_str(&response["params"]["data"].to_string()).unwrap();
1398        let msg = &trades[1];
1399
1400        let tick = parse_trade_msg(msg, &instrument, UnixNanos::default()).unwrap();
1401
1402        assert_eq!(tick.instrument_id, instrument.id());
1403        assert_eq!(tick.price, instrument.make_price(92288.5));
1404        assert_eq!(tick.size, instrument.make_qty(750.0, None));
1405        assert_eq!(tick.aggressor_side, AggressorSide::Sell);
1406        assert_eq!(tick.trade_id.to_string(), "403691825");
1407    }
1408
1409    fn make_trade_msg(
1410        instrument_name: &str,
1411        trade_id: &str,
1412        block_trade_id: Option<&str>,
1413        block_rfq_id: Option<i64>,
1414        combo_id: Option<&str>,
1415    ) -> DeribitTradeMsg {
1416        let raw = serde_json::json!({
1417            "trade_id": trade_id,
1418            "instrument_name": instrument_name,
1419            "price": 92294.5,
1420            "amount": 10.0,
1421            "direction": "buy",
1422            "timestamp": 1_765_531_356_452_u64,
1423            "trade_seq": 1,
1424            "tick_direction": 0,
1425            "index_price": 92276.75,
1426            "mark_price": 92287.11,
1427            "block_trade_id": block_trade_id,
1428            "block_rfq_id": block_rfq_id,
1429            "combo_id": combo_id,
1430        });
1431        serde_json::from_str(&raw.to_string()).unwrap()
1432    }
1433
1434    #[rstest]
1435    fn test_parse_trade_msg_tags_block_trade() {
1436        let instrument = test_perpetual_instrument();
1437        let msg = make_trade_msg("BTC-PERPETUAL", "244343055", Some("12345"), None, None);
1438        let tick = parse_trade_msg(&msg, &instrument, UnixNanos::default()).unwrap();
1439        assert_eq!(tick.trade_id.to_string(), "BLK-244343055");
1440    }
1441
1442    #[rstest]
1443    fn test_parse_trade_msg_tags_block_rfq() {
1444        let instrument = test_perpetual_instrument();
1445        let msg = make_trade_msg("BTC-PERPETUAL", "244343055", None, Some(99), None);
1446        let tick = parse_trade_msg(&msg, &instrument, UnixNanos::default()).unwrap();
1447        assert_eq!(tick.trade_id.to_string(), "RFQ-244343055");
1448    }
1449
1450    #[rstest]
1451    fn test_parse_trade_msg_tags_combo_leg() {
1452        // Per-leg trade originating from a combo: combo_id is set by Deribit
1453        // even though the instrument is a plain perp / option, so downstream
1454        // sees `COMBO-` and can detect combo-origin fills.
1455        let instrument = test_perpetual_instrument();
1456        let msg = make_trade_msg(
1457            "BTC-PERPETUAL",
1458            "244343055",
1459            None,
1460            None,
1461            Some("BTC-FS-25DEC26_PERP"),
1462        );
1463        let tick = parse_trade_msg(&msg, &instrument, UnixNanos::default()).unwrap();
1464        assert_eq!(tick.trade_id.to_string(), "COMBO-244343055");
1465    }
1466
1467    fn load_combo_option_instrument() -> InstrumentAny {
1468        let combo_json = load_test_json("http_get_instruments_option_combo.json");
1469        let combo_response: DeribitJsonRpcResponse<Vec<DeribitInstrument>> =
1470            serde_json::from_str(&combo_json).unwrap();
1471        let combo_raw = combo_response
1472            .result
1473            .unwrap()
1474            .into_iter()
1475            .find(|i| i.instrument_name == "BTC-CS-19MAY26-70000_75000")
1476            .expect("fixture must contain BTC-CS-19MAY26-70000_75000");
1477        parse_deribit_instrument_any(&combo_raw, UnixNanos::default(), UnixNanos::default())
1478            .unwrap()
1479            .unwrap()
1480    }
1481
1482    fn load_combo_trade_msgs() -> Vec<DeribitTradeMsg> {
1483        let json = load_test_json("ws_trades_option_combo.json");
1484        let response: serde_json::Value = serde_json::from_str(&json).unwrap();
1485        serde_json::from_str(&response["params"]["data"].to_string()).unwrap()
1486    }
1487
1488    #[rstest]
1489    fn test_parse_trades_data_combo_emits_single_tick() {
1490        // Step 1 finding: combo legs already publish on their own per-leg
1491        // streams. Parsing a combo trade message should produce exactly one
1492        // TradeTick (for the combo), not N+1.
1493        let combo_inst = load_combo_option_instrument();
1494        let mut cache: AHashMap<Ustr, InstrumentAny> = AHashMap::new();
1495        cache.insert(Ustr::from("BTC-CS-19MAY26-70000_75000"), combo_inst.clone());
1496
1497        let trades = load_combo_trade_msgs();
1498        // Sanity: the combo message itself carries the legs array.
1499        let legs = trades[0].legs.as_ref().expect("combo trade must have legs");
1500        assert_eq!(legs.len(), 2);
1501
1502        let data = parse_trades_data(&trades, &cache, UnixNanos::default());
1503        assert_eq!(data.len(), 1, "should emit one tick for the combo only");
1504
1505        let Data::Trade(tick) = &data[0] else {
1506            panic!("expected Data::Trade");
1507        };
1508        assert_eq!(tick.instrument_id, combo_inst.id());
1509        // Exact values from fixture; independent of the instrument under test
1510        // so a regression in price/size precision is caught here too.
1511        assert_eq!(tick.price, Price::from("0.0639"));
1512        assert_eq!(tick.size, Quantity::from("0.1"));
1513        assert_eq!(tick.aggressor_side, AggressorSide::Sell);
1514        assert_eq!(tick.trade_id.to_string(), "244365193");
1515    }
1516
1517    #[rstest]
1518    fn test_parse_trades_data_combo_not_cached_emits_no_tick() {
1519        // When the combo InstrumentAny is not in the WS handler cache,
1520        // parse_trades_data must drop the message rather than panic or
1521        // synthesize a tick against an unknown instrument.
1522        let cache: AHashMap<Ustr, InstrumentAny> = AHashMap::new();
1523        let trades = load_combo_trade_msgs();
1524        let data = parse_trades_data(&trades, &cache, UnixNanos::default());
1525        assert!(data.is_empty(), "uncached combo must not emit ticks");
1526    }
1527
1528    #[rstest]
1529    fn test_parse_trades_data_mixed_combo_and_per_leg() {
1530        // Combo trade and a plain per-leg trade on the underlying perpetual,
1531        // both cached, must each produce a tick against their own instrument.
1532        let combo_inst = load_combo_option_instrument();
1533        let perp_inst = test_perpetual_instrument();
1534
1535        let mut cache: AHashMap<Ustr, InstrumentAny> = AHashMap::new();
1536        cache.insert(Ustr::from("BTC-CS-19MAY26-70000_75000"), combo_inst.clone());
1537        cache.insert(Ustr::from("BTC-PERPETUAL"), perp_inst.clone());
1538
1539        let mut trades = load_combo_trade_msgs();
1540        let perp_msgs: Vec<DeribitTradeMsg> = {
1541            let json = load_test_json("ws_trades.json");
1542            let response: serde_json::Value = serde_json::from_str(&json).unwrap();
1543            serde_json::from_str(&response["params"]["data"].to_string()).unwrap()
1544        };
1545        trades.extend(perp_msgs);
1546
1547        let data = parse_trades_data(&trades, &cache, UnixNanos::default());
1548        // 1 combo + 2 plain BTC-PERPETUAL trades from the existing fixture.
1549        assert_eq!(data.len(), 3);
1550
1551        let mut combo_ticks = 0;
1552        let mut perp_ticks = 0;
1553
1554        for item in &data {
1555            let Data::Trade(tick) = item else {
1556                panic!("expected Data::Trade, was {item:?}");
1557            };
1558
1559            if tick.instrument_id == combo_inst.id() {
1560                combo_ticks += 1;
1561                assert_eq!(tick.trade_id.to_string(), "244365193");
1562            } else if tick.instrument_id == perp_inst.id() {
1563                perp_ticks += 1;
1564            } else {
1565                panic!("unexpected instrument_id: {}", tick.instrument_id);
1566            }
1567        }
1568        assert_eq!(combo_ticks, 1);
1569        assert_eq!(perp_ticks, 2);
1570    }
1571
1572    #[rstest]
1573    fn test_parse_book_snapshot() {
1574        let instrument = test_perpetual_instrument();
1575        let json = load_test_json("ws_book_snapshot.json");
1576        let response: serde_json::Value = serde_json::from_str(&json).unwrap();
1577        let data = response["params"]["data"].to_string();
1578        let msg: DeribitBookMsg = serde_json::from_str(&data).unwrap();
1579
1580        let deltas = parse_book_snapshot(&msg, &instrument, UnixNanos::default()).unwrap();
1581
1582        assert_eq!(deltas.instrument_id, instrument.id());
1583        // Should have CLEAR + 5 bids + 5 asks = 11 deltas
1584        assert_eq!(deltas.deltas.len(), 11);
1585
1586        // First delta should be CLEAR
1587        assert_eq!(deltas.deltas[0].action, BookAction::Clear);
1588
1589        // Check first bid
1590        let first_bid = &deltas.deltas[1];
1591        assert_eq!(first_bid.action, BookAction::Add);
1592        assert_eq!(first_bid.order.side, OrderSide::Buy.into());
1593        assert_eq!(first_bid.order.price, instrument.make_price(42500.0));
1594        assert_eq!(first_bid.order.size, instrument.make_qty(1000.0, None));
1595
1596        // Check first ask
1597        let first_ask = &deltas.deltas[6];
1598        assert_eq!(first_ask.action, BookAction::Add);
1599        assert_eq!(first_ask.order.side, OrderSide::Sell.into());
1600        assert_eq!(first_ask.order.price, instrument.make_price(42501.0));
1601        assert_eq!(first_ask.order.size, instrument.make_qty(800.0, None));
1602
1603        // Check F_LAST flag on last delta
1604        let last = deltas.deltas.last().unwrap();
1605        assert_eq!(
1606            last.flags & RecordFlag::F_LAST as u8,
1607            RecordFlag::F_LAST as u8
1608        );
1609    }
1610
1611    #[rstest]
1612    fn test_parse_book_delta() {
1613        let instrument = test_perpetual_instrument();
1614        let json = load_test_json("ws_book_delta.json");
1615        let response: serde_json::Value = serde_json::from_str(&json).unwrap();
1616        let data = response["params"]["data"].to_string();
1617        let msg: DeribitBookMsg = serde_json::from_str(&data).unwrap();
1618
1619        let deltas = parse_book_delta(&msg, &instrument, UnixNanos::default()).unwrap();
1620
1621        assert_eq!(deltas.instrument_id, instrument.id());
1622        // Should have 2 bid deltas + 2 ask deltas = 4 deltas
1623        assert_eq!(deltas.deltas.len(), 4);
1624
1625        // Check first bid - "change" action
1626        let bid_change = &deltas.deltas[0];
1627        assert_eq!(bid_change.action, BookAction::Update);
1628        assert_eq!(bid_change.order.side, OrderSide::Buy.into());
1629        assert_eq!(bid_change.order.price, instrument.make_price(42500.0));
1630        assert_eq!(bid_change.order.size, instrument.make_qty(950.0, None));
1631
1632        // Check second bid - "new" action
1633        let bid_new = &deltas.deltas[1];
1634        assert_eq!(bid_new.action, BookAction::Add);
1635        assert_eq!(bid_new.order.side, OrderSide::Buy.into());
1636        assert_eq!(bid_new.order.price, instrument.make_price(42498.5));
1637        assert_eq!(bid_new.order.size, instrument.make_qty(300.0, None));
1638
1639        // Check first ask - "delete" action
1640        let ask_delete = &deltas.deltas[2];
1641        assert_eq!(ask_delete.action, BookAction::Delete);
1642        assert_eq!(ask_delete.order.side, OrderSide::Sell.into());
1643        assert_eq!(ask_delete.order.price, instrument.make_price(42501.0));
1644        assert_eq!(ask_delete.order.size, instrument.make_qty(0.0, None));
1645
1646        // Check second ask - "change" action
1647        let ask_change = &deltas.deltas[3];
1648        assert_eq!(ask_change.action, BookAction::Update);
1649        assert_eq!(ask_change.order.side, OrderSide::Sell.into());
1650        assert_eq!(ask_change.order.price, instrument.make_price(42501.5));
1651        assert_eq!(ask_change.order.size, instrument.make_qty(700.0, None));
1652
1653        // Check F_LAST flag on last delta
1654        let last = deltas.deltas.last().unwrap();
1655        assert_eq!(
1656            last.flags & RecordFlag::F_LAST as u8,
1657            RecordFlag::F_LAST as u8
1658        );
1659    }
1660
1661    #[rstest]
1662    fn test_parse_ticker_to_quote() {
1663        let instrument = test_perpetual_instrument();
1664        let json = load_test_json("ws_ticker.json");
1665        let response: serde_json::Value = serde_json::from_str(&json).unwrap();
1666        let msg: DeribitTickerMsg =
1667            serde_json::from_str(&response["params"]["data"].to_string()).unwrap();
1668
1669        // Verify the message was deserialized correctly
1670        assert_eq!(msg.instrument_name, "BTC-PERPETUAL");
1671        assert_eq!(msg.timestamp, 1_765_541_474_086);
1672        assert_eq!(msg.best_bid_price, Some(dec!(92283.5)));
1673        assert_eq!(msg.best_ask_price, Some(dec!(92284.0)));
1674        assert_eq!(msg.best_bid_amount, Some(dec!(117660.0)));
1675        assert_eq!(msg.best_ask_amount, Some(dec!(186520.0)));
1676        assert_eq!(msg.mark_price, dec!(92281.78));
1677        assert_eq!(msg.index_price, dec!(92263.55));
1678        assert_eq!(msg.open_interest, dec!(1132329370.0));
1679
1680        let quote = parse_ticker_to_quote(&msg, &instrument, UnixNanos::default()).unwrap();
1681
1682        assert_eq!(quote.instrument_id, instrument.id());
1683        assert_eq!(quote.bid_price, instrument.make_price(92283.5));
1684        assert_eq!(quote.ask_price, instrument.make_price(92284.0));
1685        assert_eq!(quote.bid_size, instrument.make_qty(117660.0, None));
1686        assert_eq!(quote.ask_size, instrument.make_qty(186520.0, None));
1687        assert_eq!(quote.ts_event, UnixNanos::new(1_765_541_474_086_000_000));
1688    }
1689
1690    #[rstest]
1691    fn test_parse_quote_msg() {
1692        let instrument = test_perpetual_instrument();
1693        let json = load_test_json("ws_quote.json");
1694        let response: serde_json::Value = serde_json::from_str(&json).unwrap();
1695        let msg: DeribitQuoteMsg =
1696            serde_json::from_str(&response["params"]["data"].to_string()).unwrap();
1697
1698        // Verify the message was deserialized correctly
1699        assert_eq!(msg.instrument_name, "BTC-PERPETUAL");
1700        assert_eq!(msg.timestamp, 1_765_541_767_174);
1701        assert_eq!(msg.best_bid_price, dec!(92288.0));
1702        assert_eq!(msg.best_ask_price, dec!(92288.5));
1703        assert_eq!(msg.best_bid_amount, dec!(133440.0));
1704        assert_eq!(msg.best_ask_amount, dec!(99470.0));
1705
1706        let quote = parse_quote_msg(&msg, &instrument, UnixNanos::default()).unwrap();
1707
1708        assert_eq!(quote.instrument_id, instrument.id());
1709        assert_eq!(quote.bid_price, instrument.make_price(92288.0));
1710        assert_eq!(quote.ask_price, instrument.make_price(92288.5));
1711        assert_eq!(quote.bid_size, instrument.make_qty(133440.0, None));
1712        assert_eq!(quote.ask_size, instrument.make_qty(99470.0, None));
1713        assert_eq!(quote.ts_event, UnixNanos::new(1_765_541_767_174_000_000));
1714    }
1715
1716    #[rstest]
1717    fn test_parse_book_msg_snapshot() {
1718        let instrument = test_perpetual_instrument();
1719        let json = load_test_json("ws_book_snapshot.json");
1720        let response: serde_json::Value = serde_json::from_str(&json).unwrap();
1721        let data = response["params"]["data"].to_string();
1722        let msg: DeribitBookMsg = serde_json::from_str(&data).unwrap();
1723
1724        // Validate raw message format - snapshots use 3-element arrays: ["new", price, amount]
1725        assert_eq!(
1726            msg.bids[0].len(),
1727            3,
1728            "Snapshot bids should have 3 elements: [action, price, amount]"
1729        );
1730        assert_eq!(
1731            msg.bids[0][0].get(),
1732            r#""new""#,
1733            "First element should be 'new' action for snapshot"
1734        );
1735        assert_eq!(
1736            msg.asks[0].len(),
1737            3,
1738            "Snapshot asks should have 3 elements: [action, price, amount]"
1739        );
1740        assert_eq!(
1741            msg.asks[0][0].get(),
1742            r#""new""#,
1743            "First element should be 'new' action for snapshot"
1744        );
1745
1746        let deltas = parse_book_msg(&msg, &instrument, UnixNanos::default()).unwrap();
1747
1748        assert_eq!(deltas.instrument_id, instrument.id());
1749        // Should have CLEAR + 5 bids + 5 asks = 11 deltas
1750        assert_eq!(deltas.deltas.len(), 11);
1751
1752        // First delta should be CLEAR
1753        assert_eq!(deltas.deltas[0].action, BookAction::Clear);
1754
1755        // Verify first bid was parsed correctly from ["new", 42500.0, 1000.0]
1756        let first_bid = &deltas.deltas[1];
1757        assert_eq!(first_bid.action, BookAction::Add);
1758        assert_eq!(first_bid.order.side, OrderSide::Buy.into());
1759        assert_eq!(first_bid.order.price, instrument.make_price(42500.0));
1760        assert_eq!(first_bid.order.size, instrument.make_qty(1000.0, None));
1761
1762        // Verify first ask was parsed correctly from ["new", 42501.0, 800.0]
1763        let first_ask = &deltas.deltas[6];
1764        assert_eq!(first_ask.action, BookAction::Add);
1765        assert_eq!(first_ask.order.side, OrderSide::Sell.into());
1766        assert_eq!(first_ask.order.price, instrument.make_price(42501.0));
1767        assert_eq!(first_ask.order.size, instrument.make_qty(800.0, None));
1768    }
1769
1770    #[rstest]
1771    fn test_parse_book_msg_delta() {
1772        let instrument = test_perpetual_instrument();
1773        let json = load_test_json("ws_book_delta.json");
1774        let response: serde_json::Value = serde_json::from_str(&json).unwrap();
1775        let data = response["params"]["data"].to_string();
1776        let msg: DeribitBookMsg = serde_json::from_str(&data).unwrap();
1777
1778        // Validate raw message format - deltas use 3-element arrays: [action, price, amount]
1779        assert_eq!(
1780            msg.bids[0].len(),
1781            3,
1782            "Delta bids should have 3 elements: [action, price, amount]"
1783        );
1784        assert_eq!(
1785            msg.bids[0][0].get(),
1786            r#""change""#,
1787            "First bid should be 'change' action"
1788        );
1789        assert_eq!(
1790            msg.bids[1][0].get(),
1791            r#""new""#,
1792            "Second bid should be 'new' action"
1793        );
1794        assert_eq!(
1795            msg.asks[0].len(),
1796            3,
1797            "Delta asks should have 3 elements: [action, price, amount]"
1798        );
1799        assert_eq!(
1800            msg.asks[0][0].get(),
1801            r#""delete""#,
1802            "First ask should be 'delete' action"
1803        );
1804
1805        let deltas = parse_book_msg(&msg, &instrument, UnixNanos::default()).unwrap();
1806
1807        assert_eq!(deltas.instrument_id, instrument.id());
1808        // Should have 2 bid deltas + 2 ask deltas = 4 deltas
1809        assert_eq!(deltas.deltas.len(), 4);
1810
1811        // Delta should not have CLEAR action
1812        assert_ne!(deltas.deltas[0].action, BookAction::Clear);
1813
1814        // Verify first bid "change" action was parsed correctly from ["change", 42500.0, 950.0]
1815        let bid_change = &deltas.deltas[0];
1816        assert_eq!(bid_change.action, BookAction::Update);
1817        assert_eq!(bid_change.order.side, OrderSide::Buy.into());
1818        assert_eq!(bid_change.order.price, instrument.make_price(42500.0));
1819        assert_eq!(bid_change.order.size, instrument.make_qty(950.0, None));
1820
1821        // Verify second bid "new" action was parsed correctly from ["new", 42498.5, 300.0]
1822        let bid_new = &deltas.deltas[1];
1823        assert_eq!(bid_new.action, BookAction::Add);
1824        assert_eq!(bid_new.order.side, OrderSide::Buy.into());
1825        assert_eq!(bid_new.order.price, instrument.make_price(42498.5));
1826        assert_eq!(bid_new.order.size, instrument.make_qty(300.0, None));
1827
1828        // Verify first ask "delete" action was parsed correctly from ["delete", 42501.0, 0.0]
1829        let ask_delete = &deltas.deltas[2];
1830        assert_eq!(ask_delete.action, BookAction::Delete);
1831        assert_eq!(ask_delete.order.side, OrderSide::Sell.into());
1832        assert_eq!(ask_delete.order.price, instrument.make_price(42501.0));
1833
1834        // Verify second ask "change" action was parsed correctly from ["change", 42501.5, 700.0]
1835        let ask_change = &deltas.deltas[3];
1836        assert_eq!(ask_change.action, BookAction::Update);
1837        assert_eq!(ask_change.order.side, OrderSide::Sell.into());
1838        assert_eq!(ask_change.order.price, instrument.make_price(42501.5));
1839        assert_eq!(ask_change.order.size, instrument.make_qty(700.0, None));
1840    }
1841
1842    #[rstest]
1843    fn test_parse_book_grouped_snapshot() {
1844        // Test parsing grouped book channel format: book.{instrument}.{group}.{depth}.{interval}
1845        // This format has NO type field and uses 2-element arrays [price, amount]
1846        let instrument = test_perpetual_instrument();
1847        let json = load_test_json("ws_book_grouped_snapshot.json");
1848        let response: serde_json::Value = serde_json::from_str(&json).unwrap();
1849        let data = response["params"]["data"].to_string();
1850        let msg: DeribitBookMsg = serde_json::from_str(&data).unwrap();
1851
1852        // Validate raw message format - grouped channel uses 2-element arrays: [price, amount]
1853        assert_eq!(
1854            msg.bids[0].len(),
1855            2,
1856            "Grouped bids should have 2 elements: [price, amount]"
1857        );
1858        assert_eq!(
1859            msg.asks[0].len(),
1860            2,
1861            "Grouped asks should have 2 elements: [price, amount]"
1862        );
1863
1864        // Verify msg_type defaults to Snapshot (grouped channel has no type field)
1865        assert_eq!(
1866            msg.msg_type,
1867            DeribitBookMsgType::Snapshot,
1868            "Grouped channel should default to Snapshot type"
1869        );
1870
1871        let deltas = parse_book_snapshot(&msg, &instrument, UnixNanos::default()).unwrap();
1872
1873        assert_eq!(deltas.instrument_id, instrument.id());
1874        // Should have CLEAR + 10 bids + 10 asks = 21 deltas
1875        assert_eq!(deltas.deltas.len(), 21);
1876
1877        // First delta should be CLEAR
1878        assert_eq!(deltas.deltas[0].action, BookAction::Clear);
1879
1880        // Verify first bid was parsed correctly from [89532.5, 254900.0]
1881        let first_bid = &deltas.deltas[1];
1882        assert_eq!(first_bid.action, BookAction::Add);
1883        assert_eq!(first_bid.order.side, OrderSide::Buy.into());
1884        assert_eq!(first_bid.order.price, instrument.make_price(89532.5));
1885        assert_eq!(first_bid.order.size, instrument.make_qty(254900.0, None));
1886
1887        // Verify first ask was parsed correctly from [89533.0, 91570.0]
1888        let first_ask = &deltas.deltas[11];
1889        assert_eq!(first_ask.action, BookAction::Add);
1890        assert_eq!(first_ask.order.side, OrderSide::Sell.into());
1891        assert_eq!(first_ask.order.price, instrument.make_price(89533.0));
1892        assert_eq!(first_ask.order.size, instrument.make_qty(91570.0, None));
1893
1894        // Check F_LAST flag on last delta
1895        let last = deltas.deltas.last().unwrap();
1896        assert_eq!(
1897            last.flags & RecordFlag::F_LAST as u8,
1898            RecordFlag::F_LAST as u8
1899        );
1900    }
1901
1902    #[rstest]
1903    #[case::populated(true, true)]
1904    #[case::bids_only(true, false)]
1905    #[case::asks_only(false, true)]
1906    #[case::empty(false, false)]
1907    fn test_parse_book_depth(#[case] has_bids: bool, #[case] has_asks: bool) {
1908        let instrument = test_perpetual_instrument();
1909        let json = load_test_json("ws_book_grouped_snapshot.json");
1910        let mut response: serde_json::Value = serde_json::from_str(&json).unwrap();
1911        if !has_bids {
1912            response["params"]["data"]["bids"] = serde_json::json!([]);
1913        }
1914
1915        if !has_asks {
1916            response["params"]["data"]["asks"] = serde_json::json!([]);
1917        }
1918
1919        let data = response["params"]["data"].to_string();
1920        let msg: DeribitBookMsg = serde_json::from_str(&data).unwrap();
1921        let ts_init = UnixNanos::new(1_769_246_173_072_123_456);
1922        let depth = parse_book_depth(&msg, &instrument, ts_init).unwrap();
1923
1924        let bids = if has_bids {
1925            vec![
1926                ("89532.5", "254900"),
1927                ("89532.0", "1000"),
1928                ("89531.0", "2000"),
1929                ("89529.5", "3530"),
1930                ("89529.0", "4030"),
1931                ("89528.0", "500"),
1932                ("89527.5", "35170"),
1933                ("89526.0", "75010"),
1934                ("89525.0", "10000"),
1935                ("89523.5", "11000"),
1936            ]
1937        } else {
1938            vec![]
1939        };
1940
1941        let asks = if has_asks {
1942            vec![
1943                ("89533.0", "91570"),
1944                ("89533.5", "10000"),
1945                ("89537.0", "13290"),
1946                ("89538.5", "6990"),
1947                ("89540.0", "11000"),
1948                ("89540.5", "26520"),
1949                ("89541.0", "3550"),
1950                ("89542.5", "11000"),
1951                ("89543.0", "480"),
1952                ("89545.5", "29500"),
1953            ]
1954        } else {
1955            vec![]
1956        };
1957
1958        let bid_count = bids.len();
1959        let ask_count = asks.len();
1960
1961        let bids: Vec<_> = bids
1962            .into_iter()
1963            .enumerate()
1964            .map(|(i, (price, size))| {
1965                BookOrder::new(
1966                    OrderSide::Buy,
1967                    Price::from(price),
1968                    Quantity::from(size),
1969                    i as u64,
1970                )
1971            })
1972            .collect();
1973
1974        let asks: Vec<_> = asks
1975            .into_iter()
1976            .enumerate()
1977            .map(|(i, (price, size))| {
1978                BookOrder::new(
1979                    OrderSide::Sell,
1980                    Price::from(price),
1981                    Quantity::from(size),
1982                    (bid_count + i) as u64,
1983                )
1984            })
1985            .collect();
1986
1987        let expected = OrderBookDepth::new(
1988            InstrumentId::from("BTC-PERPETUAL.DERIBIT"),
1989            bids,
1990            asks,
1991            vec![0; bid_count],
1992            vec![0; ask_count],
1993            RecordFlag::F_SNAPSHOT as u8 | RecordFlag::F_LAST as u8,
1994            136_725_664_747,
1995            UnixNanos::new(1_769_246_173_071_000_000),
1996            ts_init,
1997        );
1998
1999        assert_eq!(depth, expected);
2000    }
2001
2002    #[rstest]
2003    fn test_parse_ticker_to_mark_price() {
2004        let instrument = test_perpetual_instrument();
2005        let json = load_test_json("ws_ticker.json");
2006        let response: serde_json::Value = serde_json::from_str(&json).unwrap();
2007        let msg: DeribitTickerMsg =
2008            serde_json::from_str(&response["params"]["data"].to_string()).unwrap();
2009
2010        let mark_price =
2011            parse_ticker_to_mark_price(&msg, &instrument, UnixNanos::default()).unwrap();
2012
2013        assert_eq!(mark_price.instrument_id, instrument.id());
2014        assert_eq!(mark_price.value, instrument.make_price(92281.78));
2015        assert_eq!(
2016            mark_price.ts_event,
2017            UnixNanos::new(1_765_541_474_086_000_000)
2018        );
2019    }
2020
2021    #[rstest]
2022    fn test_parse_ticker_to_index_price() {
2023        let instrument = test_perpetual_instrument();
2024        let json = load_test_json("ws_ticker.json");
2025        let response: serde_json::Value = serde_json::from_str(&json).unwrap();
2026        let msg: DeribitTickerMsg =
2027            serde_json::from_str(&response["params"]["data"].to_string()).unwrap();
2028
2029        let index_price =
2030            parse_ticker_to_index_price(&msg, &instrument, UnixNanos::default()).unwrap();
2031
2032        assert_eq!(index_price.instrument_id, instrument.id());
2033        assert_eq!(index_price.value, instrument.make_price(92263.55));
2034        assert_eq!(
2035            index_price.ts_event,
2036            UnixNanos::new(1_765_541_474_086_000_000)
2037        );
2038    }
2039
2040    #[rstest]
2041    #[case::all_present(Some(dec!(55.2)), Some(dec!(54.0)), Some(dec!(56.5)))]
2042    #[case::missing_mark(None, Some(dec!(54.0)), Some(dec!(56.5)))]
2043    #[case::missing_bid(Some(dec!(55.2)), None, Some(dec!(56.5)))]
2044    #[case::missing_ask(Some(dec!(55.2)), Some(dec!(54.0)), None)]
2045    #[case::all_missing(None, None, None)]
2046    fn test_parse_ticker_to_option_greeks(
2047        option_ticker: (DeribitTickerMsg, InstrumentAny),
2048        #[case] mark_iv: Option<Decimal>,
2049        #[case] bid_iv: Option<Decimal>,
2050        #[case] ask_iv: Option<Decimal>,
2051    ) {
2052        let (mut msg, instrument) = option_ticker;
2053        msg.mark_iv = mark_iv;
2054        msg.bid_iv = bid_iv;
2055        msg.ask_iv = ask_iv;
2056        let ts_init = UnixNanos::new(1_765_541_474_087_000_000);
2057
2058        let greeks = parse_ticker_to_option_greeks(&msg, &instrument, ts_init).unwrap();
2059
2060        assert_eq!(
2061            greeks.instrument_id,
2062            InstrumentId::from("BTC-27DEC24-100000-C.DERIBIT"),
2063        );
2064        assert_eq!(greeks.convention, GreeksConvention::BlackScholes);
2065        assert_eq!(
2066            greeks.greeks,
2067            OptionGreekValues {
2068                delta: 0.45,
2069                gamma: 0.00012,
2070                vega: 14.25,
2071                theta: -23.5,
2072                rho: 8.75,
2073            },
2074        );
2075
2076        for (actual, expected) in [
2077            (greeks.mark_iv, mark_iv.map(|_| 0.552)),
2078            (greeks.bid_iv, bid_iv.map(|_| 0.54)),
2079            (greeks.ask_iv, ask_iv.map(|_| 0.565)),
2080        ] {
2081            match expected {
2082                Some(expected) => assert!((actual.unwrap() - expected).abs() < 1e-12),
2083                None => assert_eq!(actual, None),
2084            }
2085        }
2086
2087        assert_eq!(greeks.underlying_price, Some(95000.5));
2088        assert_eq!(greeks.open_interest, Some(123.5));
2089        assert_eq!(greeks.ts_event, UnixNanos::new(1_765_541_474_086_000_000));
2090        assert_eq!(greeks.ts_init, ts_init);
2091        assert_eq!(msg.mark_iv, mark_iv);
2092        assert_eq!(msg.bid_iv, bid_iv);
2093        assert_eq!(msg.ask_iv, ask_iv);
2094    }
2095
2096    #[rstest]
2097    fn test_parse_ticker_to_option_greeks_without_greeks(
2098        option_ticker: (DeribitTickerMsg, InstrumentAny),
2099    ) {
2100        let (mut msg, instrument) = option_ticker;
2101        msg.greeks = None;
2102
2103        assert_eq!(
2104            parse_ticker_to_option_greeks(&msg, &instrument, UnixNanos::default()),
2105            None,
2106        );
2107    }
2108
2109    #[fixture]
2110    fn option_ticker() -> (DeribitTickerMsg, InstrumentAny) {
2111        let json = load_test_json("http_get_instrument_option.json");
2112        let response: DeribitJsonRpcResponse<DeribitInstrument> =
2113            serde_json::from_str(&json).unwrap();
2114        let instrument = parse_deribit_instrument_any(
2115            &response.result.unwrap(),
2116            UnixNanos::default(),
2117            UnixNanos::default(),
2118        )
2119        .unwrap()
2120        .unwrap();
2121        let json = load_test_json("ws_ticker_option.json");
2122        let response: serde_json::Value = serde_json::from_str(&json).unwrap();
2123        let msg = serde_json::from_str(&response["params"]["data"].to_string()).unwrap();
2124        (msg, instrument)
2125    }
2126
2127    #[rstest]
2128    fn test_parse_ticker_to_funding_rate() {
2129        let instrument = test_perpetual_instrument();
2130        let json = load_test_json("ws_ticker.json");
2131        let response: serde_json::Value = serde_json::from_str(&json).unwrap();
2132        let msg: DeribitTickerMsg =
2133            serde_json::from_str(&response["params"]["data"].to_string()).unwrap();
2134
2135        // Verify current_funding exists in the message
2136        assert!(msg.current_funding.is_some());
2137
2138        let funding_rate =
2139            parse_ticker_to_funding_rate(&msg, &instrument, UnixNanos::default()).unwrap();
2140
2141        assert_eq!(funding_rate.instrument_id, instrument.id());
2142        // The test fixture has current_funding value
2143        assert_eq!(
2144            funding_rate.ts_event,
2145            UnixNanos::new(1_765_541_474_086_000_000)
2146        );
2147        assert!(funding_rate.interval.is_none());
2148        assert!(funding_rate.next_funding_ns.is_none()); // Not available in ticker
2149    }
2150
2151    #[rstest]
2152    fn test_resolution_to_bar_type_1_minute() {
2153        let instrument_id = InstrumentId::from("BTC-PERPETUAL.DERIBIT");
2154        let bar_type = resolution_to_bar_type(instrument_id, "1").unwrap();
2155
2156        assert_eq!(bar_type.instrument_id(), instrument_id);
2157        assert_eq!(bar_type.spec().step.get(), 1);
2158        assert_eq!(bar_type.spec().aggregation, BarAggregation::Minute);
2159        assert_eq!(bar_type.spec().price_type, PriceType::Last);
2160        assert_eq!(bar_type.aggregation_source(), AggregationSource::External);
2161    }
2162
2163    #[rstest]
2164    fn test_resolution_to_bar_type_60_minute() {
2165        let instrument_id = InstrumentId::from("ETH-PERPETUAL.DERIBIT");
2166        let bar_type = resolution_to_bar_type(instrument_id, "60").unwrap();
2167
2168        assert_eq!(bar_type.instrument_id(), instrument_id);
2169        assert_eq!(bar_type.spec().step.get(), 1);
2170        assert_eq!(bar_type.spec().aggregation, BarAggregation::Hour);
2171    }
2172
2173    #[rstest]
2174    fn test_resolution_to_bar_type_daily() {
2175        let instrument_id = InstrumentId::from("BTC-PERPETUAL.DERIBIT");
2176        let bar_type = resolution_to_bar_type(instrument_id, "1D").unwrap();
2177
2178        assert_eq!(bar_type.instrument_id(), instrument_id);
2179        assert_eq!(bar_type.spec().step.get(), 1);
2180        assert_eq!(bar_type.spec().aggregation, BarAggregation::Day);
2181    }
2182
2183    #[rstest]
2184    fn test_resolution_to_bar_type_invalid() {
2185        let instrument_id = InstrumentId::from("BTC-PERPETUAL.DERIBIT");
2186        let result = resolution_to_bar_type(instrument_id, "invalid");
2187
2188        assert!(result.is_err());
2189        assert!(
2190            result
2191                .unwrap_err()
2192                .to_string()
2193                .contains("Unsupported Deribit resolution")
2194        );
2195    }
2196
2197    #[rstest]
2198    fn test_parse_chart_msg_uses_cost() {
2199        let instrument = test_perpetual_instrument();
2200        assert!(
2201            instrument.is_inverse(),
2202            "test fixture is expected to be an inverse perp"
2203        );
2204
2205        let json = load_test_json("ws_chart.json");
2206        let response: serde_json::Value = serde_json::from_str(&json).unwrap();
2207        let chart_msg: DeribitChartMsg =
2208            serde_json::from_str(&response["params"]["data"].to_string()).unwrap();
2209
2210        // Verify chart message was deserialized correctly
2211        assert_eq!(chart_msg.tick, 1_767_200_040_000);
2212        assert_eq!(chart_msg.open, dec!(87490.0));
2213        assert_eq!(chart_msg.high, dec!(87500.0));
2214        assert_eq!(chart_msg.low, dec!(87465.0));
2215        assert_eq!(chart_msg.close, dec!(87474.0));
2216        assert_eq!(chart_msg.volume, dec!(0.95978896));
2217        assert_eq!(chart_msg.cost, dec!(83970.0));
2218
2219        let bar_type = resolution_to_bar_type(instrument.id(), "1").unwrap();
2220
2221        // Test with timestamp_on_close=true (default)
2222        let bar = parse_chart_msg(
2223            &chart_msg,
2224            bar_type,
2225            instrument.price_precision(),
2226            instrument.size_precision(),
2227            true, // use_cost_for_volume
2228            true,
2229            UnixNanos::default(),
2230        )
2231        .unwrap();
2232
2233        assert_eq!(bar.bar_type, bar_type);
2234        assert_eq!(bar.open, instrument.make_price(87490.0));
2235        assert_eq!(bar.high, instrument.make_price(87500.0));
2236        assert_eq!(bar.low, instrument.make_price(87465.0));
2237        assert_eq!(bar.close, instrument.make_price(87474.0));
2238        assert_eq!(bar.volume, instrument.make_qty(83970.0, None));
2239
2240        // ts_event should be close time (open + 1 minute)
2241        assert_eq!(bar.ts_event, UnixNanos::new(1_767_200_100_000_000_000));
2242    }
2243
2244    #[rstest]
2245    fn test_parse_order_buy_response() {
2246        let instrument = test_perpetual_instrument();
2247        let json = load_test_json("ws_order_buy_response.json");
2248        let response: serde_json::Value = serde_json::from_str(&json).unwrap();
2249
2250        // Parse the order from the response (buy/sell responses wrap order in {"order": ...})
2251        let order_msg: DeribitOrderMsg =
2252            serde_json::from_str(&response["result"]["order"].to_string()).unwrap();
2253
2254        // Verify deserialization
2255        assert_eq!(order_msg.order_id, "USDC-104819327443");
2256        assert_eq!(
2257            order_msg.label,
2258            Some("O-19700101-000000-001-001-1".to_string())
2259        );
2260        assert_eq!(order_msg.direction, "buy");
2261        assert_eq!(order_msg.order_state, "open");
2262        assert_eq!(order_msg.order_type, "limit");
2263        assert_eq!(order_msg.price, Some(dec!(2973.55)));
2264        assert_eq!(order_msg.amount, dec!(0.001));
2265        assert_eq!(order_msg.filled_amount, rust_decimal::Decimal::ZERO);
2266        assert!(order_msg.post_only);
2267        assert!(!order_msg.reduce_only);
2268
2269        // Test parse_order_accepted
2270        let account_id = AccountId::new("DERIBIT-001");
2271        let trader_id = TraderId::new("TRADER-001");
2272        let strategy_id = StrategyId::new("PMM-001");
2273
2274        let accepted = parse_order_accepted(
2275            &order_msg,
2276            &instrument,
2277            account_id,
2278            trader_id,
2279            strategy_id,
2280            UnixNanos::default(),
2281        );
2282
2283        assert_eq!(
2284            accepted.client_order_id.to_string(),
2285            "O-19700101-000000-001-001-1"
2286        );
2287        assert_eq!(accepted.venue_order_id.to_string(), "USDC-104819327443");
2288        assert_eq!(accepted.trader_id, trader_id);
2289        assert_eq!(accepted.strategy_id, strategy_id);
2290        assert_eq!(accepted.account_id, account_id);
2291    }
2292
2293    #[rstest]
2294    fn test_parse_order_sell_response() {
2295        let instrument = test_perpetual_instrument();
2296        let json = load_test_json("ws_order_sell_response.json");
2297        let response: serde_json::Value = serde_json::from_str(&json).unwrap();
2298
2299        let order_msg: DeribitOrderMsg =
2300            serde_json::from_str(&response["result"]["order"].to_string()).unwrap();
2301
2302        // Verify deserialization
2303        assert_eq!(order_msg.order_id, "USDC-104819327458");
2304        assert_eq!(
2305            order_msg.label,
2306            Some("O-19700101-000000-001-001-2".to_string())
2307        );
2308        assert_eq!(order_msg.direction, "sell");
2309        assert_eq!(order_msg.order_state, "open");
2310        assert_eq!(order_msg.price, Some(dec!(3286.7)));
2311        assert_eq!(order_msg.amount, dec!(0.001));
2312
2313        // Test parse_order_accepted for sell order
2314        let account_id = AccountId::new("DERIBIT-001");
2315        let trader_id = TraderId::new("TRADER-001");
2316        let strategy_id = StrategyId::new("PMM-001");
2317
2318        let accepted = parse_order_accepted(
2319            &order_msg,
2320            &instrument,
2321            account_id,
2322            trader_id,
2323            strategy_id,
2324            UnixNanos::default(),
2325        );
2326
2327        assert_eq!(
2328            accepted.client_order_id.to_string(),
2329            "O-19700101-000000-001-001-2"
2330        );
2331        assert_eq!(accepted.venue_order_id.to_string(), "USDC-104819327458");
2332        assert_eq!(accepted.trader_id, trader_id);
2333        assert_eq!(accepted.strategy_id, strategy_id);
2334        assert_eq!(accepted.account_id, account_id);
2335    }
2336
2337    #[rstest]
2338    fn test_parse_order_edit_response() {
2339        let instrument = test_perpetual_instrument();
2340        let json = load_test_json("ws_order_edit_response.json");
2341        let response: serde_json::Value = serde_json::from_str(&json).unwrap();
2342
2343        let order_msg: DeribitOrderMsg =
2344            serde_json::from_str(&response["result"]["order"].to_string()).unwrap();
2345
2346        // Verify deserialization - edit response has replaced=true in raw JSON
2347        assert_eq!(order_msg.order_id, "USDC-104819327443");
2348        assert_eq!(
2349            order_msg.label,
2350            Some("O-19700101-000000-001-001-1".to_string())
2351        );
2352        assert_eq!(order_msg.direction, "buy");
2353        assert_eq!(order_msg.order_state, "open");
2354        assert!(order_msg.replaced);
2355        assert_eq!(order_msg.price, Some(dec!(3067.2))); // New price after edit
2356
2357        // Test parse_order_updated
2358        let account_id = AccountId::new("DERIBIT-001");
2359        let trader_id = TraderId::new("TRADER-001");
2360        let strategy_id = StrategyId::new("PMM-001");
2361
2362        let updated = parse_order_updated(
2363            &order_msg,
2364            &instrument,
2365            account_id,
2366            trader_id,
2367            strategy_id,
2368            UnixNanos::default(),
2369        );
2370
2371        assert_eq!(
2372            updated.client_order_id.to_string(),
2373            "O-19700101-000000-001-001-1"
2374        );
2375        assert_eq!(
2376            updated.venue_order_id.unwrap().to_string(),
2377            "USDC-104819327443"
2378        );
2379        // Note: 0.001 truncates to 0.0 due to BTC-PERPETUAL size_precision=0
2380        assert_eq!(updated.quantity.as_f64(), 0.0);
2381    }
2382
2383    #[rstest]
2384    fn test_parse_order_cancel_response() {
2385        let instrument = test_perpetual_instrument();
2386        let json = load_test_json("ws_order_cancel_response.json");
2387        let response: serde_json::Value = serde_json::from_str(&json).unwrap();
2388
2389        // Cancel response has order fields directly in result (not wrapped)
2390        let order_msg: DeribitOrderMsg =
2391            serde_json::from_str(&response["result"].to_string()).unwrap();
2392
2393        // Verify deserialization
2394        assert_eq!(order_msg.order_id, "USDC-104819327443");
2395        assert_eq!(
2396            order_msg.label,
2397            Some("O-19700101-000000-001-001-1".to_string())
2398        );
2399        assert_eq!(order_msg.order_state, "cancelled");
2400        assert_eq!(order_msg.cancel_reason, Some("user_request".to_string()));
2401
2402        // Test parse_order_canceled
2403        let account_id = AccountId::new("DERIBIT-001");
2404        let trader_id = TraderId::new("TRADER-001");
2405        let strategy_id = StrategyId::new("PMM-001");
2406
2407        let canceled = parse_order_canceled(
2408            &order_msg,
2409            &instrument,
2410            account_id,
2411            trader_id,
2412            strategy_id,
2413            UnixNanos::default(),
2414        );
2415
2416        assert_eq!(
2417            canceled.client_order_id.to_string(),
2418            "O-19700101-000000-001-001-1"
2419        );
2420        assert_eq!(
2421            canceled.venue_order_id.unwrap().to_string(),
2422            "USDC-104819327443"
2423        );
2424        assert_eq!(canceled.trader_id, trader_id);
2425        assert_eq!(canceled.strategy_id, strategy_id);
2426    }
2427
2428    #[rstest]
2429    fn test_parse_order_stop_market_response() {
2430        // Regression for https://github.com/nautechsystems/nautilus_trader/issues/3925
2431        // Deribit returns the literal string "market_price" for the price of
2432        // trigger market orders; the deserializer must map this to None rather
2433        // than failing with "Invalid decimal: unknown character".
2434        let instrument = test_perpetual_instrument();
2435        let json = load_test_json("ws_order_stop_market_response.json");
2436        let response: serde_json::Value = serde_json::from_str(&json).unwrap();
2437
2438        let order_msg: DeribitOrderMsg =
2439            serde_json::from_str(&response["result"]["order"].to_string()).unwrap();
2440
2441        assert_eq!(order_msg.order_id, "USDC-104819327499");
2442        assert_eq!(order_msg.order_type, "stop_market");
2443        assert_eq!(order_msg.order_state, "untriggered");
2444        assert_eq!(order_msg.price, None);
2445        assert_eq!(order_msg.trigger_price, Some(dec!(2228.0)));
2446        assert_eq!(order_msg.trigger.as_deref(), Some("mark_price"));
2447        assert!(order_msg.reduce_only);
2448
2449        let account_id = AccountId::new("DERIBIT-001");
2450        let report =
2451            parse_user_order_msg(&order_msg, &instrument, account_id, UnixNanos::default())
2452                .unwrap();
2453
2454        assert_eq!(report.order_type, OrderType::StopMarket);
2455        assert_eq!(report.order_status, OrderStatus::Accepted);
2456        assert!(report.price.is_none());
2457        assert!(report.trigger_price.is_some());
2458        assert!(report.reduce_only);
2459    }
2460
2461    #[rstest]
2462    fn test_parse_order_stop_market_response_missing_filled_amount() {
2463        // Regression for https://github.com/nautechsystems/nautilus_trader/issues/3995
2464        // Deribit omits `filled_amount` for untriggered trigger market orders;
2465        // the deserializer must treat the missing field as zero rather than
2466        // failing with "missing field `filled_amount`".
2467        let instrument = test_perpetual_instrument();
2468        let json = load_test_json("ws_order_stop_market_no_filled_amount.json");
2469        let response: serde_json::Value = serde_json::from_str(&json).unwrap();
2470
2471        let order_msg: DeribitOrderMsg =
2472            serde_json::from_str(&response["result"]["order"].to_string()).unwrap();
2473
2474        assert_eq!(order_msg.order_id, "USDC-SLMB-19641");
2475        assert_eq!(order_msg.order_type, "stop_market");
2476        assert_eq!(order_msg.order_state, "untriggered");
2477        assert_eq!(order_msg.filled_amount, rust_decimal::Decimal::ZERO);
2478        assert_eq!(order_msg.average_price, None);
2479
2480        let account_id = AccountId::new("DERIBIT-001");
2481        let report =
2482            parse_user_order_msg(&order_msg, &instrument, account_id, UnixNanos::default())
2483                .unwrap();
2484
2485        assert_eq!(report.order_type, OrderType::StopMarket);
2486        assert_eq!(report.order_status, OrderStatus::Accepted);
2487        assert_eq!(report.filled_qty.as_f64(), 0.0);
2488    }
2489
2490    #[rstest]
2491    fn test_parse_user_order_msg_to_status_report() {
2492        let instrument = test_perpetual_instrument();
2493        let json = load_test_json("ws_order_buy_response.json");
2494        let response: serde_json::Value = serde_json::from_str(&json).unwrap();
2495
2496        let order_msg: DeribitOrderMsg =
2497            serde_json::from_str(&response["result"]["order"].to_string()).unwrap();
2498
2499        let account_id = AccountId::new("DERIBIT-001");
2500        let report =
2501            parse_user_order_msg(&order_msg, &instrument, account_id, UnixNanos::default())
2502                .unwrap();
2503
2504        assert_eq!(report.venue_order_id.to_string(), "USDC-104819327443");
2505        assert_eq!(
2506            report.client_order_id.unwrap().to_string(),
2507            "O-19700101-000000-001-001-1"
2508        );
2509        assert_eq!(report.order_side, OrderSide::Buy.into());
2510        assert_eq!(report.order_type, OrderType::Limit);
2511        assert_eq!(report.time_in_force, TimeInForce::Gtc);
2512        assert_eq!(report.order_status, OrderStatus::Accepted);
2513        // Note: 0.001 truncates to 0.0 due to BTC-PERPETUAL size_precision=0
2514        assert_eq!(report.quantity.as_f64(), 0.0);
2515        assert_eq!(report.filled_qty.as_f64(), 0.0);
2516        assert!(report.post_only);
2517        assert!(!report.reduce_only);
2518    }
2519
2520    #[rstest]
2521    fn test_determine_order_event_type() {
2522        // New order -> Accepted
2523        assert_eq!(
2524            determine_order_event_type("open", true, false),
2525            OrderEventType::Accepted
2526        );
2527
2528        // Amended order -> Updated
2529        assert_eq!(
2530            determine_order_event_type("open", false, true),
2531            OrderEventType::Updated
2532        );
2533
2534        // Cancelled order -> Canceled
2535        assert_eq!(
2536            determine_order_event_type("cancelled", false, false),
2537            OrderEventType::Canceled
2538        );
2539
2540        // Expired order -> Expired
2541        assert_eq!(
2542            determine_order_event_type("expired", false, false),
2543            OrderEventType::Expired
2544        );
2545
2546        // Filled order -> None (handled via trades)
2547        assert_eq!(
2548            determine_order_event_type("filled", false, false),
2549            OrderEventType::None
2550        );
2551    }
2552
2553    fn perpetual_instrument_with_increments(
2554        tick_size: &str,
2555        min_trade_amount: &str,
2556    ) -> InstrumentAny {
2557        let json = load_test_json("http_get_instruments.json");
2558        let mut response: serde_json::Value = serde_json::from_str(&json).unwrap();
2559        response["result"][0]["tick_size"] = serde_json::json!(tick_size);
2560        response["result"][0]["min_trade_amount"] = serde_json::json!(min_trade_amount);
2561        let response: DeribitJsonRpcResponse<Vec<DeribitInstrument>> =
2562            serde_json::from_str(&response.to_string()).unwrap();
2563        let instrument = &response.result.unwrap()[0];
2564        parse_deribit_instrument_any(instrument, UnixNanos::default(), UnixNanos::default())
2565            .unwrap()
2566            .unwrap()
2567    }
2568
2569    fn parse_notification_data<T: DeserializeOwned>(fixture: &str) -> T {
2570        serde_json::from_str(&notification_data(fixture)).unwrap()
2571    }
2572
2573    fn notification_data(fixture: &str) -> String {
2574        let json = load_test_json(fixture);
2575
2576        let DeribitWsMessage::Notification(notification) = parse_raw_message(&json).unwrap() else {
2577            panic!("Expected notification from {fixture}");
2578        };
2579
2580        notification.params.data.get().to_string()
2581    }
2582
2583    #[rstest]
2584    fn test_parse_user_trade_msg_keeps_decimals_that_collapse_in_f64() {
2585        let instrument = perpetual_instrument_with_increments("0.000000001", "0.000000001");
2586        let trades: Vec<DeribitUserTradeMsg> = parse_notification_data("ws_user_trades_exact.json");
2587        let account_id = AccountId::new("DERIBIT-001");
2588        let btc = Currency::BTC();
2589
2590        let first = parse_user_trade_msg(&trades[0], &instrument, account_id, UnixNanos::default())
2591            .unwrap();
2592        let second =
2593            parse_user_trade_msg(&trades[1], &instrument, account_id, UnixNanos::default())
2594                .unwrap();
2595
2596        let fee_f64 = "1000000000.12345678".parse::<f64>().unwrap();
2597        let next_fee_f64 = "1000000000.12345679".parse::<f64>().unwrap();
2598        assert_eq!(fee_f64.to_bits(), next_fee_f64.to_bits());
2599        assert_eq!(instrument.price_precision(), 9);
2600        assert_eq!(instrument.size_precision(), 9);
2601        assert_eq!(first.last_px, Price::from("100000000.123456789"));
2602        assert_eq!(first.last_qty, Quantity::from("100000000.123456789"));
2603        assert_eq!(
2604            first.commission,
2605            Money::from_decimal(dec!(1000000000.12345678), btc).unwrap()
2606        );
2607        assert_eq!(second.last_px, Price::from("100000000.123456788"));
2608        assert_eq!(second.last_qty, Quantity::from("100000000.123456788"));
2609        assert_eq!(
2610            second.commission,
2611            Money::from_decimal(dec!(1000000000.12345679), btc).unwrap()
2612        );
2613        assert_eq!(trades[0].mark_price, dec!(100000000.123456788));
2614        assert_eq!(trades[0].profit_loss, Some(dec!(0.30000000000000004)));
2615    }
2616
2617    #[rstest]
2618    fn test_parse_user_trade_msg_rounds_exact_token_half_even() {
2619        let instrument = perpetual_instrument_with_increments("0.01", "0.01");
2620        let trades: Vec<DeribitUserTradeMsg> = parse_notification_data("ws_user_trades_exact.json");
2621        let account_id = AccountId::new("DERIBIT-001");
2622
2623        let fill = parse_user_trade_msg(&trades[2], &instrument, account_id, UnixNanos::default())
2624            .unwrap();
2625
2626        let token_f64 = "100000000.005000001".parse::<f64>().unwrap();
2627        let via_f64 = Price::from_decimal_dp(Decimal::try_from(token_f64).unwrap(), 2).unwrap();
2628        assert_eq!(via_f64, Price::from("100000000.00"));
2629        assert_eq!(fill.last_px, Price::from("100000000.01"));
2630        assert_eq!(fill.last_qty, Quantity::from("100000000.01"));
2631        assert_eq!(
2632            fill.commission,
2633            Money::from_decimal(dec!(0.00011403), Currency::BTC()).unwrap()
2634        );
2635    }
2636
2637    #[rstest]
2638    fn test_parse_portfolio_keeps_decimals_that_collapse_in_f64() {
2639        let portfolio: DeribitPortfolioMsg = parse_notification_data("ws_portfolio_exact.json");
2640        let account_id = AccountId::new("DERIBIT-001");
2641        let btc = Currency::BTC();
2642
2643        let state =
2644            parse_portfolio_to_account_state(&portfolio, account_id, UnixNanos::default()).unwrap();
2645
2646        assert_eq!(state.balances.len(), 1);
2647        assert_eq!(
2648            state.balances[0].total,
2649            Money::from_decimal(dec!(1000000000.12345679), btc).unwrap()
2650        );
2651        assert_eq!(
2652            state.balances[0].free,
2653            Money::from_decimal(dec!(1000000000.12345678), btc).unwrap()
2654        );
2655        assert_eq!(
2656            state.balances[0].locked,
2657            Money::from_decimal(dec!(0.00000001), btc).unwrap()
2658        );
2659        assert_eq!(state.margins.len(), 1);
2660        assert_eq!(
2661            state.margins[0].initial,
2662            Money::from_decimal(dec!(1000000000.12345678), btc).unwrap()
2663        );
2664        assert_eq!(state.margins[0].maintenance, Money::zero(btc));
2665        assert_eq!(
2666            portfolio.maintenance_margin,
2667            dec!(0.0000000000000000555111512313)
2668        );
2669    }
2670
2671    #[rstest]
2672    fn test_parse_book_snapshot_keeps_decimals_that_collapse_in_f64() {
2673        let instrument = perpetual_instrument_with_increments("0.000000001", "0.000000001");
2674        let data = notification_data("ws_book_snapshot_exact.json");
2675        let msg: DeribitBookMsg = serde_json::from_str(&data).unwrap();
2676
2677        let deltas = parse_book_msg(&msg, &instrument, UnixNanos::default()).unwrap();
2678
2679        assert_eq!(deltas.deltas.len(), 3);
2680        assert_eq!(deltas.deltas[0].action, BookAction::Clear);
2681        assert_eq!(
2682            deltas.deltas[1].order.price,
2683            Price::from("100000000.123456789")
2684        );
2685        assert_eq!(
2686            deltas.deltas[1].order.size,
2687            Quantity::from("100000000.123456789")
2688        );
2689        assert_eq!(
2690            deltas.deltas[2].order.price,
2691            Price::from("100000000.123456788")
2692        );
2693        assert_eq!(
2694            deltas.deltas[2].order.size,
2695            Quantity::from("100000000.123456788")
2696        );
2697    }
2698
2699    #[rstest]
2700    fn test_parse_book_delta_rounds_levels_beyond_decimal_scale() {
2701        let instrument = perpetual_instrument_with_increments("0.000000001", "0.000000001");
2702        let data = notification_data("ws_book_delta_exact.json");
2703        let msg: DeribitBookMsg = serde_json::from_str(&data).unwrap();
2704
2705        let deltas = parse_book_msg(&msg, &instrument, UnixNanos::default()).unwrap();
2706
2707        assert_eq!(deltas.deltas.len(), 2);
2708        assert_eq!(deltas.deltas[0].action, BookAction::Update);
2709        assert_eq!(
2710            deltas.deltas[0].order.price,
2711            Price::from("100000000.123456789")
2712        );
2713        assert_eq!(deltas.deltas[0].order.size, Quantity::from("0.123456789"));
2714        assert_eq!(deltas.deltas[1].action, BookAction::Add);
2715        assert_eq!(
2716            deltas.deltas[1].order.price,
2717            Price::from("100000000.123456788")
2718        );
2719        assert_eq!(deltas.deltas[1].order.size, Quantity::from("0.000012346"));
2720    }
2721
2722    #[rstest]
2723    fn test_parse_book_delta_maps_zero_rounding_amounts_to_delete() {
2724        let instrument = perpetual_instrument_with_increments("0.5", "1");
2725        let data = r#"{"type":"change","instrument_name":"BTC-PERPETUAL","timestamp":1700000000000,
2726            "change_id":101,"prev_change_id":100,
2727            "bids":[["change",42500.0,1.1102230246251565e-16],["new",42499.5,0.4]],
2728            "asks":[["change",42500.5,20.0],["delete",42501.0,0.0]]}"#;
2729        let msg: DeribitBookMsg = serde_json::from_str(data).unwrap();
2730
2731        let deltas = parse_book_msg(&msg, &instrument, UnixNanos::default()).unwrap();
2732
2733        let actual: Vec<_> = deltas
2734            .deltas
2735            .iter()
2736            .map(|delta| {
2737                (
2738                    delta.action,
2739                    delta.order.side,
2740                    delta.order.price,
2741                    delta.order.size,
2742                    delta.order.order_id,
2743                    delta.flags,
2744                    delta.sequence,
2745                )
2746            })
2747            .collect();
2748
2749        assert_eq!(
2750            actual,
2751            vec![
2752                (
2753                    BookAction::Delete,
2754                    Some(OrderSide::Buy),
2755                    Price::from("42500.0"),
2756                    Quantity::from("0"),
2757                    0,
2758                    0,
2759                    101,
2760                ),
2761                (
2762                    BookAction::Delete,
2763                    Some(OrderSide::Buy),
2764                    Price::from("42499.5"),
2765                    Quantity::from("0"),
2766                    1,
2767                    0,
2768                    101,
2769                ),
2770                (
2771                    BookAction::Update,
2772                    Some(OrderSide::Sell),
2773                    Price::from("42500.5"),
2774                    Quantity::from("20"),
2775                    2,
2776                    0,
2777                    101,
2778                ),
2779                (
2780                    BookAction::Delete,
2781                    Some(OrderSide::Sell),
2782                    Price::from("42501.0"),
2783                    Quantity::from("0"),
2784                    3,
2785                    RecordFlag::F_LAST as u8,
2786                    101,
2787                ),
2788            ]
2789        );
2790    }
2791
2792    #[rstest]
2793    fn test_parse_book_snapshot_skips_zero_rounding_amounts() {
2794        let instrument = perpetual_instrument_with_increments("0.5", "1");
2795        let data = r#"{"type":"snapshot","instrument_name":"BTC-PERPETUAL","timestamp":1700000000000,
2796            "change_id":100,
2797            "bids":[["new",42500.0,1.1102230246251565e-16],["new",42499.5,10.0]],
2798            "asks":[["new",42500.5,0.4]]}"#;
2799        let msg: DeribitBookMsg = serde_json::from_str(data).unwrap();
2800
2801        let deltas = parse_book_msg(&msg, &instrument, UnixNanos::default()).unwrap();
2802
2803        let actual: Vec<_> = deltas
2804            .deltas
2805            .iter()
2806            .map(|delta| {
2807                (
2808                    delta.action,
2809                    delta.order.side,
2810                    delta.order.price,
2811                    delta.order.size,
2812                    delta.order.order_id,
2813                    delta.flags,
2814                )
2815            })
2816            .collect();
2817
2818        assert_eq!(
2819            actual,
2820            vec![
2821                (
2822                    BookAction::Clear,
2823                    None,
2824                    Price::from("0"),
2825                    Quantity::from("0"),
2826                    0,
2827                    RecordFlag::F_SNAPSHOT as u8,
2828                ),
2829                (
2830                    BookAction::Add,
2831                    Some(OrderSide::Buy),
2832                    Price::from("42499.5"),
2833                    Quantity::from("10"),
2834                    1,
2835                    RecordFlag::F_SNAPSHOT as u8 | RecordFlag::F_LAST as u8,
2836                ),
2837            ]
2838        );
2839    }
2840
2841    #[rstest]
2842    #[case::short_level(serde_json::json!([42500.0]))]
2843    #[case::invalid_price(serde_json::json!(["new", "not-a-price", 10.0]))]
2844    #[case::invalid_amount(serde_json::json!(["new", 42500.0, "not-an-amount"]))]
2845    #[case::zero_price(serde_json::json!(["new", 0.0, 10.0]))]
2846    #[case::negative_price(serde_json::json!(["new", -1.0, 10.0]))]
2847    fn test_parse_book_snapshot_skips_invalid_levels(#[case] invalid_level: serde_json::Value) {
2848        let instrument = perpetual_instrument_with_increments("0.5", "1");
2849        let json = load_test_json("ws_book_snapshot.json");
2850        let mut response: serde_json::Value = serde_json::from_str(&json).unwrap();
2851        response["params"]["data"]["bids"] =
2852            serde_json::json!([invalid_level, ["new", 42500.0, 10.0],]);
2853        response["params"]["data"]["asks"] = serde_json::json!([]);
2854        let data = response["params"]["data"].to_string();
2855        let msg: DeribitBookMsg = serde_json::from_str(&data).unwrap();
2856
2857        let deltas = parse_book_snapshot(&msg, &instrument, UnixNanos::default()).unwrap();
2858
2859        let actual: Vec<_> = deltas
2860            .deltas
2861            .iter()
2862            .map(|delta| {
2863                (
2864                    delta.action,
2865                    delta.order.side,
2866                    delta.order.price,
2867                    delta.order.size,
2868                    delta.order.order_id,
2869                    delta.flags,
2870                )
2871            })
2872            .collect();
2873
2874        assert_eq!(
2875            actual,
2876            vec![
2877                (
2878                    BookAction::Clear,
2879                    None,
2880                    Price::from("0"),
2881                    Quantity::from("0"),
2882                    0,
2883                    RecordFlag::F_SNAPSHOT as u8,
2884                ),
2885                (
2886                    BookAction::Add,
2887                    Some(OrderSide::Buy),
2888                    Price::from("42500"),
2889                    Quantity::from("10"),
2890                    1,
2891                    RecordFlag::F_SNAPSHOT as u8 | RecordFlag::F_LAST as u8,
2892                ),
2893            ]
2894        );
2895    }
2896
2897    #[rstest]
2898    #[case::snapshot(
2899        r#"{"type":"snapshot","instrument_name":"BTC-PERPETUAL","timestamp":1700000000000,
2900            "change_id":100,"bids":[["new",100000000000000000000.0,10.0]],"asks":[]}"#
2901    )]
2902    #[case::delta(
2903        r#"{"type":"change","instrument_name":"BTC-PERPETUAL","timestamp":1700000000000,
2904            "change_id":101,"prev_change_id":100,
2905            "bids":[["new",100000000000000000000.0,10.0]],"asks":[]}"#
2906    )]
2907    fn test_parse_book_msg_rejects_unconvertible_price(#[case] data: &str) {
2908        let instrument = perpetual_instrument_with_increments("0.5", "1");
2909        let msg: DeribitBookMsg = serde_json::from_str(data).unwrap();
2910
2911        let error = parse_book_msg(&msg, &instrument, UnixNanos::default()).unwrap_err();
2912
2913        let expected = Price::from_decimal_dp(dec!(100000000000000000000.0), 1).unwrap_err();
2914        assert_eq!(error.to_string(), expected.to_string());
2915    }
2916}