deribit-websocket 0.3.0

WebSocket client for Deribit trading platform real-time data
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
//! WebSocket-specific types and models for Deribit API
//!
//! This module contains data structures specific to WebSocket communication,
//! including JSON-RPC message types, connection states, and WebSocket-specific
//! request/response structures.

use pretty_simple_display::{DebugPretty, DisplaySimple};
use serde::{Deserialize, Serialize};

/// WebSocket message types for JSON-RPC communication
#[derive(Clone, Serialize, Deserialize, PartialEq, DebugPretty, DisplaySimple)]
pub enum WebSocketMessage {
    /// JSON-RPC request message
    Request(JsonRpcRequest),
    /// JSON-RPC response message
    Response(JsonRpcResponse),
    /// JSON-RPC notification message (no response expected)
    Notification(JsonRpcNotification),
}

/// JSON-RPC 2.0 request structure
#[derive(Clone, Serialize, Deserialize, PartialEq, DebugPretty, DisplaySimple)]
pub struct JsonRpcRequest {
    /// JSON-RPC version (always "2.0")
    pub jsonrpc: String,
    /// Request identifier for correlation with response
    pub id: serde_json::Value,
    /// Method name to call
    pub method: String,
    /// Optional parameters for the method
    pub params: Option<serde_json::Value>,
}

/// JSON-RPC 2.0 response structure
#[derive(Clone, Serialize, Deserialize, PartialEq, DebugPretty, DisplaySimple)]
pub struct JsonRpcResponse {
    /// JSON-RPC version (always "2.0")
    pub jsonrpc: String,
    /// Request identifier for correlation
    pub id: serde_json::Value,
    /// Result or error information
    #[serde(flatten)]
    pub result: JsonRpcResult,
}

/// JSON-RPC 2.0 result or error union
#[derive(Clone, Serialize, Deserialize, PartialEq, DebugPretty, DisplaySimple)]
#[serde(untagged)]
pub enum JsonRpcResult {
    /// Successful result
    Success {
        /// Result data
        result: serde_json::Value,
    },
    /// Error result
    Error {
        /// Error information
        error: JsonRpcError,
    },
}

/// JSON-RPC 2.0 error structure
#[derive(Clone, Serialize, Deserialize, PartialEq, DebugPretty, DisplaySimple)]
pub struct JsonRpcError {
    /// Error code
    pub code: i32,
    /// Error message
    pub message: String,
    /// Optional additional error data
    pub data: Option<serde_json::Value>,
}

/// Authentication response from Deribit API
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct AuthResponse {
    /// Access token for authenticated requests
    pub access_token: String,
    /// Token type (usually "bearer")
    pub token_type: String,
    /// Token expiration time in seconds
    pub expires_in: i64,
    /// Refresh token for token renewal
    pub refresh_token: String,
    /// Scope of the token
    pub scope: String,
}

/// Hello response containing API version information
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct HelloResponse {
    /// API version string
    pub version: String,
}

/// Test connection response
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct TestResponse {
    /// API version string
    pub version: String,
}

/// JSON-RPC 2.0 notification structure (no response expected)
#[derive(Clone, Serialize, Deserialize, PartialEq, DebugPretty, DisplaySimple)]
pub struct JsonRpcNotification {
    /// JSON-RPC version (always "2.0")
    pub jsonrpc: String,
    /// Method name
    pub method: String,
    /// Optional parameters
    pub params: Option<serde_json::Value>,
}

/// WebSocket connection state
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum ConnectionState {
    /// Not connected
    Disconnected,
    /// Attempting to connect
    Connecting,
    /// Connected but not authenticated
    Connected,
    /// Connected and authenticated
    Authenticated,
    /// Attempting to reconnect
    Reconnecting,
    /// Connection failed
    Failed,
}

/// Heartbeat monitoring status
#[derive(Debug, Clone)]
pub struct HeartbeatStatus {
    /// Last ping sent timestamp
    pub last_ping: Option<std::time::Instant>,
    /// Last pong received timestamp
    pub last_pong: Option<std::time::Instant>,
    /// Number of consecutive missed pongs
    pub missed_pongs: u32,
}

