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