Skip to main content

nautilus_deribit/websocket/
messages.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//! Data structures for Deribit WebSocket JSON-RPC messages.
17//!
18//! Types with decimal fields or book levels borrow their JSON tokens, so they deserialize only from
19//! borrowed input such as `serde_json::from_str` or `serde_json::from_slice`.
20
21use std::{borrow::Cow, fmt::Debug};
22
23use nautilus_core::{
24    serialization::{
25        decimal, deserialize_decimal_token_borrowed, deserialize_optional_decimal_token_borrowed,
26    },
27    string::secret::{REDACTED, SecretString},
28};
29use nautilus_model::{
30    data::{
31        Data, FundingRateUpdate, InstrumentStatus, OrderBookDeltas, greeks::OptionGreekValues,
32        option_chain::OptionGreeks,
33    },
34    events::{
35        AccountState, OrderAccepted, OrderCancelDenied, OrderCancelRejected, OrderCanceled,
36        OrderExpired, OrderFilled, OrderModifyDenied, OrderModifyRejected, OrderRejected,
37        OrderUpdated,
38    },
39    instruments::InstrumentAny,
40    reports::{FillReport, OrderStatusReport},
41};
42use rust_decimal::{Decimal, prelude::ToPrimitive};
43use serde::{Deserialize, Deserializer, Serialize, de};
44use serde_json::value::RawValue;
45use ustr::Ustr;
46use zeroize::{Zeroize, ZeroizeOnDrop};
47
48use super::enums::{DeribitBookAction, DeribitBookMsgType, DeribitHeartbeatType};
49pub use crate::common::{
50    enums::DeribitInstrumentState,
51    rpc::{DeribitJsonRpcError, DeribitJsonRpcRequest, DeribitJsonRpcResponse},
52};
53use crate::{
54    common::{models::DeribitTradeLeg, serialization::deserialize_decimal_token_or_zero_borrowed},
55    websocket::error::DeribitWsError,
56};
57
58/// JSON-RPC subscription notification from Deribit.
59#[derive(Debug, Clone, Deserialize)]
60pub struct DeribitSubscriptionNotification<T> {
61    /// JSON-RPC version.
62    pub jsonrpc: String,
63    /// Method name (always "subscription").
64    pub method: String,
65    /// Subscription parameters containing channel and data.
66    pub params: DeribitSubscriptionParams<T>,
67}
68
69/// Subscription notification parameters.
70#[derive(Debug, Clone, Deserialize)]
71pub struct DeribitSubscriptionParams<T> {
72    /// Channel name (e.g., "trades.BTC-PERPETUAL.raw").
73    pub channel: String,
74    /// Channel-specific data.
75    pub data: T,
76}
77
78/// Authentication request parameters for client_signature grant.
79#[derive(Debug, Clone, Serialize, Zeroize)]
80pub struct DeribitAuthParams {
81    /// Grant type (client_signature for HMAC auth).
82    pub grant_type: String,
83    /// Client ID (API key).
84    pub client_id: SecretString,
85    /// Unix timestamp in milliseconds.
86    pub timestamp: u64,
87    /// HMAC-SHA256 signature.
88    pub signature: SecretString,
89    /// Random nonce.
90    pub nonce: String,
91    /// Data string (empty for WebSocket auth).
92    pub data: SecretString,
93    /// Optional scope for session-based authentication.
94    /// Use "session:name" for persistent session auth (allows skipping access_token in private requests).
95    /// Use "connection" (default) for per-connection auth (requires access_token in each private request).
96    #[serde(skip_serializing_if = "Option::is_none")]
97    pub scope: Option<String>,
98}
99
100/// Token refresh request parameters.
101#[derive(Debug, Clone, Serialize, Zeroize)]
102pub struct DeribitRefreshTokenParams {
103    /// Grant type (always "refresh_token").
104    pub grant_type: String,
105    /// The refresh token obtained from authentication.
106    pub refresh_token: SecretString,
107}
108
109/// Authentication response result.
110#[derive(Debug, Clone, Deserialize, Zeroize, ZeroizeOnDrop)]
111pub struct DeribitAuthResult {
112    /// Access token.
113    pub access_token: SecretString,
114    /// Token expiration time in seconds.
115    pub expires_in: u64,
116    /// Refresh token.
117    pub refresh_token: SecretString,
118    /// Granted scope.
119    pub scope: String,
120    /// Token type (bearer).
121    pub token_type: String,
122    /// Enabled features.
123    #[serde(default)]
124    pub enabled_features: Vec<String>,
125}
126
127/// Subscription request parameters.
128#[derive(Debug, Clone, Serialize)]
129pub struct DeribitSubscribeParams {
130    /// List of channels to subscribe to.
131    pub channels: Vec<String>,
132}
133
134/// Subscription response result.
135#[derive(Debug, Clone, Deserialize)]
136pub struct DeribitSubscribeResult(pub Vec<String>);
137
138/// Heartbeat enable request parameters.
139#[derive(Debug, Clone, Serialize)]
140pub struct DeribitHeartbeatParams {
141    /// Heartbeat interval in seconds (minimum 10).
142    pub interval: u64,
143}
144
145/// Heartbeat notification data.
146#[derive(Debug, Clone, Deserialize)]
147pub struct DeribitHeartbeatData {
148    /// Heartbeat type.
149    #[serde(rename = "type")]
150    pub heartbeat_type: DeribitHeartbeatType,
151}
152
153/// Trade data from trades.{instrument}.raw channel.
154#[derive(Debug, Clone, Deserialize)]
155pub struct DeribitTradeMsg {
156    /// Trade ID.
157    pub trade_id: String,
158    /// Instrument name.
159    pub instrument_name: Ustr,
160    /// Trade price.
161    #[serde(deserialize_with = "deserialize_decimal_token_or_zero_borrowed")]
162    pub price: Decimal,
163    /// Trade amount (contracts).
164    #[serde(deserialize_with = "deserialize_decimal_token_or_zero_borrowed")]
165    pub amount: Decimal,
166    /// Trade direction ("buy" or "sell").
167    pub direction: String,
168    /// Trade timestamp in milliseconds.
169    pub timestamp: u64,
170    /// Trade sequence number.
171    pub trade_seq: u64,
172    /// Tick direction (0-3).
173    pub tick_direction: i8,
174    /// Index price at trade time.
175    #[serde(deserialize_with = "deserialize_decimal_token_or_zero_borrowed")]
176    pub index_price: Decimal,
177    /// Mark price at trade time.
178    #[serde(deserialize_with = "deserialize_decimal_token_or_zero_borrowed")]
179    pub mark_price: Decimal,
180    /// IV (for options).
181    #[serde(
182        default,
183        deserialize_with = "deserialize_optional_decimal_token_borrowed"
184    )]
185    pub iv: Option<Decimal>,
186    /// Liquidation indicator.
187    pub liquidation: Option<String>,
188    /// Combo trade ID (if part of combo).
189    pub combo_trade_id: Option<String>,
190    /// Block trade ID.
191    pub block_trade_id: Option<String>,
192    /// Block RFQ ID (if the trade originated from a Block RFQ).
193    #[serde(default)]
194    pub block_rfq_id: Option<i64>,
195    /// Combo ID.
196    pub combo_id: Option<String>,
197    /// Per-leg trades when this is the parent combo trade.
198    #[serde(default)]
199    pub legs: Option<Vec<DeribitTradeLeg>>,
200}
201
202/// Order book data from book.{instrument}.{interval} or book.{instrument}.{group}.{depth}.{interval} channels.
203///
204/// Note: The grouped book channel (`book.{instrument}.{group}.{depth}.{interval}`) does not include
205/// a `type` field since it always sends complete snapshots. We default to `Snapshot` when not present.
206#[derive(Debug, Clone, Deserialize)]
207pub struct DeribitBookMsg<'a> {
208    /// Message type (snapshot or change). Defaults to Snapshot for grouped channels.
209    #[serde(rename = "type", default = "default_book_msg_type")]
210    pub msg_type: DeribitBookMsgType,
211    /// Instrument name.
212    pub instrument_name: Ustr,
213    /// Timestamp in milliseconds.
214    pub timestamp: u64,
215    /// Change ID for sequence tracking.
216    pub change_id: u64,
217    /// Previous change ID (for delta validation).
218    pub prev_change_id: Option<u64>,
219    /// Bid levels: [action, price, amount] where action is "new" for snapshot, "new"/"change"/"delete" for change.
220    #[serde(borrow)]
221    pub bids: Vec<Vec<&'a RawValue>>,
222    /// Ask levels: [action, price, amount] where action is "new" for snapshot, "new"/"change"/"delete" for change.
223    #[serde(borrow)]
224    pub asks: Vec<Vec<&'a RawValue>>,
225}
226
227/// Default book message type for grouped channels (always snapshot).
228fn default_book_msg_type() -> DeribitBookMsgType {
229    DeribitBookMsgType::Snapshot
230}
231
232/// Parsed order book level.
233#[derive(Debug, Clone)]
234pub struct DeribitBookLevel {
235    /// Price level.
236    pub price: Decimal,
237    /// Amount at this level.
238    pub amount: Decimal,
239    /// Action for delta updates.
240    pub action: Option<DeribitBookAction>,
241}
242
243/// Ticker data from ticker.{instrument}.raw channel.
244#[derive(Debug, Clone, Deserialize)]
245pub struct DeribitTickerMsg {
246    /// Instrument name.
247    pub instrument_name: Ustr,
248    /// Timestamp in milliseconds.
249    pub timestamp: u64,
250    /// Best bid price.
251    #[serde(
252        default,
253        deserialize_with = "deserialize_optional_decimal_token_borrowed"
254    )]
255    pub best_bid_price: Option<Decimal>,
256    /// Best bid amount.
257    #[serde(
258        default,
259        deserialize_with = "deserialize_optional_decimal_token_borrowed"
260    )]
261    pub best_bid_amount: Option<Decimal>,
262    /// Best ask price.
263    #[serde(
264        default,
265        deserialize_with = "deserialize_optional_decimal_token_borrowed"
266    )]
267    pub best_ask_price: Option<Decimal>,
268    /// Best ask amount.
269    #[serde(
270        default,
271        deserialize_with = "deserialize_optional_decimal_token_borrowed"
272    )]
273    pub best_ask_amount: Option<Decimal>,
274    /// Last trade price.
275    #[serde(
276        default,
277        deserialize_with = "deserialize_optional_decimal_token_borrowed"
278    )]
279    pub last_price: Option<Decimal>,
280    /// Mark price.
281    #[serde(deserialize_with = "deserialize_decimal_token_or_zero_borrowed")]
282    pub mark_price: Decimal,
283    /// Index price.
284    #[serde(deserialize_with = "deserialize_decimal_token_or_zero_borrowed")]
285    pub index_price: Decimal,
286    /// Open interest.
287    #[serde(deserialize_with = "deserialize_decimal_token_or_zero_borrowed")]
288    pub open_interest: Decimal,
289    /// Current funding rate (perpetuals).
290    #[serde(
291        default,
292        deserialize_with = "deserialize_optional_decimal_token_borrowed"
293    )]
294    pub current_funding: Option<Decimal>,
295    /// Funding 8h rate (perpetuals).
296    #[serde(
297        default,
298        deserialize_with = "deserialize_optional_decimal_token_borrowed"
299    )]
300    pub funding_8h: Option<Decimal>,
301    /// Settlement price (expired instruments).
302    #[serde(
303        default,
304        deserialize_with = "deserialize_optional_decimal_token_borrowed"
305    )]
306    pub settlement_price: Option<Decimal>,
307    /// 24h volume.
308    #[serde(
309        default,
310        deserialize_with = "deserialize_optional_decimal_token_borrowed"
311    )]
312    pub volume: Option<Decimal>,
313    /// 24h volume in USD.
314    #[serde(
315        default,
316        deserialize_with = "deserialize_optional_decimal_token_borrowed"
317    )]
318    pub volume_usd: Option<Decimal>,
319    /// 24h high.
320    #[serde(
321        default,
322        deserialize_with = "deserialize_optional_decimal_token_borrowed"
323    )]
324    pub high: Option<Decimal>,
325    /// 24h low.
326    #[serde(
327        default,
328        deserialize_with = "deserialize_optional_decimal_token_borrowed"
329    )]
330    pub low: Option<Decimal>,
331    /// 24h price change.
332    #[serde(
333        default,
334        deserialize_with = "deserialize_optional_decimal_token_borrowed"
335    )]
336    pub price_change: Option<Decimal>,
337    /// State of the instrument.
338    pub state: String,
339    // Options-specific fields
340    /// Greeks (options).
341    pub greeks: Option<DeribitGreeks>,
342    /// Mark implied volatility (options).
343    #[serde(
344        default,
345        deserialize_with = "deserialize_optional_decimal_token_borrowed"
346    )]
347    pub mark_iv: Option<Decimal>,
348    /// Bid implied volatility (options).
349    #[serde(
350        default,
351        deserialize_with = "deserialize_optional_decimal_token_borrowed"
352    )]
353    pub bid_iv: Option<Decimal>,
354    /// Ask implied volatility (options).
355    #[serde(
356        default,
357        deserialize_with = "deserialize_optional_decimal_token_borrowed"
358    )]
359    pub ask_iv: Option<Decimal>,
360    /// Underlying price (options).
361    #[serde(
362        default,
363        deserialize_with = "deserialize_optional_decimal_token_borrowed"
364    )]
365    pub underlying_price: Option<Decimal>,
366    /// Underlying index (options).
367    pub underlying_index: Option<String>,
368}
369
370/// Greeks for options.
371#[derive(Debug, Clone, Deserialize)]
372pub struct DeribitGreeks {
373    #[serde(deserialize_with = "deserialize_decimal_token_or_zero_borrowed")]
374    pub delta: Decimal,
375    #[serde(deserialize_with = "deserialize_decimal_token_or_zero_borrowed")]
376    pub gamma: Decimal,
377    #[serde(deserialize_with = "deserialize_decimal_token_or_zero_borrowed")]
378    pub vega: Decimal,
379    #[serde(deserialize_with = "deserialize_decimal_token_or_zero_borrowed")]
380    pub theta: Decimal,
381    #[serde(deserialize_with = "deserialize_decimal_token_or_zero_borrowed")]
382    pub rho: Decimal,
383}
384
385impl DeribitGreeks {
386    /// Converts Deribit Greeks (Decimal) to Nautilus `OptionGreekValues` (f64).
387    pub fn to_greek_values(&self) -> OptionGreekValues {
388        OptionGreekValues {
389            delta: self.delta.to_f64().unwrap_or(0.0),
390            gamma: self.gamma.to_f64().unwrap_or(0.0),
391            vega: self.vega.to_f64().unwrap_or(0.0),
392            theta: self.theta.to_f64().unwrap_or(0.0),
393            rho: self.rho.to_f64().unwrap_or(0.0),
394        }
395    }
396}
397
398/// Quote data from quote.{instrument} channel.
399#[derive(Debug, Clone, Deserialize)]
400pub struct DeribitQuoteMsg {
401    /// Instrument name.
402    pub instrument_name: Ustr,
403    /// Timestamp in milliseconds.
404    pub timestamp: u64,
405    /// Best bid price.
406    #[serde(deserialize_with = "deserialize_decimal_token_or_zero_borrowed")]
407    pub best_bid_price: Decimal,
408    /// Best bid amount.
409    #[serde(deserialize_with = "deserialize_decimal_token_or_zero_borrowed")]
410    pub best_bid_amount: Decimal,
411    /// Best ask price.
412    #[serde(deserialize_with = "deserialize_decimal_token_or_zero_borrowed")]
413    pub best_ask_price: Decimal,
414    /// Best ask amount.
415    #[serde(deserialize_with = "deserialize_decimal_token_or_zero_borrowed")]
416    pub best_ask_amount: Decimal,
417}
418
419/// Instrument state notification from `instrument.state.{kind}.{currency}` channel.
420///
421/// Notifications are sent when an instrument's lifecycle state changes.
422/// Example: `{"instrument_name":"BTC-22MAR19","state":"created","timestamp":1553080940000}`
423#[derive(Debug, Clone, Deserialize)]
424pub struct DeribitInstrumentStateMsg {
425    /// Name of the instrument.
426    pub instrument_name: Ustr,
427    /// Current state of the instrument.
428    pub state: DeribitInstrumentState,
429    /// Timestamp of the state change in milliseconds.
430    pub timestamp: u64,
431}
432
433/// Deribit perpetual interest rate message.
434///
435/// Sent via the `perpetual.{instrument_name}.{interval}` channel.
436/// Only available for perpetual instruments.
437/// Example: `{"index_price":7872.88,"interest":0.004999511380756577,"timestamp":1571386349530}`
438#[derive(Debug, Clone, Deserialize)]
439pub struct DeribitPerpetualMsg {
440    /// Current index price.
441    #[serde(deserialize_with = "deserialize_decimal_token_or_zero_borrowed")]
442    pub index_price: Decimal,
443    /// Current interest rate (funding rate).
444    #[serde(deserialize_with = "deserialize_decimal_token_or_zero_borrowed")]
445    pub interest: Decimal,
446    /// Timestamp in milliseconds since Unix epoch.
447    pub timestamp: u64,
448}
449
450/// Volatility index data from the `deribit_volatility_index.{index_name}` channel.
451#[derive(Debug, Clone, Deserialize)]
452pub struct DeribitVolatilityIndexMsg {
453    /// Timestamp in milliseconds since Unix epoch.
454    pub timestamp: u64,
455    /// Current volatility index value.
456    pub volatility: f64,
457    /// Index identifier (for example `"btc_usd"`).
458    pub index_name: String,
459}
460
461/// Chart/OHLC bar data from chart.trades.{instrument}.{resolution} channel.
462///
463/// Sent via the `chart.trades.{instrument_name}.{resolution}` channel.
464/// Status of a chart/candle bar from Deribit.
465#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
466#[serde(rename_all = "lowercase")]
467pub enum DeribitChartStatus {
468    /// Bar is closed/confirmed.
469    #[default]
470    Ok,
471    /// Bar is still in progress (imputed/partial data).
472    Imputed,
473}
474
475/// Example: `{"tick":1767199200000,"open":87699.5,"high":87699.5,"low":87699.5,"close":87699.5,"volume":1.1403e-4,"cost":10.0,"status":"ok"}`
476#[derive(Debug, Clone, Deserialize)]
477pub struct DeribitChartMsg {
478    /// Bar timestamp in milliseconds since Unix epoch.
479    pub tick: u64,
480    /// Opening price.
481    #[serde(deserialize_with = "deserialize_decimal_token_borrowed")]
482    pub open: Decimal,
483    /// Highest price.
484    #[serde(deserialize_with = "deserialize_decimal_token_borrowed")]
485    pub high: Decimal,
486    /// Lowest price.
487    #[serde(deserialize_with = "deserialize_decimal_token_borrowed")]
488    pub low: Decimal,
489    /// Closing price.
490    #[serde(deserialize_with = "deserialize_decimal_token_borrowed")]
491    pub close: Decimal,
492    /// Volume in base currency.
493    #[serde(deserialize_with = "deserialize_decimal_token_borrowed")]
494    pub volume: Decimal,
495    /// Volume in USD.
496    #[serde(deserialize_with = "deserialize_decimal_token_borrowed")]
497    pub cost: Decimal,
498    /// Bar status: `Ok` for closed bar, `Imputed` for in-progress bar.
499    #[serde(default)]
500    pub status: DeribitChartStatus,
501}
502
503/// Order parameters for private/buy and private/sell requests.
504///
505/// Decimal fields serialize as exact JSON numbers. Without `serde_json/arbitrary_precision`,
506/// serialization fails when the JSON number would change the decimal value.
507#[derive(Debug, Clone, Serialize)]
508pub struct DeribitOrderParams {
509    /// Instrument name (e.g., "BTC-PERPETUAL").
510    pub instrument_name: String,
511    /// Order amount in contracts.
512    #[serde(serialize_with = "decimal::serialize")]
513    pub amount: Decimal,
514    /// Order type: "limit", "market", "stop_limit", "stop_market", "take_limit", "take_market".
515    #[serde(rename = "type")]
516    pub order_type: String,
517    /// User-defined label (client order ID), max 64 chars alphanumeric.
518    #[serde(skip_serializing_if = "Option::is_none")]
519    pub label: Option<String>,
520    /// Limit price (required for limit orders).
521    #[serde(
522        skip_serializing_if = "Option::is_none",
523        serialize_with = "decimal::serialize_optional"
524    )]
525    pub price: Option<Decimal>,
526    /// Time in force: "good_til_cancelled", "good_til_day", "fill_or_kill", "immediate_or_cancel".
527    #[serde(skip_serializing_if = "Option::is_none")]
528    pub time_in_force: Option<String>,
529    /// Post-only flag. If true and order would take liquidity, price is adjusted
530    /// to be just below the spread (unless reject_post_only is true).
531    #[serde(skip_serializing_if = "Option::is_none")]
532    pub post_only: Option<bool>,
533    /// If true with post_only, order is rejected instead of price being adjusted.
534    /// Only valid when post_only is true.
535    #[serde(skip_serializing_if = "Option::is_none")]
536    pub reject_post_only: Option<bool>,
537    /// Reduce-only flag (only reduces position).
538    #[serde(skip_serializing_if = "Option::is_none")]
539    pub reduce_only: Option<bool>,
540    /// Trigger price for stop/take orders.
541    #[serde(
542        skip_serializing_if = "Option::is_none",
543        serialize_with = "decimal::serialize_optional"
544    )]
545    pub trigger_price: Option<Decimal>,
546    /// Trigger type: "last_price", "index_price", "mark_price".
547    #[serde(skip_serializing_if = "Option::is_none")]
548    pub trigger: Option<String>,
549    /// Maximum display quantity for iceberg orders.
550    #[serde(
551        skip_serializing_if = "Option::is_none",
552        serialize_with = "decimal::serialize_optional"
553    )]
554    pub max_show: Option<Decimal>,
555    /// GTD expiration timestamp in milliseconds.
556    #[serde(skip_serializing_if = "Option::is_none")]
557    pub valid_until: Option<u64>,
558}
559
560/// Cancel order parameters for private/cancel request.
561#[derive(Debug, Clone, Serialize)]
562pub struct DeribitCancelParams {
563    /// Venue order ID to cancel.
564    pub order_id: String,
565}
566
567/// Cancel all orders parameters for private/cancel_all_by_instrument request.
568#[derive(Debug, Clone, Serialize)]
569pub struct DeribitCancelAllByInstrumentParams {
570    /// Instrument name.
571    pub instrument_name: String,
572    /// Optional order type filter.
573    #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
574    pub order_type: Option<String>,
575}
576
577/// Edit order parameters for private/edit request.
578///
579/// Decimal fields serialize as exact JSON numbers. Without `serde_json/arbitrary_precision`,
580/// serialization fails when the JSON number would change the decimal value.
581#[derive(Debug, Clone, Serialize)]
582pub struct DeribitEditParams {
583    /// Venue order ID to modify.
584    pub order_id: String,
585    /// New amount.
586    #[serde(serialize_with = "decimal::serialize")]
587    pub amount: Decimal,
588    /// New price (for limit orders).
589    #[serde(
590        skip_serializing_if = "Option::is_none",
591        serialize_with = "decimal::serialize_optional"
592    )]
593    pub price: Option<Decimal>,
594    /// New trigger price (for stop orders).
595    #[serde(
596        skip_serializing_if = "Option::is_none",
597        serialize_with = "decimal::serialize_optional"
598    )]
599    pub trigger_price: Option<Decimal>,
600    /// Post-only flag. If true and order would take liquidity, price is adjusted
601    /// to be just below the spread (unless reject_post_only is true).
602    #[serde(skip_serializing_if = "Option::is_none")]
603    pub post_only: Option<bool>,
604    /// If true with post_only, order is rejected instead of price being adjusted.
605    /// Only valid when post_only is true.
606    #[serde(skip_serializing_if = "Option::is_none")]
607    pub reject_post_only: Option<bool>,
608    /// Reduce-only flag.
609    #[serde(skip_serializing_if = "Option::is_none")]
610    pub reduce_only: Option<bool>,
611}
612
613/// Get order state parameters for private/get_order_state request.
614#[derive(Debug, Clone, Serialize)]
615pub struct DeribitGetOrderStateParams {
616    /// Venue order ID.
617    pub order_id: String,
618}
619
620// Deribit returns the literal string `"market_price"` for the price of trigger
621// market orders (`stop_market`, `take_market`) since they have no limit price.
622// Such values are mapped to `None`; other inputs delegate to the optional exact
623// decimal reader.
624fn deserialize_optional_decimal_or_market<'de, D>(
625    deserializer: D,
626) -> Result<Option<Decimal>, D::Error>
627where
628    D: Deserializer<'de>,
629{
630    match Option::<&'de RawValue>::deserialize(deserializer)? {
631        Some(raw) if raw.get() == "\"market_price\"" => Ok(None),
632        Some(raw) => deserialize_optional_decimal_token_borrowed(raw)
633            .map_err(|_| de::Error::custom("expected a decimal or market_price")),
634        None => Ok(None),
635    }
636}
637
638/// Order response from buy/sell/edit operations.
639///
640/// Contains the order details and any trades that resulted from the order.
641#[derive(Debug, Clone, Deserialize)]
642pub struct DeribitOrderResponse {
643    /// The order details.
644    pub order: DeribitOrderMsg,
645    /// Any trades executed as part of this order.
646    #[serde(default)]
647    pub trades: Vec<DeribitUserTradeMsg>,
648}
649
650/// Order message structure from Deribit.
651///
652/// Received from order responses and user.orders subscription.
653#[derive(Debug, Clone, Deserialize)]
654pub struct DeribitOrderMsg {
655    /// Unique order ID assigned by Deribit.
656    pub order_id: String,
657    /// User-defined label (client order ID).
658    pub label: Option<String>,
659    /// Instrument name.
660    pub instrument_name: Ustr,
661    /// Order direction: "buy" or "sell".
662    pub direction: String,
663    /// Order type: "limit", "market", "stop_limit", "stop_market", "take_limit", "take_market".
664    pub order_type: String,
665    /// Order state: "open", "filled", "rejected", "cancelled", "untriggered".
666    pub order_state: String,
667    /// Whether this update reflects an order replacement or amendment.
668    #[serde(default)]
669    pub replaced: bool,
670    /// Limit price (None for market orders, or when Deribit returns the
671    /// literal `"market_price"` for trigger market orders).
672    #[serde(default, deserialize_with = "deserialize_optional_decimal_or_market")]
673    pub price: Option<Decimal>,
674    /// Original order amount in contracts.
675    #[serde(deserialize_with = "deserialize_decimal_token_or_zero_borrowed")]
676    pub amount: Decimal,
677    /// Amount filled so far. Deribit omits this field for untriggered trigger
678    /// orders (e.g. `stop_market`, `stop_limit`); treat the missing case as zero.
679    #[serde(
680        default,
681        deserialize_with = "deserialize_decimal_token_or_zero_borrowed"
682    )]
683    pub filled_amount: Decimal,
684    /// Average fill price.
685    #[serde(
686        default,
687        deserialize_with = "deserialize_optional_decimal_token_borrowed"
688    )]
689    pub average_price: Option<Decimal>,
690    /// Order creation timestamp in milliseconds.
691    pub creation_timestamp: u64,
692    /// Last update timestamp in milliseconds.
693    pub last_update_timestamp: u64,
694    /// Time in force setting.
695    pub time_in_force: String,
696    /// Commission paid in base currency.
697    #[serde(
698        default,
699        deserialize_with = "deserialize_decimal_token_or_zero_borrowed"
700    )]
701    pub commission: Decimal,
702    /// Post-only flag.
703    #[serde(default)]
704    pub post_only: bool,
705    /// Reduce-only flag.
706    #[serde(default)]
707    pub reduce_only: bool,
708    /// Trigger price for stop/take orders.
709    #[serde(
710        default,
711        deserialize_with = "deserialize_optional_decimal_token_borrowed"
712    )]
713    pub trigger_price: Option<Decimal>,
714    /// Trigger type: "last_price", "index_price", "mark_price".
715    pub trigger: Option<String>,
716    /// Max show quantity for iceberg orders.
717    #[serde(
718        default,
719        deserialize_with = "deserialize_optional_decimal_token_borrowed"
720    )]
721    pub max_show: Option<Decimal>,
722    /// API request flag.
723    #[serde(default)]
724    pub api: bool,
725    /// Reject reason if order was rejected.
726    pub reject_reason: Option<String>,
727    /// Cancel reason if order was cancelled.
728    pub cancel_reason: Option<String>,
729}
730
731/// User trade message from Deribit.
732///
733/// Received from order responses and user.trades subscription.
734#[derive(Debug, Clone, Serialize, Deserialize)]
735pub struct DeribitUserTradeMsg {
736    /// Unique trade ID.
737    pub trade_id: String,
738    /// Associated order ID.
739    pub order_id: String,
740    /// Instrument name.
741    pub instrument_name: Ustr,
742    /// Trade direction: "buy" or "sell".
743    pub direction: String,
744    /// Execution price.
745    #[serde(
746        serialize_with = "decimal::serialize",
747        deserialize_with = "deserialize_decimal_token_or_zero_borrowed"
748    )]
749    pub price: Decimal,
750    /// Trade amount in contracts.
751    #[serde(
752        serialize_with = "decimal::serialize",
753        deserialize_with = "deserialize_decimal_token_or_zero_borrowed"
754    )]
755    pub amount: Decimal,
756    /// Fee amount.
757    #[serde(
758        serialize_with = "decimal::serialize",
759        deserialize_with = "deserialize_decimal_token_or_zero_borrowed"
760    )]
761    pub fee: Decimal,
762    /// Fee currency.
763    pub fee_currency: String,
764    /// Trade timestamp in milliseconds.
765    pub timestamp: u64,
766    /// Trade sequence number.
767    pub trade_seq: u64,
768    /// Liquidity: "M" (maker) or "T" (taker).
769    pub liquidity: String,
770    /// Order type.
771    pub order_type: String,
772    /// Index price at trade time.
773    #[serde(
774        serialize_with = "decimal::serialize",
775        deserialize_with = "deserialize_decimal_token_or_zero_borrowed"
776    )]
777    pub index_price: Decimal,
778    /// Mark price at trade time.
779    #[serde(
780        serialize_with = "decimal::serialize",
781        deserialize_with = "deserialize_decimal_token_or_zero_borrowed"
782    )]
783    pub mark_price: Decimal,
784    /// Tick direction (0-3).
785    pub tick_direction: i8,
786    /// Order state after this trade.
787    pub state: String,
788    /// User-defined label (client order ID).
789    pub label: Option<String>,
790    /// Reduce-only flag.
791    #[serde(default)]
792    pub reduce_only: bool,
793    /// Post-only flag.
794    #[serde(default)]
795    pub post_only: bool,
796    /// Liquidation indicator for trades caused by liquidation.
797    #[serde(default)]
798    pub liquidation: Option<String>,
799    /// Profit/loss for this trade.
800    #[serde(
801        default,
802        serialize_with = "decimal::serialize_optional",
803        deserialize_with = "deserialize_optional_decimal_token_borrowed"
804    )]
805    pub profit_loss: Option<Decimal>,
806}
807
808/// Portfolio/margin message from user.portfolio subscription.
809#[derive(Debug, Clone, Deserialize)]
810pub struct DeribitPortfolioMsg {
811    /// Currency code (e.g., "BTC", "ETH", "USDC", "USDT").
812    pub currency: String,
813    /// Account equity (balance + unrealized PnL). Used for zero-balance filtering.
814    #[serde(deserialize_with = "deserialize_decimal_token_borrowed")]
815    pub equity: Decimal,
816    /// Account balance. Used for zero-balance filtering.
817    #[serde(deserialize_with = "deserialize_decimal_token_borrowed")]
818    pub balance: Decimal,
819    /// Available funds for trading. Maps to AccountBalance.free.
820    #[serde(deserialize_with = "deserialize_decimal_token_borrowed")]
821    pub available_funds: Decimal,
822    /// Margin balance. Maps to AccountBalance.total.
823    #[serde(deserialize_with = "deserialize_decimal_token_borrowed")]
824    pub margin_balance: Decimal,
825    /// Initial margin requirement. Maps to MarginBalance.initial.
826    #[serde(deserialize_with = "deserialize_decimal_token_borrowed")]
827    pub initial_margin: Decimal,
828    /// Maintenance margin requirement. Maps to MarginBalance.maintenance.
829    #[serde(deserialize_with = "deserialize_decimal_token_borrowed")]
830    pub maintenance_margin: Decimal,
831    /// Margin model (e.g., "segregated_sm", "cross_sm", "cross_pm")
832    #[serde(default)]
833    pub margin_model: Option<String>,
834    /// Whether cross-collateral is enabled for this currency
835    #[serde(default)]
836    pub cross_collateral_enabled: Option<bool>,
837    /// Available withdrawal funds (per-currency withdrawable amount)
838    #[serde(
839        default,
840        deserialize_with = "deserialize_optional_decimal_token_borrowed"
841    )]
842    pub available_withdrawal_funds: Option<Decimal>,
843}
844
845/// Raw Deribit WebSocket message variants.
846///
847/// Response results and notification data keep their raw JSON text so typed decoding reads
848/// exact numeric tokens.
849#[derive(Clone)]
850pub enum DeribitWsMessage {
851    /// JSON-RPC response to a request.
852    Response(DeribitJsonRpcResponse<Box<RawValue>>),
853    /// Subscription notification (trade, book, ticker data).
854    Notification(DeribitSubscriptionNotification<Box<RawValue>>),
855    /// Heartbeat message.
856    Heartbeat(DeribitHeartbeatData),
857    /// JSON-RPC error.
858    Error(DeribitJsonRpcError),
859    /// Reconnection event (internal).
860    Reconnected,
861}
862
863impl Debug for DeribitWsMessage {
864    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
865        match self {
866            Self::Response(response)
867                if response.result.as_ref().is_some_and(|result| {
868                    serde_json::from_str::<DeribitAuthTokenKeys>(result.get()).is_ok_and(|keys| {
869                        keys.access_token.is_some() || keys.refresh_token.is_some()
870                    })
871                }) =>
872            {
873                f.debug_tuple("Response").field(&REDACTED).finish()
874            }
875            Self::Response(response) => f.debug_tuple("Response").field(response).finish(),
876            Self::Notification(notification) => {
877                f.debug_tuple("Notification").field(notification).finish()
878            }
879            Self::Heartbeat(heartbeat) => f.debug_tuple("Heartbeat").field(heartbeat).finish(),
880            Self::Error(error) => f.debug_tuple("Error").field(error).finish(),
881            Self::Reconnected => f.write_str("Reconnected"),
882        }
883    }
884}
885
886/// Deribit WebSocket error for external consumers.
887#[derive(Debug, Clone, Serialize, Deserialize)]
888pub struct DeribitWebSocketError {
889    /// Error code from Deribit.
890    pub code: i64,
891    /// Error message.
892    pub message: String,
893    /// Timestamp when error occurred.
894    pub timestamp: u64,
895}
896
897impl From<DeribitJsonRpcError> for DeribitWebSocketError {
898    fn from(err: DeribitJsonRpcError) -> Self {
899        Self {
900            code: err.code,
901            message: err.message,
902            timestamp: 0,
903        }
904    }
905}
906
907/// Normalized Nautilus domain message after parsing.
908#[derive(Debug, Clone)]
909pub enum NautilusWsMessage {
910    /// Market data (trades, bars, quotes).
911    Data(Vec<Data>),
912    /// Order book deltas.
913    Deltas(OrderBookDeltas),
914    /// Instrument definition update.
915    Instrument(Box<InstrumentAny>),
916    /// Funding rate updates (for perpetual instruments).
917    FundingRates(Vec<FundingRateUpdate>),
918    /// Exchange-provided option Greeks from ticker data.
919    OptionGreeks(OptionGreeks),
920    /// Order status reports (for reconciliation, not real-time events).
921    OrderStatusReports(Vec<OrderStatusReport>),
922    /// Fill reports from user.trades subscription or order responses.
923    FillReports(Vec<FillReport>),
924    /// Fill for an order tracked by this execution client.
925    OrderFilled(OrderFilled),
926    /// Order accepted by venue.
927    OrderAccepted(OrderAccepted),
928    /// Order canceled by venue or user.
929    OrderCanceled(OrderCanceled),
930    /// Order expired.
931    OrderExpired(OrderExpired),
932    /// Order rejected by venue.
933    OrderRejected(OrderRejected),
934    /// A cancel command fails before transmission.
935    OrderCancelDenied(OrderCancelDenied),
936    /// Cancel request rejected by venue.
937    OrderCancelRejected(OrderCancelRejected),
938    /// A modify command fails before transmission.
939    OrderModifyDenied(OrderModifyDenied),
940    /// Modify request rejected by venue.
941    OrderModifyRejected(OrderModifyRejected),
942    /// Order updated (price/quantity amended).
943    OrderUpdated(OrderUpdated),
944    /// Account state update from user.portfolio subscription.
945    AccountState(AccountState),
946    /// Instrument status change.
947    InstrumentStatus(InstrumentStatus),
948    /// Error from venue.
949    Error(DeribitWsError),
950    /// Unhandled/raw message for debugging.
951    Raw(Box<RawValue>),
952    /// Reconnection completed.
953    Reconnected,
954    /// Authentication succeeded with tokens.
955    Authenticated(Box<DeribitAuthResult>),
956    /// Authentication failed with reason.
957    AuthenticationFailed(String),
958}
959
960/// Parses a raw JSON message into a DeribitWsMessage.
961///
962/// # Errors
963///
964/// Returns an error if JSON parsing fails or the message format is unrecognized.
965pub fn parse_raw_message(text: &str) -> Result<DeribitWsMessage, DeribitWsError> {
966    let header: DeribitWsHeader =
967        serde_json::from_str(text).map_err(|e| DeribitWsError::Json(e.to_string()))?;
968
969    match header.method.as_deref() {
970        Some("subscription") => {
971            let notification: DeribitSubscriptionNotification<Box<RawValue>> =
972                serde_json::from_str(text).map_err(|e| DeribitWsError::Json(e.to_string()))?;
973            return Ok(DeribitWsMessage::Notification(notification));
974        }
975        Some("heartbeat") => {
976            let heartbeat: DeribitHeartbeatNotification =
977                serde_json::from_str(text).map_err(|e| DeribitWsError::Json(e.to_string()))?;
978
979            if let Some(params) = heartbeat.params {
980                return Ok(DeribitWsMessage::Heartbeat(params));
981            }
982        }
983        _ => {}
984    }
985
986    // Both success and error responses are returned as Response so the handler can
987    // correlate them with pending requests by ID, clean up pending_requests, and emit
988    // rejection events. Messages without an ID also parse as responses.
989    let response: DeribitJsonRpcResponse<Box<RawValue>> =
990        serde_json::from_str(text).map_err(|e| DeribitWsError::Json(e.to_string()))?;
991    Ok(DeribitWsMessage::Response(response))
992}
993
994#[derive(Deserialize)]
995struct DeribitWsHeader<'a> {
996    #[serde(borrow, default)]
997    method: Option<Cow<'a, str>>,
998}
999
1000#[derive(Deserialize)]
1001struct DeribitHeartbeatNotification {
1002    #[serde(default)]
1003    params: Option<DeribitHeartbeatData>,
1004}
1005
1006#[derive(Deserialize)]
1007struct DeribitAuthTokenKeys {
1008    access_token: Option<de::IgnoredAny>,
1009    refresh_token: Option<de::IgnoredAny>,
1010}
1011
1012/// Extracts the instrument name from a channel string.
1013///
1014/// For example: "trades.BTC-PERPETUAL.raw" -> "BTC-PERPETUAL"
1015pub fn extract_instrument_from_channel(channel: &str) -> Option<&str> {
1016    let parts: Vec<&str> = channel.split('.').collect();
1017    if parts.len() >= 2 {
1018        Some(parts[1])
1019    } else {
1020        None
1021    }
1022}
1023
1024#[cfg(test)]
1025mod tests {
1026    use rstest::rstest;
1027
1028    use super::*;
1029
1030    #[rstest]
1031    #[case(f64::NAN)]
1032    #[case(f64::INFINITY)]
1033    #[case(f64::NEG_INFINITY)]
1034    fn test_order_price_rejects_non_finite_floats(#[case] value: f64) {
1035        let value = serde::de::value::F64Deserializer::<serde::de::value::Error>::new(value);
1036        assert!(deserialize_optional_decimal_or_market(value).is_err());
1037    }
1038
1039    #[rstest]
1040    #[case(serde_json::json!("market_price"), None)]
1041    #[case(serde_json::json!(""), None)]
1042    #[case(serde_json::Value::Null, None)]
1043    #[case(serde_json::json!("0.1234567890123456789012345678"), Some(Decimal::from_str_exact("0.1234567890123456789012345678").unwrap()))]
1044    #[case(serde_json::json!(9007199254740993u64), Some(Decimal::from(9_007_199_254_740_993u64)))]
1045    fn test_order_price_routes(
1046        #[case] price: serde_json::Value,
1047        #[case] expected: Option<Decimal>,
1048    ) {
1049        let mut response: serde_json::Value = serde_json::from_str(include_str!(
1050            "../../test_data/ws_order_stop_market_response.json"
1051        ))
1052        .unwrap();
1053        response["result"]["order"]["price"] = price;
1054        let order: DeribitOrderMsg =
1055            serde_json::from_str(&response["result"]["order"].to_string()).unwrap();
1056
1057        assert_eq!(order.price, expected);
1058    }
1059
1060    #[rstest]
1061    #[case("abc")]
1062    #[case("MARKET_PRICE")]
1063    fn test_order_price_rejects_invalid_strings(#[case] price: &str) {
1064        let mut response: serde_json::Value = serde_json::from_str(include_str!(
1065            "../../test_data/ws_order_stop_market_response.json"
1066        ))
1067        .unwrap();
1068        response["result"]["order"]["price"] = serde_json::json!(price);
1069        let error =
1070            serde_json::from_str::<DeribitOrderMsg>(&response["result"]["order"].to_string())
1071                .unwrap_err();
1072
1073        assert!(
1074            error
1075                .to_string()
1076                .contains("expected a decimal or market_price")
1077        );
1078    }
1079
1080    #[rstest]
1081    #[case(None, "55.00055")]
1082    #[case(
1083        Some("0.12345678901234567890123456789"),
1084        "0.1234567890123456789012345679"
1085    )]
1086    fn test_portfolio_decimal_routes(#[case] equity: Option<&str>, #[case] expected: &str) {
1087        let response: serde_json::Value =
1088            serde_json::from_str(include_str!("../../test_data/ws_portfolio.json")).unwrap();
1089        let mut data = response["params"]["data"].clone();
1090
1091        if let Some(equity) = equity {
1092            data["equity"] = serde_json::json!(equity);
1093        }
1094
1095        let portfolio: DeribitPortfolioMsg = serde_json::from_str(&data.to_string()).unwrap();
1096        assert_eq!(portfolio.currency, "USDT");
1097        assert_eq!(portfolio.equity, Decimal::from_str_exact(expected).unwrap());
1098        assert_eq!(portfolio.balance, Decimal::new(5500055, 5));
1099        assert_eq!(portfolio.available_funds, Decimal::new(53868247, 6));
1100        assert_eq!(portfolio.margin_balance, Decimal::new(54968258, 6));
1101        assert_eq!(portfolio.initial_margin, Decimal::new(1100011, 6));
1102        assert_eq!(portfolio.maintenance_margin, Decimal::ZERO);
1103        assert_eq!(portfolio.margin_model.as_deref(), Some("cross_sm"));
1104        assert_eq!(portfolio.cross_collateral_enabled, Some(true));
1105        assert_eq!(
1106            portfolio.available_withdrawal_funds,
1107            Some(Decimal::new(54968257, 6))
1108        );
1109
1110        for invalid in [
1111            serde_json::Value::Null,
1112            serde_json::json!(""),
1113            serde_json::json!(true),
1114        ] {
1115            let mut data = data.clone();
1116            data["equity"] = invalid;
1117            assert!(serde_json::from_str::<DeribitPortfolioMsg>(&data.to_string()).is_err());
1118        }
1119    }
1120
1121    fn assert_zeroize_on_drop<T: ZeroizeOnDrop>() {}
1122
1123    #[rstest]
1124    fn auth_messages_preserve_wire_values_and_redact_debug() {
1125        let params = DeribitAuthParams {
1126            grant_type: "client_signature".to_string(),
1127            client_id: SecretString::from("client-id-value"),
1128            timestamp: 1_700_000_000_000,
1129            signature: SecretString::from("signature-value"),
1130            nonce: "nonce-value".to_string(),
1131            data: SecretString::from("data-value"),
1132            scope: Some("session:test".to_string()),
1133        };
1134        let refresh = DeribitRefreshTokenParams {
1135            grant_type: "refresh_token".to_string(),
1136            refresh_token: SecretString::from("refresh-token-value"),
1137        };
1138
1139        let params_json = serde_json::to_value(&params).unwrap();
1140        let refresh_json = serde_json::to_value(&refresh).unwrap();
1141        let formatted = format!("{params:?} {refresh:?}");
1142
1143        assert_eq!(params_json["client_id"], "client-id-value");
1144        assert_eq!(params_json["signature"], "signature-value");
1145        assert_eq!(params_json["data"], "data-value");
1146        assert_eq!(refresh_json["refresh_token"], "refresh-token-value");
1147        assert!(!formatted.contains("client-id-value"));
1148        assert!(!formatted.contains("signature-value"));
1149        assert!(!formatted.contains("data-value"));
1150        assert!(!formatted.contains("refresh-token-value"));
1151
1152        let DeribitAuthParams {
1153            client_id,
1154            signature,
1155            data,
1156            ..
1157        } = params;
1158        let DeribitRefreshTokenParams { refresh_token, .. } = refresh;
1159        assert_eq!(client_id.expose_secret(), "client-id-value");
1160        assert_eq!(signature.expose_secret(), "signature-value");
1161        assert_eq!(data.expose_secret(), "data-value");
1162        assert_eq!(refresh_token.expose_secret(), "refresh-token-value");
1163    }
1164
1165    #[rstest]
1166    fn auth_result_zeroizes_on_drop() {
1167        assert_zeroize_on_drop::<DeribitAuthResult>();
1168
1169        let result = DeribitAuthResult {
1170            access_token: SecretString::from("access-token-value"),
1171            expires_in: 900,
1172            refresh_token: SecretString::from("refresh-token-value"),
1173            scope: "session:test".to_string(),
1174            token_type: "bearer".to_string(),
1175            enabled_features: vec!["feature".to_string()],
1176        };
1177        let formatted = format!("{result:?}");
1178
1179        assert_eq!(formatted.matches(REDACTED).count(), 2);
1180        assert!(!formatted.contains(result.access_token.expose_secret()));
1181        assert!(!formatted.contains(result.refresh_token.expose_secret()));
1182    }
1183
1184    #[rstest]
1185    fn test_parse_subscription_notification() {
1186        let json = r#"{
1187            "jsonrpc": "2.0",
1188            "method": "subscription",
1189            "params": {
1190                "channel": "trades.BTC-PERPETUAL.raw",
1191                "data": [{"trade_id": "123", "price": 50000.0}]
1192            }
1193        }"#;
1194
1195        let msg = parse_raw_message(json).unwrap();
1196        assert!(matches!(msg, DeribitWsMessage::Notification(_)));
1197    }
1198
1199    #[rstest]
1200    fn test_parse_response() {
1201        let json = r#"{
1202            "jsonrpc": "2.0",
1203            "id": 1,
1204            "result": ["trades.BTC-PERPETUAL.raw"],
1205            "testnet": true,
1206            "usIn": 1234567890,
1207            "usOut": 1234567891,
1208            "usDiff": 1
1209        }"#;
1210
1211        let msg = parse_raw_message(json).unwrap();
1212        assert!(matches!(msg, DeribitWsMessage::Response(_)));
1213    }
1214
1215    #[rstest]
1216    #[case::plain_keys("access_token", "refresh_token")]
1217    #[case::escaped_keys(r"access\u005ftoken", r"refresh\u005ftoken")]
1218    fn test_auth_response_debug_redacts_tokens(
1219        #[case] access_key: &str,
1220        #[case] refresh_key: &str,
1221    ) {
1222        let access_token = "access-token-value";
1223        let refresh_token = "refresh-token-value";
1224        let json = format!(
1225            r#"{{
1226                "jsonrpc": "2.0",
1227                "id": 1,
1228                "result": {{
1229                    "{access_key}": "{access_token}",
1230                    "{refresh_key}": "{refresh_token}"
1231                }}
1232            }}"#,
1233        );
1234
1235        let msg = parse_raw_message(&json).unwrap();
1236        let debug = format!("{msg:?}");
1237
1238        assert!(debug.contains(REDACTED));
1239        assert!(!debug.contains(access_token));
1240        assert!(!debug.contains(refresh_token));
1241    }
1242
1243    #[rstest]
1244    fn test_parse_error_response() {
1245        // Error responses with an ID are returned as Response (not Error)
1246        // so the handler can correlate them with pending requests
1247        let json = r#"{
1248            "jsonrpc": "2.0",
1249            "id": 1,
1250            "error": {
1251                "code": 10028,
1252                "message": "too_many_requests"
1253            }
1254        }"#;
1255
1256        let msg = parse_raw_message(json).unwrap();
1257        match msg {
1258            DeribitWsMessage::Response(resp) => {
1259                assert!(resp.error.is_some());
1260                let error = resp.error.unwrap();
1261                assert_eq!(error.code, 10028);
1262                assert_eq!(error.message, "too_many_requests");
1263            }
1264            _ => panic!("Expected Response with error, was {msg:?}"),
1265        }
1266    }
1267
1268    #[rstest]
1269    fn test_extract_instrument_from_channel() {
1270        assert_eq!(
1271            extract_instrument_from_channel("trades.BTC-PERPETUAL.raw"),
1272            Some("BTC-PERPETUAL")
1273        );
1274        assert_eq!(
1275            extract_instrument_from_channel("book.ETH-25DEC25.raw"),
1276            Some("ETH-25DEC25")
1277        );
1278        assert_eq!(extract_instrument_from_channel("platform_state"), None);
1279    }
1280
1281    #[rstest]
1282    fn test_parse_volatility_index_payload() {
1283        let value = serde_json::json!({
1284            "timestamp": 1619777946007_u64,
1285            "volatility": 129.36_f64,
1286            "index_name": "btc_usd",
1287        });
1288
1289        let payload: DeribitVolatilityIndexMsg = serde_json::from_value(value).unwrap();
1290        assert_eq!(payload.index_name, "btc_usd");
1291        assert_eq!(payload.volatility, 129.36);
1292        assert_eq!(payload.timestamp, 1619777946007_u64);
1293    }
1294}