/// WebSocket subscription channel types
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub enum SubscriptionChannel {
    /// Ticker data for a specific instrument
    Ticker(String),
    /// Order book data for a specific instrument
    OrderBook(String),
    /// Trade data for a specific instrument
    Trades(String),
    /// Chart trade data for a specific instrument with resolution
    ChartTrades {
        /// The trading instrument (e.g., "BTC-PERPETUAL")
        instrument: String,
        /// Chart resolution (e.g., "1", "5", "15", "60" for minutes)
        resolution: String,
    },
    /// User's order updates
    UserOrders,
    /// User's trade updates
    UserTrades,
    /// User's portfolio updates
    UserPortfolio,
    /// User's position changes for a specific instrument with interval
    UserChanges {
        /// The trading instrument (e.g., "BTC-PERPETUAL")
        instrument: String,
        /// Update interval (e.g., "raw", "100ms")
        interval: String,
    },
    /// Price index updates
    PriceIndex(String),
    /// Estimated delivery price
    EstimatedExpirationPrice(String),
    /// Mark price updates
    MarkPrice(String),
    /// Funding rate updates
    Funding(String),
    /// Perpetual updates with configurable interval
    Perpetual {
        /// The trading instrument (e.g., "BTC-PERPETUAL")
        instrument: String,
        /// Update interval (e.g., "raw", "100ms")
        interval: String,
    },
    /// Quote updates
    Quote(String),
    /// Platform state updates
    PlatformState,
    /// Platform state public methods state updates
    PlatformStatePublicMethods,
    /// Instrument state changes for a specific kind and currency
    InstrumentState {
        /// Instrument kind (e.g., "future", "option", "spot")
        kind: String,
        /// Currency (e.g., "BTC", "ETH")
        currency: String,
    },
    /// Grouped order book with configurable depth and interval
    GroupedOrderBook {
        /// The trading instrument (e.g., "BTC-PERPETUAL")
        instrument: String,
        /// Grouping level for aggregation
        group: String,
        /// Order book depth (e.g., "1", "10", "20")
        depth: String,
        /// Update interval (e.g., "100ms", "agg2")
        interval: String,
    },
    /// Incremental ticker updates for a specific instrument
    IncrementalTicker(String),
    /// Trades by instrument kind (e.g., future, option) and currency
    TradesByKind {
        /// Instrument kind (e.g., "future", "option", "spot", "any")
        kind: String,
        /// Currency (e.g., "BTC", "ETH", "any")
        currency: String,
        /// Update interval (e.g., "raw", "100ms")
        interval: String,
    },
    /// Price ranking data for an index
    PriceRanking(String),
    /// Price statistics for an index
    PriceStatistics(String),
    /// Volatility index data
    VolatilityIndex(String),
    /// Block RFQ trades for a specific currency
    BlockRfqTrades(String),
    /// Block trade confirmations (all currencies)
    BlockTradeConfirmations,
    /// Block trade confirmations for a specific currency
    BlockTradeConfirmationsByCurrency(String),
    /// User MMP (Market Maker Protection) trigger for a specific index
    UserMmpTrigger(String),
    /// User API access log
    UserAccessLog,
    /// User account lock status
    UserLock,
    /// Unknown or unrecognized channel
    Unknown(String),
}

/// WebSocket request structure for Deribit API
#[derive(Clone, Serialize, Deserialize, PartialEq, DebugPretty, DisplaySimple)]
pub struct WsRequest {
    /// JSON-RPC version
    pub jsonrpc: String,
    /// Request ID for correlation with responses
    pub id: serde_json::Value,
    /// API method name to call
    pub method: String,
    /// Parameters for the API method
    pub params: Option<serde_json::Value>,
}

