1use 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#[derive(Debug, Clone, Deserialize)]
60pub struct DeribitSubscriptionNotification<T> {
61 pub jsonrpc: String,
63 pub method: String,
65 pub params: DeribitSubscriptionParams<T>,
67}
68
69#[derive(Debug, Clone, Deserialize)]
71pub struct DeribitSubscriptionParams<T> {
72 pub channel: String,
74 pub data: T,
76}
77
78#[derive(Debug, Clone, Serialize, Zeroize)]
80pub struct DeribitAuthParams {
81 pub grant_type: String,
83 pub client_id: SecretString,
85 pub timestamp: u64,
87 pub signature: SecretString,
89 pub nonce: String,
91 pub data: SecretString,
93 #[serde(skip_serializing_if = "Option::is_none")]
97 pub scope: Option<String>,
98}
99
100#[derive(Debug, Clone, Serialize, Zeroize)]
102pub struct DeribitRefreshTokenParams {
103 pub grant_type: String,
105 pub refresh_token: SecretString,
107}
108
109#[derive(Debug, Clone, Deserialize, Zeroize, ZeroizeOnDrop)]
111pub struct DeribitAuthResult {
112 pub access_token: SecretString,
114 pub expires_in: u64,
116 pub refresh_token: SecretString,
118 pub scope: String,
120 pub token_type: String,
122 #[serde(default)]
124 pub enabled_features: Vec<String>,
125}
126
127#[derive(Debug, Clone, Serialize)]
129pub struct DeribitSubscribeParams {
130 pub channels: Vec<String>,
132}
133
134#[derive(Debug, Clone, Deserialize)]
136pub struct DeribitSubscribeResult(pub Vec<String>);
137
138#[derive(Debug, Clone, Serialize)]
140pub struct DeribitHeartbeatParams {
141 pub interval: u64,
143}
144
145#[derive(Debug, Clone, Deserialize)]
147pub struct DeribitHeartbeatData {
148 #[serde(rename = "type")]
150 pub heartbeat_type: DeribitHeartbeatType,
151}
152
153#[derive(Debug, Clone, Deserialize)]
155pub struct DeribitTradeMsg {
156 pub trade_id: String,
158 pub instrument_name: Ustr,
160 #[serde(deserialize_with = "deserialize_decimal_token_or_zero_borrowed")]
162 pub price: Decimal,
163 #[serde(deserialize_with = "deserialize_decimal_token_or_zero_borrowed")]
165 pub amount: Decimal,
166 pub direction: String,
168 pub timestamp: u64,
170 pub trade_seq: u64,
172 pub tick_direction: i8,
174 #[serde(deserialize_with = "deserialize_decimal_token_or_zero_borrowed")]
176 pub index_price: Decimal,
177 #[serde(deserialize_with = "deserialize_decimal_token_or_zero_borrowed")]
179 pub mark_price: Decimal,
180 #[serde(
182 default,
183 deserialize_with = "deserialize_optional_decimal_token_borrowed"
184 )]
185 pub iv: Option<Decimal>,
186 pub liquidation: Option<String>,
188 pub combo_trade_id: Option<String>,
190 pub block_trade_id: Option<String>,
192 #[serde(default)]
194 pub block_rfq_id: Option<i64>,
195 pub combo_id: Option<String>,
197 #[serde(default)]
199 pub legs: Option<Vec<DeribitTradeLeg>>,
200}
201
202#[derive(Debug, Clone, Deserialize)]
207pub struct DeribitBookMsg<'a> {
208 #[serde(rename = "type", default = "default_book_msg_type")]
210 pub msg_type: DeribitBookMsgType,
211 pub instrument_name: Ustr,
213 pub timestamp: u64,
215 pub change_id: u64,
217 pub prev_change_id: Option<u64>,
219 #[serde(borrow)]
221 pub bids: Vec<Vec<&'a RawValue>>,
222 #[serde(borrow)]
224 pub asks: Vec<Vec<&'a RawValue>>,
225}
226
227fn default_book_msg_type() -> DeribitBookMsgType {
229 DeribitBookMsgType::Snapshot
230}
231
232#[derive(Debug, Clone)]
234pub struct DeribitBookLevel {
235 pub price: Decimal,
237 pub amount: Decimal,
239 pub action: Option<DeribitBookAction>,
241}
242
243#[derive(Debug, Clone, Deserialize)]
245pub struct DeribitTickerMsg {
246 pub instrument_name: Ustr,
248 pub timestamp: u64,
250 #[serde(
252 default,
253 deserialize_with = "deserialize_optional_decimal_token_borrowed"
254 )]
255 pub best_bid_price: Option<Decimal>,
256 #[serde(
258 default,
259 deserialize_with = "deserialize_optional_decimal_token_borrowed"
260 )]
261 pub best_bid_amount: Option<Decimal>,
262 #[serde(
264 default,
265 deserialize_with = "deserialize_optional_decimal_token_borrowed"
266 )]
267 pub best_ask_price: Option<Decimal>,
268 #[serde(
270 default,
271 deserialize_with = "deserialize_optional_decimal_token_borrowed"
272 )]
273 pub best_ask_amount: Option<Decimal>,
274 #[serde(
276 default,
277 deserialize_with = "deserialize_optional_decimal_token_borrowed"
278 )]
279 pub last_price: Option<Decimal>,
280 #[serde(deserialize_with = "deserialize_decimal_token_or_zero_borrowed")]
282 pub mark_price: Decimal,
283 #[serde(deserialize_with = "deserialize_decimal_token_or_zero_borrowed")]
285 pub index_price: Decimal,
286 #[serde(deserialize_with = "deserialize_decimal_token_or_zero_borrowed")]
288 pub open_interest: Decimal,
289 #[serde(
291 default,
292 deserialize_with = "deserialize_optional_decimal_token_borrowed"
293 )]
294 pub current_funding: Option<Decimal>,
295 #[serde(
297 default,
298 deserialize_with = "deserialize_optional_decimal_token_borrowed"
299 )]
300 pub funding_8h: Option<Decimal>,
301 #[serde(
303 default,
304 deserialize_with = "deserialize_optional_decimal_token_borrowed"
305 )]
306 pub settlement_price: Option<Decimal>,
307 #[serde(
309 default,
310 deserialize_with = "deserialize_optional_decimal_token_borrowed"
311 )]
312 pub volume: Option<Decimal>,
313 #[serde(
315 default,
316 deserialize_with = "deserialize_optional_decimal_token_borrowed"
317 )]
318 pub volume_usd: Option<Decimal>,
319 #[serde(
321 default,
322 deserialize_with = "deserialize_optional_decimal_token_borrowed"
323 )]
324 pub high: Option<Decimal>,
325 #[serde(
327 default,
328 deserialize_with = "deserialize_optional_decimal_token_borrowed"
329 )]
330 pub low: Option<Decimal>,
331 #[serde(
333 default,
334 deserialize_with = "deserialize_optional_decimal_token_borrowed"
335 )]
336 pub price_change: Option<Decimal>,
337 pub state: String,
339 pub greeks: Option<DeribitGreeks>,
342 #[serde(
344 default,
345 deserialize_with = "deserialize_optional_decimal_token_borrowed"
346 )]
347 pub mark_iv: Option<Decimal>,
348 #[serde(
350 default,
351 deserialize_with = "deserialize_optional_decimal_token_borrowed"
352 )]
353 pub bid_iv: Option<Decimal>,
354 #[serde(
356 default,
357 deserialize_with = "deserialize_optional_decimal_token_borrowed"
358 )]
359 pub ask_iv: Option<Decimal>,
360 #[serde(
362 default,
363 deserialize_with = "deserialize_optional_decimal_token_borrowed"
364 )]
365 pub underlying_price: Option<Decimal>,
366 pub underlying_index: Option<String>,
368}
369
370#[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 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#[derive(Debug, Clone, Deserialize)]
400pub struct DeribitQuoteMsg {
401 pub instrument_name: Ustr,
403 pub timestamp: u64,
405 #[serde(deserialize_with = "deserialize_decimal_token_or_zero_borrowed")]
407 pub best_bid_price: Decimal,
408 #[serde(deserialize_with = "deserialize_decimal_token_or_zero_borrowed")]
410 pub best_bid_amount: Decimal,
411 #[serde(deserialize_with = "deserialize_decimal_token_or_zero_borrowed")]
413 pub best_ask_price: Decimal,
414 #[serde(deserialize_with = "deserialize_decimal_token_or_zero_borrowed")]
416 pub best_ask_amount: Decimal,
417}
418
419#[derive(Debug, Clone, Deserialize)]
424pub struct DeribitInstrumentStateMsg {
425 pub instrument_name: Ustr,
427 pub state: DeribitInstrumentState,
429 pub timestamp: u64,
431}
432
433#[derive(Debug, Clone, Deserialize)]
439pub struct DeribitPerpetualMsg {
440 #[serde(deserialize_with = "deserialize_decimal_token_or_zero_borrowed")]
442 pub index_price: Decimal,
443 #[serde(deserialize_with = "deserialize_decimal_token_or_zero_borrowed")]
445 pub interest: Decimal,
446 pub timestamp: u64,
448}
449
450#[derive(Debug, Clone, Deserialize)]
452pub struct DeribitVolatilityIndexMsg {
453 pub timestamp: u64,
455 pub volatility: f64,
457 pub index_name: String,
459}
460
461#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
466#[serde(rename_all = "lowercase")]
467pub enum DeribitChartStatus {
468 #[default]
470 Ok,
471 Imputed,
473}
474
475#[derive(Debug, Clone, Deserialize)]
477pub struct DeribitChartMsg {
478 pub tick: u64,
480 #[serde(deserialize_with = "deserialize_decimal_token_borrowed")]
482 pub open: Decimal,
483 #[serde(deserialize_with = "deserialize_decimal_token_borrowed")]
485 pub high: Decimal,
486 #[serde(deserialize_with = "deserialize_decimal_token_borrowed")]
488 pub low: Decimal,
489 #[serde(deserialize_with = "deserialize_decimal_token_borrowed")]
491 pub close: Decimal,
492 #[serde(deserialize_with = "deserialize_decimal_token_borrowed")]
494 pub volume: Decimal,
495 #[serde(deserialize_with = "deserialize_decimal_token_borrowed")]
497 pub cost: Decimal,
498 #[serde(default)]
500 pub status: DeribitChartStatus,
501}
502
503#[derive(Debug, Clone, Serialize)]
508pub struct DeribitOrderParams {
509 pub instrument_name: String,
511 #[serde(serialize_with = "decimal::serialize")]
513 pub amount: Decimal,
514 #[serde(rename = "type")]
516 pub order_type: String,
517 #[serde(skip_serializing_if = "Option::is_none")]
519 pub label: Option<String>,
520 #[serde(
522 skip_serializing_if = "Option::is_none",
523 serialize_with = "decimal::serialize_optional"
524 )]
525 pub price: Option<Decimal>,
526 #[serde(skip_serializing_if = "Option::is_none")]
528 pub time_in_force: Option<String>,
529 #[serde(skip_serializing_if = "Option::is_none")]
532 pub post_only: Option<bool>,
533 #[serde(skip_serializing_if = "Option::is_none")]
536 pub reject_post_only: Option<bool>,
537 #[serde(skip_serializing_if = "Option::is_none")]
539 pub reduce_only: Option<bool>,
540 #[serde(
542 skip_serializing_if = "Option::is_none",
543 serialize_with = "decimal::serialize_optional"
544 )]
545 pub trigger_price: Option<Decimal>,
546 #[serde(skip_serializing_if = "Option::is_none")]
548 pub trigger: Option<String>,
549 #[serde(
551 skip_serializing_if = "Option::is_none",
552 serialize_with = "decimal::serialize_optional"
553 )]
554 pub max_show: Option<Decimal>,
555 #[serde(skip_serializing_if = "Option::is_none")]
557 pub valid_until: Option<u64>,
558}
559
560#[derive(Debug, Clone, Serialize)]
562pub struct DeribitCancelParams {
563 pub order_id: String,
565}
566
567#[derive(Debug, Clone, Serialize)]
569pub struct DeribitCancelAllByInstrumentParams {
570 pub instrument_name: String,
572 #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
574 pub order_type: Option<String>,
575}
576
577#[derive(Debug, Clone, Serialize)]
582pub struct DeribitEditParams {
583 pub order_id: String,
585 #[serde(serialize_with = "decimal::serialize")]
587 pub amount: Decimal,
588 #[serde(
590 skip_serializing_if = "Option::is_none",
591 serialize_with = "decimal::serialize_optional"
592 )]
593 pub price: Option<Decimal>,
594 #[serde(
596 skip_serializing_if = "Option::is_none",
597 serialize_with = "decimal::serialize_optional"
598 )]
599 pub trigger_price: Option<Decimal>,
600 #[serde(skip_serializing_if = "Option::is_none")]
603 pub post_only: Option<bool>,
604 #[serde(skip_serializing_if = "Option::is_none")]
607 pub reject_post_only: Option<bool>,
608 #[serde(skip_serializing_if = "Option::is_none")]
610 pub reduce_only: Option<bool>,
611}
612
613#[derive(Debug, Clone, Serialize)]
615pub struct DeribitGetOrderStateParams {
616 pub order_id: String,
618}
619
620fn 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#[derive(Debug, Clone, Deserialize)]
642pub struct DeribitOrderResponse {
643 pub order: DeribitOrderMsg,
645 #[serde(default)]
647 pub trades: Vec<DeribitUserTradeMsg>,
648}
649
650#[derive(Debug, Clone, Deserialize)]
654pub struct DeribitOrderMsg {
655 pub order_id: String,
657 pub label: Option<String>,
659 pub instrument_name: Ustr,
661 pub direction: String,
663 pub order_type: String,
665 pub order_state: String,
667 #[serde(default)]
669 pub replaced: bool,
670 #[serde(default, deserialize_with = "deserialize_optional_decimal_or_market")]
673 pub price: Option<Decimal>,
674 #[serde(deserialize_with = "deserialize_decimal_token_or_zero_borrowed")]
676 pub amount: Decimal,
677 #[serde(
680 default,
681 deserialize_with = "deserialize_decimal_token_or_zero_borrowed"
682 )]
683 pub filled_amount: Decimal,
684 #[serde(
686 default,
687 deserialize_with = "deserialize_optional_decimal_token_borrowed"
688 )]
689 pub average_price: Option<Decimal>,
690 pub creation_timestamp: u64,
692 pub last_update_timestamp: u64,
694 pub time_in_force: String,
696 #[serde(
698 default,
699 deserialize_with = "deserialize_decimal_token_or_zero_borrowed"
700 )]
701 pub commission: Decimal,
702 #[serde(default)]
704 pub post_only: bool,
705 #[serde(default)]
707 pub reduce_only: bool,
708 #[serde(
710 default,
711 deserialize_with = "deserialize_optional_decimal_token_borrowed"
712 )]
713 pub trigger_price: Option<Decimal>,
714 pub trigger: Option<String>,
716 #[serde(
718 default,
719 deserialize_with = "deserialize_optional_decimal_token_borrowed"
720 )]
721 pub max_show: Option<Decimal>,
722 #[serde(default)]
724 pub api: bool,
725 pub reject_reason: Option<String>,
727 pub cancel_reason: Option<String>,
729}
730
731#[derive(Debug, Clone, Serialize, Deserialize)]
735pub struct DeribitUserTradeMsg {
736 pub trade_id: String,
738 pub order_id: String,
740 pub instrument_name: Ustr,
742 pub direction: String,
744 #[serde(
746 serialize_with = "decimal::serialize",
747 deserialize_with = "deserialize_decimal_token_or_zero_borrowed"
748 )]
749 pub price: Decimal,
750 #[serde(
752 serialize_with = "decimal::serialize",
753 deserialize_with = "deserialize_decimal_token_or_zero_borrowed"
754 )]
755 pub amount: Decimal,
756 #[serde(
758 serialize_with = "decimal::serialize",
759 deserialize_with = "deserialize_decimal_token_or_zero_borrowed"
760 )]
761 pub fee: Decimal,
762 pub fee_currency: String,
764 pub timestamp: u64,
766 pub trade_seq: u64,
768 pub liquidity: String,
770 pub order_type: String,
772 #[serde(
774 serialize_with = "decimal::serialize",
775 deserialize_with = "deserialize_decimal_token_or_zero_borrowed"
776 )]
777 pub index_price: Decimal,
778 #[serde(
780 serialize_with = "decimal::serialize",
781 deserialize_with = "deserialize_decimal_token_or_zero_borrowed"
782 )]
783 pub mark_price: Decimal,
784 pub tick_direction: i8,
786 pub state: String,
788 pub label: Option<String>,
790 #[serde(default)]
792 pub reduce_only: bool,
793 #[serde(default)]
795 pub post_only: bool,
796 #[serde(default)]
798 pub liquidation: Option<String>,
799 #[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#[derive(Debug, Clone, Deserialize)]
810pub struct DeribitPortfolioMsg {
811 pub currency: String,
813 #[serde(deserialize_with = "deserialize_decimal_token_borrowed")]
815 pub equity: Decimal,
816 #[serde(deserialize_with = "deserialize_decimal_token_borrowed")]
818 pub balance: Decimal,
819 #[serde(deserialize_with = "deserialize_decimal_token_borrowed")]
821 pub available_funds: Decimal,
822 #[serde(deserialize_with = "deserialize_decimal_token_borrowed")]
824 pub margin_balance: Decimal,
825 #[serde(deserialize_with = "deserialize_decimal_token_borrowed")]
827 pub initial_margin: Decimal,
828 #[serde(deserialize_with = "deserialize_decimal_token_borrowed")]
830 pub maintenance_margin: Decimal,
831 #[serde(default)]
833 pub margin_model: Option<String>,
834 #[serde(default)]
836 pub cross_collateral_enabled: Option<bool>,
837 #[serde(
839 default,
840 deserialize_with = "deserialize_optional_decimal_token_borrowed"
841 )]
842 pub available_withdrawal_funds: Option<Decimal>,
843}
844
845#[derive(Clone)]
850pub enum DeribitWsMessage {
851 Response(DeribitJsonRpcResponse<Box<RawValue>>),
853 Notification(DeribitSubscriptionNotification<Box<RawValue>>),
855 Heartbeat(DeribitHeartbeatData),
857 Error(DeribitJsonRpcError),
859 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#[derive(Debug, Clone, Serialize, Deserialize)]
888pub struct DeribitWebSocketError {
889 pub code: i64,
891 pub message: String,
893 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#[derive(Debug, Clone)]
909pub enum NautilusWsMessage {
910 Data(Vec<Data>),
912 Deltas(OrderBookDeltas),
914 Instrument(Box<InstrumentAny>),
916 FundingRates(Vec<FundingRateUpdate>),
918 OptionGreeks(OptionGreeks),
920 OrderStatusReports(Vec<OrderStatusReport>),
922 FillReports(Vec<FillReport>),
924 OrderFilled(OrderFilled),
926 OrderAccepted(OrderAccepted),
928 OrderCanceled(OrderCanceled),
930 OrderExpired(OrderExpired),
932 OrderRejected(OrderRejected),
934 OrderCancelDenied(OrderCancelDenied),
936 OrderCancelRejected(OrderCancelRejected),
938 OrderModifyDenied(OrderModifyDenied),
940 OrderModifyRejected(OrderModifyRejected),
942 OrderUpdated(OrderUpdated),
944 AccountState(AccountState),
946 InstrumentStatus(InstrumentStatus),
948 Error(DeribitWsError),
950 Raw(Box<RawValue>),
952 Reconnected,
954 Authenticated(Box<DeribitAuthResult>),
956 AuthenticationFailed(String),
958}
959
960pub 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 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
1012pub 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(¶ms).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 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}