Skip to main content

nautilus_deribit/http/
models.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//! Deribit HTTP API models and types.
17//!
18//! Types with decimal fields borrow their JSON tokens, so they deserialize only from borrowed input
19//! such as `serde_json::from_str` or `serde_json::from_slice`.
20
21use ahash::AHashMap;
22use nautilus_core::serialization::{decimal, deserialize_optional_decimal_token_borrowed};
23use rust_decimal::Decimal;
24use serde::{Deserialize, Serialize};
25use ustr::Ustr;
26
27use crate::common::serialization::{
28    deserialize_decimal_token_or_zero_borrowed, deserialize_decimal_token_pairs_borrowed,
29    deserialize_decimal_token_vec_borrowed,
30};
31pub use crate::common::{
32    enums::{DeribitCurrency, DeribitOptionType, DeribitProductType},
33    models::DeribitTradeLeg,
34    rpc::{DeribitJsonRpcError, DeribitJsonRpcRequest, DeribitJsonRpcResponse},
35};
36
37/// JSON-RPC 2.0 response payload (either success or error).
38#[derive(Debug, Serialize, Deserialize)]
39#[serde(untagged)]
40pub enum DeribitResponsePayload<T> {
41    /// Successful response with result data
42    Success { result: T },
43    /// Error response with error details
44    Error { error: DeribitJsonRpcError },
45}
46
47/// Deribit instrument definition.
48#[derive(Clone, Debug, Serialize, Deserialize)]
49pub struct DeribitInstrument {
50    /// The underlying currency being traded
51    pub base_currency: Ustr,
52    /// Block trade commission for instrument
53    #[serde(
54        default,
55        deserialize_with = "deserialize_optional_decimal_token_borrowed"
56    )]
57    pub block_trade_commission: Option<Decimal>,
58    /// Minimum amount for block trading
59    #[serde(
60        default,
61        deserialize_with = "deserialize_optional_decimal_token_borrowed"
62    )]
63    pub block_trade_min_trade_amount: Option<Decimal>,
64    /// Specifies minimal price change for block trading
65    #[serde(
66        default,
67        deserialize_with = "deserialize_optional_decimal_token_borrowed"
68    )]
69    pub block_trade_tick_size: Option<Decimal>,
70    /// Contract size for instrument
71    #[serde(deserialize_with = "deserialize_decimal_token_or_zero_borrowed")]
72    pub contract_size: Decimal,
73    /// Counter currency for the instrument
74    pub counter_currency: Option<Ustr>,
75    /// The time when the instrument was first created (milliseconds since UNIX epoch)
76    pub creation_timestamp: i64,
77    /// The time when the instrument will expire (milliseconds since UNIX epoch)
78    pub expiration_timestamp: Option<i64>,
79    /// Future type (deprecated, use instrument_type instead)
80    pub future_type: Option<String>,
81    /// Instrument ID
82    pub instrument_id: i64,
83    /// Unique instrument identifier (e.g., "BTC-PERPETUAL")
84    pub instrument_name: Ustr,
85    /// Type of the instrument: "linear" or "reversed"
86    pub instrument_type: Option<String>,
87    /// Indicates if the instrument can currently be traded
88    pub is_active: bool,
89    /// Product type: "future", "option", "spot", "future_combo", "option_combo"
90    pub kind: DeribitProductType,
91    /// Maker commission for instrument
92    #[serde(deserialize_with = "deserialize_decimal_token_or_zero_borrowed")]
93    pub maker_commission: Decimal,
94    /// Maximal leverage for instrument (only for futures)
95    pub max_leverage: Option<i64>,
96    /// Maximal liquidation trade commission for instrument (only for futures)
97    #[serde(
98        default,
99        deserialize_with = "deserialize_optional_decimal_token_borrowed"
100    )]
101    pub max_liquidation_commission: Option<Decimal>,
102    /// Minimum amount for trading
103    #[serde(deserialize_with = "deserialize_decimal_token_or_zero_borrowed")]
104    pub min_trade_amount: Decimal,
105    /// The option type (only for options)
106    pub option_type: Option<DeribitOptionType>,
107    /// Name of price index that is used for this instrument
108    pub price_index: Option<String>,
109    /// The currency in which the instrument prices are quoted
110    pub quote_currency: Ustr,
111    /// Settlement currency for the instrument (not present for spot)
112    pub settlement_currency: Option<Ustr>,
113    /// The settlement period (not present for spot)
114    pub settlement_period: Option<String>,
115    /// The strike value (only for options)
116    #[serde(
117        default,
118        deserialize_with = "deserialize_optional_decimal_token_borrowed"
119    )]
120    pub strike: Option<Decimal>,
121    /// Taker commission for instrument
122    #[serde(deserialize_with = "deserialize_decimal_token_or_zero_borrowed")]
123    pub taker_commission: Decimal,
124    /// Specifies minimal price change and number of decimal places for instrument prices
125    #[serde(deserialize_with = "deserialize_decimal_token_or_zero_borrowed")]
126    pub tick_size: Decimal,
127    /// Tick size steps for different price ranges
128    pub tick_size_steps: Option<Vec<DeribitTickSizeStep>>,
129    /// Presence identifies spot instruments routed to Coinbase Exchange.
130    #[serde(skip_serializing_if = "Option::is_none")]
131    pub is_cbe_routed: Option<bool>,
132    /// Alias for the Coinbase Exchange routing flag.
133    #[serde(skip_serializing_if = "Option::is_none")]
134    pub is_csr: Option<bool>,
135}
136
137/// Tick size step definition for price-dependent tick sizes.
138#[derive(Clone, Debug, Serialize, Deserialize)]
139pub struct DeribitTickSizeStep {
140    /// The price from which the increased tick size applies
141    #[serde(deserialize_with = "deserialize_decimal_token_or_zero_borrowed")]
142    pub above_price: Decimal,
143    /// Tick size to be used above the price
144    #[serde(deserialize_with = "deserialize_decimal_token_or_zero_borrowed")]
145    pub tick_size: Decimal,
146}
147
148/// Deribit combo definition from `public/get_combos`.
149#[derive(Clone, Debug, Serialize, Deserialize)]
150pub struct DeribitCombo {
151    /// Unique combo identifier, matching the combo instrument name.
152    pub id: Ustr,
153    /// Combo state, e.g. `active`.
154    pub state: String,
155    /// Combo leg makeup.
156    pub legs: Vec<DeribitComboLeg>,
157    /// Combo creation timestamp in milliseconds since UNIX epoch.
158    pub creation_timestamp: i64,
159    /// Numeric Deribit instrument ID.
160    pub instrument_id: i64,
161    /// State timestamp in milliseconds since UNIX epoch.
162    pub state_timestamp: i64,
163}
164
165/// A single leg entry of a Deribit combo definition.
166#[derive(Clone, Debug, Serialize, Deserialize)]
167pub struct DeribitComboLeg {
168    /// Signed leg amount. Positive is long, negative is short.
169    #[serde(deserialize_with = "deserialize_decimal_token_or_zero_borrowed")]
170    pub amount: Decimal,
171    /// Leg instrument name.
172    pub instrument_name: Ustr,
173}
174
175/// Wrapper for the account summaries response.
176///
177/// The API returns an object with a `summaries` field containing the array of account summaries,
178/// plus account-level metadata.
179#[derive(Debug, Clone, Serialize, Deserialize)]
180pub struct DeribitAccountSummariesResponse {
181    /// Array of per-currency account summaries
182    pub summaries: Vec<DeribitAccountSummary>,
183    /// Account ID
184    #[serde(default)]
185    pub id: Option<i64>,
186    /// Account email
187    #[serde(default)]
188    pub email: Option<String>,
189    /// System name
190    #[serde(default)]
191    pub system_name: Option<String>,
192    /// Account username
193    #[serde(default)]
194    pub username: Option<String>,
195    /// Account type (e.g., "main", "subaccount")
196    #[serde(rename = "type", default)]
197    pub account_type: Option<String>,
198    /// Account creation timestamp (milliseconds since UNIX epoch)
199    #[serde(default)]
200    pub creation_timestamp: Option<i64>,
201    /// Referrer ID (affiliation program)
202    #[serde(default)]
203    pub referrer_id: Option<String>,
204    /// Whether login is enabled for this account
205    #[serde(default)]
206    pub login_enabled: Option<bool>,
207    /// Whether security keys are enabled
208    #[serde(default)]
209    pub security_keys_enabled: Option<bool>,
210    /// Whether MMP (Market Maker Protection) is enabled
211    #[serde(default)]
212    pub mmp_enabled: Option<bool>,
213    /// Whether inter-user transfers are enabled
214    #[serde(default)]
215    pub interuser_transfers_enabled: Option<bool>,
216    /// Self-trading reject mode
217    #[serde(default)]
218    pub self_trading_reject_mode: Option<String>,
219    /// Whether self-trading is extended to subaccounts
220    #[serde(default)]
221    pub self_trading_extended_to_subaccounts: Option<bool>,
222    /// Block RFQ self match prevention
223    #[serde(default)]
224    pub block_rfq_self_match_prevention: Option<bool>,
225}
226
227/// Account summary for a single currency.
228///
229/// Contains balance, equity, margin information, and profit/loss data.
230#[derive(Debug, Clone, Serialize, Deserialize)]
231pub struct DeribitAccountSummary {
232    /// Currency code (e.g., "BTC", "ETH")
233    pub currency: Ustr,
234    /// Account equity (balance + unrealized PnL)
235    #[serde(deserialize_with = "deserialize_decimal_token_or_zero_borrowed")]
236    pub equity: Decimal,
237    /// Account balance
238    #[serde(deserialize_with = "deserialize_decimal_token_or_zero_borrowed")]
239    pub balance: Decimal,
240    /// Available funds for trading
241    #[serde(deserialize_with = "deserialize_decimal_token_or_zero_borrowed")]
242    pub available_funds: Decimal,
243    /// Margin balance (for derivatives)
244    #[serde(deserialize_with = "deserialize_decimal_token_or_zero_borrowed")]
245    pub margin_balance: Decimal,
246    /// Initial margin (required for current positions)
247    #[serde(
248        default,
249        deserialize_with = "deserialize_optional_decimal_token_borrowed"
250    )]
251    pub initial_margin: Option<Decimal>,
252    /// Maintenance margin
253    #[serde(
254        default,
255        deserialize_with = "deserialize_optional_decimal_token_borrowed"
256    )]
257    pub maintenance_margin: Option<Decimal>,
258    /// Total profit/loss
259    #[serde(
260        default,
261        deserialize_with = "deserialize_optional_decimal_token_borrowed"
262    )]
263    pub total_pl: Option<Decimal>,
264    /// Session unrealized profit/loss
265    #[serde(
266        default,
267        deserialize_with = "deserialize_optional_decimal_token_borrowed"
268    )]
269    pub session_upl: Option<Decimal>,
270    /// Session realized profit/loss
271    #[serde(
272        default,
273        deserialize_with = "deserialize_optional_decimal_token_borrowed"
274    )]
275    pub session_rpl: Option<Decimal>,
276    /// Portfolio margining enabled
277    #[serde(default)]
278    pub portfolio_margining_enabled: Option<bool>,
279    /// Margin model (e.g., "segregated_sm", "cross_sm", "cross_pm")
280    #[serde(default)]
281    pub margin_model: Option<String>,
282    /// Whether cross-collateral is enabled for this currency
283    #[serde(default)]
284    pub cross_collateral_enabled: Option<bool>,
285    /// Available withdrawal funds (per-currency withdrawable amount)
286    #[serde(
287        default,
288        deserialize_with = "deserialize_optional_decimal_token_borrowed"
289    )]
290    pub available_withdrawal_funds: Option<Decimal>,
291}
292
293/// Extended account summary with additional account details.
294///
295/// Returned by `private/get_account_summary` with `extended=true`.
296/// Contains all fields from [`DeribitAccountSummary`] plus account metadata,
297/// position Greeks, detailed margins, and fee structures.
298#[derive(Debug, Clone, Serialize, Deserialize)]
299pub struct DeribitAccountSummaryExtended {
300    /// Currency code (e.g., "BTC", "ETH")
301    pub currency: Ustr,
302    /// Account equity (balance + unrealized PnL)
303    #[serde(deserialize_with = "deserialize_decimal_token_or_zero_borrowed")]
304    pub equity: Decimal,
305    /// Account balance
306    #[serde(deserialize_with = "deserialize_decimal_token_or_zero_borrowed")]
307    pub balance: Decimal,
308    /// Available funds for trading
309    #[serde(deserialize_with = "deserialize_decimal_token_or_zero_borrowed")]
310    pub available_funds: Decimal,
311    /// Margin balance (for derivatives)
312    #[serde(deserialize_with = "deserialize_decimal_token_or_zero_borrowed")]
313    pub margin_balance: Decimal,
314    /// Initial margin (required for current positions)
315    #[serde(
316        default,
317        deserialize_with = "deserialize_optional_decimal_token_borrowed"
318    )]
319    pub initial_margin: Option<Decimal>,
320    /// Maintenance margin
321    #[serde(
322        default,
323        deserialize_with = "deserialize_optional_decimal_token_borrowed"
324    )]
325    pub maintenance_margin: Option<Decimal>,
326    /// Total profit/loss
327    #[serde(
328        default,
329        deserialize_with = "deserialize_optional_decimal_token_borrowed"
330    )]
331    pub total_pl: Option<Decimal>,
332    /// Session unrealized profit/loss
333    #[serde(
334        default,
335        deserialize_with = "deserialize_optional_decimal_token_borrowed"
336    )]
337    pub session_upl: Option<Decimal>,
338    /// Session realized profit/loss
339    #[serde(
340        default,
341        deserialize_with = "deserialize_optional_decimal_token_borrowed"
342    )]
343    pub session_rpl: Option<Decimal>,
344    /// Portfolio margining enabled
345    #[serde(default)]
346    pub portfolio_margining_enabled: Option<bool>,
347    // Extended fields below
348    /// Account ID
349    #[serde(default)]
350    pub id: Option<i64>,
351    /// Account email
352    #[serde(default)]
353    pub email: Option<String>,
354    /// Account username
355    #[serde(default)]
356    pub username: Option<String>,
357    /// System name
358    #[serde(default)]
359    pub system_name: Option<String>,
360    /// Account type (e.g., "main", "subaccount")
361    #[serde(rename = "type", default)]
362    pub account_type: Option<String>,
363    /// Futures session unrealized P&L
364    #[serde(
365        default,
366        deserialize_with = "deserialize_optional_decimal_token_borrowed"
367    )]
368    pub futures_session_upl: Option<Decimal>,
369    /// Futures session realized P&L
370    #[serde(
371        default,
372        deserialize_with = "deserialize_optional_decimal_token_borrowed"
373    )]
374    pub futures_session_rpl: Option<Decimal>,
375    /// Options session unrealized P&L
376    #[serde(
377        default,
378        deserialize_with = "deserialize_optional_decimal_token_borrowed"
379    )]
380    pub options_session_upl: Option<Decimal>,
381    /// Options session realized P&L
382    #[serde(
383        default,
384        deserialize_with = "deserialize_optional_decimal_token_borrowed"
385    )]
386    pub options_session_rpl: Option<Decimal>,
387    /// Futures profit/loss
388    #[serde(
389        default,
390        deserialize_with = "deserialize_optional_decimal_token_borrowed"
391    )]
392    pub futures_pl: Option<Decimal>,
393    /// Options profit/loss
394    #[serde(
395        default,
396        deserialize_with = "deserialize_optional_decimal_token_borrowed"
397    )]
398    pub options_pl: Option<Decimal>,
399    /// Options delta
400    #[serde(
401        default,
402        deserialize_with = "deserialize_optional_decimal_token_borrowed"
403    )]
404    pub options_delta: Option<Decimal>,
405    /// Options gamma
406    #[serde(
407        default,
408        deserialize_with = "deserialize_optional_decimal_token_borrowed"
409    )]
410    pub options_gamma: Option<Decimal>,
411    /// Options vega
412    #[serde(
413        default,
414        deserialize_with = "deserialize_optional_decimal_token_borrowed"
415    )]
416    pub options_vega: Option<Decimal>,
417    /// Options theta
418    #[serde(
419        default,
420        deserialize_with = "deserialize_optional_decimal_token_borrowed"
421    )]
422    pub options_theta: Option<Decimal>,
423    /// Options value
424    #[serde(
425        default,
426        deserialize_with = "deserialize_optional_decimal_token_borrowed"
427    )]
428    pub options_value: Option<Decimal>,
429    /// Total delta across all positions
430    #[serde(
431        default,
432        deserialize_with = "deserialize_optional_decimal_token_borrowed"
433    )]
434    pub delta_total: Option<Decimal>,
435    /// Projected delta total
436    #[serde(
437        default,
438        deserialize_with = "deserialize_optional_decimal_token_borrowed"
439    )]
440    pub projected_delta_total: Option<Decimal>,
441    /// Projected initial margin
442    #[serde(
443        default,
444        deserialize_with = "deserialize_optional_decimal_token_borrowed"
445    )]
446    pub projected_initial_margin: Option<Decimal>,
447    /// Projected maintenance margin
448    #[serde(
449        default,
450        deserialize_with = "deserialize_optional_decimal_token_borrowed"
451    )]
452    pub projected_maintenance_margin: Option<Decimal>,
453    /// Estimated liquidation ratio
454    #[serde(
455        default,
456        deserialize_with = "deserialize_optional_decimal_token_borrowed"
457    )]
458    pub estimated_liquidation_ratio: Option<Decimal>,
459    /// Available withdrawal funds
460    #[serde(
461        default,
462        deserialize_with = "deserialize_optional_decimal_token_borrowed"
463    )]
464    pub available_withdrawal_funds: Option<Decimal>,
465    /// Spot reserve
466    #[serde(
467        default,
468        deserialize_with = "deserialize_optional_decimal_token_borrowed"
469    )]
470    pub spot_reserve: Option<Decimal>,
471    /// Fee balance
472    #[serde(
473        default,
474        deserialize_with = "deserialize_optional_decimal_token_borrowed"
475    )]
476    pub fee_balance: Option<Decimal>,
477    /// Margin model (e.g., "segregated_sm", "cross_pm")
478    #[serde(default)]
479    pub margin_model: Option<String>,
480    /// Cross collateral enabled
481    #[serde(default)]
482    pub cross_collateral_enabled: Option<bool>,
483    /// Account creation timestamp (milliseconds since UNIX epoch)
484    #[serde(default)]
485    pub creation_timestamp: Option<i64>,
486    /// Whether login is enabled for this account
487    #[serde(default)]
488    pub login_enabled: Option<bool>,
489    /// Whether security keys are enabled
490    #[serde(default)]
491    pub security_keys_enabled: Option<bool>,
492    /// Whether MMP (Market Maker Protection) is enabled
493    #[serde(default)]
494    pub mmp_enabled: Option<bool>,
495    /// Whether inter-user transfers are enabled
496    #[serde(default)]
497    pub interuser_transfers_enabled: Option<bool>,
498    /// Self-trading reject mode
499    #[serde(default)]
500    pub self_trading_reject_mode: Option<String>,
501    /// Whether self-trading is extended to subaccounts
502    #[serde(default)]
503    pub self_trading_extended_to_subaccounts: Option<bool>,
504    /// Referrer ID (affiliation program)
505    #[serde(default)]
506    pub referrer_id: Option<String>,
507    /// Block RFQ self match prevention
508    #[serde(default)]
509    pub block_rfq_self_match_prevention: Option<bool>,
510}
511
512/// Deribit public trade data from the market data API.
513///
514/// Represents a single trade returned by `/public/get_last_trades_by_instrument_and_time`
515/// and other trade-related endpoints.
516#[derive(Clone, Debug, Serialize, Deserialize)]
517pub struct DeribitPublicTrade {
518    /// Trade amount. For perpetual and inverse futures the amount is in USD units.
519    /// For options and linear futures it is the underlying base currency coin.
520    #[serde(deserialize_with = "deserialize_decimal_token_or_zero_borrowed")]
521    pub amount: Decimal,
522    /// Trade size in contract units (optional, may be absent in historical trades).
523    #[serde(
524        default,
525        deserialize_with = "deserialize_optional_decimal_token_borrowed"
526    )]
527    pub contracts: Option<Decimal>,
528    /// Direction of the trade: "buy" or "sell"
529    pub direction: String,
530    /// Index Price at the moment of trade (can be empty for some trade types).
531    #[serde(
532        default,
533        deserialize_with = "deserialize_optional_decimal_token_borrowed"
534    )]
535    pub index_price: Option<Decimal>,
536    /// Unique instrument identifier.
537    pub instrument_name: String,
538    /// Option implied volatility for the price (Option only).
539    #[serde(
540        default,
541        deserialize_with = "deserialize_optional_decimal_token_borrowed"
542    )]
543    pub iv: Option<Decimal>,
544    /// Optional field (only for trades caused by liquidation).
545    #[serde(default)]
546    pub liquidation: Option<String>,
547    /// Mark Price at the moment of trade (can be empty for some trade types).
548    #[serde(
549        default,
550        deserialize_with = "deserialize_optional_decimal_token_borrowed"
551    )]
552    pub mark_price: Option<Decimal>,
553    /// Price in base currency.
554    #[serde(deserialize_with = "deserialize_decimal_token_or_zero_borrowed")]
555    pub price: Decimal,
556    /// Direction of the "tick" (0 = Plus Tick, 1 = Zero-Plus Tick, 2 = Minus Tick, 3 = Zero-Minus Tick).
557    pub tick_direction: i32,
558    /// The timestamp of the trade (milliseconds since the UNIX epoch).
559    pub timestamp: i64,
560    /// Unique (per currency) trade identifier.
561    pub trade_id: String,
562    /// The sequence number of the trade within instrument.
563    pub trade_seq: i64,
564    /// Block trade id - when trade was part of a block trade.
565    #[serde(default)]
566    pub block_trade_id: Option<String>,
567    /// Block trade leg count - when trade was part of a block trade.
568    #[serde(default)]
569    pub block_trade_leg_count: Option<i32>,
570    /// ID of the Block RFQ - when trade was part of the Block RFQ.
571    #[serde(default)]
572    pub block_rfq_id: Option<i64>,
573    /// Optional field containing combo instrument name if the trade is a combo trade.
574    #[serde(default)]
575    pub combo_id: Option<String>,
576    /// Optional field containing combo trade identifier if the trade is a combo trade.
577    #[serde(default)]
578    pub combo_trade_id: Option<String>,
579    /// Per-leg trades when this is the parent combo trade.
580    #[serde(default)]
581    pub legs: Option<Vec<DeribitTradeLeg>>,
582}
583
584/// Response wrapper for trades endpoints.
585///
586/// Contains the trades array and pagination information.
587#[derive(Clone, Debug, Serialize, Deserialize)]
588pub struct DeribitTradesResponse {
589    /// Whether there are more trades available.
590    pub has_more: bool,
591    /// Array of trade objects.
592    pub trades: Vec<DeribitPublicTrade>,
593}
594
595/// Expiration strings grouped by instrument kind.
596#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
597pub struct DeribitExpirationsByKind {
598    /// Future expirations, including `PERPETUAL` when present.
599    #[serde(default)]
600    pub future: Vec<String>,
601    /// Option expirations.
602    #[serde(default)]
603    pub option: Vec<String>,
604    /// Future combo expirations.
605    #[serde(default)]
606    pub future_combo: Vec<String>,
607    /// Option combo expirations.
608    #[serde(default)]
609    pub option_combo: Vec<String>,
610}
611
612/// Response from `public/get_expirations` endpoint.
613///
614/// Deribit returns a currency-keyed object for concrete or `grouped` currencies,
615/// and a direct kind-keyed object for `currency=any`.
616#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
617#[serde(untagged)]
618pub enum DeribitExpirationsResponse {
619    /// Expirations keyed by lowercase currency code.
620    ByCurrency(AHashMap<String, DeribitExpirationsByKind>),
621    /// Expirations returned without currency grouping.
622    Expirations(DeribitExpirationsByKind),
623}
624
625impl DeribitExpirationsResponse {
626    /// Returns expirations for a currency code, or the direct result for `currency=any`.
627    #[must_use]
628    pub fn expirations_for_currency(&self, currency: &str) -> Option<&DeribitExpirationsByKind> {
629        match self {
630            Self::ByCurrency(expirations) => {
631                let key = currency.to_ascii_lowercase();
632                expirations.get(&key)
633            }
634            Self::Expirations(expirations) => Some(expirations),
635        }
636    }
637}
638
639/// Response from `public/get_tradingview_chart_data` endpoint.
640///
641/// Contains OHLCV data in array format where each array element corresponds
642/// to a single candle at the index in the `ticks` array.
643#[derive(Clone, Debug, Serialize, Deserialize)]
644pub struct DeribitTradingViewChartData {
645    /// List of prices at close (one per candle)
646    #[serde(deserialize_with = "deserialize_decimal_token_vec_borrowed")]
647    pub close: Vec<Decimal>,
648    /// List of cost bars (volume in quote currency, one per candle)
649    #[serde(deserialize_with = "deserialize_decimal_token_vec_borrowed")]
650    pub cost: Vec<Decimal>,
651    /// List of highest price levels (one per candle)
652    #[serde(deserialize_with = "deserialize_decimal_token_vec_borrowed")]
653    pub high: Vec<Decimal>,
654    /// List of lowest price levels (one per candle)
655    #[serde(deserialize_with = "deserialize_decimal_token_vec_borrowed")]
656    pub low: Vec<Decimal>,
657    /// List of prices at open (one per candle)
658    #[serde(deserialize_with = "deserialize_decimal_token_vec_borrowed")]
659    pub open: Vec<Decimal>,
660    /// Status of the query: "ok" or "no_data"
661    pub status: String,
662    /// Values of the time axis given in milliseconds since UNIX epoch
663    pub ticks: Vec<i64>,
664    /// List of volume bars (in base currency, one per candle)
665    #[serde(deserialize_with = "deserialize_decimal_token_vec_borrowed")]
666    pub volume: Vec<Decimal>,
667}
668
669/// Response from `public/get_order_book` endpoint.
670///
671/// Contains the current order book state with bids, asks, and market data.
672#[derive(Clone, Debug, Serialize, Deserialize)]
673pub struct DeribitOrderBook {
674    /// The timestamp of the order book (milliseconds since UNIX epoch)
675    pub timestamp: i64,
676    /// Unique instrument identifier
677    pub instrument_name: String,
678    /// List of bids as [price, amount] pairs.
679    #[serde(deserialize_with = "deserialize_decimal_token_pairs_borrowed")]
680    pub bids: Vec<[Decimal; 2]>,
681    /// List of asks as [price, amount] pairs.
682    #[serde(deserialize_with = "deserialize_decimal_token_pairs_borrowed")]
683    pub asks: Vec<[Decimal; 2]>,
684    /// The state of the order book: "open" or "closed"
685    pub state: String,
686    /// The current best bid price (null if there aren't any bids)
687    #[serde(
688        default,
689        deserialize_with = "deserialize_optional_decimal_token_borrowed"
690    )]
691    pub best_bid_price: Option<Decimal>,
692    /// The current best ask price (null if there aren't any asks)
693    #[serde(
694        default,
695        deserialize_with = "deserialize_optional_decimal_token_borrowed"
696    )]
697    pub best_ask_price: Option<Decimal>,
698    /// The order size of all best bids
699    #[serde(
700        default,
701        deserialize_with = "deserialize_optional_decimal_token_borrowed"
702    )]
703    pub best_bid_amount: Option<Decimal>,
704    /// The order size of all best asks
705    #[serde(
706        default,
707        deserialize_with = "deserialize_optional_decimal_token_borrowed"
708    )]
709    pub best_ask_amount: Option<Decimal>,
710    /// The mark price for the instrument
711    #[serde(
712        default,
713        deserialize_with = "deserialize_optional_decimal_token_borrowed"
714    )]
715    pub mark_price: Option<Decimal>,
716    /// The price for the last trade
717    #[serde(
718        default,
719        deserialize_with = "deserialize_optional_decimal_token_borrowed"
720    )]
721    pub last_price: Option<Decimal>,
722    /// Current index price
723    #[serde(
724        default,
725        deserialize_with = "deserialize_optional_decimal_token_borrowed"
726    )]
727    pub index_price: Option<Decimal>,
728    /// The total amount of outstanding contracts
729    #[serde(
730        default,
731        deserialize_with = "deserialize_optional_decimal_token_borrowed"
732    )]
733    pub open_interest: Option<Decimal>,
734    /// The maximum price for the future
735    #[serde(
736        default,
737        deserialize_with = "deserialize_optional_decimal_token_borrowed"
738    )]
739    pub max_price: Option<Decimal>,
740    /// The minimum price for the future
741    #[serde(
742        default,
743        deserialize_with = "deserialize_optional_decimal_token_borrowed"
744    )]
745    pub min_price: Option<Decimal>,
746    /// Current funding (perpetual only)
747    #[serde(
748        default,
749        deserialize_with = "deserialize_optional_decimal_token_borrowed"
750    )]
751    pub current_funding: Option<Decimal>,
752    /// Funding 8h (perpetual only)
753    #[serde(
754        default,
755        deserialize_with = "deserialize_optional_decimal_token_borrowed"
756    )]
757    pub funding_8h: Option<Decimal>,
758    /// The settlement price for the instrument (when state = open)
759    #[serde(
760        default,
761        deserialize_with = "deserialize_optional_decimal_token_borrowed"
762    )]
763    pub settlement_price: Option<Decimal>,
764    /// The settlement/delivery price for the instrument (when state = closed)
765    #[serde(
766        default,
767        deserialize_with = "deserialize_optional_decimal_token_borrowed"
768    )]
769    pub delivery_price: Option<Decimal>,
770    /// (Only for option) implied volatility for best bid
771    #[serde(
772        default,
773        deserialize_with = "deserialize_optional_decimal_token_borrowed"
774    )]
775    pub bid_iv: Option<Decimal>,
776    /// (Only for option) implied volatility for best ask
777    #[serde(
778        default,
779        deserialize_with = "deserialize_optional_decimal_token_borrowed"
780    )]
781    pub ask_iv: Option<Decimal>,
782    /// (Only for option) implied volatility for mark price
783    #[serde(
784        default,
785        deserialize_with = "deserialize_optional_decimal_token_borrowed"
786    )]
787    pub mark_iv: Option<Decimal>,
788    /// Underlying price for implied volatility calculations (options only)
789    #[serde(
790        default,
791        deserialize_with = "deserialize_optional_decimal_token_borrowed"
792    )]
793    pub underlying_price: Option<Decimal>,
794    /// Name of the underlying future, or index_price (options only)
795    #[serde(default)]
796    pub underlying_index: Option<serde_json::Value>,
797    /// Interest rate used in implied volatility calculations (options only)
798    #[serde(
799        default,
800        deserialize_with = "deserialize_optional_decimal_token_borrowed"
801    )]
802    pub interest_rate: Option<Decimal>,
803}
804
805/// Wire DTO for `/public/get_book_summary_by_currency` entries.
806///
807/// Pure venue payload (no engine timestamps). Convert to the domain
808/// [`crate::data_types::DeribitBookSummary`] before emitting custom data.
809#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
810pub struct DeribitBookSummaryRaw {
811    /// Unique instrument identifier (e.g. "BTC-28MAR25-90000-C")
812    pub instrument_name: String,
813    /// The forward/underlying price for implied volatility calculations
814    #[serde(
815        default,
816        deserialize_with = "deserialize_optional_decimal_token_borrowed"
817    )]
818    pub underlying_price: Option<Decimal>,
819    /// Name of the underlying future or index (e.g. "BTC-28MAR25" or "SYN.BTC-28MAR25")
820    #[serde(default)]
821    pub underlying_index: Option<String>,
822    /// Mark price for the instrument
823    #[serde(
824        default,
825        deserialize_with = "deserialize_optional_decimal_token_borrowed"
826    )]
827    pub mark_price: Option<Decimal>,
828    /// Mid price
829    #[serde(
830        default,
831        deserialize_with = "deserialize_optional_decimal_token_borrowed"
832    )]
833    pub mid_price: Option<Decimal>,
834    /// Best bid price
835    #[serde(
836        default,
837        deserialize_with = "deserialize_optional_decimal_token_borrowed"
838    )]
839    pub bid_price: Option<Decimal>,
840    /// Best ask price
841    #[serde(
842        default,
843        deserialize_with = "deserialize_optional_decimal_token_borrowed"
844    )]
845    pub ask_price: Option<Decimal>,
846    /// Last traded price (`last` on the wire)
847    #[serde(
848        default,
849        rename = "last",
850        deserialize_with = "deserialize_optional_decimal_token_borrowed"
851    )]
852    pub last_price: Option<Decimal>,
853    /// Mark implied volatility (options; may be absent on some product kinds)
854    #[serde(
855        default,
856        deserialize_with = "deserialize_optional_decimal_token_borrowed"
857    )]
858    pub mark_iv: Option<Decimal>,
859    /// Bid implied volatility (options)
860    #[serde(
861        default,
862        deserialize_with = "deserialize_optional_decimal_token_borrowed"
863    )]
864    pub bid_iv: Option<Decimal>,
865    /// Ask implied volatility (options)
866    #[serde(
867        default,
868        deserialize_with = "deserialize_optional_decimal_token_borrowed"
869    )]
870    pub ask_iv: Option<Decimal>,
871    /// Interest rate used in IV calculations (options)
872    #[serde(
873        default,
874        deserialize_with = "deserialize_optional_decimal_token_borrowed"
875    )]
876    pub interest_rate: Option<Decimal>,
877    /// Open interest
878    #[serde(
879        default,
880        deserialize_with = "deserialize_optional_decimal_token_borrowed"
881    )]
882    pub open_interest: Option<Decimal>,
883    /// Open interest value when provided by the venue
884    #[serde(
885        default,
886        deserialize_with = "deserialize_optional_decimal_token_borrowed"
887    )]
888    pub open_interest_value: Option<Decimal>,
889    /// 24h volume in contracts / base units
890    #[serde(
891        default,
892        deserialize_with = "deserialize_optional_decimal_token_borrowed"
893    )]
894    pub volume: Option<Decimal>,
895    /// 24h volume in USD
896    #[serde(
897        default,
898        deserialize_with = "deserialize_optional_decimal_token_borrowed"
899    )]
900    pub volume_usd: Option<Decimal>,
901    /// 24h notional volume
902    #[serde(
903        default,
904        deserialize_with = "deserialize_optional_decimal_token_borrowed"
905    )]
906    pub volume_notional: Option<Decimal>,
907    /// 24h volume in BTC (when provided)
908    #[serde(
909        default,
910        deserialize_with = "deserialize_optional_decimal_token_borrowed"
911    )]
912    pub volume_btc: Option<Decimal>,
913    /// 24h high price
914    #[serde(
915        default,
916        deserialize_with = "deserialize_optional_decimal_token_borrowed"
917    )]
918    pub high: Option<Decimal>,
919    /// 24h low price
920    #[serde(
921        default,
922        deserialize_with = "deserialize_optional_decimal_token_borrowed"
923    )]
924    pub low: Option<Decimal>,
925    /// 24h price change (`price_change` on the wire)
926    #[serde(
927        default,
928        rename = "price_change",
929        deserialize_with = "deserialize_optional_decimal_token_borrowed"
930    )]
931    pub price_change: Option<Decimal>,
932    /// Estimated delivery price
933    #[serde(
934        default,
935        deserialize_with = "deserialize_optional_decimal_token_borrowed"
936    )]
937    pub estimated_delivery_price: Option<Decimal>,
938    /// Settlement/delivery price when present
939    #[serde(
940        default,
941        deserialize_with = "deserialize_optional_decimal_token_borrowed"
942    )]
943    pub delivery_price: Option<Decimal>,
944    /// Base currency
945    #[serde(default)]
946    pub base_currency: Option<String>,
947    /// Quote currency
948    #[serde(default)]
949    pub quote_currency: Option<String>,
950    /// Book summary snapshot time (milliseconds since UNIX epoch)
951    #[serde(default)]
952    pub creation_timestamp: i64,
953}
954
955#[cfg(test)]
956mod book_summary_tests {
957    use rstest::rstest;
958    use rust_decimal_macros::dec;
959
960    use super::*;
961
962    #[rstest]
963    fn test_book_summary_raw_deserializes_full_option_payload() {
964        let json = r#"{
965            "instrument_name": "BTC-28MAR25-90000-C",
966            "underlying_price": 95000.5,
967            "underlying_index": "SYN.BTC-28MAR25",
968            "mark_price": 0.042,
969            "mid_price": 0.041,
970            "bid_price": 0.040,
971            "ask_price": 0.042,
972            "last": 0.0415,
973            "mark_iv": 55.2,
974            "bid_iv": 54.0,
975            "ask_iv": 56.1,
976            "interest_rate": 0.0,
977            "open_interest": 123.5,
978            "volume": 10.0,
979            "volume_usd": 950000.0,
980            "volume_notional": 10.0,
981            "high": 0.05,
982            "low": 0.03,
983            "price_change": 0.01,
984            "estimated_delivery_price": 94900.0,
985            "base_currency": "BTC",
986            "quote_currency": "USD",
987            "creation_timestamp": 1710000000000
988        }"#;
989
990        let summary: DeribitBookSummaryRaw = serde_json::from_str(json).unwrap();
991        assert_eq!(summary.instrument_name, "BTC-28MAR25-90000-C");
992        assert_eq!(summary.underlying_price, Some(dec!(95000.5)));
993        assert_eq!(summary.underlying_index.as_deref(), Some("SYN.BTC-28MAR25"));
994        assert_eq!(summary.mark_price, Some(dec!(0.042)));
995        assert_eq!(summary.last_price, Some(dec!(0.0415)));
996        assert_eq!(summary.mark_iv, Some(dec!(55.2)));
997        assert_eq!(summary.bid_price, Some(dec!(0.040)));
998        assert_eq!(summary.ask_price, Some(dec!(0.042)));
999        assert_eq!(summary.open_interest, Some(dec!(123.5)));
1000        assert_eq!(summary.volume_usd, Some(dec!(950000.0)));
1001        assert_eq!(summary.price_change, Some(dec!(0.01)));
1002        assert_eq!(summary.creation_timestamp, 1_710_000_000_000);
1003    }
1004
1005    #[rstest]
1006    fn test_book_summary_raw_deserializes_minimal_payload() {
1007        let json = r#"{
1008            "instrument_name": "BTC-28MAR25-90000-C",
1009            "creation_timestamp": 1710000000000
1010        }"#;
1011
1012        let summary: DeribitBookSummaryRaw = serde_json::from_str(json).unwrap();
1013        assert_eq!(summary.instrument_name, "BTC-28MAR25-90000-C");
1014        assert!(summary.mark_iv.is_none());
1015        assert!(summary.open_interest.is_none());
1016        assert_eq!(summary.creation_timestamp, 1_710_000_000_000);
1017    }
1018}
1019
1020/// Ticker data from `/public/ticker` endpoint.
1021///
1022/// Selected option ticker fields are included;
1023/// serde will ignore the many additional fields returned by the API.
1024#[derive(Clone, Debug, Serialize, Deserialize)]
1025pub struct DeribitTicker {
1026    /// Unique instrument identifier (e.g., "BTC-28FEB26-65000-C")
1027    pub instrument_name: String,
1028    /// Underlying price for implied volatility calculations (options only)
1029    #[serde(
1030        default,
1031        deserialize_with = "deserialize_optional_decimal_token_borrowed"
1032    )]
1033    pub underlying_price: Option<Decimal>,
1034    /// Name of the underlying future or index (e.g., "BTC-28MAR25" or "SYN.BTC-28MAR25")
1035    #[serde(default)]
1036    pub underlying_index: Option<String>,
1037}
1038
1039/// Position data from `/private/get_positions` endpoint.
1040///
1041/// Contains information about a single position in a specific instrument.
1042#[derive(Debug, Clone, Serialize, Deserialize)]
1043pub struct DeribitPosition {
1044    /// Unique instrument identifier
1045    pub instrument_name: Ustr,
1046    /// Position direction: "buy" (long), "sell" (short), or "zero" (flat)
1047    pub direction: String,
1048    /// Position size in contracts (positive = long, negative = short)
1049    #[serde(
1050        serialize_with = "decimal::serialize",
1051        deserialize_with = "deserialize_decimal_token_or_zero_borrowed"
1052    )]
1053    pub size: Decimal,
1054    /// Average entry price
1055    #[serde(
1056        serialize_with = "decimal::serialize",
1057        deserialize_with = "deserialize_decimal_token_or_zero_borrowed"
1058    )]
1059    pub average_price: Decimal,
1060    /// Current mark price
1061    #[serde(
1062        serialize_with = "decimal::serialize",
1063        deserialize_with = "deserialize_decimal_token_or_zero_borrowed"
1064    )]
1065    pub mark_price: Decimal,
1066    /// Current index price
1067    #[serde(
1068        default,
1069        serialize_with = "decimal::serialize_optional",
1070        deserialize_with = "deserialize_optional_decimal_token_borrowed"
1071    )]
1072    pub index_price: Option<Decimal>,
1073    /// Maintenance margin
1074    #[serde(
1075        serialize_with = "decimal::serialize",
1076        deserialize_with = "deserialize_decimal_token_or_zero_borrowed"
1077    )]
1078    pub maintenance_margin: Decimal,
1079    /// Initial margin
1080    #[serde(
1081        serialize_with = "decimal::serialize",
1082        deserialize_with = "deserialize_decimal_token_or_zero_borrowed"
1083    )]
1084    pub initial_margin: Decimal,
1085    /// Current available leverage for a future position (can be fractional)
1086    #[serde(
1087        default,
1088        serialize_with = "decimal::serialize_optional",
1089        deserialize_with = "deserialize_optional_decimal_token_borrowed"
1090    )]
1091    pub leverage: Option<Decimal>,
1092    /// Current unrealized profit/loss
1093    #[serde(
1094        serialize_with = "decimal::serialize",
1095        deserialize_with = "deserialize_decimal_token_or_zero_borrowed"
1096    )]
1097    pub floating_profit_loss: Decimal,
1098    /// Realized profit/loss for this position
1099    #[serde(
1100        serialize_with = "decimal::serialize",
1101        deserialize_with = "deserialize_decimal_token_or_zero_borrowed"
1102    )]
1103    pub realized_profit_loss: Decimal,
1104    /// Total profit/loss (floating + realized)
1105    #[serde(
1106        serialize_with = "decimal::serialize",
1107        deserialize_with = "deserialize_decimal_token_or_zero_borrowed"
1108    )]
1109    pub total_profit_loss: Decimal,
1110    /// Product type: future, option, spot, etc.
1111    pub kind: DeribitProductType,
1112    /// Position size in currency units (for currency-quoted positions)
1113    #[serde(
1114        default,
1115        serialize_with = "decimal::serialize_optional",
1116        deserialize_with = "deserialize_optional_decimal_token_borrowed"
1117    )]
1118    pub size_currency: Option<Decimal>,
1119    /// Estimated liquidation price
1120    #[serde(
1121        default,
1122        serialize_with = "decimal::serialize_optional",
1123        deserialize_with = "deserialize_optional_decimal_token_borrowed"
1124    )]
1125    pub estimated_liquidation_price: Option<Decimal>,
1126    /// Position delta (for options)
1127    #[serde(
1128        default,
1129        serialize_with = "decimal::serialize_optional",
1130        deserialize_with = "deserialize_optional_decimal_token_borrowed"
1131    )]
1132    pub delta: Option<Decimal>,
1133    /// Position gamma (for options)
1134    #[serde(
1135        default,
1136        serialize_with = "decimal::serialize_optional",
1137        deserialize_with = "deserialize_optional_decimal_token_borrowed"
1138    )]
1139    pub gamma: Option<Decimal>,
1140    /// Position vega (for options)
1141    #[serde(
1142        default,
1143        serialize_with = "decimal::serialize_optional",
1144        deserialize_with = "deserialize_optional_decimal_token_borrowed"
1145    )]
1146    pub vega: Option<Decimal>,
1147    /// Position theta (for options)
1148    #[serde(
1149        default,
1150        serialize_with = "decimal::serialize_optional",
1151        deserialize_with = "deserialize_optional_decimal_token_borrowed"
1152    )]
1153    pub theta: Option<Decimal>,
1154    /// Settlement price (if settled)
1155    #[serde(
1156        default,
1157        serialize_with = "decimal::serialize_optional",
1158        deserialize_with = "deserialize_optional_decimal_token_borrowed"
1159    )]
1160    pub settlement_price: Option<Decimal>,
1161    /// Open orders margin for this position
1162    #[serde(
1163        default,
1164        serialize_with = "decimal::serialize_optional",
1165        deserialize_with = "deserialize_optional_decimal_token_borrowed"
1166    )]
1167    pub open_orders_margin: Option<Decimal>,
1168    /// Average price in USD (for currency-margined contracts)
1169    #[serde(
1170        default,
1171        serialize_with = "decimal::serialize_optional",
1172        deserialize_with = "deserialize_optional_decimal_token_borrowed"
1173    )]
1174    pub average_price_usd: Option<Decimal>,
1175    /// Realized profit loss (session)
1176    #[serde(
1177        default,
1178        serialize_with = "decimal::serialize_optional",
1179        deserialize_with = "deserialize_optional_decimal_token_borrowed"
1180    )]
1181    pub realized_profit_loss_session: Option<Decimal>,
1182    /// Floating profit loss in USD
1183    #[serde(
1184        default,
1185        serialize_with = "decimal::serialize_optional",
1186        deserialize_with = "deserialize_optional_decimal_token_borrowed"
1187    )]
1188    pub floating_profit_loss_usd: Option<Decimal>,
1189}
1190
1191/// Response wrapper for user trades endpoints.
1192///
1193/// Contains the trades array and pagination information.
1194/// Used by `/private/get_user_trades_by_*` endpoints.
1195#[derive(Clone, Debug, Serialize, Deserialize)]
1196pub struct DeribitUserTradesResponse {
1197    /// Whether there are more trades available.
1198    pub has_more: bool,
1199    /// Array of user trade objects.
1200    pub trades: Vec<crate::websocket::messages::DeribitUserTradeMsg>,
1201}
1202
1203#[cfg(test)]
1204mod tests {
1205    use rstest::rstest;
1206    use rust_decimal_macros::dec;
1207
1208    use super::*;
1209
1210    // One decimal field keeps the error independent of `serde_json/preserve_order` key order
1211    #[rstest]
1212    fn test_decimal_fields_reject_value_input() {
1213        let value = serde_json::json!({ "amount": -1, "instrument_name": "BTC-PERPETUAL" });
1214
1215        let error = serde_json::from_value::<DeribitComboLeg>(value).unwrap_err();
1216
1217        assert_eq!(
1218            error.to_string(),
1219            r#"invalid type: string "-1", expected raw value"#
1220        );
1221    }
1222
1223    #[rstest]
1224    #[case::integer(r#""leverage": 50,"#, Some(dec!(50)))]
1225    #[case::whole_float(r#""leverage": 50.0,"#, Some(dec!(50)))]
1226    #[case::fractional(r#""leverage": 35.639422,"#, Some(dec!(35.639422)))]
1227    #[case::null(r#""leverage": null,"#, None)]
1228    #[case::missing("", None)]
1229    fn test_deserialize_position_leverage(#[case] field: &str, #[case] expected: Option<Decimal>) {
1230        let json = format!(
1231            r#"{{
1232                "average_price": 7440.18,
1233                "direction": "buy",
1234                "floating_profit_loss": 0,
1235                "initial_margin": 0.000197283,
1236                "instrument_name": "BTC-PERPETUAL",
1237                "kind": "future",
1238                {field}
1239                "maintenance_margin": 0.000143783,
1240                "mark_price": 7476.65,
1241                "realized_profit_loss": -9e-9,
1242                "size": 50,
1243                "total_profit_loss": 0.000032781
1244            }}"#
1245        );
1246
1247        let position: DeribitPosition = serde_json::from_str(&json).unwrap();
1248
1249        assert_eq!(position.leverage, expected);
1250    }
1251
1252    #[rstest]
1253    fn test_deserialize_public_trade_with_empty_mark_and_index_price() {
1254        let json = r#"{
1255            "amount": 1.0,
1256            "direction": "sell",
1257            "index_price": "",
1258            "instrument_name": "ETH-PERPETUAL",
1259            "mark_price": "",
1260            "price": 2968.3,
1261            "tick_direction": 0,
1262            "timestamp": 1766332040636,
1263            "trade_id": "ETH-123",
1264            "trade_seq": 1
1265        }"#;
1266
1267        let trade: DeribitPublicTrade = serde_json::from_str(json).unwrap();
1268        assert_eq!(trade.index_price, None);
1269        assert_eq!(trade.mark_price, None);
1270        assert_eq!(trade.price, dec!(2968.3));
1271    }
1272
1273    #[rstest]
1274    fn test_deserialize_public_trade_with_missing_mark_and_index_price() {
1275        let json = r#"{
1276            "amount": 1.0,
1277            "direction": "sell",
1278            "instrument_name": "ETH-PERPETUAL",
1279            "price": 2968.3,
1280            "tick_direction": 0,
1281            "timestamp": 1766332040636,
1282            "trade_id": "ETH-123",
1283            "trade_seq": 1
1284        }"#;
1285
1286        let trade: DeribitPublicTrade = serde_json::from_str(json).unwrap();
1287        assert_eq!(trade.index_price, None);
1288        assert_eq!(trade.mark_price, None);
1289    }
1290
1291    #[rstest]
1292    fn test_deserialize_public_trade_with_present_mark_and_index_price() {
1293        let json = r#"{
1294            "amount": 1.0,
1295            "direction": "sell",
1296            "index_price": 2967.73,
1297            "instrument_name": "ETH-PERPETUAL",
1298            "mark_price": 2968.01,
1299            "price": 2968.3,
1300            "tick_direction": 0,
1301            "timestamp": 1766332040636,
1302            "trade_id": "ETH-123",
1303            "trade_seq": 1
1304        }"#;
1305
1306        let trade: DeribitPublicTrade = serde_json::from_str(json).unwrap();
1307        assert_eq!(trade.index_price, Some(dec!(2967.73)));
1308        assert_eq!(trade.mark_price, Some(dec!(2968.01)));
1309    }
1310
1311    #[rstest]
1312    fn test_deserialize_expirations_currency_keyed_response() {
1313        let json = r#"{
1314            "btc": {
1315                "option": ["20MAY26", "26JUN26"],
1316                "future": ["20MAY26", "PERPETUAL"]
1317            }
1318        }"#;
1319
1320        let response: DeribitExpirationsResponse = serde_json::from_str(json).unwrap();
1321        let expirations = response.expirations_for_currency("BTC").unwrap();
1322        assert_eq!(expirations.option, vec!["20MAY26", "26JUN26"]);
1323        assert_eq!(expirations.future, vec!["20MAY26", "PERPETUAL"]);
1324    }
1325
1326    #[rstest]
1327    fn test_deserialize_expirations_direct_response() {
1328        let json = r#"{
1329            "option": ["20MAY26", "26JUN26"],
1330            "future": ["20MAY26", "PERPETUAL"]
1331        }"#;
1332
1333        let response: DeribitExpirationsResponse = serde_json::from_str(json).unwrap();
1334        let expirations = response.expirations_for_currency("any").unwrap();
1335        assert_eq!(expirations.option, vec!["20MAY26", "26JUN26"]);
1336        assert_eq!(expirations.future, vec!["20MAY26", "PERPETUAL"]);
1337    }
1338}