/// WebSocket response structure for Deribit API
#[derive(Clone, Serialize, Deserialize, PartialEq, DebugPretty, DisplaySimple)]
pub struct WsResponse {
    /// JSON-RPC version
    pub jsonrpc: String,
    /// Request ID for correlation (None for notifications)
    pub id: Option<serde_json::Value>,
    /// Result data if the request was successful
    pub result: Option<serde_json::Value>,
    /// Error information if the request failed
    pub error: Option<JsonRpcError>,
}

impl JsonRpcRequest {
    /// Create a new JSON-RPC request
    pub fn new<T: Serialize>(id: serde_json::Value, method: &str, params: Option<T>) -> Self {
        Self {
            jsonrpc: "2.0".to_string(),
            id,
            method: method.to_string(),
            params: params.map(|p| serde_json::to_value(p).unwrap_or(serde_json::Value::Null)),
        }
    }
}

impl JsonRpcResponse {
    /// Create a new successful JSON-RPC response
    pub fn success(id: serde_json::Value, result: serde_json::Value) -> Self {
        Self {
            jsonrpc: "2.0".to_string(),
            id,
            result: JsonRpcResult::Success { result },
        }
    }

    /// Create a new error JSON-RPC response
    pub fn error(id: serde_json::Value, error: JsonRpcError) -> Self {
        Self {
            jsonrpc: "2.0".to_string(),
            id,
            result: JsonRpcResult::Error { error },
        }
    }
}

impl JsonRpcNotification {
    /// Create a new JSON-RPC notification
    pub fn new<T: Serialize>(method: &str, params: Option<T>) -> Self {
        Self {
            jsonrpc: "2.0".to_string(),
            method: method.to_string(),
            params: params.map(|p| serde_json::to_value(p).unwrap_or(serde_json::Value::Null)),
        }
    }
}

impl SubscriptionChannel {
    /// Convert subscription channel to channel name
    pub fn channel_name(&self) -> String {
        match self {
            SubscriptionChannel::Ticker(instrument) => format!("ticker.{}", instrument),
            SubscriptionChannel::OrderBook(instrument) => format!("book.{}.raw", instrument),
            SubscriptionChannel::Trades(instrument) => format!("trades.{}.raw", instrument),
            SubscriptionChannel::ChartTrades {
                instrument,
                resolution,
            } => {
                format!("chart.trades.{}.{}", instrument, resolution)
            }
            SubscriptionChannel::UserOrders => "user.orders.any.any.raw".to_string(),
            SubscriptionChannel::UserTrades => "user.trades.any.any.raw".to_string(),
            SubscriptionChannel::UserPortfolio => "user.portfolio.any".to_string(),
            SubscriptionChannel::UserChanges {
                instrument,
                interval,
            } => {
                format!("user.changes.{}.{}", instrument, interval)
            }
            SubscriptionChannel::PriceIndex(currency) => {
                format!("deribit_price_index.{}_usd", currency.to_lowercase())
            }
            SubscriptionChannel::EstimatedExpirationPrice(instrument) => {
                format!("estimated_expiration_price.{}", instrument)
            }
            SubscriptionChannel::MarkPrice(instrument) => {
                format!("markprice.options.{}", instrument)
            }
            SubscriptionChannel::Funding(instrument) => format!("perpetual.{}.raw", instrument),
            SubscriptionChannel::Perpetual {
                instrument,
                interval,
            } => {
                format!("perpetual.{}.{}", instrument, interval)
            }
            SubscriptionChannel::Quote(instrument) => format!("quote.{}", instrument),
            SubscriptionChannel::PlatformState => "platform_state".to_string(),
            SubscriptionChannel::PlatformStatePublicMethods => {
                "platform_state.public_methods_state".to_string()
            }
            SubscriptionChannel::InstrumentState { kind, currency } => {
                format!("instrument.state.{}.{}", kind, currency)
            }
            SubscriptionChannel::GroupedOrderBook {
                instrument,
                group,
                depth,
                interval,
            } => {
                format!("book.{}.{}.{}.{}", instrument, group, depth, interval)
            }
            SubscriptionChannel::IncrementalTicker(instrument) => {
                format!("incremental_ticker.{}", instrument)
            }
            SubscriptionChannel::TradesByKind {
                kind,
                currency,
                interval,
            } => {
                format!("trades.{}.{}.{}", kind, currency, interval)
            }
            SubscriptionChannel::PriceRanking(index_name) => {
                format!("deribit_price_ranking.{}", index_name)
            }
            SubscriptionChannel::PriceStatistics(index_name) => {
                format!("deribit_price_statistics.{}", index_name)
            }
            SubscriptionChannel::VolatilityIndex(index_name) => {
                format!("deribit_volatility_index.{}", index_name)
            }
            SubscriptionChannel::BlockRfqTrades(currency) => {
                format!("block_rfq.trades.{}", currency)
            }
            SubscriptionChannel::BlockTradeConfirmations => "block_trade_confirmations".to_string(),
            SubscriptionChannel::BlockTradeConfirmationsByCurrency(currency) => {
                format!("block_trade_confirmations.{}", currency)
            }
            SubscriptionChannel::UserMmpTrigger(index_name) => {
                format!("user.mmp_trigger.{}", index_name)
            }
            SubscriptionChannel::UserAccessLog => "user.access_log".to_string(),
            SubscriptionChannel::UserLock => "user.lock".to_string(),
            SubscriptionChannel::Unknown(channel) => channel.clone(),
        }
    }

