Skip to main content

nautilus_deribit/common/
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 Deribit API responses into Nautilus domain types.
17
18use anyhow::Context;
19use indexmap::IndexMap;
20use nautilus_core::{
21    Params,
22    datetime::{NANOSECONDS_IN_MICROSECOND, NANOSECONDS_IN_MILLISECOND},
23    nanos::UnixNanos,
24    uuid::UUID4,
25};
26use nautilus_model::{
27    data::{Bar, BarType, BookOrder, TradeTick},
28    enums::{
29        AccountType, AggressorSide, BookType, ExerciseStyle, InstrumentClass, OptionKind, OrderSide,
30    },
31    events::AccountState,
32    identifiers::{AccountId, InstrumentId, Symbol, TradeId},
33    instruments::{
34        CryptoFuture, CryptoFuturesSpread, CryptoOption, CryptoOptionSpread, CryptoPerpetual,
35        CurrencyPair, Instrument, any::InstrumentAny,
36    },
37    orderbook::OrderBook,
38    types::{AccountBalance, Currency, MarginBalance, Money, Price, Quantity},
39};
40use rust_decimal::Decimal;
41use ustr::Ustr;
42
43use crate::{
44    common::{
45        capabilities::{IS_CBE_ROUTED, IS_CSR},
46        consts::DERIBIT_VENUE,
47        enums::{DeribitOptionType, DeribitProductType},
48    },
49    http::models::{
50        DeribitAccountSummary, DeribitInstrument, DeribitOrderBook, DeribitPublicTrade,
51        DeribitTradingViewChartData,
52    },
53    websocket::messages::DeribitPortfolioMsg,
54};
55
56/// Parses a Deribit instrument ID into kind and currency for WebSocket channel subscription.
57///
58/// Deribit instrument naming conventions (per Deribit docs):
59/// - **Future**: `{CURRENCY}-{DMMMYY}` (e.g., "BTC-25MAR23", "BTC-5AUG23")
60/// - **Perpetual**: `{CURRENCY}-PERPETUAL` (e.g., "BTC-PERPETUAL")
61/// - **Option**: `{CURRENCY}-{DMMMYY}-{STRIKE}-{C|P}` (e.g., "BTC-25MAR23-420-C", "BTC-5AUG23-580-P")
62/// - **Linear Option**: `{BASE}_{QUOTE}-{DMMMYY}-{STRIKE}-{C|P}` (e.g., "XRP_USDC-30JUN23-0d625-C")
63///   - Note: `d` is used as decimal point for decimal strikes (0d625 = 0.625)
64/// - **Future combo**: `{CURRENCY}-FS-{LEG_A}_{LEG_B}` (e.g., "BTC-FS-19MAY26_PERP")
65/// - **Option combo**: `{CURRENCY}-{STRATEGY}-{DMMMYY}-{STRIKES}` (e.g., "BTC-CS-19MAY26-70000_75000",
66///   "BTC-STRG-29MAY26-72000_80000", "BTC-STRD-29MAY26-77000", "BTC-BOX-25DEC26-58000_60000")
67/// - **Spot**: `{BASE}_{QUOTE}` (e.g., "BTC_USDC")
68///
69/// Returns `(kind, currency)` tuple for `instrument.state.{kind}.{currency}` channel.
70///
71/// Valid kinds: `future`, `option`, `spot`, `future_combo`, `option_combo`, `any`
72/// Valid currencies: `BTC`, `ETH`, `USDC`, `USDT`, `EURR`, `any`
73#[must_use]
74pub fn parse_instrument_kind_currency(instrument_id: &InstrumentId) -> (String, String) {
75    let symbol = instrument_id.symbol.as_str();
76
77    // Determine kind from instrument name pattern
78    // Order matters: check most specific patterns first
79    let kind = if symbol.contains("PERPETUAL") {
80        "future" // Perpetuals are treated as futures in Deribit API
81    } else if symbol.ends_with("-C") || symbol.ends_with("-P") {
82        // Options end with -C (call) or -P (put)
83        "option"
84    } else if symbol.contains('_') && !symbol.contains('-') {
85        // Spot pairs have underscore but no dash (e.g., "BTC_USDC")
86        "spot"
87    } else if is_combo_symbol(symbol) {
88        // Combos have an alphabetic strategy code as the second segment.
89        // "FS" -> future spread (e.g., BTC-FS-19MAY26_PERP);
90        // any other alpha code -> option combo (CS, STRG, STRD, BOX, RR, ...).
91        match second_segment(symbol) {
92            Some("FS") => "future_combo",
93            _ => "option_combo",
94        }
95    } else {
96        // Default to future for expiry dates like "BTC-25MAR23"
97        "future"
98    };
99
100    // Extract currency (first part before '-' or '_')
101    // For most instruments, currency is the first segment
102    let currency = if let Some(idx) = symbol.find('-') {
103        // Futures, perpetuals, options: "BTC-..." → "BTC"
104        // Linear options: "XRP_USDC-..." → extract base currency "XRP"
105        let first_part = &symbol[..idx];
106        if let Some(underscore_idx) = first_part.find('_') {
107            first_part[..underscore_idx].to_string()
108        } else {
109            first_part.to_string()
110        }
111    } else if let Some(idx) = symbol.find('_') {
112        // Spot: "BTC_USDC" → "BTC"
113        symbol[..idx].to_string()
114    } else {
115        "any".to_string()
116    };
117
118    (kind.to_string(), currency)
119}
120
121/// Returns the segment of a Deribit symbol immediately after the currency.
122///
123/// For `BTC-FS-19MAY26_PERP` returns `Some("FS")`. For `BTC-PERPETUAL` returns
124/// `Some("PERPETUAL")`. Returns `None` for symbols without two `-`-delimited
125/// segments.
126fn second_segment(symbol: &str) -> Option<&str> {
127    let mut parts = symbol.split('-');
128    parts.next()?;
129    parts.next()
130}
131
132/// Returns `true` when the symbol matches a Deribit option- or future-combo pattern.
133///
134/// A combo has an alphabetic strategy code in the second segment that is not
135/// `PERPETUAL` and does not look like a date (date segments start with a digit,
136/// e.g., `25MAR23`).
137fn is_combo_symbol(symbol: &str) -> bool {
138    let Some(seg) = second_segment(symbol) else {
139        return false;
140    };
141
142    if seg.is_empty() || seg == "PERPETUAL" {
143        return false;
144    }
145    // Combo strategy codes are alphabetic; date segments start with a digit.
146    seg.chars().next().is_some_and(|c| c.is_ascii_alphabetic())
147        && seg.chars().all(|c| c.is_ascii_alphabetic())
148}
149
150/// Extracts server timestamp from response and converts to UnixNanos.
151///
152/// # Errors
153///
154/// Returns an error if the server timestamp (us_out) is missing from the response.
155pub fn extract_server_timestamp(us_out: Option<u64>) -> anyhow::Result<UnixNanos> {
156    let us_out =
157        us_out.ok_or_else(|| anyhow::anyhow!("Missing server timestamp (us_out) in response"))?;
158    Ok(UnixNanos::from(us_out * NANOSECONDS_IN_MICROSECOND))
159}
160
161/// Parses a Deribit instrument into a Nautilus [`InstrumentAny`].
162///
163/// Returns `Ok(None)` for unsupported instrument types.
164///
165/// # Errors
166///
167/// Returns an error if:
168/// - Required fields are missing (e.g., strike price for options).
169/// - Timestamp conversion fails.
170/// - Decimal conversion fails for fees.
171/// - Instrument validation fails.
172pub fn parse_deribit_instrument_any(
173    instrument: &DeribitInstrument,
174    ts_init: UnixNanos,
175    ts_event: UnixNanos,
176) -> anyhow::Result<Option<InstrumentAny>> {
177    match instrument.kind {
178        DeribitProductType::Spot => parse_spot_instrument(instrument, ts_init, ts_event).map(Some),
179        DeribitProductType::Future => {
180            // Check if it's a perpetual
181            if instrument.instrument_name.contains("PERPETUAL") {
182                parse_perpetual_instrument(instrument, ts_init, ts_event).map(Some)
183            } else {
184                parse_future_instrument(instrument, ts_init, ts_event).map(Some)
185            }
186        }
187        DeribitProductType::Option => {
188            parse_option_instrument(instrument, ts_init, ts_event).map(Some)
189        }
190        DeribitProductType::FutureCombo => {
191            parse_future_combo_instrument(instrument, ts_init, ts_event).map(Some)
192        }
193        DeribitProductType::OptionCombo => {
194            parse_option_combo_instrument(instrument, ts_init, ts_event).map(Some)
195        }
196    }
197}
198
199/// Parses a spot instrument into a [`CurrencyPair`].
200fn parse_spot_instrument(
201    instrument: &DeribitInstrument,
202    ts_init: UnixNanos,
203    ts_event: UnixNanos,
204) -> anyhow::Result<InstrumentAny> {
205    let instrument_id = InstrumentId::new(Symbol::new(instrument.instrument_name), *DERIBIT_VENUE);
206
207    let base_currency = Currency::get_or_create_crypto(instrument.base_currency);
208    let quote_currency = Currency::get_or_create_crypto(instrument.quote_currency);
209
210    let price_increment = Price::from_decimal(instrument.tick_size)?;
211    let size_increment = parse_min_trade_amount(instrument)?;
212    let min_quantity = parse_min_trade_amount(instrument)?;
213
214    let mut info = IndexMap::new();
215    if let Some(value) = instrument.is_cbe_routed {
216        info.insert(IS_CBE_ROUTED.to_string(), value.into());
217    }
218
219    if let Some(value) = instrument.is_csr {
220        info.insert(IS_CSR.to_string(), value.into());
221    }
222
223    let currency_pair = CurrencyPair::builder()
224        .instrument_id(instrument_id)
225        .raw_symbol(instrument.instrument_name.into())
226        .base_currency(base_currency)
227        .quote_currency(quote_currency)
228        .price_precision(price_increment.precision)
229        .size_precision(size_increment.precision)
230        .price_increment(price_increment)
231        .size_increment(size_increment)
232        .min_quantity(min_quantity)
233        .maybe_info((!info.is_empty()).then(|| Params::new(info)))
234        .ts_event(ts_event)
235        .ts_init(ts_init)
236        .build()?;
237
238    Ok(InstrumentAny::CurrencyPair(currency_pair))
239}
240
241/// Parses a perpetual swap instrument into a [`CryptoPerpetual`].
242fn parse_perpetual_instrument(
243    instrument: &DeribitInstrument,
244    ts_init: UnixNanos,
245    ts_event: UnixNanos,
246) -> anyhow::Result<InstrumentAny> {
247    let instrument_id = InstrumentId::new(Symbol::new(instrument.instrument_name), *DERIBIT_VENUE);
248
249    let base_currency = Currency::get_or_create_crypto(instrument.base_currency);
250    let quote_currency = Currency::get_or_create_crypto(instrument.quote_currency);
251    let settlement_currency = instrument
252        .settlement_currency
253        .map_or(base_currency, Currency::get_or_create_crypto);
254
255    let is_inverse = instrument
256        .instrument_type
257        .as_ref()
258        .is_some_and(|t| t == "reversed");
259
260    let price_increment = Price::from_decimal(instrument.tick_size)?;
261    let size_increment = parse_min_trade_amount(instrument)?;
262    let min_quantity = parse_min_trade_amount(instrument)?;
263
264    let multiplier = Some(deribit_amount_quantity_multiplier());
265    let lot_size = Some(size_increment);
266
267    let perpetual = CryptoPerpetual::builder()
268        .instrument_id(instrument_id)
269        .raw_symbol(instrument.instrument_name.into())
270        .base_currency(base_currency)
271        .quote_currency(quote_currency)
272        .settlement_currency(settlement_currency)
273        .is_inverse(is_inverse)
274        .price_precision(price_increment.precision)
275        .size_precision(size_increment.precision)
276        .price_increment(price_increment)
277        .size_increment(size_increment)
278        .maybe_multiplier(multiplier)
279        .maybe_lot_size(lot_size)
280        // max_quantity - Deribit doesn't specify a hard max
281        .min_quantity(min_quantity)
282        .ts_event(ts_event)
283        .ts_init(ts_init)
284        .build()?;
285
286    Ok(InstrumentAny::CryptoPerpetual(perpetual))
287}
288
289/// Parses a futures instrument into a [`CryptoFuture`].
290fn parse_future_instrument(
291    instrument: &DeribitInstrument,
292    ts_init: UnixNanos,
293    ts_event: UnixNanos,
294) -> anyhow::Result<InstrumentAny> {
295    let instrument_id = InstrumentId::new(Symbol::new(instrument.instrument_name), *DERIBIT_VENUE);
296
297    let underlying = Currency::get_or_create_crypto(instrument.base_currency);
298    let quote_currency = Currency::get_or_create_crypto(instrument.quote_currency);
299    let settlement_currency = instrument
300        .settlement_currency
301        .map_or(underlying, Currency::get_or_create_crypto);
302
303    let is_inverse = instrument
304        .instrument_type
305        .as_ref()
306        .is_some_and(|t| t == "reversed");
307
308    // Convert timestamps from milliseconds to nanoseconds
309    let activation_ns = (instrument.creation_timestamp as u64) * 1_000_000;
310    let expiration_ns = instrument
311        .expiration_timestamp
312        .context("Missing expiration_timestamp for future")? as u64
313        * 1_000_000; // milliseconds to nanoseconds
314
315    let price_increment = Price::from_decimal(instrument.tick_size)?;
316    let size_increment = parse_min_trade_amount(instrument)?;
317    let min_quantity = parse_min_trade_amount(instrument)?;
318
319    let multiplier = Some(deribit_amount_quantity_multiplier());
320    let lot_size = Some(size_increment); // Use min_trade_amount as lot size
321
322    let future = CryptoFuture::builder()
323        .instrument_id(instrument_id)
324        .raw_symbol(instrument.instrument_name.into())
325        .underlying(underlying)
326        .quote_currency(quote_currency)
327        .settlement_currency(settlement_currency)
328        .is_inverse(is_inverse)
329        .activation_ns(UnixNanos::from(activation_ns))
330        .expiration_ns(UnixNanos::from(expiration_ns))
331        .price_precision(price_increment.precision)
332        .size_precision(size_increment.precision)
333        .price_increment(price_increment)
334        .size_increment(size_increment)
335        .maybe_multiplier(multiplier)
336        .maybe_lot_size(lot_size)
337        // max_quantity - Deribit doesn't specify a hard max
338        .min_quantity(min_quantity)
339        .ts_event(ts_event)
340        .ts_init(ts_init)
341        .build()?;
342
343    Ok(InstrumentAny::CryptoFuture(future))
344}
345
346/// Parses an options instrument into a [`CryptoOption`].
347fn parse_option_instrument(
348    instrument: &DeribitInstrument,
349    ts_init: UnixNanos,
350    ts_event: UnixNanos,
351) -> anyhow::Result<InstrumentAny> {
352    let instrument_id = InstrumentId::new(Symbol::new(instrument.instrument_name), *DERIBIT_VENUE);
353    let underlying = Currency::get_or_create_crypto(instrument.base_currency);
354    let quote_currency = Currency::get_or_create_crypto(instrument.quote_currency);
355    let settlement = instrument
356        .settlement_currency
357        .unwrap_or(instrument.base_currency);
358    let settlement_currency = Currency::get_or_create_crypto(settlement);
359
360    // Determine if inverse (settled in base currency) or linear (settled in quote/USDC)
361    let is_inverse = instrument
362        .instrument_type
363        .as_ref()
364        .is_some_and(|t| t == "reversed");
365
366    // Determine option kind
367    let option_kind = match instrument.option_type {
368        Some(DeribitOptionType::Call) => OptionKind::Call,
369        Some(DeribitOptionType::Put) => OptionKind::Put,
370        None => anyhow::bail!("Missing option_type for option instrument"),
371    };
372
373    // Parse strike price
374    let strike = instrument.strike.context("Missing strike for option")?;
375    let strike_price = Price::from_decimal(strike)?;
376
377    // Convert timestamps from milliseconds to nanoseconds
378    let activation_ns = (instrument.creation_timestamp as u64) * 1_000_000;
379    let expiration_ns = instrument
380        .expiration_timestamp
381        .context("Missing expiration_timestamp for option")? as u64
382        * 1_000_000;
383
384    let price_increment = Price::from_decimal(instrument.tick_size)?;
385
386    let multiplier = deribit_amount_quantity_multiplier();
387    let min_trade_amount = parse_min_trade_amount(instrument)?;
388
389    let option = CryptoOption::builder()
390        .instrument_id(instrument_id)
391        .raw_symbol(instrument.instrument_name.into())
392        .underlying(underlying)
393        .quote_currency(quote_currency)
394        .settlement_currency(settlement_currency)
395        .is_inverse(is_inverse)
396        .option_kind(option_kind)
397        .strike_price(strike_price)
398        .activation_ns(UnixNanos::from(activation_ns))
399        .expiration_ns(UnixNanos::from(expiration_ns))
400        .price_precision(price_increment.precision)
401        .size_precision(min_trade_amount.precision)
402        .price_increment(price_increment)
403        .size_increment(min_trade_amount)
404        .multiplier(multiplier)
405        .lot_size(min_trade_amount)
406        .min_quantity(min_trade_amount)
407        .exercise_style(ExerciseStyle::European)
408        .ts_event(ts_event)
409        .ts_init(ts_init)
410        .build()?;
411
412    Ok(InstrumentAny::CryptoOption(option))
413}
414
415/// Parses a Deribit option combo into a [`CryptoOptionSpread`].
416fn parse_option_combo_instrument(
417    instrument: &DeribitInstrument,
418    ts_init: UnixNanos,
419    ts_event: UnixNanos,
420) -> anyhow::Result<InstrumentAny> {
421    let spread = build_spread_common(instrument)?;
422    let option_spread = CryptoOptionSpread::builder()
423        .instrument_id(spread.id)
424        .raw_symbol(spread.raw_symbol)
425        .underlying(spread.underlying)
426        .quote_currency(spread.quote_currency)
427        .settlement_currency(spread.settlement_currency)
428        .is_inverse(spread.is_inverse)
429        .strategy_type(spread.strategy_type)
430        .activation_ns(spread.activation_ns)
431        .expiration_ns(spread.expiration_ns)
432        .price_precision(spread.price_precision)
433        .size_precision(spread.size_precision)
434        .price_increment(spread.price_increment)
435        .size_increment(spread.size_increment)
436        .multiplier(spread.multiplier)
437        .lot_size(spread.lot_size)
438        .min_quantity(spread.size_increment)
439        .ts_event(ts_event)
440        .ts_init(ts_init)
441        .build()?;
442    Ok(InstrumentAny::CryptoOptionSpread(option_spread))
443}
444
445/// Parses a Deribit future combo into a [`CryptoFuturesSpread`].
446fn parse_future_combo_instrument(
447    instrument: &DeribitInstrument,
448    ts_init: UnixNanos,
449    ts_event: UnixNanos,
450) -> anyhow::Result<InstrumentAny> {
451    let spread = build_spread_common(instrument)?;
452    let futures_spread = CryptoFuturesSpread::builder()
453        .instrument_id(spread.id)
454        .raw_symbol(spread.raw_symbol)
455        .underlying(spread.underlying)
456        .quote_currency(spread.quote_currency)
457        .settlement_currency(spread.settlement_currency)
458        .is_inverse(spread.is_inverse)
459        .strategy_type(spread.strategy_type)
460        .activation_ns(spread.activation_ns)
461        .expiration_ns(spread.expiration_ns)
462        .price_precision(spread.price_precision)
463        .size_precision(spread.size_precision)
464        .price_increment(spread.price_increment)
465        .size_increment(spread.size_increment)
466        .multiplier(spread.multiplier)
467        .lot_size(spread.lot_size)
468        .min_quantity(spread.size_increment)
469        .ts_event(ts_event)
470        .ts_init(ts_init)
471        .build()?;
472    Ok(InstrumentAny::CryptoFuturesSpread(futures_spread))
473}
474
475/// Fields shared by [`CryptoOptionSpread`] and [`CryptoFuturesSpread`] construction
476/// from a Deribit combo instrument response.
477struct DeribitSpreadCommon {
478    id: InstrumentId,
479    raw_symbol: Symbol,
480    underlying: Currency,
481    quote_currency: Currency,
482    settlement_currency: Currency,
483    is_inverse: bool,
484    strategy_type: Ustr,
485    activation_ns: UnixNanos,
486    expiration_ns: UnixNanos,
487    price_precision: u8,
488    price_increment: Price,
489    size_precision: u8,
490    size_increment: Quantity,
491    multiplier: Quantity,
492    lot_size: Quantity,
493}
494
495fn build_spread_common(instrument: &DeribitInstrument) -> anyhow::Result<DeribitSpreadCommon> {
496    let id = InstrumentId::new(Symbol::new(instrument.instrument_name), *DERIBIT_VENUE);
497    let raw_symbol = Symbol::new(instrument.instrument_name);
498    let underlying = Currency::get_or_create_crypto(instrument.base_currency);
499    let quote_currency = Currency::get_or_create_crypto(instrument.quote_currency);
500    let settlement_currency = instrument
501        .settlement_currency
502        .map_or(underlying, Currency::get_or_create_crypto);
503    let is_inverse = instrument
504        .instrument_type
505        .as_ref()
506        .is_some_and(|t| t == "reversed");
507    let strategy_type = second_segment(instrument.instrument_name.as_str())
508        .map_or_else(|| Ustr::from("SPREAD"), Ustr::from);
509
510    let activation_ns = UnixNanos::from((instrument.creation_timestamp as u64) * 1_000_000);
511    let expiration_ns = UnixNanos::from(
512        instrument
513            .expiration_timestamp
514            .context("Missing expiration_timestamp for combo")? as u64
515            * 1_000_000,
516    );
517
518    let price_increment = Price::from_decimal(instrument.tick_size)?;
519    let size_increment = parse_min_trade_amount(instrument)?;
520    let multiplier = deribit_amount_quantity_multiplier();
521
522    Ok(DeribitSpreadCommon {
523        id,
524        raw_symbol,
525        underlying,
526        quote_currency,
527        settlement_currency,
528        is_inverse,
529        strategy_type,
530        activation_ns,
531        expiration_ns,
532        price_precision: price_increment.precision,
533        price_increment,
534        size_precision: size_increment.precision,
535        size_increment,
536        multiplier,
537        lot_size: size_increment,
538    })
539}
540
541fn parse_min_trade_amount(instrument: &DeribitInstrument) -> anyhow::Result<Quantity> {
542    // Arbitrary-precision JSON keeps trailing zeros (`10.0`) that the default float route
543    // drops; normalize so size precision does not depend on the JSON feature set.
544    let min_trade_amount = instrument.min_trade_amount.normalize();
545    Ok(Quantity::from_decimal(min_trade_amount)?)
546}
547
548fn deribit_amount_quantity_multiplier() -> Quantity {
549    // Deribit quantities use `amount`; `contract_size` converts amount to contract count
550    Quantity::from(1)
551}
552
553/// Parses Deribit account summaries into a Nautilus [`AccountState`].
554///
555/// Processes multiple currency summaries and creates balance entries for each currency.
556///
557/// # Errors
558///
559/// Returns an error if:
560/// - Money conversion fails for any balance field.
561/// - Decimal conversion fails for margin values.
562pub fn parse_account_state(
563    summaries: &[DeribitAccountSummary],
564    account_id: AccountId,
565    ts_init: UnixNanos,
566    ts_event: UnixNanos,
567) -> anyhow::Result<AccountState> {
568    let mut balances = Vec::new();
569    let mut margins = Vec::new();
570
571    // Parse each currency summary
572    for summary in summaries {
573        let ccy_str = summary.currency.trim();
574
575        // Skip balances with empty currency codes
576        if ccy_str.is_empty() {
577            log::debug!("Skipping balance detail with empty currency code | raw_data={summary:?}");
578            continue;
579        }
580
581        let currency = Currency::get_or_create_crypto_with_context(
582            ccy_str,
583            Some("DERIBIT - Parsing account state"),
584        );
585
586        // Segregated mode: `margin_balance` and `available_funds` are per-currency scoped.
587        // Cross-margin mode: both are the cross-collateral portfolio value re-denominated
588        // in this currency, summing them across currencies N-fold overcounts the same value.
589        // Use `equity` (actual per-currency holdings) for total and `available_withdrawal_funds`
590        // (per-currency withdrawable, ~ equity minus fee buffer) for free.
591        //
592        // Trade-off: in cross-margin, the risk engine reads `balance.free` as buying power
593        // for new orders (see `Account::balance_free`), so this is conservative versus the
594        // venue-reported `available_funds` which includes cross-collateral. Preserving that
595        // value would require breaking the `total = locked + free` invariant or re-introducing
596        // the cross-denominated overcount, so per-currency consistency wins here.
597        let is_cross_margin = summary.cross_collateral_enabled.unwrap_or(false);
598        let (total, free) = if is_cross_margin {
599            (
600                summary.equity,
601                summary.available_withdrawal_funds.unwrap_or(Decimal::ZERO),
602            )
603        } else {
604            (summary.margin_balance, summary.available_funds)
605        };
606        let balance = AccountBalance::from_total_and_free(total, free, currency)?;
607        balances.push(balance);
608
609        // Parse margin balances if present
610        if let (Some(initial_margin), Some(maintenance_margin)) =
611            (summary.initial_margin, summary.maintenance_margin)
612            && (!initial_margin.is_zero() || !maintenance_margin.is_zero())
613        {
614            let initial = Money::from_decimal(initial_margin, currency)?;
615            let maintenance = Money::from_decimal(maintenance_margin, currency)?;
616            // Deribit reports cross-margin per collateral currency; emit as an
617            // account-wide entry keyed by that currency.
618            margins.push(MarginBalance::new(initial, maintenance, None));
619        }
620    }
621
622    // Ensure at least one balance exists (Nautilus requires non-empty balances)
623    if balances.is_empty() {
624        let zero_currency = Currency::USD();
625        let zero_money = Money::zero(zero_currency);
626        let zero_balance = AccountBalance::new(zero_money, zero_money, zero_money);
627        balances.push(zero_balance);
628    }
629
630    let account_type = AccountType::Margin;
631    let is_reported = true;
632
633    Ok(AccountState::new(
634        account_id,
635        account_type,
636        balances,
637        margins,
638        is_reported,
639        UUID4::new(),
640        ts_event,
641        ts_init,
642        None,
643    ))
644}
645
646/// Parses a Deribit WebSocket portfolio message into a Nautilus [`AccountState`].
647///
648/// This function converts real-time portfolio updates from the `user.portfolio.{currency}`
649/// subscription channel into Nautilus account state events.
650///
651/// # Returns
652///
653/// An `AccountState` containing balances and margin information.
654///
655/// # Errors
656///
657/// Returns an error if Money conversion fails for any balance field.
658pub fn parse_portfolio_to_account_state(
659    portfolio: &DeribitPortfolioMsg,
660    account_id: AccountId,
661    ts_init: UnixNanos,
662) -> anyhow::Result<AccountState> {
663    let ccy_str = portfolio.currency.trim();
664
665    // Skip empty currency codes
666    if ccy_str.is_empty() {
667        anyhow::bail!("Portfolio message has empty currency code");
668    }
669
670    let currency = Currency::get_or_create_crypto_with_context(
671        ccy_str,
672        Some("DERIBIT - Parsing portfolio update"),
673    );
674
675    // See `parse_account_state` for the rationale: cross-margin uses equity and
676    // `available_withdrawal_funds` (per-currency consistency, conservative free balance);
677    // segregated uses `margin_balance` and `available_funds` (per-currency scoped).
678    let is_cross_margin = portfolio.cross_collateral_enabled.unwrap_or(false);
679    let (total, free) = if is_cross_margin {
680        (
681            portfolio.equity,
682            portfolio
683                .available_withdrawal_funds
684                .unwrap_or(Decimal::ZERO),
685        )
686    } else {
687        (portfolio.margin_balance, portfolio.available_funds)
688    };
689    let balance = AccountBalance::from_total_and_free(total, free, currency)?;
690    let balances = vec![balance];
691
692    // Parse margin balances
693    let mut margins = Vec::new();
694    let initial_margin = portfolio.initial_margin;
695    let maintenance_margin = portfolio.maintenance_margin;
696
697    // Only create margin balance if there are actual margin requirements
698    if !initial_margin.is_zero() || !maintenance_margin.is_zero() {
699        let initial = Money::from_decimal(initial_margin, currency)?;
700        let maintenance = Money::from_decimal(maintenance_margin, currency)?;
701        // Deribit reports cross-margin per collateral currency; emit as an
702        // account-wide entry keyed by that currency.
703        margins.push(MarginBalance::new(initial, maintenance, None));
704    }
705
706    let account_type = AccountType::Margin;
707    let is_reported = true;
708
709    Ok(AccountState::new(
710        account_id,
711        account_type,
712        balances,
713        margins,
714        is_reported,
715        UUID4::new(),
716        ts_init, // Use ts_init for both since we don't have server timestamp in portfolio msg
717        ts_init,
718        None,
719    ))
720}
721
722/// Builds a [`TradeId`] for a Deribit public trade, prefixing the venue ID with
723/// the trade's provenance when applicable.
724///
725/// Strategies that need to distinguish RFQ-, block-, or combo-origin trades from
726/// plain trades can pattern-match the prefix on the resulting `TradeId`. The
727/// raw Deribit `trade_id` is preserved after the prefix so correlation back to
728/// the venue is straightforward via a prefix strip.
729///
730/// Precedence (most specific wins): `RFQ-` > `BLK-` > `COMBO-` > unprefixed.
731/// Block RFQs are themselves block trades on Deribit, so the `RFQ-` tag is the
732/// stronger signal; combo trades executed as blocks are tagged `BLK-` since
733/// the block flow is the more important reconciliation signal.
734#[must_use]
735pub fn build_public_trade_id(
736    trade_id: &str,
737    block_rfq_id: Option<i64>,
738    block_trade_id: Option<&str>,
739    combo_id: Option<&str>,
740) -> TradeId {
741    if block_rfq_id.is_some() {
742        TradeId::new(format!("RFQ-{trade_id}"))
743    } else if block_trade_id.is_some() {
744        TradeId::new(format!("BLK-{trade_id}"))
745    } else if combo_id.is_some() {
746        TradeId::new(format!("COMBO-{trade_id}"))
747    } else {
748        TradeId::new(trade_id)
749    }
750}
751
752// Parses a Deribit public trade into a Nautilus [`TradeTick`].
753///
754/// # Errors
755///
756/// Returns an error if:
757/// - The direction is not "buy" or "sell".
758/// - Decimal conversion fails for price or size.
759pub fn parse_trade_tick(
760    trade: &DeribitPublicTrade,
761    instrument_id: InstrumentId,
762    price_precision: u8,
763    size_precision: u8,
764    ts_init: UnixNanos,
765) -> anyhow::Result<TradeTick> {
766    // Parse aggressor side from direction
767    let aggressor_side = match trade.direction.as_str() {
768        "buy" => AggressorSide::Buy,
769        "sell" => AggressorSide::Sell,
770        other => anyhow::bail!("Invalid trade direction: {other}"),
771    };
772    let price = Price::from_decimal_dp(trade.price, price_precision)?;
773    let size = Quantity::from_decimal_dp(trade.amount, size_precision)?;
774    let ts_event = UnixNanos::from((trade.timestamp as u64) * NANOSECONDS_IN_MILLISECOND);
775    let trade_id = build_public_trade_id(
776        &trade.trade_id,
777        trade.block_rfq_id,
778        trade.block_trade_id.as_deref(),
779        trade.combo_id.as_deref(),
780    );
781
782    Ok(TradeTick::new(
783        instrument_id,
784        price,
785        size,
786        aggressor_side,
787        trade_id,
788        ts_event,
789        ts_init,
790    ))
791}
792
793/// Returns true when `Bar.volume` should be populated from the chart `cost` field (USD) instead
794/// of the `volume` field (base currency).
795///
796/// Deribit's `trades.{instrument}` channel reports each trade's `amount` in USD for inverse
797/// perpetuals and inverse futures, and in the underlying base currency for options and linear
798/// futures. To keep `Bar.volume` and `TradeTick.size` on a single unit per instrument, route
799/// inverse non-option products through `cost`. Options and option spreads stay on `volume` even
800/// when flagged `is_inverse`, because their trade `amount` is reported in base currency.
801///
802/// Reference: <https://docs.deribit.com/api-reference/market-data/public-get_last_trades_by_currency>
803#[must_use]
804pub fn use_cost_for_bar_volume(instrument: &InstrumentAny) -> bool {
805    if !instrument.is_inverse() {
806        return false;
807    }
808    !matches!(
809        instrument.instrument_class(),
810        InstrumentClass::Option | InstrumentClass::OptionSpread
811    )
812}
813
814/// Parses Deribit TradingView chart data into Nautilus [`Bar`]s.
815///
816/// Converts OHLCV arrays from the `public/get_tradingview_chart_data` endpoint
817/// into a vector of [`Bar`] objects.
818///
819/// When `use_cost_for_volume` is true, `Bar.volume` is populated from `chart_data.cost` (USD)
820/// instead of `chart_data.volume` (base currency) - see [`use_cost_for_bar_volume`].
821///
822/// # Errors
823///
824/// Returns an error if:
825/// - The status is not "ok".
826/// - Array lengths are inconsistent.
827/// - No data points are present.
828pub fn parse_bars(
829    chart_data: &DeribitTradingViewChartData,
830    bar_type: BarType,
831    price_precision: u8,
832    size_precision: u8,
833    use_cost_for_volume: bool,
834    ts_init: UnixNanos,
835) -> anyhow::Result<Vec<Bar>> {
836    // Check status
837    if chart_data.status != "ok" {
838        anyhow::bail!(
839            "Chart data status is '{}', expected 'ok'",
840            chart_data.status
841        );
842    }
843
844    let num_bars = chart_data.ticks.len();
845
846    // Verify array lengths match
847    anyhow::ensure!(
848        chart_data.open.len() == num_bars
849            && chart_data.high.len() == num_bars
850            && chart_data.low.len() == num_bars
851            && chart_data.close.len() == num_bars
852            && chart_data.volume.len() == num_bars
853            && chart_data.cost.len() == num_bars,
854        "Inconsistent array lengths in chart data"
855    );
856
857    if num_bars == 0 {
858        return Ok(Vec::new());
859    }
860
861    let mut bars = Vec::with_capacity(num_bars);
862
863    for i in 0..num_bars {
864        let open = Price::from_decimal_dp(chart_data.open[i], price_precision)
865            .with_context(|| format!("Invalid open price at index {i}"))?;
866        let high = Price::from_decimal_dp(chart_data.high[i], price_precision)
867            .with_context(|| format!("Invalid high price at index {i}"))?;
868        let low = Price::from_decimal_dp(chart_data.low[i], price_precision)
869            .with_context(|| format!("Invalid low price at index {i}"))?;
870        let close = Price::from_decimal_dp(chart_data.close[i], price_precision)
871            .with_context(|| format!("Invalid close price at index {i}"))?;
872        let raw_volume = if use_cost_for_volume {
873            chart_data.cost[i]
874        } else {
875            chart_data.volume[i]
876        };
877
878        let volume = Quantity::from_decimal_dp(raw_volume, size_precision)
879            .with_context(|| format!("Invalid volume at index {i}"))?;
880
881        // Convert timestamp from milliseconds to nanoseconds
882        let ts_event = UnixNanos::from((chart_data.ticks[i] as u64) * NANOSECONDS_IN_MILLISECOND);
883
884        let bar = Bar::new_checked(bar_type, open, high, low, close, volume, ts_event, ts_init)
885            .with_context(|| format!("Invalid OHLC bar at index {i}"))?;
886        bars.push(bar);
887    }
888
889    Ok(bars)
890}
891
892/// Parses Deribit order book data into a Nautilus [`OrderBook`].
893///
894/// Converts bids and asks from the `public/get_order_book` endpoint
895/// into an L2_MBP order book.
896///
897/// # Errors
898///
899/// Returns an error if order book creation fails or a level price or amount is invalid.
900pub fn parse_order_book(
901    order_book_data: &DeribitOrderBook,
902    instrument_id: InstrumentId,
903    price_precision: u8,
904    size_precision: u8,
905    ts_init: UnixNanos,
906) -> anyhow::Result<OrderBook> {
907    let ts_event = UnixNanos::from((order_book_data.timestamp as u64) * NANOSECONDS_IN_MILLISECOND);
908    let mut book = OrderBook::new(instrument_id, BookType::L2_MBP);
909
910    for (idx, [price, amount]) in order_book_data.bids.iter().enumerate() {
911        let price = Price::from_decimal_dp(*price, price_precision)?;
912        let size = Quantity::from_decimal_dp(*amount, size_precision)?;
913        let order = BookOrder::new(OrderSide::Buy, price, size, idx as u64);
914        book.add(order, 0, idx as u64, ts_event);
915    }
916
917    let bids_len = order_book_data.bids.len();
918    for (idx, [price, amount]) in order_book_data.asks.iter().enumerate() {
919        let price = Price::from_decimal_dp(*price, price_precision)?;
920        let size = Quantity::from_decimal_dp(*amount, size_precision)?;
921        let order = BookOrder::new(OrderSide::Sell, price, size, (bids_len + idx) as u64);
922        book.add(order, 0, (bids_len + idx) as u64, ts_event);
923    }
924
925    book.ts_last = ts_init;
926
927    Ok(book)
928}
929
930/// Converts a Nautilus BarType to a Deribit chart resolution.
931///
932/// Deribit resolutions: "1", "3", "5", "10", "15", "30", "60", "120", "180", "360", "720", "1D"
933pub fn bar_spec_to_resolution(bar_type: &BarType) -> String {
934    use nautilus_model::enums::BarAggregation;
935
936    let spec = bar_type.spec();
937    match spec.aggregation {
938        BarAggregation::Minute => {
939            let step = spec.step.get();
940            // Map to nearest Deribit resolution
941            match step {
942                1 => "1".to_string(),
943                2..=3 => "3".to_string(),
944                4..=5 => "5".to_string(),
945                6..=10 => "10".to_string(),
946                11..=15 => "15".to_string(),
947                16..=30 => "30".to_string(),
948                31..=60 => "60".to_string(),
949                61..=120 => "120".to_string(),
950                121..=180 => "180".to_string(),
951                181..=360 => "360".to_string(),
952                361..=720 => "720".to_string(),
953                _ => "1D".to_string(),
954            }
955        }
956        BarAggregation::Hour => {
957            let step = spec.step.get();
958            match step {
959                1 => "60".to_string(),
960                2 => "120".to_string(),
961                3 => "180".to_string(),
962                4..=6 => "360".to_string(),
963                7..=12 => "720".to_string(),
964                _ => "1D".to_string(),
965            }
966        }
967        BarAggregation::Day => "1D".to_string(),
968        _ => {
969            log::warn!(
970                "Unsupported bar aggregation {:?}, defaulting to 1 minute",
971                spec.aggregation
972            );
973            "1".to_string()
974        }
975    }
976}
977
978#[cfg(test)]
979mod tests {
980    use nautilus_model::{instruments::Instrument, types::Money};
981    use rstest::rstest;
982    use rust_decimal_macros::dec;
983
984    use super::*;
985    use crate::{
986        common::testing::load_test_json,
987        http::models::{
988            DeribitAccountSummariesResponse, DeribitJsonRpcResponse, DeribitTradesResponse,
989        },
990    };
991
992    #[rstest]
993    #[case(dec!(-0.5999))]
994    #[case(dec!(0))]
995    fn test_parse_spot_invalid_tick_returns_error(#[case] tick_size: Decimal) {
996        let json = load_test_json("http_get_instrument_routed_spot.json");
997        let mut definition: DeribitInstrument = serde_json::from_str(&json).unwrap();
998        definition.tick_size = tick_size;
999
1000        let error =
1001            parse_deribit_instrument_any(&definition, UnixNanos::default(), UnixNanos::default())
1002                .unwrap_err();
1003
1004        assert_eq!(
1005            error.to_string(),
1006            format!("invalid `Price` for 'price_increment' not positive, was {tick_size}")
1007        );
1008    }
1009
1010    #[rstest]
1011    #[case(false)]
1012    #[case(true)]
1013    fn test_parse_perpetual_invalid_tick_or_min_trade_returns_error(#[case] zero_min_trade: bool) {
1014        let json = load_test_json("http_get_instrument.json");
1015        let response: DeribitJsonRpcResponse<DeribitInstrument> =
1016            serde_json::from_str(&json).unwrap();
1017        let mut definition = response.result.expect("Test data must have result");
1018        if zero_min_trade {
1019            definition.min_trade_amount = dec!(0);
1020        } else {
1021            definition.tick_size = dec!(0);
1022        }
1023
1024        let error =
1025            parse_deribit_instrument_any(&definition, UnixNanos::default(), UnixNanos::default())
1026                .unwrap_err();
1027
1028        let expected = if zero_min_trade {
1029            "invalid `Quantity` for 'size_increment' not positive, was 0"
1030        } else {
1031            "invalid `Price` for 'price_increment' not positive, was 0"
1032        };
1033
1034        assert_eq!(error.to_string(), expected);
1035    }
1036
1037    #[rstest]
1038    #[case(false)]
1039    #[case(true)]
1040    fn test_parse_future_invalid_tick_or_min_trade_returns_error(#[case] zero_min_trade: bool) {
1041        let json_data = load_test_json("http_get_instruments.json");
1042        let response: DeribitJsonRpcResponse<Vec<DeribitInstrument>> =
1043            serde_json::from_str(&json_data).unwrap();
1044        let mut instruments = response.result.expect("Test data must have result");
1045        let definition = instruments
1046            .iter_mut()
1047            .find(|i| i.instrument_name == "BTC-27DEC24")
1048            .expect("Test data must contain BTC-27DEC24");
1049
1050        if zero_min_trade {
1051            definition.min_trade_amount = dec!(0);
1052        } else {
1053            definition.tick_size = dec!(0);
1054        }
1055
1056        let error =
1057            parse_deribit_instrument_any(definition, UnixNanos::default(), UnixNanos::default())
1058                .unwrap_err();
1059
1060        let expected = if zero_min_trade {
1061            "invalid `Quantity` for 'size_increment' not positive, was 0"
1062        } else {
1063            "invalid `Price` for 'price_increment' not positive, was 0"
1064        };
1065
1066        assert_eq!(error.to_string(), expected);
1067    }
1068
1069    #[rstest]
1070    #[case(false)]
1071    #[case(true)]
1072    fn test_parse_option_invalid_tick_or_min_trade_returns_error(#[case] zero_min_trade: bool) {
1073        let json_data = load_test_json("http_get_instruments.json");
1074        let response: DeribitJsonRpcResponse<Vec<DeribitInstrument>> =
1075            serde_json::from_str(&json_data).unwrap();
1076        let mut instruments = response.result.expect("Test data must have result");
1077        let definition = instruments
1078            .iter_mut()
1079            .find(|i| i.instrument_name == "BTC-27DEC24-100000-C")
1080            .expect("Test data must contain BTC-27DEC24-100000-C");
1081
1082        if zero_min_trade {
1083            definition.min_trade_amount = dec!(0);
1084        } else {
1085            definition.tick_size = dec!(0);
1086        }
1087
1088        let error =
1089            parse_deribit_instrument_any(definition, UnixNanos::default(), UnixNanos::default())
1090                .unwrap_err();
1091
1092        let expected = if zero_min_trade {
1093            "invalid `Quantity` for 'size_increment' not positive, was 0"
1094        } else {
1095            "invalid `Price` for 'price_increment' not positive, was 0"
1096        };
1097
1098        assert_eq!(error.to_string(), expected);
1099    }
1100
1101    #[rstest]
1102    #[case(false)]
1103    #[case(true)]
1104    fn test_parse_option_combo_invalid_tick_or_min_trade_returns_error(
1105        #[case] zero_min_trade: bool,
1106    ) {
1107        let json_data = load_test_json("http_get_instruments_option_combo.json");
1108        let response: DeribitJsonRpcResponse<Vec<DeribitInstrument>> =
1109            serde_json::from_str(&json_data).unwrap();
1110        let mut instruments = response.result.expect("Test data must have result");
1111        let definition = instruments
1112            .iter_mut()
1113            .find(|i| i.instrument_name == "BTC-STRG-19MAY26-74000_79000")
1114            .expect("fixture must contain BTC-STRG-19MAY26-74000_79000");
1115
1116        if zero_min_trade {
1117            definition.min_trade_amount = dec!(0);
1118        } else {
1119            definition.tick_size = dec!(0);
1120        }
1121
1122        let error =
1123            parse_deribit_instrument_any(definition, UnixNanos::default(), UnixNanos::default())
1124                .unwrap_err();
1125
1126        let expected = if zero_min_trade {
1127            "invalid `Quantity` for 'size_increment' not positive, was 0"
1128        } else {
1129            "invalid `Price` for 'price_increment' not positive, was 0"
1130        };
1131
1132        assert_eq!(error.to_string(), expected);
1133    }
1134
1135    #[rstest]
1136    #[case(false)]
1137    #[case(true)]
1138    fn test_parse_future_combo_invalid_tick_or_min_trade_returns_error(
1139        #[case] zero_min_trade: bool,
1140    ) {
1141        let json_data = load_test_json("http_get_instruments_future_combo.json");
1142        let response: DeribitJsonRpcResponse<Vec<DeribitInstrument>> =
1143            serde_json::from_str(&json_data).unwrap();
1144        let mut instruments = response.result.expect("Test data must have result");
1145        let definition = instruments
1146            .iter_mut()
1147            .find(|i| i.instrument_name == "BTC-FS-19MAY26_PERP")
1148            .expect("fixture must contain BTC-FS-19MAY26_PERP");
1149
1150        if zero_min_trade {
1151            definition.min_trade_amount = dec!(0);
1152        } else {
1153            definition.tick_size = dec!(0);
1154        }
1155
1156        let error =
1157            parse_deribit_instrument_any(definition, UnixNanos::default(), UnixNanos::default())
1158                .unwrap_err();
1159
1160        let expected = if zero_min_trade {
1161            "invalid `Quantity` for 'size_increment' not positive, was 0"
1162        } else {
1163            "invalid `Price` for 'price_increment' not positive, was 0"
1164        };
1165
1166        assert_eq!(error.to_string(), expected);
1167    }
1168
1169    #[rstest]
1170    fn test_parse_perpetual_instrument() {
1171        let json_data = load_test_json("http_get_instrument.json");
1172        let response: DeribitJsonRpcResponse<DeribitInstrument> =
1173            serde_json::from_str(&json_data).unwrap();
1174        let deribit_inst = response.result.expect("Test data must have result");
1175
1176        let instrument_any =
1177            parse_deribit_instrument_any(&deribit_inst, UnixNanos::default(), UnixNanos::default())
1178                .unwrap();
1179        let instrument = instrument_any.expect("Should parse perpetual instrument");
1180
1181        let InstrumentAny::CryptoPerpetual(perpetual) = instrument else {
1182            panic!("Expected CryptoPerpetual, was {instrument:?}");
1183        };
1184        assert_eq!(perpetual.id(), InstrumentId::from("BTC-PERPETUAL.DERIBIT"));
1185        assert_eq!(perpetual.raw_symbol(), Symbol::from("BTC-PERPETUAL"));
1186        assert_eq!(perpetual.base_currency().unwrap().code, "BTC");
1187        assert_eq!(perpetual.quote_currency().code, "USD");
1188        assert_eq!(perpetual.settlement_currency().code, "BTC");
1189        assert!(perpetual.is_inverse());
1190        assert_eq!(perpetual.price_precision(), 1);
1191        assert_eq!(perpetual.size_precision(), 0);
1192        assert_eq!(perpetual.price_increment(), Price::from("0.5"));
1193        assert_eq!(perpetual.size_increment(), Quantity::from("10"));
1194        assert_eq!(perpetual.multiplier(), Quantity::from("1"));
1195        assert_eq!(
1196            perpetual.calculate_notional_value(
1197                Quantity::from("10"),
1198                Price::from("50000"),
1199                Some(false)
1200            ),
1201            Money::from("0.0002 BTC")
1202        );
1203        assert_eq!(
1204            perpetual.calculate_notional_value(
1205                Quantity::from("10"),
1206                Price::from("50000"),
1207                Some(true)
1208            ),
1209            Money::from("10 USD")
1210        );
1211        assert_eq!(perpetual.lot_size(), Some(Quantity::from("10")));
1212        assert_eq!(perpetual.max_quantity(), None);
1213        assert_eq!(perpetual.min_quantity(), Some(Quantity::from("10")));
1214    }
1215
1216    #[rstest]
1217    fn test_parse_future_instrument() {
1218        let json_data = load_test_json("http_get_instruments.json");
1219        let response: DeribitJsonRpcResponse<Vec<DeribitInstrument>> =
1220            serde_json::from_str(&json_data).unwrap();
1221        let instruments = response.result.expect("Test data must have result");
1222        let deribit_inst = instruments
1223            .iter()
1224            .find(|i| i.instrument_name == "BTC-27DEC24")
1225            .expect("Test data must contain BTC-27DEC24");
1226
1227        let instrument_any =
1228            parse_deribit_instrument_any(deribit_inst, UnixNanos::default(), UnixNanos::default())
1229                .unwrap();
1230        let instrument = instrument_any.expect("Should parse future instrument");
1231
1232        let InstrumentAny::CryptoFuture(future) = instrument else {
1233            panic!("Expected CryptoFuture, was {instrument:?}");
1234        };
1235        assert_eq!(future.id(), InstrumentId::from("BTC-27DEC24.DERIBIT"));
1236        assert_eq!(future.raw_symbol(), Symbol::from("BTC-27DEC24"));
1237        assert_eq!(future.underlying().unwrap(), "BTC");
1238        assert_eq!(future.quote_currency().code, "USD");
1239        assert_eq!(future.settlement_currency().code, "BTC");
1240        assert!(future.is_inverse());
1241
1242        // Verify timestamps
1243        assert_eq!(
1244            future.activation_ns(),
1245            Some(UnixNanos::from(1719561600000_u64 * 1_000_000))
1246        );
1247        assert_eq!(
1248            future.expiration_ns(),
1249            Some(UnixNanos::from(1735300800000_u64 * 1_000_000))
1250        );
1251        assert_eq!(future.price_precision(), 1);
1252        assert_eq!(future.size_precision(), 0);
1253        assert_eq!(future.price_increment(), Price::from("0.5"));
1254        assert_eq!(future.size_increment(), Quantity::from("10"));
1255        assert_eq!(future.multiplier(), Quantity::from("1"));
1256        assert_eq!(future.lot_size(), Some(Quantity::from("10")));
1257    }
1258
1259    #[rstest]
1260    fn test_parse_option_instrument() {
1261        let json_data = load_test_json("http_get_instruments.json");
1262        let response: DeribitJsonRpcResponse<Vec<DeribitInstrument>> =
1263            serde_json::from_str(&json_data).unwrap();
1264        let instruments = response.result.expect("Test data must have result");
1265        let deribit_inst = instruments
1266            .iter()
1267            .find(|i| i.instrument_name == "BTC-27DEC24-100000-C")
1268            .expect("Test data must contain BTC-27DEC24-100000-C");
1269
1270        let instrument_any =
1271            parse_deribit_instrument_any(deribit_inst, UnixNanos::default(), UnixNanos::default())
1272                .unwrap();
1273        let instrument = instrument_any.expect("Should parse option instrument");
1274
1275        // Verify it's a CryptoOption
1276        let InstrumentAny::CryptoOption(option) = instrument else {
1277            panic!("Expected CryptoOption, was {instrument:?}");
1278        };
1279
1280        assert_eq!(
1281            option.id(),
1282            InstrumentId::from("BTC-27DEC24-100000-C.DERIBIT")
1283        );
1284        assert_eq!(option.raw_symbol(), Symbol::from("BTC-27DEC24-100000-C"));
1285        assert_eq!(option.underlying.code, "BTC");
1286        assert_eq!(option.underlying_instrument_id, None);
1287        assert_eq!(option.exercise_style, Some(ExerciseStyle::European));
1288        assert_eq!(option.settlement_type, None);
1289        assert_eq!(option.quote_currency.code, "BTC");
1290        assert_eq!(option.settlement_currency.code, "BTC");
1291        assert!(option.is_inverse);
1292        assert_eq!(option.option_kind, OptionKind::Call);
1293        assert_eq!(option.strike_price, Price::from("100000"));
1294        assert_eq!(
1295            option.activation_ns,
1296            UnixNanos::from(1719561600000_u64 * 1_000_000)
1297        );
1298        assert_eq!(
1299            option.expiration_ns,
1300            UnixNanos::from(1735300800000_u64 * 1_000_000)
1301        );
1302        assert_eq!(option.price_precision, 4);
1303        assert_eq!(option.price_increment, Price::from("0.0005"));
1304        assert_eq!(option.size_precision, 1);
1305        assert_eq!(option.size_increment, Quantity::from("0.1"));
1306        assert_eq!(option.multiplier, Quantity::from("1"));
1307        assert_eq!(option.lot_size, Quantity::from("0.1"));
1308    }
1309
1310    #[rstest]
1311    fn test_parse_account_state_with_positions() {
1312        let json_data = load_test_json("http_get_account_summaries.json");
1313        let response: DeribitJsonRpcResponse<DeribitAccountSummariesResponse> =
1314            serde_json::from_str(&json_data).unwrap();
1315        let result = response.result.expect("Test data must have result");
1316
1317        let account_id = AccountId::from("DERIBIT-001");
1318
1319        // Extract server timestamp from response
1320        let ts_event =
1321            extract_server_timestamp(response.us_out).expect("Test data must have us_out");
1322        let ts_init = UnixNanos::default();
1323
1324        let account_state = parse_account_state(&result.summaries, account_id, ts_init, ts_event)
1325            .expect("Should parse account state");
1326
1327        // Verify we got 2 currencies (BTC and ETH)
1328        assert_eq!(account_state.balances.len(), 2);
1329
1330        // Test BTC balance (has open positions with unrealized PnL)
1331        let btc_balance = account_state
1332            .balances
1333            .iter()
1334            .find(|b| b.currency.code == "BTC")
1335            .expect("BTC balance should exist");
1336
1337        // From test data:
1338        // margin_balance: 302.62729214, available_funds: 301.38059622
1339        // initial_margin: 1.24669592
1340        //
1341        // Using margin_balance:
1342        // total = margin_balance = 302.62729214
1343        // free = available_funds = 301.38059622
1344        // locked = total - free = 302.62729214 - 301.38059622 = 1.24669592 (exactly initial_margin!)
1345        assert_eq!(btc_balance.total.as_f64(), 302.62729214);
1346        assert_eq!(btc_balance.free.as_f64(), 301.38059622);
1347
1348        // Verify locked equals initial_margin exactly
1349        let locked = btc_balance.locked.as_f64();
1350        assert!(
1351            locked > 0.0,
1352            "Locked should be positive when positions exist"
1353        );
1354        assert!(
1355            (locked - 1.24669592).abs() < 0.0001,
1356            "Locked ({locked}) should equal initial_margin (1.24669592)"
1357        );
1358
1359        // Test ETH balance (no positions)
1360        let eth_balance = account_state
1361            .balances
1362            .iter()
1363            .find(|b| b.currency.code == "ETH")
1364            .expect("ETH balance should exist");
1365
1366        // From test data: margin_balance: 100, available_funds: 99.999598, initial_margin: 0.000402
1367        // total = margin_balance = 100
1368        // free = available_funds = 99.999598
1369        // locked = 100 - 99.999598 = 0.000402 (equals initial_margin)
1370        assert_eq!(eth_balance.total.as_f64(), 100.0);
1371        assert_eq!(eth_balance.free.as_f64(), 99.999598);
1372        assert_eq!(eth_balance.locked.as_f64(), 0.000402);
1373
1374        // Verify account metadata
1375        assert_eq!(account_state.account_id, account_id);
1376        assert_eq!(account_state.account_type, AccountType::Margin);
1377        assert!(account_state.is_reported);
1378
1379        // Verify ts_event matches server timestamp (us_out = 1687352432005000 microseconds)
1380        let expected_ts_event = UnixNanos::from(1687352432005000_u64 * NANOSECONDS_IN_MICROSECOND);
1381        assert_eq!(
1382            account_state.ts_event, expected_ts_event,
1383            "ts_event should match server timestamp from response"
1384        );
1385    }
1386
1387    #[rstest]
1388    fn test_parse_account_state_cross_margin() {
1389        let json_data = load_test_json("http_get_account_summaries_cross_margin.json");
1390        let response: DeribitJsonRpcResponse<DeribitAccountSummariesResponse> =
1391            serde_json::from_str(&json_data).unwrap();
1392        let result = response.result.expect("Test data must have result");
1393
1394        let account_id = AccountId::from("DERIBIT-001");
1395        let ts_event =
1396            extract_server_timestamp(response.us_out).expect("Test data must have us_out");
1397        let ts_init = UnixNanos::default();
1398
1399        let account_state = parse_account_state(&result.summaries, account_id, ts_init, ts_event)
1400            .expect("Should parse cross-margin account state");
1401
1402        // All 4 currencies in fixture have cross_collateral_enabled=true (cross_pm mode)
1403        // BTC: equity=2.288e-5 (actual holding), margin_balance=3.1639e-4 (portfolio-wide)
1404        // USDT: equity=23.61869 (actual holding), margin_balance=25.713074 (portfolio-wide)
1405        // SOL: equity=0 (no holding), margin_balance=0.29488918 (phantom)
1406        // ETH: equity=8.6e-5 (small holding), margin_balance=0.01089 (portfolio-wide)
1407
1408        assert_eq!(account_state.balances.len(), 4);
1409
1410        // BTC: total should be equity (2.288e-5), NOT margin_balance (3.1639e-4)
1411        let btc = account_state
1412            .balances
1413            .iter()
1414            .find(|b| b.currency.code == "BTC")
1415            .expect("BTC balance should exist");
1416        assert_eq!(btc.total.as_f64(), 2.288e-5);
1417        assert_eq!(btc.free.as_f64(), 2.288e-5); // available_withdrawal_funds
1418        assert_eq!(btc.locked.as_f64(), 0.0);
1419
1420        // USDT: total should be equity (23.61869), NOT margin_balance (25.713074)
1421        let usdt = account_state
1422            .balances
1423            .iter()
1424            .find(|b| b.currency.code == "USDT")
1425            .expect("USDT balance should exist");
1426        assert_eq!(usdt.total.as_f64(), 23.61869);
1427        assert_eq!(usdt.free.as_f64(), 23.618645); // available_withdrawal_funds
1428        let usdt_locked = usdt.locked.as_f64();
1429        assert!(
1430            (usdt_locked - 0.000045).abs() < 0.001,
1431            "USDT locked ({usdt_locked}) should be close to 0.000045"
1432        );
1433
1434        // SOL: equity=0, should produce zero balance (not margin_balance=0.29488918)
1435        let sol = account_state
1436            .balances
1437            .iter()
1438            .find(|b| b.currency.code == "SOL")
1439            .expect("SOL balance should exist");
1440        assert_eq!(sol.total.as_f64(), 0.0);
1441        assert_eq!(sol.free.as_f64(), 0.0);
1442
1443        // ETH: equity=8.6e-5 (small holding), NOT margin_balance=0.01089 (portfolio-wide)
1444        let eth = account_state
1445            .balances
1446            .iter()
1447            .find(|b| b.currency.code == "ETH")
1448            .expect("ETH balance should exist");
1449        assert_eq!(eth.total.as_f64(), 8.6e-5);
1450        assert_eq!(eth.free.as_f64(), 8.5e-5); // available_withdrawal_funds
1451
1452        // Verify account metadata
1453        assert_eq!(account_state.account_type, AccountType::Margin);
1454        assert!(account_state.is_reported);
1455    }
1456
1457    #[rstest]
1458    fn test_parse_trade_tick_sell() {
1459        let json_data = load_test_json("http_get_last_trades.json");
1460        let response: DeribitJsonRpcResponse<DeribitTradesResponse> =
1461            serde_json::from_str(&json_data).unwrap();
1462        let result = response.result.expect("Test data must have result");
1463
1464        assert!(result.has_more, "has_more should be true");
1465        assert_eq!(result.trades.len(), 10, "Should have 10 trades");
1466
1467        let raw_trade = &result.trades[0];
1468        let instrument_id = InstrumentId::from("ETH-PERPETUAL.DERIBIT");
1469        let ts_init = UnixNanos::from(1766335632425576_u64 * 1000); // from usOut
1470
1471        let trade = parse_trade_tick(raw_trade, instrument_id, 1, 0, ts_init)
1472            .expect("Should parse trade tick");
1473
1474        assert_eq!(trade.instrument_id, instrument_id);
1475        assert_eq!(trade.price, Price::from("2968.3"));
1476        assert_eq!(trade.size, Quantity::from("1"));
1477        assert_eq!(trade.aggressor_side, AggressorSide::Sell);
1478        assert_eq!(trade.trade_id, TradeId::new("ETH-284830839"));
1479        // timestamp 1766332040636 ms -> ns
1480        assert_eq!(
1481            trade.ts_event,
1482            UnixNanos::from(1766332040636_u64 * 1_000_000)
1483        );
1484        assert_eq!(trade.ts_init, ts_init);
1485    }
1486
1487    #[rstest]
1488    fn test_parse_trade_tick_buy() {
1489        let json_data = load_test_json("http_get_last_trades.json");
1490        let response: DeribitJsonRpcResponse<DeribitTradesResponse> =
1491            serde_json::from_str(&json_data).unwrap();
1492        let result = response.result.expect("Test data must have result");
1493
1494        // Last trade is a buy with amount 106
1495        let raw_trade = &result.trades[9];
1496        let instrument_id = InstrumentId::from("ETH-PERPETUAL.DERIBIT");
1497        let ts_init = UnixNanos::default();
1498
1499        let trade = parse_trade_tick(raw_trade, instrument_id, 1, 0, ts_init)
1500            .expect("Should parse trade tick");
1501
1502        assert_eq!(trade.instrument_id, instrument_id);
1503        assert_eq!(trade.price, Price::from("2968.3"));
1504        assert_eq!(trade.size, Quantity::from("106"));
1505        assert_eq!(trade.aggressor_side, AggressorSide::Buy);
1506        assert_eq!(trade.trade_id, TradeId::new("ETH-284830854"));
1507    }
1508
1509    /// Builds a minimal [`DeribitPublicTrade`] via JSON to exercise the HTTP
1510    /// trade-tick path. Mirrors the WS-side `make_trade_msg` fixture constructor.
1511    fn make_public_trade(
1512        trade_id: &str,
1513        block_trade_id: Option<&str>,
1514        block_rfq_id: Option<i64>,
1515        combo_id: Option<&str>,
1516    ) -> DeribitPublicTrade {
1517        let raw = serde_json::json!({
1518            "trade_id": trade_id,
1519            "instrument_name": "BTC-PERPETUAL",
1520            "price": 77000.0,
1521            "amount": 10.0,
1522            "direction": "buy",
1523            "timestamp": 1_779_107_386_210_i64,
1524            "trade_seq": 1,
1525            "tick_direction": 0,
1526            "block_trade_id": block_trade_id,
1527            "block_rfq_id": block_rfq_id,
1528            "combo_id": combo_id,
1529        });
1530        serde_json::from_str(&raw.to_string()).unwrap()
1531    }
1532
1533    #[rstest]
1534    #[case::block_rfq(None, Some(99_i64), None, "RFQ-244343055")]
1535    #[case::block_trade(Some("12345"), None, None, "BLK-244343055")]
1536    #[case::combo_leg(None, None, Some("BTC-FS-25DEC26_PERP"), "COMBO-244343055")]
1537    fn test_parse_trade_tick_provenance_prefix(
1538        #[case] block_trade_id: Option<&str>,
1539        #[case] block_rfq_id: Option<i64>,
1540        #[case] combo_id: Option<&str>,
1541        #[case] expected_trade_id: &str,
1542    ) {
1543        let trade = make_public_trade("244343055", block_trade_id, block_rfq_id, combo_id);
1544        let instrument_id = InstrumentId::from("BTC-PERPETUAL.DERIBIT");
1545        let tick = parse_trade_tick(&trade, instrument_id, 1, 0, UnixNanos::default())
1546            .expect("Should parse trade tick");
1547        assert_eq!(tick.trade_id, TradeId::new(expected_trade_id));
1548    }
1549
1550    #[rstest]
1551    fn test_use_cost_for_bar_volume() {
1552        // Inverse perpetual: BTC-PERPETUAL → cost (USD)
1553        let perp_json = load_test_json("http_get_instrument.json");
1554        let perp_response: DeribitJsonRpcResponse<DeribitInstrument> =
1555            serde_json::from_str(&perp_json).unwrap();
1556        let perp_inst = perp_response.result.expect("Test data must have result");
1557        let perp =
1558            parse_deribit_instrument_any(&perp_inst, UnixNanos::default(), UnixNanos::default())
1559                .unwrap()
1560                .expect("Should parse perpetual");
1561        assert!(perp.is_inverse());
1562        assert!(use_cost_for_bar_volume(&perp));
1563
1564        // BTC inverse option: is_inverse, but trade amount is in BTC, so stay on volume
1565        let instruments_json = load_test_json("http_get_instruments.json");
1566        let instruments_response: DeribitJsonRpcResponse<Vec<DeribitInstrument>> =
1567            serde_json::from_str(&instruments_json).unwrap();
1568        let instruments = instruments_response
1569            .result
1570            .expect("Test data must have result");
1571
1572        let option_inst = instruments
1573            .iter()
1574            .find(|i| i.instrument_name == "BTC-27DEC24-100000-C")
1575            .expect("Test data must contain BTC-27DEC24-100000-C");
1576        let option =
1577            parse_deribit_instrument_any(option_inst, UnixNanos::default(), UnixNanos::default())
1578                .unwrap()
1579                .expect("Should parse option");
1580        assert!(option.is_inverse());
1581        assert!(
1582            !use_cost_for_bar_volume(&option),
1583            "options report trade amount in base currency, must keep using volume",
1584        );
1585
1586        // Inverse future: same convention as perp - cost (USD)
1587        let future_inst = instruments
1588            .iter()
1589            .find(|i| i.instrument_name == "BTC-27DEC24")
1590            .expect("Test data must contain BTC-27DEC24");
1591        let future =
1592            parse_deribit_instrument_any(future_inst, UnixNanos::default(), UnixNanos::default())
1593                .unwrap()
1594                .expect("Should parse future");
1595        assert!(future.is_inverse());
1596        assert!(use_cost_for_bar_volume(&future));
1597    }
1598
1599    #[rstest]
1600    fn test_parse_bars_uses_volume_field() {
1601        let json_data = load_test_json("http_get_tradingview_chart_data.json");
1602        let response: DeribitJsonRpcResponse<DeribitTradingViewChartData> =
1603            serde_json::from_str(&json_data).unwrap();
1604        let chart_data = response.result.expect("Test data must have result");
1605
1606        let bar_type = BarType::from("BTC-PERPETUAL.DERIBIT-1-MINUTE-LAST-EXTERNAL");
1607        let ts_init = UnixNanos::from(1766487086146245_u64 * NANOSECONDS_IN_MICROSECOND);
1608
1609        let bars =
1610            parse_bars(&chart_data, bar_type, 1, 8, false, ts_init).expect("Should parse bars");
1611
1612        assert_eq!(bars.len(), 5, "Should parse 5 bars");
1613
1614        // Verify first bar
1615        let first_bar = &bars[0];
1616        assert_eq!(first_bar.bar_type, bar_type);
1617        assert_eq!(first_bar.open, Price::from("87451.0"));
1618        assert_eq!(first_bar.high, Price::from("87456.5"));
1619        assert_eq!(first_bar.low, Price::from("87451.0"));
1620        assert_eq!(first_bar.close, Price::from("87456.5"));
1621        assert_eq!(first_bar.volume, Quantity::from("2.94375216"));
1622        assert_eq!(
1623            first_bar.ts_event,
1624            UnixNanos::from(1766483460000_u64 * NANOSECONDS_IN_MILLISECOND)
1625        );
1626        assert_eq!(first_bar.ts_init, ts_init);
1627
1628        // Verify last bar
1629        let last_bar = &bars[4];
1630        assert_eq!(last_bar.open, Price::from("87456.0"));
1631        assert_eq!(last_bar.high, Price::from("87456.5"));
1632        assert_eq!(last_bar.low, Price::from("87456.0"));
1633        assert_eq!(last_bar.close, Price::from("87456.0"));
1634        assert_eq!(last_bar.volume, Quantity::from("0.1018798"));
1635        assert_eq!(
1636            last_bar.ts_event,
1637            UnixNanos::from(1766483700000_u64 * NANOSECONDS_IN_MILLISECOND)
1638        );
1639    }
1640
1641    #[rstest]
1642    fn test_parse_bars_cost_path() {
1643        let json_data = load_test_json("http_get_tradingview_chart_data.json");
1644        let response: DeribitJsonRpcResponse<DeribitTradingViewChartData> =
1645            serde_json::from_str(&json_data).unwrap();
1646        let chart_data = response.result.expect("Test data must have result");
1647
1648        let bar_type = BarType::from("BTC-PERPETUAL.DERIBIT-1-MINUTE-LAST-EXTERNAL");
1649        let ts_init = UnixNanos::from(1766487086146245_u64 * NANOSECONDS_IN_MICROSECOND);
1650
1651        // Cost path picks `cost` (USD), matching trade `amount` on inverse perps/futures.
1652        let bars =
1653            parse_bars(&chart_data, bar_type, 1, 0, true, ts_init).expect("Should parse bars");
1654        assert_eq!(bars.len(), 5);
1655        assert_eq!(bars[0].volume, Quantity::from("257490"));
1656        assert_eq!(bars[4].volume, Quantity::from("8910"));
1657    }
1658
1659    #[rstest]
1660    fn test_parse_order_book_keeps_decimals_that_collapse_in_f64() {
1661        let json_data = load_test_json("http_get_order_book_exact.json");
1662        let response: DeribitJsonRpcResponse<DeribitOrderBook> =
1663            serde_json::from_str(&json_data).unwrap();
1664        let order_book_data = response.result.expect("Test data must have result");
1665        let instrument_id = InstrumentId::from("BTC-PERPETUAL.DERIBIT");
1666
1667        let book =
1668            parse_order_book(&order_book_data, instrument_id, 9, 9, UnixNanos::default()).unwrap();
1669
1670        assert_eq!(
1671            order_book_data.bids,
1672            vec![[dec!(100000000.123456789), dec!(100000000.123456789)]]
1673        );
1674        assert_eq!(
1675            order_book_data.asks,
1676            vec![[dec!(100000000.123456788), dec!(0.00011403)]]
1677        );
1678        assert_eq!(
1679            book.best_bid_price(),
1680            Some(Price::from("100000000.123456789"))
1681        );
1682        assert_eq!(
1683            book.best_bid_size(),
1684            Some(Quantity::from("100000000.123456789"))
1685        );
1686        assert_eq!(
1687            book.best_ask_price(),
1688            Some(Price::from("100000000.123456788"))
1689        );
1690        assert_eq!(book.best_ask_size(), Some(Quantity::from("0.000114030")));
1691    }
1692
1693    #[rstest]
1694    fn test_parse_order_book() {
1695        let json_data = load_test_json("http_get_order_book.json");
1696        let response: DeribitJsonRpcResponse<DeribitOrderBook> =
1697            serde_json::from_str(&json_data).unwrap();
1698        let order_book_data = response.result.expect("Test data must have result");
1699
1700        let instrument_id = InstrumentId::from("BTC-PERPETUAL.DERIBIT");
1701        let ts_init = UnixNanos::from(1766554855146274_u64 * NANOSECONDS_IN_MICROSECOND);
1702
1703        let book = parse_order_book(&order_book_data, instrument_id, 1, 0, ts_init)
1704            .expect("Should parse order book");
1705
1706        // Verify book metadata
1707        assert_eq!(book.instrument_id, instrument_id);
1708        assert_eq!(book.book_type, BookType::L2_MBP);
1709        assert_eq!(book.ts_last, ts_init);
1710
1711        // Verify book has both sides
1712        assert!(book.has_bid(), "Book should have bids");
1713        assert!(book.has_ask(), "Book should have asks");
1714
1715        // Verify best bid using OrderBook methods
1716        assert_eq!(
1717            book.best_bid_price(),
1718            Some(Price::from("87002.5")),
1719            "Best bid price should match"
1720        );
1721        assert_eq!(
1722            book.best_bid_size(),
1723            Some(Quantity::from("199190")),
1724            "Best bid size should match"
1725        );
1726
1727        // Verify best ask using OrderBook methods
1728        assert_eq!(
1729            book.best_ask_price(),
1730            Some(Price::from("87003.0")),
1731            "Best ask price should match"
1732        );
1733        assert_eq!(
1734            book.best_ask_size(),
1735            Some(Quantity::from("125090")),
1736            "Best ask size should match"
1737        );
1738
1739        // Verify spread (best_ask - best_bid = 87003.0 - 87002.5 = 0.5)
1740        let spread = book.spread().expect("Spread should exist");
1741        assert!(
1742            (spread - 0.5).abs() < 0.0001,
1743            "Spread should be 0.5, was {spread}"
1744        );
1745
1746        // Verify midpoint ((87003.0 + 87002.5) / 2 = 87002.75)
1747        let midpoint = book.midpoint().expect("Midpoint should exist");
1748        assert!(
1749            (midpoint - 87002.75).abs() < 0.0001,
1750            "Midpoint should be 87002.75, was {midpoint}"
1751        );
1752
1753        // Verify level counts match input data
1754        let bid_count = book.bids(None).count();
1755        let ask_count = book.asks(None).count();
1756        assert_eq!(
1757            bid_count,
1758            order_book_data.bids.len(),
1759            "Bid levels count should match input data"
1760        );
1761        assert_eq!(
1762            ask_count,
1763            order_book_data.asks.len(),
1764            "Ask levels count should match input data"
1765        );
1766        assert_eq!(bid_count, 20, "Should have 20 bid levels");
1767        assert_eq!(ask_count, 20, "Should have 20 ask levels");
1768
1769        // Verify depth limiting works (get top 5 levels)
1770        assert_eq!(
1771            book.bids(Some(5)).count(),
1772            5,
1773            "Should limit to 5 bid levels"
1774        );
1775        assert_eq!(
1776            book.asks(Some(5)).count(),
1777            5,
1778            "Should limit to 5 ask levels"
1779        );
1780
1781        // Verify bids_as_map and asks_as_map
1782        let bids_map = book.bids_as_map(None);
1783        let asks_map = book.asks_as_map(None);
1784        assert_eq!(bids_map.len(), 20, "Bids map should have 20 entries");
1785        assert_eq!(asks_map.len(), 20, "Asks map should have 20 entries");
1786
1787        // Verify specific prices exist in maps
1788        assert!(
1789            bids_map.contains_key(&dec!(87002.5)),
1790            "Bids map should contain best bid price"
1791        );
1792        assert!(
1793            asks_map.contains_key(&dec!(87003.0)),
1794            "Asks map should contain best ask price"
1795        );
1796
1797        // Verify worst levels exist
1798        assert!(
1799            bids_map.contains_key(&dec!(86980.0)),
1800            "Bids map should contain worst bid price"
1801        );
1802        assert!(
1803            asks_map.contains_key(&dec!(87031.5)),
1804            "Asks map should contain worst ask price"
1805        );
1806    }
1807
1808    fn make_instrument_id(symbol: &str) -> InstrumentId {
1809        InstrumentId::new(Symbol::from(symbol), *DERIBIT_VENUE)
1810    }
1811
1812    #[rstest]
1813    fn test_parse_futures_and_perpetuals() {
1814        // Perpetuals are classified as "future" in Deribit API
1815        let cases = [
1816            ("BTC-PERPETUAL", "future", "BTC"),
1817            ("ETH-PERPETUAL", "future", "ETH"),
1818            ("SOL-PERPETUAL", "future", "SOL"),
1819            // Futures with expiry dates
1820            ("BTC-25MAR23", "future", "BTC"),
1821            ("BTC-5AUG23", "future", "BTC"), // Single digit day
1822            ("ETH-28MAR25", "future", "ETH"),
1823        ];
1824
1825        for (symbol, expected_kind, expected_currency) in cases {
1826            let (kind, currency) = parse_instrument_kind_currency(&make_instrument_id(symbol));
1827            assert_eq!(kind, expected_kind, "kind mismatch for {symbol}");
1828            assert_eq!(
1829                currency, expected_currency,
1830                "currency mismatch for {symbol}"
1831            );
1832        }
1833    }
1834
1835    #[rstest]
1836    fn test_parse_options() {
1837        let cases = [
1838            // Standard options: {CURRENCY}-{DMMMYY}-{STRIKE}-{C|P}
1839            ("BTC-25MAR23-420-C", "option", "BTC"),
1840            ("BTC-5AUG23-580-P", "option", "BTC"),
1841            ("ETH-28MAR25-4000-C", "option", "ETH"),
1842            // Linear option with decimal strike (d = decimal point)
1843            ("XRP_USDC-30JUN23-0d625-C", "option", "XRP"),
1844        ];
1845
1846        for (symbol, expected_kind, expected_currency) in cases {
1847            let (kind, currency) = parse_instrument_kind_currency(&make_instrument_id(symbol));
1848            assert_eq!(kind, expected_kind, "kind mismatch for {symbol}");
1849            assert_eq!(
1850                currency, expected_currency,
1851                "currency mismatch for {symbol}"
1852            );
1853        }
1854    }
1855
1856    #[rstest]
1857    // Future combos: {CURRENCY}-FS-...
1858    #[case::future_combo_vs_perp("BTC-FS-19MAY26_PERP", "future_combo", "BTC")]
1859    #[case::future_combo_inter_month("BTC-FS-22MAY26_19MAY26", "future_combo", "BTC")]
1860    #[case::future_combo_eth("ETH-FS-26JUN26_PERP", "future_combo", "ETH")]
1861    // Option combos: {CURRENCY}-{STRATEGY}-...
1862    #[case::option_combo_call_spread("BTC-CS-19MAY26-70000_75000", "option_combo", "BTC")]
1863    #[case::option_combo_strangle("BTC-STRG-19MAY26-74000_79000", "option_combo", "BTC")]
1864    #[case::option_combo_straddle("BTC-STRD-29MAY26-77000", "option_combo", "BTC")]
1865    #[case::option_combo_box("BTC-BOX-25DEC26-58000_60000", "option_combo", "BTC")]
1866    #[case::option_combo_put_spread_eth("ETH-PS-26JUN26-3500_4000", "option_combo", "ETH")]
1867    fn test_parse_combo_kinds(
1868        #[case] symbol: &str,
1869        #[case] expected_kind: &str,
1870        #[case] expected_currency: &str,
1871    ) {
1872        let (kind, currency) = parse_instrument_kind_currency(&make_instrument_id(symbol));
1873        assert_eq!(kind, expected_kind, "kind mismatch for {symbol}");
1874        assert_eq!(
1875            currency, expected_currency,
1876            "currency mismatch for {symbol}"
1877        );
1878    }
1879
1880    #[rstest]
1881    fn test_parse_option_combo_instrument() {
1882        let json_data = load_test_json("http_get_instruments_option_combo.json");
1883        let response: DeribitJsonRpcResponse<Vec<DeribitInstrument>> =
1884            serde_json::from_str(&json_data).unwrap();
1885        let instruments = response.result.expect("Test data must have result");
1886        let raw = instruments
1887            .iter()
1888            .find(|i| i.instrument_name == "BTC-STRG-19MAY26-74000_79000")
1889            .expect("fixture must contain BTC-STRG-19MAY26-74000_79000");
1890
1891        let any = parse_deribit_instrument_any(raw, UnixNanos::default(), UnixNanos::default())
1892            .unwrap()
1893            .expect("Should parse option combo");
1894
1895        let InstrumentAny::CryptoOptionSpread(spread) = any else {
1896            panic!("Expected CryptoOptionSpread, was {any:?}");
1897        };
1898        assert_eq!(
1899            spread.id,
1900            InstrumentId::from("BTC-STRG-19MAY26-74000_79000.DERIBIT")
1901        );
1902        assert_eq!(spread.underlying.code, "BTC");
1903        assert_eq!(spread.strategy_type, "STRG");
1904        assert_eq!(spread.quote_currency.code, "BTC");
1905        assert_eq!(spread.settlement_currency.code, "BTC");
1906        assert!(spread.is_inverse);
1907        assert_eq!(spread.price_precision, 4);
1908        assert_eq!(spread.price_increment, Price::from("0.0001"));
1909        assert_eq!(spread.size_precision, 1);
1910        assert_eq!(spread.size_increment, Quantity::from("0.1"));
1911        assert_eq!(spread.multiplier, Quantity::from("1"));
1912        assert_eq!(spread.lot_size, Quantity::from("0.1"));
1913        assert_eq!(
1914            spread.expiration_ns,
1915            UnixNanos::from(1779177600000_u64 * 1_000_000)
1916        );
1917        assert_eq!(
1918            spread.activation_ns,
1919            UnixNanos::from(1779100724000_u64 * 1_000_000)
1920        );
1921    }
1922
1923    #[rstest]
1924    fn test_deserialize_option_combo_trade_with_legs() {
1925        let json_data = load_test_json("http_get_last_trades_option_combo.json");
1926        let response: DeribitJsonRpcResponse<DeribitTradesResponse> =
1927            serde_json::from_str(&json_data).unwrap();
1928        let result = response.result.expect("Test data must have result");
1929
1930        let combo_trade = &result.trades[0];
1931        assert_eq!(combo_trade.trade_id, "244365193");
1932        assert_eq!(combo_trade.instrument_name, "BTC-CS-19MAY26-70000_75000");
1933        assert_eq!(combo_trade.combo_id.as_deref(), None);
1934        assert_eq!(combo_trade.combo_trade_id.as_deref(), None);
1935
1936        let legs = combo_trade
1937            .legs
1938            .as_ref()
1939            .expect("Combo trade must have legs");
1940        assert_eq!(legs.len(), 2);
1941
1942        let leg_75c = &legs[0];
1943        assert_eq!(leg_75c.instrument_name, "BTC-19MAY26-75000-C");
1944        assert_eq!(leg_75c.trade_id, "244365195");
1945        assert_eq!(leg_75c.combo_trade_id, "244365193");
1946        assert_eq!(leg_75c.combo_id, "BTC-CS-19MAY26-70000_75000");
1947        assert_eq!(leg_75c.direction, "buy");
1948        assert_eq!(leg_75c.price, dec!(0.0174));
1949        assert_eq!(leg_75c.amount, dec!(0.1));
1950        assert_eq!(leg_75c.iv, Some(dec!(41.01)));
1951
1952        let leg_70c = &legs[1];
1953        assert_eq!(leg_70c.instrument_name, "BTC-19MAY26-70000-C");
1954        assert_eq!(leg_70c.trade_id, "244365194");
1955        assert_eq!(leg_70c.direction, "sell");
1956        assert_eq!(leg_70c.iv, Some(dec!(83.39)));
1957    }
1958
1959    #[rstest]
1960    fn test_deserialize_future_combo_trade_with_legs() {
1961        let json_data = load_test_json("http_get_last_trades_future_combo.json");
1962        let response: DeribitJsonRpcResponse<DeribitTradesResponse> =
1963            serde_json::from_str(&json_data).unwrap();
1964        let result = response.result.expect("Test data must have result");
1965
1966        let combo_trade = &result.trades[0];
1967        assert_eq!(combo_trade.trade_id, "244343053");
1968        assert_eq!(combo_trade.instrument_name, "BTC-FS-25DEC26_PERP");
1969        assert_eq!(combo_trade.price, dec!(1320.0));
1970        assert_eq!(combo_trade.amount, dec!(10.0));
1971
1972        let legs = combo_trade
1973            .legs
1974            .as_ref()
1975            .expect("Future combo trade must have legs");
1976        assert_eq!(legs.len(), 2);
1977
1978        // Leg 1: BTC-25DEC26 sell. Exact field values rather than is_empty.
1979        let leg_25dec = &legs[0];
1980        assert_eq!(leg_25dec.instrument_name, "BTC-25DEC26");
1981        assert_eq!(leg_25dec.trade_id, "244343055");
1982        assert_eq!(leg_25dec.combo_id, "BTC-FS-25DEC26_PERP");
1983        assert_eq!(leg_25dec.combo_trade_id, "244343053");
1984        assert_eq!(leg_25dec.direction, "sell");
1985        assert_eq!(leg_25dec.price, dec!(78624.0));
1986        assert_eq!(leg_25dec.amount, dec!(10.0));
1987        assert_eq!(leg_25dec.contracts, Some(dec!(1.0)));
1988        assert!(leg_25dec.iv.is_none(), "future leg must not carry iv");
1989
1990        // Leg 2: BTC-PERPETUAL buy.
1991        let leg_perp = &legs[1];
1992        assert_eq!(leg_perp.instrument_name, "BTC-PERPETUAL");
1993        assert_eq!(leg_perp.trade_id, "244343054");
1994        assert_eq!(leg_perp.combo_id, "BTC-FS-25DEC26_PERP");
1995        assert_eq!(leg_perp.combo_trade_id, "244343053");
1996        assert_eq!(leg_perp.direction, "buy");
1997        assert_eq!(leg_perp.price, dec!(77304.0));
1998        assert!(leg_perp.iv.is_none(), "future leg must not carry iv");
1999    }
2000
2001    #[rstest]
2002    fn test_deserialize_historical_combo_leg_with_missing_optional_fields() {
2003        // Pins the review-fix loop's optionality decisions on DeribitTradeLeg.
2004        // Synthesized fixture: one combo trade where the parent omits
2005        // contracts/index_price/mark_price (already optional pre-patch), and
2006        // legs omit varying subsets of the same Option<Decimal> fields plus
2007        // `iv`. A regression that re-tightens any of them will fail here.
2008        let json_data = load_test_json("http_get_last_trades_historical_combo.json");
2009        let response: DeribitJsonRpcResponse<DeribitTradesResponse> =
2010            serde_json::from_str(&json_data).unwrap();
2011        let result = response.result.expect("Test data must have result");
2012
2013        let combo_trade = &result.trades[0];
2014        assert_eq!(combo_trade.trade_id, "999000000");
2015        assert_eq!(combo_trade.instrument_name, "BTC-CS-19MAY26-70000_75000");
2016        // Parent-level optional fields all absent on this historical sample.
2017        assert!(combo_trade.contracts.is_none());
2018        assert!(combo_trade.index_price.is_none());
2019        assert!(combo_trade.mark_price.is_none());
2020
2021        let legs = combo_trade
2022            .legs
2023            .as_ref()
2024            .expect("Combo trade must have legs");
2025        assert_eq!(legs.len(), 2);
2026
2027        // Leg 1: every Option<Decimal> field absent (contracts, index_price,
2028        // mark_price, iv). Required fields still strong-asserted.
2029        let leg1 = &legs[0];
2030        assert_eq!(leg1.instrument_name, "BTC-19MAY26-75000-C");
2031        assert_eq!(leg1.trade_id, "999000001");
2032        assert_eq!(leg1.combo_id, "BTC-CS-19MAY26-70000_75000");
2033        assert_eq!(leg1.combo_trade_id, "999000000");
2034        assert_eq!(leg1.direction, "buy");
2035        assert_eq!(leg1.price, dec!(0.0174));
2036        assert_eq!(leg1.amount, dec!(0.1));
2037        assert!(leg1.contracts.is_none());
2038        assert!(leg1.index_price.is_none());
2039        assert!(leg1.mark_price.is_none());
2040        assert!(leg1.iv.is_none());
2041
2042        // Leg 2: contracts and mark_price absent; iv and index_price present.
2043        // Confirms the optional fields are independently parsed.
2044        let leg2 = &legs[1];
2045        assert_eq!(leg2.instrument_name, "BTC-19MAY26-70000-C");
2046        assert_eq!(leg2.trade_id, "999000002");
2047        assert!(leg2.contracts.is_none());
2048        assert!(leg2.mark_price.is_none());
2049        assert_eq!(leg2.index_price, Some(dec!(76185.14)));
2050        assert_eq!(leg2.iv, Some(dec!(83.39)));
2051    }
2052
2053    #[rstest]
2054    fn test_parse_combo_instrument_missing_expiration_errors() {
2055        // Locks invariant I9: build_spread_common must reject combo
2056        // instruments without an expiration_timestamp rather than producing a
2057        // zero-expiration InstrumentAny.
2058        let json_data = load_test_json("http_get_instruments_option_combo.json");
2059        let response: DeribitJsonRpcResponse<Vec<DeribitInstrument>> =
2060            serde_json::from_str(&json_data).unwrap();
2061        let mut instruments = response.result.expect("Test data must have result");
2062        let raw = instruments
2063            .iter_mut()
2064            .find(|i| i.instrument_name == "BTC-STRG-19MAY26-74000_79000")
2065            .expect("fixture must contain BTC-STRG-19MAY26-74000_79000");
2066        raw.expiration_timestamp = None;
2067
2068        let result = parse_deribit_instrument_any(raw, UnixNanos::default(), UnixNanos::default());
2069        let err = result.expect_err("Should error when expiration_timestamp is missing");
2070        let msg = format!("{err:#}");
2071        assert!(
2072            msg.contains("Missing expiration_timestamp for combo"),
2073            "unexpected error: {msg}"
2074        );
2075    }
2076
2077    #[rstest]
2078    fn test_deserialize_perpetual_combo_leg_tags() {
2079        // Per-leg stream carries combo_id + combo_trade_id when the leg
2080        // originated from a combo (gating evidence from Step 1).
2081        let json_data = load_test_json("http_get_last_trades_perpetual_with_combo_tags.json");
2082        let response: DeribitJsonRpcResponse<DeribitTradesResponse> =
2083            serde_json::from_str(&json_data).unwrap();
2084        let result = response.result.expect("Test data must have result");
2085
2086        for trade in &result.trades {
2087            assert_eq!(trade.instrument_name, "BTC-PERPETUAL");
2088            assert_eq!(trade.combo_id.as_deref(), Some("BTC-FS-25DEC26_PERP"));
2089            assert!(
2090                trade.combo_trade_id.is_some(),
2091                "Per-leg trade should carry combo_trade_id"
2092            );
2093            // Per-leg stream entries never carry a nested `legs` array.
2094            assert!(trade.legs.is_none());
2095        }
2096    }
2097
2098    #[rstest]
2099    fn test_parse_future_combo_instrument() {
2100        let json_data = load_test_json("http_get_instruments_future_combo.json");
2101        let response: DeribitJsonRpcResponse<Vec<DeribitInstrument>> =
2102            serde_json::from_str(&json_data).unwrap();
2103        let instruments = response.result.expect("Test data must have result");
2104        let raw = instruments
2105            .iter()
2106            .find(|i| i.instrument_name == "BTC-FS-19MAY26_PERP")
2107            .expect("fixture must contain BTC-FS-19MAY26_PERP");
2108
2109        let any = parse_deribit_instrument_any(raw, UnixNanos::default(), UnixNanos::default())
2110            .unwrap()
2111            .expect("Should parse future combo");
2112
2113        let InstrumentAny::CryptoFuturesSpread(spread) = any else {
2114            panic!("Expected CryptoFuturesSpread, was {any:?}");
2115        };
2116        assert_eq!(spread.id, InstrumentId::from("BTC-FS-19MAY26_PERP.DERIBIT"));
2117        assert_eq!(spread.underlying.code, "BTC");
2118        assert_eq!(spread.strategy_type, "FS");
2119        // Future combo quote_currency on BTC contracts is USD.
2120        assert_eq!(spread.quote_currency.code, "USD");
2121        assert_eq!(spread.settlement_currency.code, "BTC");
2122        assert!(spread.is_inverse);
2123        assert_eq!(spread.price_precision, 1);
2124        assert_eq!(spread.price_increment, Price::from("0.5"));
2125        assert_eq!(spread.size_precision, 0);
2126        assert_eq!(spread.size_increment, Quantity::from("10"));
2127        assert_eq!(spread.multiplier, Quantity::from("1"));
2128        assert_eq!(spread.lot_size, Quantity::from("10"));
2129        assert_eq!(
2130            spread.expiration_ns,
2131            UnixNanos::from(1779177600000_u64 * 1_000_000)
2132        );
2133    }
2134
2135    #[rstest]
2136    fn test_build_public_trade_id_plain() {
2137        let id = build_public_trade_id("244343053", None, None, None);
2138        assert_eq!(id.as_str(), "244343053");
2139    }
2140
2141    #[rstest]
2142    fn test_build_public_trade_id_combo_only() {
2143        let id = build_public_trade_id("244365195", None, None, Some("BTC-CS-19MAY26-70000_75000"));
2144        assert_eq!(id.as_str(), "COMBO-244365195");
2145    }
2146
2147    #[rstest]
2148    fn test_build_public_trade_id_block_only() {
2149        let id = build_public_trade_id("244343053", None, Some("12345"), None);
2150        assert_eq!(id.as_str(), "BLK-244343053");
2151    }
2152
2153    #[rstest]
2154    fn test_build_public_trade_id_rfq_only() {
2155        let id = build_public_trade_id("244343053", Some(99), None, None);
2156        assert_eq!(id.as_str(), "RFQ-244343053");
2157    }
2158
2159    #[rstest]
2160    fn test_build_public_trade_id_precedence_block_beats_combo() {
2161        // A combo executed as a block carries both combo_id and block_trade_id.
2162        // The block tag wins because it is the more important reconciliation signal.
2163        let id = build_public_trade_id(
2164            "244343053",
2165            None,
2166            Some("12345"),
2167            Some("BTC-FS-25DEC26_PERP"),
2168        );
2169        assert_eq!(id.as_str(), "BLK-244343053");
2170    }
2171
2172    #[rstest]
2173    fn test_build_public_trade_id_precedence_rfq_beats_all() {
2174        let id = build_public_trade_id(
2175            "244343053",
2176            Some(99),
2177            Some("12345"),
2178            Some("BTC-FS-25DEC26_PERP"),
2179        );
2180        assert_eq!(id.as_str(), "RFQ-244343053");
2181    }
2182
2183    #[rstest]
2184    fn test_parse_spot() {
2185        let cases = [
2186            ("BTC_USDC", "spot", "BTC"),
2187            ("ETH_USDT", "spot", "ETH"),
2188            ("SOL_USDC", "spot", "SOL"),
2189        ];
2190
2191        for (symbol, expected_kind, expected_currency) in cases {
2192            let (kind, currency) = parse_instrument_kind_currency(&make_instrument_id(symbol));
2193            assert_eq!(kind, expected_kind, "kind mismatch for {symbol}");
2194            assert_eq!(
2195                currency, expected_currency,
2196                "currency mismatch for {symbol}"
2197            );
2198        }
2199    }
2200
2201    #[rstest]
2202    fn test_parse_portfolio_to_account_state() {
2203        let json_data = load_test_json("ws_portfolio.json");
2204        let notification: serde_json::Value = serde_json::from_str(&json_data).unwrap();
2205
2206        // Extract the data field from the notification
2207        let data = notification
2208            .get("params")
2209            .and_then(|p| p.get("data"))
2210            .expect("Test data must have params.data");
2211
2212        let portfolio: DeribitPortfolioMsg =
2213            serde_json::from_str(&data.to_string()).expect("Should deserialize portfolio message");
2214
2215        // Verify deserialization
2216        assert_eq!(portfolio.currency, "USDT");
2217        assert_eq!(portfolio.equity, dec!(55.00055));
2218        assert_eq!(portfolio.balance, dec!(55.00055));
2219        assert_eq!(portfolio.available_funds, dec!(53.868247));
2220        assert_eq!(portfolio.margin_balance, dec!(54.968258));
2221        assert_eq!(portfolio.initial_margin, dec!(1.100011));
2222        assert_eq!(portfolio.maintenance_margin, dec!(0.0));
2223        assert_eq!(portfolio.cross_collateral_enabled, Some(true));
2224        assert_eq!(portfolio.margin_model.as_deref(), Some("cross_sm"));
2225
2226        // Test parsing to AccountState
2227        let account_id = AccountId::new("DERIBIT-master");
2228        let ts_init = UnixNanos::from(1700000000000000000_u64);
2229
2230        let account_state =
2231            parse_portfolio_to_account_state(&portfolio, account_id, ts_init).unwrap();
2232
2233        // Verify account state
2234        assert_eq!(account_state.account_id, account_id);
2235        assert_eq!(account_state.account_type, AccountType::Margin);
2236        assert!(account_state.is_reported);
2237
2238        // Verify balances (should have 1 balance for USDT)
2239        // cross_collateral_enabled=true so total=equity, free=available_withdrawal_funds
2240        assert_eq!(account_state.balances.len(), 1);
2241        let balance = &account_state.balances[0];
2242        assert_eq!(balance.currency.code, "USDT");
2243        assert_eq!(balance.total.as_f64(), 55.00055); // equity (not margin_balance)
2244        assert_eq!(balance.free.as_f64(), 54.968257); // available_withdrawal_funds (not available_funds)
2245
2246        // locked = total - free = 55.00055 - 54.968257 = 0.032293
2247        let locked = balance.locked.as_f64();
2248        assert!(
2249            (locked - 0.032293).abs() < 0.001,
2250            "Locked ({locked}) should be close to 0.032293"
2251        );
2252
2253        // Verify margins (should have 1 margin since initial_margin > 0)
2254        assert_eq!(account_state.margins.len(), 1);
2255        let margin = &account_state.margins[0];
2256        assert_eq!(margin.initial.as_f64(), 1.100011);
2257        assert_eq!(margin.maintenance.as_f64(), 0.0);
2258        assert!(margin.instrument_id.is_none());
2259        assert_eq!(margin.currency.code, "USDT");
2260    }
2261
2262    #[rstest]
2263    #[case::minute_1(1, "MINUTE", "1")]
2264    #[case::minute_2(2, "MINUTE", "3")]
2265    #[case::minute_3(3, "MINUTE", "3")]
2266    #[case::minute_4(4, "MINUTE", "5")]
2267    #[case::minute_5(5, "MINUTE", "5")]
2268    #[case::minute_6(6, "MINUTE", "10")]
2269    #[case::minute_10(10, "MINUTE", "10")]
2270    #[case::minute_12(12, "MINUTE", "15")]
2271    #[case::minute_15(15, "MINUTE", "15")]
2272    #[case::minute_20(20, "MINUTE", "30")]
2273    #[case::minute_30(30, "MINUTE", "30")]
2274    #[case::hour_1(1, "HOUR", "60")]
2275    #[case::hour_2(2, "HOUR", "120")]
2276    #[case::hour_3(3, "HOUR", "180")]
2277    #[case::hour_4(4, "HOUR", "360")]
2278    #[case::hour_6(6, "HOUR", "360")]
2279    #[case::hour_12(12, "HOUR", "720")]
2280    #[case::day_1(1, "DAY", "1D")]
2281    fn test_bar_spec_to_resolution(
2282        #[case] step: u64,
2283        #[case] aggregation: &str,
2284        #[case] expected: &str,
2285    ) {
2286        let bar_type_str = format!("BTC-PERPETUAL.DERIBIT-{step}-{aggregation}-LAST-EXTERNAL");
2287        let bar_type = BarType::from(bar_type_str.as_str());
2288        let resolution = bar_spec_to_resolution(&bar_type);
2289        assert_eq!(resolution, expected);
2290    }
2291}