Skip to main content

nautilus_deribit/websocket/
client.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//! WebSocket client for the Deribit API.
17//!
18//! The [`DeribitWebSocketClient`] provides connectivity to Deribit's WebSocket API using
19//! JSON-RPC 2.0. It supports subscribing to market data channels including trades, order books,
20//! and tickers.
21
22use std::{
23    fmt::Debug,
24    sync::{
25        Arc,
26        atomic::{AtomicBool, AtomicU8, Ordering},
27    },
28    time::Duration,
29};
30
31use arc_swap::ArcSwap;
32use futures_util::{FutureExt, Stream, StreamExt, stream::FuturesUnordered};
33use nautilus_common::{enums::LogColor, log_debug};
34use nautilus_core::{
35    AtomicMap, AtomicSet, UUID4, env::get_or_env_var_opt, string::secret::SecretString,
36    time::get_atomic_clock_realtime,
37};
38use nautilus_live::{SocketControl, book::DEFAULT_BOOK_SNAPSHOT_TIMEOUT_SECS, task::TaskGroup};
39use nautilus_model::{
40    data::BarType,
41    enums::OrderSide,
42    identifiers::{AccountId, ClientOrderId, InstrumentId, StrategyId, TraderId},
43    instruments::{Instrument, InstrumentAny},
44};
45use nautilus_network::{
46    ConnectionUrl,
47    http::create_standard_nautilus_headers,
48    mode::ConnectionMode,
49    websocket::{
50        AuthTracker, SubscriptionState, TransportBackend, WebSocketClient, WebSocketConfig,
51        channel_message_handler,
52    },
53};
54use parking_lot::{Mutex, RwLock, RwLockReadGuard};
55use tokio_util::sync::CancellationToken;
56use ustr::Ustr;
57
58use super::{
59    auth::{AuthState, refresh_token_after_delay, send_auth_request},
60    enums::{DeribitUpdateInterval, DeribitWsChannel},
61    error::{DeribitWsError, DeribitWsResult},
62    handler::{DeribitWsFeedHandler, HandlerCommand},
63    messages::{
64        DeribitCancelAllByInstrumentParams, DeribitCancelParams, DeribitEditParams,
65        DeribitOrderParams, NautilusWsMessage,
66    },
67};
68use crate::common::{
69    capabilities,
70    consts::{
71        DERIBIT_BOOK_DEFAULT_DEPTH, DERIBIT_TESTNET_WS_URL, DERIBIT_WS_HEARTBEAT_SECS,
72        DERIBIT_WS_ORDER_KEY, DERIBIT_WS_ORDER_QUOTA, DERIBIT_WS_SUBSCRIPTION_KEY,
73        DERIBIT_WS_SUBSCRIPTION_QUOTA, DERIBIT_WS_URL,
74    },
75    credential::{Credential, credential_env_vars},
76    enums::DeribitEnvironment,
77    parse::bar_spec_to_resolution,
78};
79
80/// Authentication timeout in seconds.
81const AUTHENTICATION_TIMEOUT_SECS: u64 = 30;
82
83type CommandSender = tokio::sync::mpsc::UnboundedSender<HandlerCommand>;
84
85/// WebSocket client for connecting to Deribit.
86#[derive(Clone)]
87pub struct DeribitWebSocketClient {
88    url: ConnectionUrl,
89    environment: DeribitEnvironment,
90    heartbeat_interval: Option<u64>,
91    auth_timeout_secs: u64,
92    credential: Option<Credential>,
93    auth_state: Arc<tokio::sync::RwLock<Option<AuthState>>>,
94    signal: Arc<AtomicBool>,
95    connection_mode: Arc<ArcSwap<AtomicU8>>,
96    auth_tracker: AuthTracker,
97    cmd_tx: Arc<RwLock<CommandSender>>,
98    out_rx: Option<Arc<tokio::sync::mpsc::UnboundedReceiver<NautilusWsMessage>>>,
99    handler_tasks: Arc<TaskGroup>,
100    connect_lock: Arc<tokio::sync::Mutex<()>>,
101    subscriptions_state: SubscriptionState,
102    instruments_cache: Arc<AtomicMap<Ustr, InstrumentAny>>,
103    option_greeks_subs: Arc<AtomicSet<InstrumentId>>,
104    mark_price_subs: Arc<AtomicSet<InstrumentId>>,
105    index_price_subs: Arc<AtomicSet<InstrumentId>>,
106    book_depth_subs: Arc<tokio::sync::Mutex<SubscriptionState>>,
107    book_snapshot_timeout_secs: u64,
108    book_stale_threshold_secs: u64,
109    cancellation_token: CancellationToken,
110    account_id: Option<AccountId>,
111    bars_timestamp_on_close: bool,
112    subscribe_errors: Arc<Mutex<Vec<String>>>,
113    transport_backend: TransportBackend,
114    proxy_url: Option<SecretString>,
115    socket_control: Option<SocketControl>,
116}
117
118impl Debug for DeribitWebSocketClient {
119    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
120        f.debug_struct(stringify!(DeribitWebSocketClient))
121            .field("url", &self.url)
122            .field("environment", &self.environment)
123            .field("has_credentials", &self.credential.is_some())
124            .field("is_authenticated", &self.auth_tracker.is_authenticated())
125            .field(
126                "has_auth_state",
127                &self.auth_state.try_read().is_ok_and(|s| s.is_some()),
128            )
129            .field("heartbeat_interval", &self.heartbeat_interval)
130            .finish_non_exhaustive()
131    }
132}
133
134impl DeribitWebSocketClient {
135    /// Creates a new [`DeribitWebSocketClient`] instance.
136    ///
137    /// Falls back to environment variables if credentials are not provided.
138    ///
139    /// # Errors
140    ///
141    /// Returns an error if only one of `api_key` or `api_secret` is provided.
142    #[expect(clippy::too_many_arguments)]
143    pub fn new(
144        url: Option<String>,
145        api_key: Option<String>,
146        api_secret: Option<String>,
147        heartbeat_interval: u64,
148        auth_timeout_secs: Option<u64>,
149        environment: DeribitEnvironment,
150        transport_backend: TransportBackend,
151        proxy_url: Option<String>,
152    ) -> anyhow::Result<Self> {
153        Self::new_inner(
154            url,
155            api_key,
156            api_secret,
157            heartbeat_interval,
158            auth_timeout_secs,
159            environment,
160            true,
161            transport_backend,
162            proxy_url,
163        )
164    }
165
166    /// Internal constructor with control over environment variable fallback.
167    #[expect(clippy::too_many_arguments)]
168    fn new_inner(
169        url: Option<String>,
170        api_key: Option<String>,
171        api_secret: Option<String>,
172        heartbeat_interval: u64,
173        auth_timeout_secs: Option<u64>,
174        environment: DeribitEnvironment,
175        env_fallback: bool,
176        transport_backend: TransportBackend,
177        proxy_url: Option<String>,
178    ) -> anyhow::Result<Self> {
179        let url = url.unwrap_or_else(|| match environment {
180            DeribitEnvironment::Testnet => DERIBIT_TESTNET_WS_URL.to_string(),
181            DeribitEnvironment::Mainnet => DERIBIT_WS_URL.to_string(),
182        });
183
184        // Resolve credential from config or environment variables (if env_fallback is true)
185        let credential =
186            Credential::resolve_with_env_fallback(api_key, api_secret, environment, env_fallback)?;
187
188        if credential.is_some() {
189            log::debug!("Credentials loaded ({environment})");
190        } else {
191            log::debug!("No credentials configured - unauthenticated mode");
192        }
193
194        let signal = Arc::new(AtomicBool::new(false));
195        let subscriptions_state = SubscriptionState::new('.');
196
197        Ok(Self {
198            url: url.into(),
199            environment,
200            heartbeat_interval: Some(heartbeat_interval),
201            auth_timeout_secs: auth_timeout_secs.unwrap_or(AUTHENTICATION_TIMEOUT_SECS),
202            credential,
203            auth_state: Arc::new(tokio::sync::RwLock::new(None)),
204            signal,
205            connection_mode: Arc::new(ArcSwap::from_pointee(AtomicU8::new(
206                ConnectionMode::Closed.as_u8(),
207            ))),
208            auth_tracker: AuthTracker::new(),
209            cmd_tx: {
210                let (tx, _) = tokio::sync::mpsc::unbounded_channel();
211                Arc::new(RwLock::new(tx))
212            },
213            out_rx: None,
214            handler_tasks: Arc::new(TaskGroup::new()),
215            connect_lock: Arc::new(tokio::sync::Mutex::new(())),
216            subscriptions_state,
217            instruments_cache: Arc::new(AtomicMap::new()),
218            option_greeks_subs: Arc::new(AtomicSet::new()),
219            mark_price_subs: Arc::new(AtomicSet::new()),
220            index_price_subs: Arc::new(AtomicSet::new()),
221            book_depth_subs: Arc::new(tokio::sync::Mutex::new(SubscriptionState::new('.'))),
222            book_snapshot_timeout_secs: DEFAULT_BOOK_SNAPSHOT_TIMEOUT_SECS,
223            book_stale_threshold_secs: 120,
224            cancellation_token: CancellationToken::new(),
225            account_id: None,
226            bars_timestamp_on_close: true,
227            subscribe_errors: Arc::new(Mutex::new(Vec::new())),
228            transport_backend,
229            proxy_url: proxy_url.map(SecretString::from),
230            socket_control: None,
231        })
232    }
233
234    pub(crate) fn begin_shutdown(&self) {
235        self.handler_tasks.begin_shutdown();
236        self.signal.store(true, Ordering::Relaxed);
237    }
238
239    /// Configures socket state reporting and reconnect control.
240    #[must_use]
241    pub fn with_socket_control(mut self, control: SocketControl) -> Self {
242        self.socket_control = Some(control);
243        self
244    }
245
246    /// Configures the order book snapshot and stale-feed timers, in seconds.
247    ///
248    /// A zero value disables the corresponding timer.
249    #[must_use]
250    pub fn with_book_timeouts(
251        mut self,
252        snapshot_timeout_secs: u64,
253        stale_threshold_secs: u64,
254    ) -> Self {
255        self.book_snapshot_timeout_secs = snapshot_timeout_secs;
256        self.book_stale_threshold_secs = stale_threshold_secs;
257        self
258    }
259
260    /// Creates a new public (unauthenticated) client.
261    ///
262    /// Does NOT fall back to environment variables for credentials.
263    ///
264    /// # Errors
265    ///
266    /// Returns an error if initialization fails.
267    pub fn new_public(
268        environment: DeribitEnvironment,
269        proxy_url: Option<String>,
270    ) -> anyhow::Result<Self> {
271        Self::new_inner(
272            None,
273            None,
274            None,
275            DERIBIT_WS_HEARTBEAT_SECS,
276            None,
277            environment,
278            false,
279            TransportBackend::default(),
280            proxy_url,
281        )
282    }
283
284    /// Creates an unauthenticated client with a custom URL.
285    ///
286    /// Does NOT fall back to environment variables for credentials.
287    /// Useful for testing against mock servers.
288    ///
289    /// # Errors
290    ///
291    /// Returns an error if initialization fails.
292    pub fn new_unauthenticated(
293        url: Option<String>,
294        heartbeat_interval: u64,
295        environment: DeribitEnvironment,
296    ) -> anyhow::Result<Self> {
297        Self::new_inner(
298            url,
299            None,
300            None,
301            heartbeat_interval,
302            None,
303            environment,
304            false,
305            TransportBackend::default(),
306            None,
307        )
308    }
309
310    /// Creates an authenticated client with credentials.
311    ///
312    /// Resolves each credential from the provided argument first, falling back
313    /// to the environment variable for the given `environment`:
314    /// - Testnet: `DERIBIT_TESTNET_API_KEY` and `DERIBIT_TESTNET_API_SECRET`
315    /// - Mainnet: `DERIBIT_API_KEY` and `DERIBIT_API_SECRET`
316    ///
317    /// # Errors
318    ///
319    /// Returns an error if neither the argument nor the environment variable
320    /// provides a credential.
321    pub fn with_credentials(
322        environment: DeribitEnvironment,
323        api_key: Option<String>,
324        api_secret: Option<String>,
325        auth_timeout_secs: Option<u64>,
326        proxy_url: Option<String>,
327    ) -> anyhow::Result<Self> {
328        let (key_env, secret_env) = credential_env_vars(environment);
329
330        let api_key = get_or_env_var_opt(api_key, key_env)
331            .ok_or_else(|| anyhow::anyhow!("Missing environment variable: {key_env}"))?;
332        let api_secret = get_or_env_var_opt(api_secret, secret_env)
333            .ok_or_else(|| anyhow::anyhow!("Missing environment variable: {secret_env}"))?;
334
335        Self::new(
336            None,
337            Some(api_key),
338            Some(api_secret),
339            DERIBIT_WS_HEARTBEAT_SECS,
340            auth_timeout_secs,
341            environment,
342            TransportBackend::default(),
343            proxy_url,
344        )
345    }
346
347    /// Returns the current connection mode.
348    fn connection_mode(&self) -> ConnectionMode {
349        let mode_u8 = self.connection_mode.load().load(Ordering::Relaxed);
350        ConnectionMode::from_u8(mode_u8)
351    }
352
353    /// Returns whether the client is actively connected.
354    #[must_use]
355    pub fn is_active(&self) -> bool {
356        self.connection_mode() == ConnectionMode::Active
357    }
358
359    /// Returns the WebSocket URL.
360    #[must_use]
361    pub fn url(&self) -> &str {
362        self.url.expose()
363    }
364
365    /// Returns the environment for this client.
366    #[must_use]
367    pub fn environment(&self) -> DeribitEnvironment {
368        self.environment
369    }
370
371    /// Returns whether the client is closed.
372    #[must_use]
373    pub fn is_closed(&self) -> bool {
374        let mode = self.connection_mode();
375        mode == ConnectionMode::Disconnect || mode == ConnectionMode::Closed
376    }
377
378    /// Cancel all pending WebSocket requests.
379    pub fn cancel_all_requests(&self) {
380        self.cancellation_token.cancel();
381    }
382
383    /// Returns the cancellation token for this client.
384    #[must_use]
385    pub fn cancellation_token(&self) -> &CancellationToken {
386        &self.cancellation_token
387    }
388
389    /// Waits until the client is active or timeout expires.
390    ///
391    /// # Errors
392    ///
393    /// Returns an error if the timeout expires before the client becomes active.
394    pub async fn wait_until_active(&self, timeout_secs: f64) -> DeribitWsResult<()> {
395        let timeout = tokio::time::Duration::from_secs_f64(timeout_secs);
396
397        tokio::time::timeout(timeout, async {
398            while !self.is_active() {
399                tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;
400            }
401        })
402        .await
403        .map_err(|_| {
404            DeribitWsError::Timeout(format!(
405                "WebSocket connection timeout after {timeout_secs} seconds"
406            ))
407        })?;
408
409        Ok(())
410    }
411
412    /// Waits until all pending subscriptions are confirmed by the server.
413    ///
414    /// # Errors
415    ///
416    /// Returns an error if the timeout expires before all subscriptions are confirmed.
417    pub async fn wait_for_subscriptions_confirmed(&self, timeout_secs: f64) -> DeribitWsResult<()> {
418        let timeout = Duration::from_secs_f64(timeout_secs);
419
420        tokio::time::timeout(timeout, async {
421            loop {
422                // Fail fast on permanent subscribe errors
423                let subscribe_error = {
424                    let mut errors = self.subscribe_errors.lock();
425                    if errors.is_empty() {
426                        None
427                    } else {
428                        let msg = errors.join("; ");
429                        errors.clear();
430                        Some(msg)
431                    }
432                };
433
434                if let Some(msg) = subscribe_error {
435                    return Err(DeribitWsError::Subscribe(msg));
436                }
437
438                let pending = self.subscriptions_state.pending_subscribe_topics();
439                if pending.is_empty() {
440                    return Ok(());
441                }
442                tokio::time::sleep(Duration::from_millis(10)).await;
443            }
444        })
445        .await
446        .map_err(|_| {
447            let pending = self.subscriptions_state.pending_subscribe_topics();
448            DeribitWsError::Timeout(format!(
449                "Subscription confirmation timeout after {timeout_secs}s, \
450                still pending: {pending:?}"
451            ))
452        })?
453    }
454
455    /// Caches instruments for use during message parsing.
456    pub fn cache_instruments(&self, instruments: &[InstrumentAny]) {
457        let tx = self.command_sender();
458
459        self.instruments_cache.rcu(|m| {
460            for inst in instruments {
461                m.insert(inst.raw_symbol().inner(), inst.clone());
462            }
463        });
464        log::debug!("Cached {} instruments", self.instruments_cache.len());
465
466        // Send per-instrument updates to the live handler rather than a full snapshot, avoiding
467        // out-of-order snapshot races, in every mode since the handler outlives a reconnect and
468        // connect() replays the cache via InitializeInstruments when no handler is running.
469        for inst in instruments {
470            let _ = tx.send(HandlerCommand::UpdateInstrument(Box::new(inst.clone())));
471        }
472    }
473
474    /// Caches a single instrument.
475    pub fn cache_instrument(&self, instrument: InstrumentAny) {
476        let tx = self.command_sender();
477        let symbol = instrument.raw_symbol().inner();
478        self.instruments_cache.insert(symbol, instrument);
479
480        // Send in every mode, see `cache_instruments`
481        if let Some(inst) = self.instruments_cache.get_cloned(&symbol) {
482            let _ = tx.send(HandlerCommand::UpdateInstrument(Box::new(inst)));
483        }
484    }
485
486    /// Sets the shared option greeks subscription set for handler-side gating.
487    pub fn set_option_greeks_subs(&mut self, subs: Arc<AtomicSet<InstrumentId>>) {
488        self.option_greeks_subs = subs;
489    }
490
491    /// Sets the shared mark price subscription set for handler-side gating.
492    pub fn set_mark_price_subs(&mut self, subs: Arc<AtomicSet<InstrumentId>>) {
493        self.mark_price_subs = subs;
494    }
495
496    /// Sets the shared index price subscription set for handler-side gating.
497    pub fn set_index_price_subs(&mut self, subs: Arc<AtomicSet<InstrumentId>>) {
498        self.index_price_subs = subs;
499    }
500
501    /// Registers an instrument for mark price emission from ticker messages.
502    pub fn add_mark_price_sub(&self, instrument_id: InstrumentId) {
503        self.mark_price_subs.insert(instrument_id);
504    }
505
506    /// Unregisters an instrument from mark price emission.
507    pub fn remove_mark_price_sub(&self, instrument_id: &InstrumentId) {
508        self.mark_price_subs.remove(instrument_id);
509    }
510
511    /// Registers an instrument for index price emission from ticker messages.
512    pub fn add_index_price_sub(&self, instrument_id: InstrumentId) {
513        self.index_price_subs.insert(instrument_id);
514    }
515
516    /// Unregisters an instrument from index price emission.
517    pub fn remove_index_price_sub(&self, instrument_id: &InstrumentId) {
518        self.index_price_subs.remove(instrument_id);
519    }
520
521    /// Registers an instrument for option greeks emission from ticker messages.
522    pub fn add_option_greeks_sub(&self, instrument_id: InstrumentId) {
523        self.option_greeks_subs.insert(instrument_id);
524    }
525
526    /// Unregisters an instrument from option greeks emission.
527    pub fn remove_option_greeks_sub(&self, instrument_id: &InstrumentId) {
528        self.option_greeks_subs.remove(instrument_id);
529    }
530
531    /// Connects to the Deribit WebSocket API.
532    ///
533    /// # Errors
534    ///
535    /// Returns an error if the connection fails.
536    pub async fn connect(&mut self) -> anyhow::Result<()> {
537        let connect_lock = Arc::clone(&self.connect_lock);
538        let _connect_guard = connect_lock.lock().await;
539
540        log_debug!(
541            "Connecting to WebSocket: {}",
542            self.url.origin(),
543            color = LogColor::Blue
544        );
545
546        if !self.handler_tasks.is_open() || !self.handler_tasks.is_empty() {
547            self.handler_tasks.begin_shutdown();
548            self.signal.store(true, Ordering::Relaxed);
549            self.finish_handler()
550                .await
551                .map_err(|e| anyhow::anyhow!("failed to stop prior WebSocket handler: {e}"))?;
552            self.handler_tasks.start_generation().map_err(|e| {
553                anyhow::anyhow!("failed to start WebSocket handler task generation: {e}")
554            })?;
555        }
556        let handler_spawner = self.handler_tasks.spawner().map_err(|e| {
557            anyhow::anyhow!("failed to acquire WebSocket handler task spawner: {e}")
558        })?;
559
560        // Reset stop signal and subscription state so callers can
561        // resubscribe cleanly after a manual disconnect/connect cycle.
562        self.signal.store(false, Ordering::Relaxed);
563        self.subscriptions_state.clear();
564        self.book_depth_subs.lock().await.clear();
565
566        // Create message handler and channel
567        let (message_handler, raw_rx) = channel_message_handler();
568
569        // No-op ping handler: handler responds to pings directly
570        // Inbound Ping frames are answered by the transport, so no ping handler is needed;
571        // the reader routes them away from the message channel and the handler never sees them.
572
573        // Configure WebSocket client
574        let headers = create_standard_nautilus_headers();
575
576        let config = WebSocketConfig {
577            url: self.url.expose().to_owned(),
578            headers,
579            heartbeat_interval_secs: self.heartbeat_interval,
580            heartbeat_payload: None, // Deribit uses JSON-RPC heartbeat, not text ping
581            connect_timeout_ms: Some(5_000),
582            reconnect_delay_initial_ms: None,
583            reconnect_delay_max_ms: None,
584            reconnect_backoff_factor: None,
585            reconnect_jitter_ms: None,
586            reconnect_max_attempts: None,
587            heartbeat_timeout_secs: None,
588            idle_timeout_ms: None,
589            writer_capacity: None,
590            backend: self.transport_backend,
591            proxy_url: self
592                .proxy_url
593                .as_ref()
594                .map(|value| value.expose_secret().to_owned()),
595            max_message_size_bytes: None,
596            max_frame_size_bytes: None,
597        };
598
599        // Configure rate limits
600        let keyed_quotas = vec![
601            (
602                DERIBIT_WS_SUBSCRIPTION_KEY.to_string(),
603                *DERIBIT_WS_SUBSCRIPTION_QUOTA,
604            ),
605            (DERIBIT_WS_ORDER_KEY.to_string(), *DERIBIT_WS_ORDER_QUOTA),
606        ];
607
608        // Connect the WebSocket
609        let ws_client = WebSocketClient::builder()
610            .config(config)
611            .message_handler(message_handler)
612            .keyed_quotas(keyed_quotas)
613            .default_quota(*DERIBIT_WS_SUBSCRIPTION_QUOTA)
614            .maybe_state_sink(self.socket_control.as_ref().map(SocketControl::sink))
615            .connect()
616            .await?;
617
618        let connection_mode = ws_client.connection_mode_atomic();
619        let reconnect_handle = ws_client.reconnect_handle();
620
621        // Create message channels
622        let (cmd_tx, cmd_rx) = tokio::sync::mpsc::unbounded_channel();
623        let (out_tx, out_rx) = tokio::sync::mpsc::unbounded_channel();
624
625        self.out_rx = Some(Arc::new(out_rx));
626
627        self.subscribe_errors.lock().clear();
628
629        // Create handler
630        let mut handler = DeribitWsFeedHandler::new(
631            self.signal.clone(),
632            cmd_rx,
633            raw_rx,
634            out_tx,
635            self.auth_tracker.clone(),
636            self.subscriptions_state.clone(),
637            self.option_greeks_subs.clone(),
638            self.mark_price_subs.clone(),
639            self.index_price_subs.clone(),
640            self.account_id,
641            self.bars_timestamp_on_close,
642            self.subscribe_errors.clone(),
643        );
644
645        handler.set_book_depth_subs(self.book_depth_subs.clone());
646        handler.set_book_sync(
647            cmd_tx.clone(),
648            Duration::from_secs(self.book_snapshot_timeout_secs),
649            Duration::from_secs(self.book_stale_threshold_secs),
650        );
651
652        if let Some(control) = &self.socket_control {
653            control.register(move || reconnect_handle.request_reconnect());
654        }
655
656        // Cache updates hold a read guard while mutating the central cache. Publishing the new
657        // sender under the write guard ensures later subscriptions follow this cache snapshot.
658        {
659            let mut command_sender = self.cmd_tx.write();
660            let _ = cmd_tx.send(HandlerCommand::SetClient(ws_client));
661
662            let instruments: Vec<InstrumentAny> =
663                self.instruments_cache.load().values().cloned().collect();
664
665            if !instruments.is_empty() {
666                log::debug!(
667                    "Sending {} cached instruments to handler",
668                    instruments.len()
669                );
670                let _ = cmd_tx.send(HandlerCommand::InitializeInstruments(instruments));
671            }
672
673            if let Some(interval) = self.heartbeat_interval {
674                let _ = cmd_tx.send(HandlerCommand::SetHeartbeat { interval });
675            }
676
677            *command_sender = cmd_tx.clone();
678            self.connection_mode.store(connection_mode);
679        }
680
681        // Spawn handler task
682        let subscriptions_state = self.subscriptions_state.clone();
683        let credential = self.credential.clone();
684        let auth_tracker = self.auth_tracker.clone();
685        let auth_state = self.auth_state.clone();
686        let heartbeat_interval = self.heartbeat_interval;
687
688        let handler_task = async move {
689            const MAX_REAUTH_ATTEMPTS: u32 = 3;
690
691            let mut pending_reauth = false;
692            let mut reauth_attempts: u32 = 0;
693
694            let mut refresh_cancel = CancellationToken::new();
695            let mut retry_cancel = CancellationToken::new();
696            let mut lifecycle_futures = FuturesUnordered::new();
697
698            loop {
699                let message = {
700                    // `handler.next()` can dequeue work before awaiting transport I/O, so keep the
701                    // same future alive while handler-owned lifecycle futures complete.
702                    let next = handler.next();
703                    tokio::pin!(next);
704
705                    loop {
706                        tokio::select! {
707                            message = &mut next => break message,
708                            _ = lifecycle_futures.next(), if !lifecycle_futures.is_empty() => {}
709                        }
710                    }
711                };
712
713                match message {
714                    Some(msg) => match msg {
715                        NautilusWsMessage::Reconnected => {
716                            log::info!("Reconnected to WebSocket");
717
718                            // Cancel stale refresh and retry tasks from prior connection
719                            refresh_cancel.cancel();
720                            refresh_cancel = CancellationToken::new();
721                            retry_cancel.cancel();
722                            retry_cancel = CancellationToken::new();
723
724                            // Deribit scopes `set_heartbeat` to the connection, so the replacement
725                            // starts with heartbeats off and the venue sends no further
726                            // `test_request` until they are re-armed.
727                            if let Some(interval) = heartbeat_interval {
728                                let _ = cmd_tx.send(HandlerCommand::SetHeartbeat { interval });
729                            }
730
731                            let channels = subscriptions_state.reset_after_reconnect();
732
733                            // Check if we need to re-authenticate
734                            if let Some(cred) = &credential {
735                                log::info!("Re-authenticating after reconnection...");
736
737                                let _rx = auth_tracker.begin();
738                                pending_reauth = true;
739                                reauth_attempts = 1;
740
741                                let previous_scope =
742                                    auth_state.read().await.as_ref().map(|s| s.scope.clone());
743
744                                send_auth_request(cred, previous_scope, &cmd_tx);
745                            } else {
746                                // No credentials - resubscribe immediately
747                                if !channels.is_empty() {
748                                    let _ = cmd_tx.send(HandlerCommand::Subscribe { channels });
749                                }
750                            }
751                        }
752                        NautilusWsMessage::Authenticated(result) => {
753                            let result = *result;
754                            let timestamp = get_atomic_clock_realtime().get_time_ms();
755                            let new_auth_state = AuthState::from_auth_result(&result, timestamp);
756                            *auth_state.write().await = Some(new_auth_state);
757
758                            refresh_cancel.cancel();
759                            refresh_cancel = CancellationToken::new();
760                            retry_cancel.cancel();
761                            retry_cancel = CancellationToken::new();
762
763                            lifecycle_futures.push(
764                                refresh_token_after_delay(
765                                    result.expires_in,
766                                    result.refresh_token.clone(),
767                                    cmd_tx.clone(),
768                                    refresh_cancel.clone(),
769                                )
770                                .boxed(),
771                            );
772
773                            if pending_reauth {
774                                pending_reauth = false;
775                                reauth_attempts = 0;
776                                log::info!(
777                                    "Re-authentication successful (scope: {}), resubscribing to channels",
778                                    result.scope
779                                );
780
781                                let channels = subscriptions_state.all_topics();
782
783                                if !channels.is_empty() {
784                                    let _ = cmd_tx.send(HandlerCommand::Subscribe { channels });
785                                }
786                            } else {
787                                log::debug!(
788                                    "Auth state stored: scope={}, expires_in={}s",
789                                    result.scope,
790                                    result.expires_in
791                                );
792                            }
793                        }
794                        NautilusWsMessage::AuthenticationFailed(reason) => {
795                            if pending_reauth && reauth_attempts < MAX_REAUTH_ATTEMPTS {
796                                let delay_secs = 1u64 << reauth_attempts; // 2s, 4s
797                                log::warn!(
798                                    "Re-authentication attempt {reauth_attempts}/{MAX_REAUTH_ATTEMPTS} \
799                                    failed: {reason} - retrying in {delay_secs}s",
800                                );
801                                reauth_attempts += 1;
802
803                                // Spawn delayed retry so the handler loop keeps
804                                // processing messages during the backoff
805                                if let Some(cred) = &credential {
806                                    let cred = cred.clone();
807                                    let auth_state = auth_state.clone();
808                                    let auth_tracker = auth_tracker.clone();
809                                    let cmd_tx = cmd_tx.clone();
810                                    let cancel = retry_cancel.clone();
811
812                                    lifecycle_futures.push(
813                                        async move {
814                                            tokio::select! {
815                                                () = tokio::time::sleep(Duration::from_secs(delay_secs)) => {}
816                                                () = cancel.cancelled() => return,
817                                            }
818                                            let _rx = auth_tracker.begin();
819                                            let previous_scope = auth_state
820                                                .read()
821                                                .await
822                                                .as_ref()
823                                                .map(|s| s.scope.clone());
824                                            send_auth_request(&cred, previous_scope, &cmd_tx);
825                                        }
826                                        .boxed(),
827                                    );
828                                }
829                            } else if pending_reauth {
830                                pending_reauth = false;
831                                reauth_attempts = 0;
832                                log::error!(
833                                    "Re-authentication failed after {MAX_REAUTH_ATTEMPTS} \
834                                    attempts: {reason} \
835                                    - resubscribing to public channels only"
836                                );
837
838                                let all = subscriptions_state.all_topics();
839                                let mut public_channels = Vec::new();
840
841                                for ch in &all {
842                                    if DeribitWsChannel::requires_auth(ch) {
843                                        // Release private channels so future subscribe
844                                        // calls aren't skipped as already referenced
845                                        subscriptions_state.mark_unsubscribe(ch);
846                                        subscriptions_state.confirm_unsubscribe(ch);
847                                        subscriptions_state.remove_reference(ch);
848                                    } else {
849                                        public_channels.push(ch.clone());
850                                    }
851                                }
852
853                                if !public_channels.is_empty() {
854                                    let _ = cmd_tx.send(HandlerCommand::Subscribe {
855                                        channels: public_channels,
856                                    });
857                                }
858                            } else {
859                                log::error!("Authentication failed: {reason}");
860                            }
861                        }
862                        _ => {}
863                    },
864                    None => {
865                        log::debug!("Handler returned None, stopping task");
866                        break;
867                    }
868                }
869            }
870        };
871
872        if let Err(e) = handler_spawner.spawn(handler_task) {
873            if let Some(control) = &self.socket_control {
874                control.deregister();
875            }
876            self.out_rx = None;
877            anyhow::bail!("failed to register WebSocket handler task: {e}");
878        }
879        log::debug!("Connected to WebSocket");
880
881        Ok(())
882    }
883
884    /// Closes the WebSocket connection.
885    ///
886    /// # Errors
887    ///
888    /// Returns an error if the close operation fails.
889    pub async fn close(&self) -> DeribitWsResult<()> {
890        self.begin_shutdown();
891        let connect_lock = Arc::clone(&self.connect_lock);
892        let _connect_guard = connect_lock.lock().await;
893        self.close_locked().await
894    }
895
896    async fn close_locked(&self) -> DeribitWsResult<()> {
897        log::debug!("Closing WebSocket connection");
898        self.begin_shutdown();
899
900        let _ = self.command_sender().send(HandlerCommand::Disconnect);
901
902        self.finish_handler().await?;
903
904        self.auth_tracker.invalidate();
905
906        if let Some(control) = &self.socket_control {
907            control.deregister();
908        }
909        Ok(())
910    }
911
912    async fn finish_handler(&self) -> DeribitWsResult<()> {
913        self.handler_tasks
914            .finish_shutdown(Duration::from_secs(2), Duration::from_secs(2))
915            .await
916            .map_err(|e| {
917                DeribitWsError::ClientError(format!("WebSocket handler shutdown failed: {e}"))
918            })
919    }
920
921    /// Returns a stream of WebSocket messages.
922    ///
923    /// # Errors
924    ///
925    /// Returns an error if called before `connect()` or if called more than once.
926    pub fn stream(&mut self) -> DeribitWsResult<impl Stream<Item = NautilusWsMessage> + 'static> {
927        let rx = self.out_rx.take().ok_or_else(|| {
928            DeribitWsError::ClientError(
929                "Stream receiver already taken or not connected".to_string(),
930            )
931        })?;
932        let mut rx = Arc::try_unwrap(rx).map_err(|_| {
933            DeribitWsError::ClientError(
934                "Cannot take stream ownership - other references exist".to_string(),
935            )
936        })?;
937
938        Ok(async_stream::stream! {
939            while let Some(msg) = rx.recv().await {
940                yield msg;
941            }
942        })
943    }
944
945    /// Returns whether the client has credentials configured.
946    #[must_use]
947    pub fn has_credentials(&self) -> bool {
948        self.credential.is_some()
949    }
950
951    /// Returns whether the client is authenticated.
952    #[must_use]
953    pub fn is_authenticated(&self) -> bool {
954        self.auth_tracker.is_authenticated()
955    }
956
957    /// Authenticates the WebSocket session with Deribit.
958    ///
959    /// Uses the `client_signature` grant type with HMAC-SHA256 signature.
960    /// This must be called before subscribing to raw data streams.
961    ///
962    /// # Arguments
963    ///
964    /// * `session_name` - Optional session name for session-scoped authentication.
965    ///   When provided, uses `session:<name>` scope which allows skipping `access_token`
966    ///   in subsequent private requests. When `None`, uses default `connection` scope.
967    ///   Recommended to use session scope for order execution compatibility.
968    ///
969    /// # Errors
970    ///
971    /// Returns an error if:
972    /// - No credentials are configured.
973    /// - The authentication request fails.
974    /// - The authentication times out.
975    pub async fn authenticate(&self, session_name: Option<&str>) -> DeribitWsResult<()> {
976        let credential = self.credential.as_ref().ok_or_else(|| {
977            DeribitWsError::Authentication("API credentials not configured".to_string())
978        })?;
979
980        // Determine scope
981        let scope = session_name.map(|name| format!("session:{name}"));
982
983        log::debug!("Authenticating WebSocket...");
984
985        let rx = self.auth_tracker.begin();
986
987        // Send authentication request
988        let cmd_tx = self.command_sender().clone();
989        send_auth_request(credential, scope, &cmd_tx);
990
991        // Wait for authentication result with timeout
992        match self
993            .auth_tracker
994            .wait_for_result::<DeribitWsError>(Duration::from_secs(self.auth_timeout_secs), rx)
995            .await
996        {
997            Ok(()) => {
998                log::debug!("WebSocket authenticated successfully");
999                Ok(())
1000            }
1001            Err(e) => {
1002                log::error!("WebSocket authentication failed: error={e}");
1003                Err(e)
1004            }
1005        }
1006    }
1007
1008    /// Authenticates with session scope using the provided session name.
1009    ///
1010    /// Use `DERIBIT_DATA_SESSION_NAME` for data clients and
1011    /// `DERIBIT_EXECUTION_SESSION_NAME` for execution clients.
1012    ///
1013    /// # Errors
1014    ///
1015    /// Returns an error if authentication fails.
1016    pub async fn authenticate_session(&self, session_name: &str) -> DeribitWsResult<()> {
1017        self.authenticate(Some(session_name)).await
1018    }
1019
1020    /// Returns the current authentication state containing tokens.
1021    ///
1022    /// Returns `None` if not authenticated or tokens haven't been stored yet.
1023    pub async fn auth_state(&self) -> Option<AuthState> {
1024        self.auth_state.read().await.clone()
1025    }
1026
1027    /// Returns the current access token if available.
1028    pub async fn access_token(&self) -> Option<SecretString> {
1029        self.auth_state
1030            .read()
1031            .await
1032            .as_ref()
1033            .map(|s| s.access_token.clone())
1034    }
1035
1036    /// Sets the account ID for order/fill reports.
1037    pub fn set_account_id(&mut self, account_id: AccountId) {
1038        self.account_id = Some(account_id);
1039    }
1040
1041    /// Sets whether bar timestamps should use the close time.
1042    ///
1043    /// When `true` (default), bar `ts_event` is set to the bar's close time.
1044    pub fn set_bars_timestamp_on_close(&mut self, value: bool) {
1045        self.bars_timestamp_on_close = value;
1046    }
1047
1048    async fn send_subscribe(&self, channels: Vec<String>) -> DeribitWsResult<()> {
1049        let mut channels_to_subscribe = Vec::new();
1050
1051        for channel in channels {
1052            if self.subscriptions_state.add_reference(&channel) {
1053                self.subscriptions_state.mark_subscribe(&channel);
1054                channels_to_subscribe.push(channel);
1055            } else {
1056                log::debug!("Already subscribed to {channel}, skipping duplicate subscription");
1057            }
1058        }
1059
1060        if channels_to_subscribe.is_empty() {
1061            return Ok(());
1062        }
1063
1064        if let Err(e) = self.command_sender().send(HandlerCommand::Subscribe {
1065            channels: channels_to_subscribe.clone(),
1066        }) {
1067            // Roll back: remove reference and clear pending_subscribe
1068            for channel in &channels_to_subscribe {
1069                self.subscriptions_state.remove_reference(channel);
1070                self.subscriptions_state.mark_unsubscribe(channel);
1071                self.subscriptions_state.confirm_unsubscribe(channel);
1072            }
1073            return Err(DeribitWsError::Send(e.to_string()));
1074        }
1075
1076        log::debug!(
1077            "Sent subscribe for {} channels",
1078            channels_to_subscribe.len()
1079        );
1080        Ok(())
1081    }
1082
1083    async fn send_unsubscribe(&self, channels: Vec<String>) -> DeribitWsResult<()> {
1084        let mut channels_to_unsubscribe = Vec::new();
1085
1086        for channel in channels {
1087            if self.subscriptions_state.remove_reference(&channel) {
1088                self.subscriptions_state.mark_unsubscribe(&channel);
1089                channels_to_unsubscribe.push(channel);
1090            } else {
1091                log::debug!("Still has references to {channel}, skipping unsubscription");
1092            }
1093        }
1094
1095        if channels_to_unsubscribe.is_empty() {
1096            return Ok(());
1097        }
1098
1099        if let Err(e) = self.command_sender().send(HandlerCommand::Unsubscribe {
1100            channels: channels_to_unsubscribe.clone(),
1101        }) {
1102            // Send only fails when the handler task is dead, meaning the
1103            // connection is broken. Restore refcount and mark confirmed so
1104            // the topic is not wedged in pending_unsubscribe. This may
1105            // promote a pending_subscribe topic to confirmed, but that is
1106            // harmless: connect() calls clear() on the next connection
1107            // attempt, resetting all subscription state.
1108            for channel in &channels_to_unsubscribe {
1109                self.subscriptions_state.confirm_unsubscribe(channel);
1110                self.subscriptions_state.add_reference(channel);
1111                self.subscriptions_state.mark_subscribe(channel);
1112                self.subscriptions_state.confirm_subscribe(channel);
1113            }
1114            return Err(DeribitWsError::Send(e.to_string()));
1115        }
1116
1117        log::debug!(
1118            "Sent unsubscribe for {} channels",
1119            channels_to_unsubscribe.len()
1120        );
1121        Ok(())
1122    }
1123
1124    /// Subscribes to trade updates for an instrument.
1125    ///
1126    /// # Arguments
1127    ///
1128    /// * `instrument_id` - The instrument to subscribe to
1129    /// * `interval` - Update interval. Defaults to `Ms100` (100ms). `Raw` requires authentication.
1130    ///
1131    /// # Errors
1132    ///
1133    /// Returns an error if subscription fails or raw is requested without authentication.
1134    pub async fn subscribe_trades(
1135        &self,
1136        instrument_id: InstrumentId,
1137        interval: Option<DeribitUpdateInterval>,
1138    ) -> DeribitWsResult<()> {
1139        self.validate_public_trades(instrument_id)?;
1140        let interval = interval.unwrap_or_default();
1141        self.check_auth_requirement(interval)?;
1142        let channel =
1143            DeribitWsChannel::Trades.format_channel(instrument_id.symbol.as_str(), Some(interval));
1144        self.send_subscribe(vec![channel]).await
1145    }
1146
1147    /// Unsubscribes from trade updates for an instrument.
1148    ///
1149    /// # Errors
1150    ///
1151    /// Returns an error if unsubscription fails.
1152    pub async fn unsubscribe_trades(
1153        &self,
1154        instrument_id: InstrumentId,
1155        interval: Option<DeribitUpdateInterval>,
1156    ) -> DeribitWsResult<()> {
1157        let interval = interval.unwrap_or_default();
1158        let channel =
1159            DeribitWsChannel::Trades.format_channel(instrument_id.symbol.as_str(), Some(interval));
1160        self.send_unsubscribe(vec![channel]).await
1161    }
1162
1163    /// Subscribes to order book updates for an instrument.
1164    ///
1165    /// # Arguments
1166    ///
1167    /// * `instrument_id` - The instrument to subscribe to
1168    /// * `interval` - Update interval. Defaults to `Ms100` (100ms). `Raw` requires authentication.
1169    ///
1170    /// # Errors
1171    ///
1172    /// Returns an error if subscription fails or raw is requested without authentication.
1173    pub async fn subscribe_book(
1174        &self,
1175        instrument_id: InstrumentId,
1176        interval: Option<DeribitUpdateInterval>,
1177    ) -> DeribitWsResult<()> {
1178        let interval = interval.unwrap_or_default();
1179        self.check_auth_requirement(interval)?;
1180        let channel =
1181            DeribitWsChannel::Book.format_channel(instrument_id.symbol.as_str(), Some(interval));
1182        self.send_subscribe(vec![channel]).await
1183    }
1184
1185    /// Unsubscribes from order book updates for an instrument.
1186    ///
1187    /// # Errors
1188    ///
1189    /// Returns an error if unsubscription fails.
1190    pub async fn unsubscribe_book(
1191        &self,
1192        instrument_id: InstrumentId,
1193        interval: Option<DeribitUpdateInterval>,
1194    ) -> DeribitWsResult<()> {
1195        let interval = interval.unwrap_or_default();
1196        let channel =
1197            DeribitWsChannel::Book.format_channel(instrument_id.symbol.as_str(), Some(interval));
1198        self.send_unsubscribe(vec![channel]).await
1199    }
1200
1201    /// Subscribes to grouped (depth-limited) order book updates for an instrument.
1202    ///
1203    /// Uses the Deribit grouped book channel format: `book.{instrument}.{group}.{depth}.{interval}`
1204    ///
1205    /// Depth is normalized to Deribit supported values: 1, 10, or 20.
1206    ///
1207    /// # Errors
1208    ///
1209    /// Returns an error if subscription fails or raw is requested without authentication.
1210    pub async fn subscribe_book_grouped(
1211        &self,
1212        instrument_id: InstrumentId,
1213        group: &str,
1214        depth: u32,
1215        interval: Option<DeribitUpdateInterval>,
1216    ) -> DeribitWsResult<()> {
1217        let channel = grouped_book_channel(instrument_id, group, depth, interval);
1218        log::debug!("Subscribing to grouped book channel: {channel}");
1219        self.send_subscribe(vec![channel]).await
1220    }
1221
1222    pub(crate) async fn subscribe_book_depth(
1223        &self,
1224        instrument_id: InstrumentId,
1225        group: &str,
1226        interval: Option<DeribitUpdateInterval>,
1227    ) -> DeribitWsResult<()> {
1228        let channel =
1229            grouped_book_channel(instrument_id, group, DERIBIT_BOOK_DEFAULT_DEPTH, interval);
1230        let depth_subs = self.book_depth_subs.lock().await;
1231        depth_subs.add_reference(&channel);
1232        if let Err(e) = self.send_subscribe(vec![channel.clone()]).await {
1233            depth_subs.remove_reference(&channel);
1234            return Err(e);
1235        }
1236
1237        Ok(())
1238    }
1239
1240    /// Unsubscribes from grouped (depth-limited) order book updates for an instrument.
1241    ///
1242    /// Depth is normalized to Deribit supported values: 1, 10, or 20.
1243    ///
1244    /// # Errors
1245    ///
1246    /// Returns an error if unsubscription fails.
1247    pub async fn unsubscribe_book_grouped(
1248        &self,
1249        instrument_id: InstrumentId,
1250        group: &str,
1251        depth: u32,
1252        interval: Option<DeribitUpdateInterval>,
1253    ) -> DeribitWsResult<()> {
1254        let channel = grouped_book_channel(instrument_id, group, depth, interval);
1255        self.send_unsubscribe(vec![channel]).await
1256    }
1257
1258    pub(crate) async fn unsubscribe_book_depth(
1259        &self,
1260        instrument_id: InstrumentId,
1261        group: &str,
1262        interval: Option<DeribitUpdateInterval>,
1263    ) -> DeribitWsResult<()> {
1264        let channel =
1265            grouped_book_channel(instrument_id, group, DERIBIT_BOOK_DEFAULT_DEPTH, interval);
1266        let depth_subs = self.book_depth_subs.lock().await;
1267        if depth_subs.get_reference_count(&channel) == 0 {
1268            return Ok(());
1269        }
1270
1271        self.send_unsubscribe(vec![channel.clone()]).await?;
1272        depth_subs.remove_reference(&channel);
1273        Ok(())
1274    }
1275
1276    /// Subscribes to ticker updates for an instrument.
1277    ///
1278    /// # Arguments
1279    ///
1280    /// * `instrument_id` - The instrument to subscribe to
1281    /// * `interval` - Update interval. Defaults to `Ms100` (100ms). `Raw` requires authentication.
1282    ///
1283    /// # Errors
1284    ///
1285    /// Returns an error if subscription fails or raw is requested without authentication.
1286    pub async fn subscribe_ticker(
1287        &self,
1288        instrument_id: InstrumentId,
1289        interval: Option<DeribitUpdateInterval>,
1290    ) -> DeribitWsResult<()> {
1291        let interval = interval.unwrap_or_default();
1292        self.check_auth_requirement(interval)?;
1293        let channel =
1294            DeribitWsChannel::Ticker.format_channel(instrument_id.symbol.as_str(), Some(interval));
1295        self.send_subscribe(vec![channel]).await
1296    }
1297
1298    /// Unsubscribes from ticker updates for an instrument.
1299    ///
1300    /// # Errors
1301    ///
1302    /// Returns an error if unsubscription fails.
1303    pub async fn unsubscribe_ticker(
1304        &self,
1305        instrument_id: InstrumentId,
1306        interval: Option<DeribitUpdateInterval>,
1307    ) -> DeribitWsResult<()> {
1308        let interval = interval.unwrap_or_default();
1309        let channel =
1310            DeribitWsChannel::Ticker.format_channel(instrument_id.symbol.as_str(), Some(interval));
1311        self.send_unsubscribe(vec![channel]).await
1312    }
1313
1314    /// Subscribes to quote (best bid/ask) updates for an instrument.
1315    ///
1316    /// Note: Quote channel does not support interval parameter.
1317    ///
1318    /// # Errors
1319    ///
1320    /// Returns an error if subscription fails.
1321    pub async fn subscribe_quotes(&self, instrument_id: InstrumentId) -> DeribitWsResult<()> {
1322        let channel = DeribitWsChannel::Quote.format_channel(instrument_id.symbol.as_str(), None);
1323        self.send_subscribe(vec![channel]).await
1324    }
1325
1326    /// Unsubscribes from quote updates for an instrument.
1327    ///
1328    /// # Errors
1329    ///
1330    /// Returns an error if unsubscription fails.
1331    pub async fn unsubscribe_quotes(&self, instrument_id: InstrumentId) -> DeribitWsResult<()> {
1332        let channel = DeribitWsChannel::Quote.format_channel(instrument_id.symbol.as_str(), None);
1333        self.send_unsubscribe(vec![channel]).await
1334    }
1335
1336    /// Subscribes to instrument status changes for lifecycle notifications.
1337    ///
1338    /// Channel format: `instrument.state.{kind}.{currency}`
1339    ///
1340    /// # Errors
1341    ///
1342    /// Returns an error if subscription fails.
1343    pub async fn subscribe_instrument_status(
1344        &self,
1345        kind: &str,
1346        currency: &str,
1347    ) -> DeribitWsResult<()> {
1348        let channel = DeribitWsChannel::format_instrument_state_channel(kind, currency);
1349        self.send_subscribe(vec![channel]).await
1350    }
1351
1352    /// Unsubscribes from instrument status changes.
1353    ///
1354    /// # Errors
1355    ///
1356    /// Returns an error if unsubscription fails.
1357    pub async fn unsubscribe_instrument_status(
1358        &self,
1359        kind: &str,
1360        currency: &str,
1361    ) -> DeribitWsResult<()> {
1362        let channel = DeribitWsChannel::format_instrument_state_channel(kind, currency);
1363        self.send_unsubscribe(vec![channel]).await
1364    }
1365
1366    /// Subscribes to volatility index updates for the given index name.
1367    ///
1368    /// Channel format: `deribit_volatility_index.{index_name}`
1369    ///
1370    /// # Errors
1371    ///
1372    /// Returns an error if subscription fails.
1373    pub async fn subscribe_volatility_index(&self, index_name: &str) -> DeribitWsResult<()> {
1374        let channel = DeribitWsChannel::VolatilityIndex.format_channel(index_name, None);
1375        self.send_subscribe(vec![channel]).await
1376    }
1377
1378    /// Unsubscribes from volatility index updates for the given index name.
1379    ///
1380    /// # Errors
1381    ///
1382    /// Returns an error if unsubscription fails.
1383    pub async fn unsubscribe_volatility_index(&self, index_name: &str) -> DeribitWsResult<()> {
1384        let channel = DeribitWsChannel::VolatilityIndex.format_channel(index_name, None);
1385        self.send_unsubscribe(vec![channel]).await
1386    }
1387
1388    /// Subscribes to perpetual interest rates updates.
1389    ///
1390    /// Channel format: `perpetual.{instrument_name}.{interval}`
1391    ///
1392    /// # Errors
1393    ///
1394    /// Returns an error if subscription fails.
1395    pub async fn subscribe_perpetual_interests_rates_updates(
1396        &self,
1397        instrument_id: InstrumentId,
1398        interval: Option<DeribitUpdateInterval>,
1399    ) -> DeribitWsResult<()> {
1400        let interval = interval.unwrap_or(DeribitUpdateInterval::Ms100);
1401        let channel = DeribitWsChannel::Perpetual
1402            .format_channel(instrument_id.symbol.as_str(), Some(interval));
1403
1404        self.send_subscribe(vec![channel]).await
1405    }
1406
1407    /// Unsubscribes from perpetual interest rates updates.
1408    ///
1409    /// # Errors
1410    ///
1411    /// Returns an error if subscription fails.
1412    pub async fn unsubscribe_perpetual_interest_rates_updates(
1413        &self,
1414        instrument_id: InstrumentId,
1415        interval: Option<DeribitUpdateInterval>,
1416    ) -> DeribitWsResult<()> {
1417        let interval = interval.unwrap_or(DeribitUpdateInterval::Ms100);
1418        let channel = DeribitWsChannel::Perpetual
1419            .format_channel(instrument_id.symbol.as_str(), Some(interval));
1420
1421        self.send_unsubscribe(vec![channel]).await
1422    }
1423
1424    /// Subscribes to chart/OHLC bar updates for an instrument.
1425    ///
1426    /// # Arguments
1427    ///
1428    /// * `instrument_id` - The instrument to subscribe to
1429    /// * `resolution` - Bar resolution: "1", "3", "5", "10", "15", "30", "60", "120", "180",
1430    ///   "360", "720", "1D" (minutes or 1D for daily)
1431    ///
1432    /// # Errors
1433    ///
1434    /// Returns an error if subscription fails.
1435    pub async fn subscribe_chart(
1436        &self,
1437        instrument_id: InstrumentId,
1438        resolution: &str,
1439    ) -> DeribitWsResult<()> {
1440        self.validate_public_trades(instrument_id)?;
1441        // Chart channel format: chart.trades.{instrument}.{resolution}
1442        let channel = format!("chart.trades.{}.{}", instrument_id.symbol, resolution);
1443        self.send_subscribe(vec![channel]).await
1444    }
1445
1446    fn validate_public_trades(&self, instrument_id: InstrumentId) -> DeribitWsResult<()> {
1447        if let Some(instrument) = self
1448            .instruments_cache
1449            .get_cloned(&instrument_id.symbol.inner())
1450        {
1451            capabilities::validate_public_trades(&instrument)
1452                .map_err(|e| DeribitWsError::Subscribe(e.to_string()))?;
1453        }
1454
1455        Ok(())
1456    }
1457
1458    /// Unsubscribes from chart/OHLC bar updates.
1459    ///
1460    /// # Errors
1461    ///
1462    /// Returns an error if unsubscription fails.
1463    pub async fn unsubscribe_chart(
1464        &self,
1465        instrument_id: InstrumentId,
1466        resolution: &str,
1467    ) -> DeribitWsResult<()> {
1468        let channel = format!("chart.trades.{}.{}", instrument_id.symbol, resolution);
1469        self.send_unsubscribe(vec![channel]).await
1470    }
1471
1472    /// Subscribes to bar updates for an instrument using a BarType specification.
1473    ///
1474    /// Converts the BarType to the nearest supported Deribit resolution and subscribes
1475    /// to the chart channel.
1476    ///
1477    /// # Errors
1478    ///
1479    /// Returns an error if the subscription request fails.
1480    pub async fn subscribe_bars(&self, bar_type: BarType) -> DeribitWsResult<()> {
1481        let resolution = bar_spec_to_resolution(&bar_type);
1482        self.subscribe_chart(bar_type.instrument_id(), &resolution)
1483            .await
1484    }
1485
1486    /// Unsubscribes from bar updates for an instrument using a BarType specification.
1487    ///
1488    /// # Errors
1489    ///
1490    /// Returns an error if the unsubscription request fails.
1491    pub async fn unsubscribe_bars(&self, bar_type: BarType) -> DeribitWsResult<()> {
1492        let resolution = bar_spec_to_resolution(&bar_type);
1493        self.unsubscribe_chart(bar_type.instrument_id(), &resolution)
1494            .await
1495    }
1496
1497    /// Checks if authentication is required for the given interval.
1498    ///
1499    /// # Errors
1500    ///
1501    /// Returns an error if raw interval is requested but client is not authenticated.
1502    fn check_auth_requirement(&self, interval: DeribitUpdateInterval) -> DeribitWsResult<()> {
1503        if interval.requires_auth() && !self.is_authenticated() {
1504            return Err(DeribitWsError::Authentication(
1505                "Raw streams require authentication. Call authenticate() first.".to_string(),
1506            ));
1507        }
1508        Ok(())
1509    }
1510
1511    /// Subscribes to user order updates for all instruments.
1512    ///
1513    /// Requires authentication. Subscribes to `user.orders.any.any.raw` channel.
1514    ///
1515    /// # Errors
1516    ///
1517    /// Returns an error if client is not authenticated or subscription fails.
1518    pub async fn subscribe_user_orders(&self) -> DeribitWsResult<()> {
1519        if !self.is_authenticated() {
1520            return Err(DeribitWsError::Authentication(
1521                "User orders subscription requires authentication".to_string(),
1522            ));
1523        }
1524        self.send_subscribe(vec!["user.orders.any.any.raw".to_string()])
1525            .await
1526    }
1527
1528    /// Unsubscribes from user order updates for all instruments.
1529    ///
1530    /// # Errors
1531    ///
1532    /// Returns an error if unsubscription fails.
1533    pub async fn unsubscribe_user_orders(&self) -> DeribitWsResult<()> {
1534        self.send_unsubscribe(vec!["user.orders.any.any.raw".to_string()])
1535            .await
1536    }
1537
1538    /// Subscribes to user trade/fill updates for all instruments.
1539    ///
1540    /// Requires authentication. Subscribes to `user.trades.any.any.raw` channel.
1541    ///
1542    /// # Errors
1543    ///
1544    /// Returns an error if client is not authenticated or subscription fails.
1545    pub async fn subscribe_user_trades(&self) -> DeribitWsResult<()> {
1546        if !self.is_authenticated() {
1547            return Err(DeribitWsError::Authentication(
1548                "User trades subscription requires authentication".to_string(),
1549            ));
1550        }
1551        self.send_subscribe(vec!["user.trades.any.any.raw".to_string()])
1552            .await
1553    }
1554
1555    /// Unsubscribes from user trade/fill updates for all instruments.
1556    ///
1557    /// # Errors
1558    ///
1559    /// Returns an error if unsubscription fails.
1560    pub async fn unsubscribe_user_trades(&self) -> DeribitWsResult<()> {
1561        self.send_unsubscribe(vec!["user.trades.any.any.raw".to_string()])
1562            .await
1563    }
1564
1565    /// Subscribes to user portfolio updates for all currencies.
1566    ///
1567    /// Requires authentication. Subscribes to `user.portfolio.any` channel which
1568    /// provides real-time account balance and margin updates for all currencies
1569    /// (BTC, ETH, USDC, USDT, etc.).
1570    ///
1571    /// # Errors
1572    ///
1573    /// Returns an error if client is not authenticated or subscription fails.
1574    pub async fn subscribe_user_portfolio(&self) -> DeribitWsResult<()> {
1575        if !self.is_authenticated() {
1576            return Err(DeribitWsError::Authentication(
1577                "User portfolio subscription requires authentication".to_string(),
1578            ));
1579        }
1580        self.send_subscribe(vec!["user.portfolio.any".to_string()])
1581            .await
1582    }
1583
1584    /// Unsubscribes from user portfolio updates for all currencies.
1585    ///
1586    /// # Errors
1587    ///
1588    /// Returns an error if unsubscription fails.
1589    pub async fn unsubscribe_user_portfolio(&self) -> DeribitWsResult<()> {
1590        self.send_unsubscribe(vec!["user.portfolio.any".to_string()])
1591            .await
1592    }
1593
1594    /// Subscribes to multiple channels at once.
1595    ///
1596    /// # Errors
1597    ///
1598    /// Returns an error if subscription fails.
1599    pub async fn subscribe(&self, channels: Vec<String>) -> DeribitWsResult<()> {
1600        self.send_subscribe(channels).await
1601    }
1602
1603    /// Unsubscribes from multiple channels at once.
1604    ///
1605    /// # Errors
1606    ///
1607    /// Returns an error if unsubscription fails.
1608    pub async fn unsubscribe(&self, channels: Vec<String>) -> DeribitWsResult<()> {
1609        self.send_unsubscribe(channels).await
1610    }
1611
1612    /// Submits an order to Deribit via WebSocket.
1613    ///
1614    /// Routes to `private/buy` or `private/sell` JSON-RPC method based on order side.
1615    /// Requires authentication (call `authenticate_session()` first).
1616    ///
1617    /// # Errors
1618    ///
1619    /// Returns an error if:
1620    /// - The client is not authenticated.
1621    /// - The command fails to send.
1622    pub async fn submit_order(
1623        &self,
1624        order_side: OrderSide,
1625        params: DeribitOrderParams,
1626        client_order_id: ClientOrderId,
1627        trader_id: TraderId,
1628        strategy_id: StrategyId,
1629        instrument_id: InstrumentId,
1630    ) -> DeribitWsResult<()> {
1631        if !self.is_authenticated() {
1632            return Err(DeribitWsError::Authentication(
1633                "Submit order requires authentication. Call authenticate_session() first."
1634                    .to_string(),
1635            ));
1636        }
1637
1638        log::debug!(
1639            "Sending {} order: instrument={}, amount={}, price={:?}, client_order_id={}",
1640            order_side,
1641            params.instrument_name,
1642            params.amount,
1643            params.price,
1644            client_order_id
1645        );
1646
1647        let cmd = match order_side {
1648            OrderSide::Buy => HandlerCommand::Buy {
1649                params,
1650                client_order_id,
1651                trader_id,
1652                strategy_id,
1653                instrument_id,
1654            },
1655            OrderSide::Sell => HandlerCommand::Sell {
1656                params,
1657                client_order_id,
1658                trader_id,
1659                strategy_id,
1660                instrument_id,
1661            },
1662        };
1663
1664        self.command_sender()
1665            .send(cmd)
1666            .map_err(|_| DeribitWsError::AdmissionClosed)?;
1667
1668        Ok(())
1669    }
1670
1671    /// Modifies an existing order on Deribit via WebSocket.
1672    ///
1673    /// The order parameters are sent using the `private/edit` JSON-RPC method.
1674    /// Requires authentication (call `authenticate_session()` first).
1675    ///
1676    /// # Errors
1677    ///
1678    /// Returns an error if:
1679    /// - The client is not authenticated.
1680    /// - The command fails to send.
1681    pub async fn modify_order(
1682        &self,
1683        params: DeribitEditParams,
1684        client_order_id: ClientOrderId,
1685        trader_id: TraderId,
1686        strategy_id: StrategyId,
1687        instrument_id: InstrumentId,
1688    ) -> DeribitWsResult<()> {
1689        self.modify_order_with_causation(
1690            params,
1691            client_order_id,
1692            trader_id,
1693            strategy_id,
1694            instrument_id,
1695            None,
1696        )
1697        .await
1698    }
1699
1700    pub(crate) async fn modify_order_with_causation(
1701        &self,
1702        params: DeribitEditParams,
1703        client_order_id: ClientOrderId,
1704        trader_id: TraderId,
1705        strategy_id: StrategyId,
1706        instrument_id: InstrumentId,
1707        causation_id: Option<UUID4>,
1708    ) -> DeribitWsResult<()> {
1709        if !self.is_authenticated() {
1710            return Err(DeribitWsError::Authentication(
1711                "Modify order requires authentication. Call authenticate_session() first."
1712                    .to_string(),
1713            ));
1714        }
1715
1716        log::debug!(
1717            "Sending modify order: order_id={}, amount={}, price={:?}, client_order_id={client_order_id}",
1718            params.order_id,
1719            params.amount,
1720            params.price,
1721        );
1722
1723        self.command_sender()
1724            .send(HandlerCommand::Edit {
1725                causation_id,
1726                params,
1727                client_order_id,
1728                trader_id,
1729                strategy_id,
1730                instrument_id,
1731            })
1732            .map_err(|_| DeribitWsError::AdmissionClosed)?;
1733
1734        Ok(())
1735    }
1736
1737    /// Cancels an existing order on Deribit via WebSocket.
1738    ///
1739    /// The order is cancelled using the `private/cancel` JSON-RPC method.
1740    /// Requires authentication (call `authenticate_session()` first).
1741    ///
1742    /// # Errors
1743    ///
1744    /// Returns an error if:
1745    /// - The client is not authenticated.
1746    /// - The command fails to send.
1747    pub async fn cancel_order(
1748        &self,
1749        order_id: &str,
1750        client_order_id: ClientOrderId,
1751        trader_id: TraderId,
1752        strategy_id: StrategyId,
1753        instrument_id: InstrumentId,
1754    ) -> DeribitWsResult<()> {
1755        self.cancel_order_with_causation(
1756            order_id,
1757            client_order_id,
1758            trader_id,
1759            strategy_id,
1760            instrument_id,
1761            None,
1762        )
1763        .await
1764    }
1765
1766    pub(crate) async fn cancel_order_with_causation(
1767        &self,
1768        order_id: &str,
1769        client_order_id: ClientOrderId,
1770        trader_id: TraderId,
1771        strategy_id: StrategyId,
1772        instrument_id: InstrumentId,
1773        causation_id: Option<UUID4>,
1774    ) -> DeribitWsResult<()> {
1775        if !self.is_authenticated() {
1776            return Err(DeribitWsError::Authentication(
1777                "Cancel order requires authentication. Call authenticate_session() first."
1778                    .to_string(),
1779            ));
1780        }
1781
1782        let params = DeribitCancelParams {
1783            order_id: order_id.to_string(),
1784        };
1785
1786        log::debug!("Sending cancel order: order_id={order_id}, client_order_id={client_order_id}");
1787
1788        self.command_sender()
1789            .send(HandlerCommand::Cancel {
1790                causation_id,
1791                params,
1792                client_order_id,
1793                trader_id,
1794                strategy_id,
1795                instrument_id,
1796            })
1797            .map_err(|_| DeribitWsError::AdmissionClosed)?;
1798
1799        Ok(())
1800    }
1801
1802    /// Cancels all orders for a specific instrument on Deribit via WebSocket.
1803    ///
1804    /// Uses the `private/cancel_all_by_instrument` JSON-RPC method.
1805    /// Requires authentication (call `authenticate_session()` first).
1806    ///
1807    /// # Errors
1808    ///
1809    /// Returns an error if:
1810    /// - The client is not authenticated.
1811    /// - The command fails to send.
1812    pub async fn cancel_all_orders(
1813        &self,
1814        instrument_id: InstrumentId,
1815        order_type: Option<String>,
1816    ) -> DeribitWsResult<()> {
1817        if !self.is_authenticated() {
1818            return Err(DeribitWsError::Authentication(
1819                "Cancel all orders requires authentication. Call authenticate_session() first."
1820                    .to_string(),
1821            ));
1822        }
1823
1824        let instrument_name = instrument_id.symbol.to_string();
1825        let params = DeribitCancelAllByInstrumentParams {
1826            instrument_name: instrument_name.clone(),
1827            order_type,
1828        };
1829
1830        log::debug!("Sending cancel_all_orders: instrument={instrument_name}");
1831
1832        self.command_sender()
1833            .send(HandlerCommand::CancelAllByInstrument {
1834                params,
1835                instrument_id,
1836            })
1837            .map_err(|_| DeribitWsError::AdmissionClosed)?;
1838
1839        Ok(())
1840    }
1841
1842    /// Queries the state of an order on Deribit via WebSocket.
1843    ///
1844    /// Uses the `private/get_order_state` JSON-RPC method.
1845    /// Requires authentication (call `authenticate_session()` first).
1846    ///
1847    /// # Errors
1848    ///
1849    /// Returns an error if:
1850    /// - The client is not authenticated.
1851    /// - The command fails to send.
1852    pub async fn query_order(
1853        &self,
1854        order_id: &str,
1855        client_order_id: ClientOrderId,
1856        trader_id: TraderId,
1857        strategy_id: StrategyId,
1858        instrument_id: InstrumentId,
1859    ) -> DeribitWsResult<()> {
1860        if !self.is_authenticated() {
1861            return Err(DeribitWsError::Authentication(
1862                "Query order state requires authentication. Call authenticate_session() first."
1863                    .to_string(),
1864            ));
1865        }
1866
1867        log::debug!("Sending query_order: order_id={order_id}, client_order_id={client_order_id}");
1868
1869        self.command_sender()
1870            .send(HandlerCommand::GetOrderState {
1871                order_id: order_id.to_string(),
1872                client_order_id,
1873                trader_id,
1874                strategy_id,
1875                instrument_id,
1876            })
1877            .map_err(|e| DeribitWsError::Send(e.to_string()))?;
1878
1879        Ok(())
1880    }
1881
1882    fn command_sender(&self) -> RwLockReadGuard<'_, CommandSender> {
1883        self.cmd_tx.read()
1884    }
1885}
1886
1887fn grouped_book_channel(
1888    instrument_id: InstrumentId,
1889    group: &str,
1890    depth: u32,
1891    interval: Option<DeribitUpdateInterval>,
1892) -> String {
1893    let interval = match interval {
1894        Some(DeribitUpdateInterval::Raw) | None => DeribitUpdateInterval::Ms100,
1895        Some(i) => i,
1896    };
1897
1898    let depth = if depth < 5 {
1899        1
1900    } else if depth < 15 {
1901        10
1902    } else {
1903        20
1904    };
1905
1906    format!(
1907        "book.{}.{group}.{depth}.{}",
1908        instrument_id.symbol,
1909        interval.as_str()
1910    )
1911}
1912
1913#[cfg(test)]
1914mod tests {
1915    use futures_util::StreamExt;
1916    use nautilus_core::UnixNanos;
1917    use rstest::rstest;
1918
1919    use super::*;
1920    use crate::{
1921        common::{
1922            parse::parse_deribit_instrument_any,
1923            rpc::DeribitJsonRpcResponse,
1924            testing::{load_test_json, routed_spot_instrument},
1925        },
1926        http::models::DeribitInstrument,
1927    };
1928
1929    #[tokio::test]
1930    async fn routed_spot_rejects_trades_and_charts_but_subscribes_books() {
1931        let ws_client =
1932            DeribitWebSocketClient::new_public(DeribitEnvironment::Testnet, None).unwrap();
1933        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
1934        *ws_client.cmd_tx.write() = tx;
1935        let instrument = routed_spot_instrument();
1936        let instrument_id = instrument.id();
1937        ws_client.cache_instruments(std::slice::from_ref(&instrument));
1938
1939        let HandlerCommand::UpdateInstrument(updated) = rx.try_recv().unwrap() else {
1940            panic!("expected instrument update");
1941        };
1942
1943        let trades_error = ws_client
1944            .subscribe_trades(instrument_id, None)
1945            .await
1946            .unwrap_err();
1947        let chart_error = ws_client
1948            .subscribe_chart(instrument_id, "1")
1949            .await
1950            .unwrap_err();
1951        let bars_error = ws_client
1952            .subscribe_bars("BTC_USDC.DERIBIT-1-MINUTE-LAST-EXTERNAL".parse().unwrap())
1953            .await
1954            .unwrap_err();
1955        ws_client.subscribe_book(instrument_id, None).await.unwrap();
1956        let command = rx.try_recv().unwrap();
1957
1958        assert_eq!(updated.id(), instrument_id);
1959        assert_eq!(updated.info(), instrument.info());
1960
1961        for error in [trades_error, chart_error, bars_error] {
1962            assert_eq!(
1963                error.to_string(),
1964                "Subscribe error: Deribit routed spot does not support public trades or charts for BTC_USDC.DERIBIT"
1965            );
1966        }
1967
1968        assert!(
1969            matches!(command, HandlerCommand::Subscribe { channels } if channels == vec!["book.BTC_USDC.100ms"])
1970        );
1971        assert!(matches!(
1972            rx.try_recv(),
1973            Err(tokio::sync::mpsc::error::TryRecvError::Empty)
1974        ));
1975    }
1976
1977    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1978    async fn active_state_waits_for_sender_publication() {
1979        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
1980        let addr = listener.local_addr().unwrap();
1981        let server = tokio::spawn(async move {
1982            let (socket, _) = listener.accept().await.unwrap();
1983            let mut socket = tokio_tungstenite::accept_async(socket).await.unwrap();
1984
1985            while matches!(socket.next().await, Some(Ok(_))) {}
1986        });
1987
1988        let mut ws_client = DeribitWebSocketClient::new_unauthenticated(
1989            Some(format!("ws://{addr}")),
1990            30,
1991            DeribitEnvironment::Testnet,
1992        )
1993        .unwrap();
1994        let observer = ws_client.clone();
1995        let sender = Arc::clone(&ws_client.cmd_tx);
1996        let (held_tx, held_rx) = tokio::sync::oneshot::channel();
1997
1998        let publication = tokio::task::spawn_blocking(move || {
1999            let guard = sender.read();
2000            held_tx.send(()).unwrap();
2001            let deadline = std::time::Instant::now() + Duration::from_secs(5);
2002
2003            while sender.try_read().is_some() {
2004                assert!(
2005                    std::time::Instant::now() < deadline,
2006                    "connect must queue its writer"
2007                );
2008                std::thread::yield_now();
2009            }
2010
2011            let active = observer.is_active();
2012            drop(guard);
2013            active
2014        });
2015
2016        held_rx.await.unwrap();
2017        ws_client.connect().await.unwrap();
2018        let active_before_publication = publication.await.unwrap();
2019        let active_after_publication = ws_client.is_active();
2020        ws_client.close().await.unwrap();
2021        server.abort();
2022
2023        assert!(!active_before_publication);
2024        assert!(active_after_publication);
2025    }
2026
2027    struct DropSignal(Arc<AtomicBool>);
2028
2029    impl Drop for DropSignal {
2030        fn drop(&mut self) {
2031            self.0.store(true, Ordering::Release);
2032        }
2033    }
2034
2035    #[tokio::test]
2036    async fn test_last_client_owner_drop_aborts_handler_task() {
2037        let client = DeribitWebSocketClient::new_unauthenticated(
2038            Some("ws://127.0.0.1:0/ws/api/v2".to_string()),
2039            30,
2040            DeribitEnvironment::Testnet,
2041        )
2042        .unwrap();
2043        let (started_tx, started_rx) = tokio::sync::oneshot::channel();
2044        let dropped = Arc::new(AtomicBool::new(false));
2045        let drop_signal = DropSignal(Arc::clone(&dropped));
2046        client
2047            .handler_tasks
2048            .spawn(async move {
2049                let _drop_signal = drop_signal;
2050                started_tx.send(()).expect("started receiver");
2051                std::future::pending::<()>().await;
2052            })
2053            .expect("handler task should register");
2054        started_rx.await.expect("handler task started");
2055        let clone = client.clone();
2056
2057        drop(client);
2058        assert!(!dropped.load(Ordering::Acquire));
2059        drop(clone);
2060
2061        tokio::time::timeout(Duration::from_secs(1), async {
2062            while !dropped.load(Ordering::Acquire) {
2063                tokio::task::yield_now().await;
2064            }
2065        })
2066        .await
2067        .expect("handler task aborted");
2068    }
2069
2070    #[rstest]
2071    #[case::depth_last(true)]
2072    #[case::deltas_last(false)]
2073    #[tokio::test]
2074    async fn test_book_depth_shared_subscription_lifetime(#[case] depth_last: bool) {
2075        let client = DeribitWebSocketClient::new_public(DeribitEnvironment::Testnet, None).unwrap();
2076        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
2077        *client.cmd_tx.write() = tx;
2078        let instrument_id = InstrumentId::from("BTC-PERPETUAL.DERIBIT");
2079        let channel = "book.BTC-PERPETUAL.none.10.100ms";
2080        client
2081            .subscribe_book_depth(instrument_id, "none", None)
2082            .await
2083            .unwrap();
2084        client
2085            .subscribe_book_depth(instrument_id, "none", None)
2086            .await
2087            .unwrap();
2088        client
2089            .subscribe_book_grouped(instrument_id, "none", 10, None)
2090            .await
2091            .unwrap();
2092
2093        assert_eq!(
2094            client
2095                .book_depth_subs
2096                .lock()
2097                .await
2098                .get_reference_count(channel),
2099            2
2100        );
2101        assert_eq!(client.subscriptions_state.get_reference_count(channel), 3);
2102
2103        let HandlerCommand::Subscribe { channels } = rx.try_recv().unwrap() else {
2104            panic!("expected subscribe");
2105        };
2106
2107        assert_eq!(channels, [channel]);
2108        assert!(rx.try_recv().is_err());
2109
2110        client
2111            .unsubscribe_book_depth(instrument_id, "none", None)
2112            .await
2113            .unwrap();
2114        assert_eq!(
2115            client
2116                .book_depth_subs
2117                .lock()
2118                .await
2119                .get_reference_count(channel),
2120            1
2121        );
2122        assert_eq!(client.subscriptions_state.get_reference_count(channel), 2);
2123        assert!(rx.try_recv().is_err());
2124
2125        if depth_last {
2126            client
2127                .unsubscribe_book_grouped(instrument_id, "none", 10, None)
2128                .await
2129                .unwrap();
2130        } else {
2131            client
2132                .unsubscribe_book_depth(instrument_id, "none", None)
2133                .await
2134                .unwrap();
2135        }
2136
2137        assert_eq!(
2138            client
2139                .book_depth_subs
2140                .lock()
2141                .await
2142                .get_reference_count(channel),
2143            usize::from(depth_last)
2144        );
2145        assert_eq!(client.subscriptions_state.get_reference_count(channel), 1);
2146        assert!(rx.try_recv().is_err());
2147
2148        if depth_last {
2149            client
2150                .unsubscribe_book_depth(instrument_id, "none", None)
2151                .await
2152                .unwrap();
2153        } else {
2154            client
2155                .unsubscribe_book_grouped(instrument_id, "none", 10, None)
2156                .await
2157                .unwrap();
2158        }
2159
2160        let HandlerCommand::Unsubscribe { channels } = rx.try_recv().unwrap() else {
2161            panic!("expected unsubscribe");
2162        };
2163
2164        assert_eq!(channels, [channel]);
2165        assert_eq!(
2166            client
2167                .book_depth_subs
2168                .lock()
2169                .await
2170                .get_reference_count(channel),
2171            0
2172        );
2173        assert_eq!(client.subscriptions_state.get_reference_count(channel), 0);
2174        assert!(rx.try_recv().is_err());
2175    }
2176
2177    #[tokio::test]
2178    async fn test_book_depth_unsubscribe_without_reference_preserves_grouped_subscription() {
2179        let client = DeribitWebSocketClient::new_public(DeribitEnvironment::Testnet, None).unwrap();
2180        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
2181        *client.cmd_tx.write() = tx;
2182        let instrument_id = InstrumentId::from("BTC-PERPETUAL.DERIBIT");
2183        let channel = "book.BTC-PERPETUAL.none.10.100ms";
2184        client
2185            .subscribe_book_grouped(instrument_id, "none", 10, None)
2186            .await
2187            .unwrap();
2188
2189        let HandlerCommand::Subscribe { channels } = rx.try_recv().unwrap() else {
2190            panic!("expected subscribe");
2191        };
2192
2193        assert_eq!(channels, [channel]);
2194
2195        client
2196            .unsubscribe_book_depth(instrument_id, "none", None)
2197            .await
2198            .unwrap();
2199
2200        assert_eq!(
2201            client
2202                .book_depth_subs
2203                .lock()
2204                .await
2205                .get_reference_count(channel),
2206            0
2207        );
2208        assert_eq!(client.subscriptions_state.get_reference_count(channel), 1);
2209        assert_eq!(client.subscriptions_state.all_topics(), [channel]);
2210        assert!(rx.try_recv().is_err());
2211    }
2212
2213    #[tokio::test]
2214    async fn test_book_depth_subscribe_send_failure_restores_intent() {
2215        let client = DeribitWebSocketClient::new_public(DeribitEnvironment::Testnet, None).unwrap();
2216        let instrument_id = InstrumentId::from("BTC-PERPETUAL.DERIBIT");
2217        let error = client
2218            .subscribe_book_depth(instrument_id, "none", None)
2219            .await
2220            .unwrap_err();
2221
2222        assert!(matches!(error, DeribitWsError::Send(_)));
2223        assert_eq!(
2224            client
2225                .book_depth_subs
2226                .lock()
2227                .await
2228                .get_reference_count("book.BTC-PERPETUAL.none.10.100ms"),
2229            0
2230        );
2231        assert_eq!(
2232            client
2233                .subscriptions_state
2234                .get_reference_count("book.BTC-PERPETUAL.none.10.100ms"),
2235            0
2236        );
2237    }
2238
2239    #[tokio::test]
2240    async fn test_book_depth_unsubscribe_send_failure_preserves_intent() {
2241        let client = DeribitWebSocketClient::new_public(DeribitEnvironment::Testnet, None).unwrap();
2242        let instrument_id = InstrumentId::from("BTC-PERPETUAL.DERIBIT");
2243        let channel = "book.BTC-PERPETUAL.none.10.100ms";
2244        client.book_depth_subs.lock().await.add_reference(channel);
2245        client.subscriptions_state.add_reference(channel);
2246        client.subscriptions_state.mark_subscribe(channel);
2247        client.subscriptions_state.confirm_subscribe(channel);
2248        let error = client
2249            .unsubscribe_book_depth(instrument_id, "none", None)
2250            .await
2251            .unwrap_err();
2252
2253        assert!(matches!(error, DeribitWsError::Send(_)));
2254        assert_eq!(
2255            client
2256                .book_depth_subs
2257                .lock()
2258                .await
2259                .get_reference_count(channel),
2260            1
2261        );
2262        assert_eq!(client.subscriptions_state.get_reference_count(channel), 1);
2263        assert_eq!(client.subscriptions_state.all_topics(), [channel]);
2264    }
2265
2266    #[rstest]
2267    #[tokio::test]
2268    async fn test_unsubscribe_send_failure_restores_subscription() {
2269        let client = DeribitWebSocketClient::new_unauthenticated(
2270            Some("ws://127.0.0.1:0/ws/api/v2".to_string()),
2271            30,
2272            DeribitEnvironment::Testnet,
2273        )
2274        .unwrap();
2275        let channel = "trades.BTC-PERPETUAL.raw";
2276        client.subscriptions_state.add_reference(channel);
2277        client.subscriptions_state.mark_subscribe(channel);
2278        client.subscriptions_state.confirm_subscribe(channel);
2279
2280        let error = client
2281            .send_unsubscribe(vec![channel.to_string()])
2282            .await
2283            .unwrap_err();
2284
2285        assert!(matches!(error, DeribitWsError::Send(_)));
2286        assert_eq!(client.subscriptions_state.get_reference_count(channel), 1);
2287        assert_eq!(client.subscriptions_state.len(), 1);
2288        assert_eq!(client.subscriptions_state.all_topics(), [channel]);
2289        assert!(
2290            client
2291                .subscriptions_state
2292                .pending_subscribe_topics()
2293                .is_empty()
2294        );
2295        assert!(
2296            client
2297                .subscriptions_state
2298                .pending_unsubscribe_topics()
2299                .is_empty()
2300        );
2301    }
2302
2303    #[rstest]
2304    #[case::active(ConnectionMode::Active)]
2305    #[case::reconnect(ConnectionMode::Reconnect)]
2306    fn test_cache_instruments_updates_handler(#[case] mode: ConnectionMode) {
2307        let client = DeribitWebSocketClient::new_public(DeribitEnvironment::Testnet, None).unwrap();
2308        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
2309        *client.cmd_tx.write() = tx;
2310        client
2311            .connection_mode
2312            .store(Arc::new(AtomicU8::new(mode.as_u8())));
2313        let response: DeribitJsonRpcResponse<Vec<DeribitInstrument>> =
2314            serde_json::from_str(&load_test_json("http_get_instruments.json")).unwrap();
2315        let definition = response.result.unwrap().remove(0);
2316        let ts_init = UnixNanos::default();
2317        let instrument = parse_deribit_instrument_any(&definition, ts_init, ts_init)
2318            .unwrap()
2319            .unwrap();
2320
2321        client.cache_instruments(std::slice::from_ref(&instrument));
2322        client.cache_instrument(instrument.clone());
2323
2324        for _ in 0..2 {
2325            let HandlerCommand::UpdateInstrument(update) = rx.try_recv().unwrap() else {
2326                panic!("expected instrument update");
2327            };
2328            assert_eq!(update.id(), instrument.id());
2329        }
2330        assert!(rx.try_recv().is_err());
2331    }
2332
2333    fn order_params(client_order_id: &str) -> DeribitOrderParams {
2334        DeribitOrderParams {
2335            instrument_name: "BTC-PERPETUAL".to_string(),
2336            amount: rust_decimal::Decimal::new(1, 0),
2337            order_type: "limit".to_string(),
2338            label: Some(client_order_id.to_string()),
2339            price: Some(rust_decimal::Decimal::new(50_000, 0)),
2340            time_in_force: Some("good_til_cancelled".to_string()),
2341            post_only: None,
2342            reject_post_only: None,
2343            reduce_only: None,
2344            trigger_price: None,
2345            trigger: None,
2346            max_show: None,
2347            valid_until: None,
2348        }
2349    }
2350
2351    #[tokio::test]
2352    async fn unauthenticated_submit_sends_no_command() {
2353        let client = DeribitWebSocketClient::new_public(DeribitEnvironment::Testnet, None).unwrap();
2354        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
2355        *client.cmd_tx.write() = tx;
2356        let client_order_id = ClientOrderId::new("auth-closed-001");
2357
2358        let error = client
2359            .submit_order(
2360                OrderSide::Buy,
2361                order_params(client_order_id.as_str()),
2362                client_order_id,
2363                TraderId::from("TESTER-001"),
2364                StrategyId::from("S-001"),
2365                InstrumentId::from("BTC-PERPETUAL.DERIBIT"),
2366            )
2367            .await
2368            .unwrap_err();
2369
2370        assert!(matches!(error, DeribitWsError::Authentication(_)));
2371        assert!(rx.try_recv().is_err());
2372    }
2373
2374    #[tokio::test]
2375    async fn closed_command_channel_sends_no_order_command() {
2376        let client = DeribitWebSocketClient::new_public(DeribitEnvironment::Testnet, None).unwrap();
2377        client.auth_tracker.succeed();
2378        let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
2379        drop(rx);
2380        *client.cmd_tx.write() = tx;
2381        let client_order_id = ClientOrderId::new("admission-closed-001");
2382
2383        let error = client
2384            .submit_order(
2385                OrderSide::Sell,
2386                order_params(client_order_id.as_str()),
2387                client_order_id,
2388                TraderId::from("TESTER-001"),
2389                StrategyId::from("S-001"),
2390                InstrumentId::from("BTC-PERPETUAL.DERIBIT"),
2391            )
2392            .await
2393            .unwrap_err();
2394
2395        assert!(matches!(error, DeribitWsError::AdmissionClosed));
2396    }
2397}