    /// Parse subscription channel from string
    ///
    /// Returns the appropriate `SubscriptionChannel` variant for recognized channel patterns,
    /// or `Unknown(String)` for unrecognized patterns.
    #[must_use]
    pub fn from_string(s: &str) -> Self {
        let parts: Vec<&str> = s.split('.').collect();
        match parts.as_slice() {
            ["ticker", instrument] => SubscriptionChannel::Ticker(instrument.to_string()),
            ["ticker", instrument, _interval] => {
                SubscriptionChannel::Ticker(instrument.to_string())
            }
            ["book", instrument, "raw"] => SubscriptionChannel::OrderBook(instrument.to_string()),
            ["book", instrument, group, depth, interval] => SubscriptionChannel::GroupedOrderBook {
                instrument: instrument.to_string(),
                group: group.to_string(),
                depth: depth.to_string(),
                interval: interval.to_string(),
            },
            ["book", instrument, _depth, _interval] => {
                SubscriptionChannel::OrderBook(instrument.to_string())
            }
            ["incremental_ticker", instrument] => {
                SubscriptionChannel::IncrementalTicker(instrument.to_string())
            }
            ["trades", instrument, "raw"] => SubscriptionChannel::Trades(instrument.to_string()),
            ["trades", kind, currency, interval] if !Self::looks_like_instrument(kind) => {
                SubscriptionChannel::TradesByKind {
                    kind: kind.to_string(),
                    currency: currency.to_string(),
                    interval: interval.to_string(),
                }
            }
            ["trades", instrument, _interval] => {
                SubscriptionChannel::Trades(instrument.to_string())
            }
            ["chart", "trades", instrument, resolution] => SubscriptionChannel::ChartTrades {
                instrument: instrument.to_string(),
                resolution: resolution.to_string(),
            },
            ["user", "orders", ..] => SubscriptionChannel::UserOrders,
            ["user", "trades", ..] => SubscriptionChannel::UserTrades,
            ["user", "portfolio", ..] => SubscriptionChannel::UserPortfolio,
            ["user", "changes", instrument, interval] => SubscriptionChannel::UserChanges {
                instrument: instrument.to_string(),
                interval: interval.to_string(),
            },
            ["deribit_price_index", currency_pair] => {
                let currency = currency_pair
                    .strip_suffix("_usd")
                    .map(|c| c.to_uppercase())
                    .unwrap_or_else(|| currency_pair.to_uppercase());
                SubscriptionChannel::PriceIndex(currency)
            }
            ["estimated_expiration_price", instrument] => {
                SubscriptionChannel::EstimatedExpirationPrice(instrument.to_string())
            }
            ["markprice", "options", instrument] => {
                SubscriptionChannel::MarkPrice(instrument.to_string())
            }
            ["perpetual", instrument, interval] => SubscriptionChannel::Perpetual {
                instrument: instrument.to_string(),
                interval: interval.to_string(),
            },
            ["quote", instrument] => SubscriptionChannel::Quote(instrument.to_string()),
            ["platform_state"] => SubscriptionChannel::PlatformState,
            ["platform_state", "public_methods_state"] => {
                SubscriptionChannel::PlatformStatePublicMethods
            }
            ["instrument", "state", kind, currency] => SubscriptionChannel::InstrumentState {
                kind: kind.to_string(),
                currency: currency.to_string(),
            },
            ["deribit_price_ranking", index_name] => {
                SubscriptionChannel::PriceRanking(index_name.to_string())
            }
            ["deribit_price_statistics", index_name] => {
                SubscriptionChannel::PriceStatistics(index_name.to_string())
            }
            ["deribit_volatility_index", index_name] => {
                SubscriptionChannel::VolatilityIndex(index_name.to_string())
            }
            ["block_rfq", "trades", currency] => {
                SubscriptionChannel::BlockRfqTrades(currency.to_string())
            }
            ["block_trade_confirmations"] => SubscriptionChannel::BlockTradeConfirmations,
            ["block_trade_confirmations", currency] => {
                SubscriptionChannel::BlockTradeConfirmationsByCurrency(currency.to_string())
            }
            ["user", "mmp_trigger", index_name] => {
                SubscriptionChannel::UserMmpTrigger(index_name.to_string())
            }
            ["user", "access_log"] => SubscriptionChannel::UserAccessLog,
            ["user", "lock"] => SubscriptionChannel::UserLock,
            _ => SubscriptionChannel::Unknown(s.to_string()),
        }
    }

    /// Check if this channel is unknown/unrecognized
    #[must_use]
    pub fn is_unknown(&self) -> bool {
        matches!(self, SubscriptionChannel::Unknown(_))
    }

    /// Check if a string looks like an instrument name (contains hyphen).
    ///
    /// Used to distinguish between `trades.{instrument}.{interval}` and
    /// `trades.{kind}.{currency}.{interval}` patterns.
    #[must_use]
    fn looks_like_instrument(s: &str) -> bool {
        s.contains('-')
    }
}

impl std::fmt::Display for SubscriptionChannel {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.channel_name())
    }
}

impl ConnectionState {
    /// Check if the connection is in a connected state
    pub fn is_connected(&self) -> bool {
        matches!(
            self,
            ConnectionState::Connected | ConnectionState::Authenticated
        )
    }

    /// Check if the connection is authenticated
    pub fn is_authenticated(&self) -> bool {
        matches!(self, ConnectionState::Authenticated)
    }

    /// Check if the connection is in a transitional state
    pub fn is_transitional(&self) -> bool {
        matches!(
            self,
            ConnectionState::Connecting | ConnectionState::Reconnecting
        )
    }
}

impl HeartbeatStatus {
    /// Create a new heartbeat status
    pub fn new() -> Self {
        Self {
            last_ping: None,
            last_pong: None,
            missed_pongs: 0,
        }
    }

    /// Record a ping sent
    pub fn ping_sent(&mut self) {
        self.last_ping = Some(std::time::Instant::now());
    }

    /// Record a pong received
    pub fn pong_received(&mut self) {
        self.last_pong = Some(std::time::Instant::now());
        self.missed_pongs = 0;
    }

    /// Record a missed pong
    pub fn missed_pong(&mut self) {
        self.missed_pongs += 1;
    }

    /// Check if connection is considered stale
    pub fn is_stale(&self, max_missed_pongs: u32) -> bool {
        self.missed_pongs >= max_missed_pongs
    }
}

impl Default for HeartbeatStatus {
    fn default() -> Self {
        Self::new()
    }
}