nautilus-coinbase 0.59.0

Coinbase Advanced Trade integration adapter for the Nautilus trading engine
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
// -------------------------------------------------------------------------------------------------
//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
//  https://nautechsystems.io
//
//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
//  You may not use this file except in compliance with the License.
//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
// -------------------------------------------------------------------------------------------------

//! Coinbase Advanced Trade data client for NautilusTrader.
//!
//! Implements the [`DataClient`] trait, providing market data subscriptions and
//! historical data requests through the Coinbase Advanced Trade API.

use std::sync::{
    Arc, Mutex,
    atomic::{AtomicBool, Ordering},
};

use ahash::AHashSet;
use anyhow::Context;
use nautilus_common::{
    cache::InstrumentLookupError,
    clients::DataClient,
    live::{runner::get_data_event_sender, runtime::get_runtime},
    messages::{
        DataEvent,
        data::{
            BarsResponse, BookResponse, DataResponse, InstrumentResponse, InstrumentsResponse,
            RequestBars, RequestBookSnapshot, RequestInstrument, RequestInstruments, RequestTrades,
            SubscribeBars, SubscribeBookDeltas, SubscribeFundingRates, SubscribeIndexPrices,
            SubscribeInstrument, SubscribeInstrumentStatus, SubscribeMarkPrices, SubscribeQuotes,
            SubscribeTrades, TradesResponse, UnsubscribeBars, UnsubscribeBookDeltas,
            UnsubscribeFundingRates, UnsubscribeIndexPrices, UnsubscribeInstrument,
            UnsubscribeInstrumentStatus, UnsubscribeMarkPrices, UnsubscribeQuotes,
            UnsubscribeTrades,
        },
    },
};
use nautilus_core::{
    AtomicMap, MUTEX_POISONED,
    datetime::datetime_to_unix_nanos,
    time::{AtomicTime, get_atomic_clock_realtime},
};
use nautilus_model::{
    data::{Data, OrderBookDeltas_API},
    enums::{BarAggregation, BookType, OrderSide},
    identifiers::{ClientId, InstrumentId, Venue},
    instruments::{Instrument, InstrumentAny},
    orderbook::OrderBook,
};
use tokio::task::JoinHandle;
use tokio_util::sync::CancellationToken;
use ustr::Ustr;

pub(crate) mod poll;

use crate::{
    common::{
        consts::COINBASE_VENUE, credential::CoinbaseCredential, enums::CoinbaseWsChannel,
        parse::bar_type_to_granularity,
    },
    config::CoinbaseDataClientConfig,
    data::poll::DerivPollManager,
    http::{
        client::{CoinbaseHttpClient, data_client_retry_config},
        models::{CandlesResponse, PriceBook, TickerResponse},
        parse::{parse_bar, parse_product_book_snapshot, parse_trade_tick},
    },
    provider::CoinbaseInstrumentProvider,
    websocket::{client::CoinbaseWebSocketClient, handler::NautilusWsMessage},
};

/// Data client for Coinbase Advanced Trade.
///
/// Owns an HTTP client, WebSocket client, and instrument provider. Bootstraps
/// instruments on connect, subscribes to WS channels for live data, and handles
/// historical data requests through the REST API.
#[derive(Debug)]
pub struct CoinbaseDataClient {
    client_id: ClientId,
    #[allow(dead_code)]
    config: CoinbaseDataClientConfig,
    http_client: CoinbaseHttpClient,
    ws_client: CoinbaseWebSocketClient,
    provider: CoinbaseInstrumentProvider,
    is_connected: AtomicBool,
    cancellation_token: CancellationToken,
    tasks: Vec<JoinHandle<()>>,
    data_sender: tokio::sync::mpsc::UnboundedSender<DataEvent>,
    instruments: Arc<AtomicMap<InstrumentId, InstrumentAny>>,
    deriv_polls: DerivPollManager,
    clock: &'static AtomicTime,
    instrument_status_subs: Arc<Mutex<AHashSet<InstrumentId>>>,
}

impl CoinbaseDataClient {
    /// Creates a new [`CoinbaseDataClient`] instance.
    ///
    /// # Errors
    ///
    /// Returns an error if the HTTP client fails to initialize.
    pub fn new(client_id: ClientId, config: CoinbaseDataClientConfig) -> anyhow::Result<Self> {
        let clock = get_atomic_clock_realtime();
        let data_sender = get_data_event_sender();

        let retry_config = data_client_retry_config();

        let http_client = match CoinbaseCredential::resolve(
            config.api_key.as_deref(),
            config.api_secret.as_deref(),
        ) {
            Some(credential) => CoinbaseHttpClient::with_credentials(
                credential,
                config.environment,
                config.http_timeout_secs,
                config.proxy_url.clone(),
                Some(retry_config),
            )
            .map_err(|e| anyhow::anyhow!("Failed to create HTTP client: {e}"))?,
            None => CoinbaseHttpClient::new(
                config.environment,
                config.http_timeout_secs,
                config.proxy_url.clone(),
                Some(retry_config),
            )
            .map_err(|e| anyhow::anyhow!("Failed to create HTTP client: {e}"))?,
        };

        if let Some(url) = &config.base_url_rest {
            http_client.set_base_url(url.clone());
        }

        let ws_url = config.ws_url();
        let ws_client = CoinbaseWebSocketClient::new(
            &ws_url,
            config.transport_backend,
            config.proxy_url.clone(),
        );
        let provider = CoinbaseInstrumentProvider::new(http_client.clone());

        let deriv_polls = DerivPollManager::new(
            http_client.clone(),
            data_sender.clone(),
            clock,
            config.derivatives_poll_interval_secs,
        );

        Ok(Self {
            client_id,
            config,
            http_client,
            ws_client,
            provider,
            is_connected: AtomicBool::new(false),
            cancellation_token: CancellationToken::new(),
            tasks: Vec::new(),
            data_sender,
            instruments: Arc::new(AtomicMap::new()),
            deriv_polls,
            clock,
            instrument_status_subs: Arc::new(Mutex::new(AHashSet::new())),
        })
    }

    fn venue(&self) -> Venue {
        *COINBASE_VENUE
    }

    async fn bootstrap_instruments(&self) -> anyhow::Result<Vec<InstrumentAny>> {
        let instruments = self
            .provider
            .load_all()
            .await
            .context("failed to fetch instruments during bootstrap")?;

        self.instruments.rcu(|m| {
            for instrument in &instruments {
                m.insert(instrument.id(), instrument.clone());
            }
        });

        for instrument in &instruments {
            self.ws_client.update_instrument(instrument.clone()).await;
        }

        log::info!("Bootstrapped {} instruments", instruments.len());
        Ok(instruments)
    }

    async fn spawn_ws(&mut self) -> anyhow::Result<()> {
        self.ws_client
            .connect()
            .await
            .context("failed to connect to Coinbase WebSocket")?;

        let mut out_rx = self
            .ws_client
            .take_out_rx()
            .ok_or_else(|| anyhow::anyhow!("WebSocket output receiver not available"))?;

        let data_sender = self.data_sender.clone();
        let cancellation_token = self.cancellation_token.clone();
        let status_subs = Arc::clone(&self.instrument_status_subs);

        let task = get_runtime().spawn(async move {
            log::info!("Coinbase WebSocket consumption loop started");

            loop {
                tokio::select! {
                    () = cancellation_token.cancelled() => {
                        log::info!("WebSocket consumption loop cancelled");
                        break;
                    }
                    msg_opt = out_rx.recv() => {
                        match msg_opt {
                            Some(msg) => dispatch_ws_message(msg, &data_sender, &status_subs),
                            None => {
                                log::debug!("WebSocket output channel closed");
                                break;
                            }
                        }
                    }
                }
            }

            log::info!("Coinbase WebSocket consumption loop finished");
        });

        self.tasks.push(task);
        log::info!("WebSocket consumption task spawned");
        Ok(())
    }

    fn product_id(instrument_id: InstrumentId) -> Ustr {
        instrument_id.symbol.inner()
    }

    // Resolves a caller-supplied product id to Coinbase's canonical alias (if
    // any). Coinbase consolidates aliased pairs into a single book server-side
    // and rewrites WS subscription confirmations and inbound messages to use
    // the canonical id (e.g. BTC-USDC -> BTC-USD), so we must subscribe with
    // the canonical id and remember the mapping so inbound messages can be
    // re-keyed to what the strategy actually subscribed to.
    fn resolve_wire_product_id(&self, subscribed: Ustr) -> Ustr {
        self.http_client
            .product_aliases()
            .get_cloned(&subscribed)
            .filter(|alias| !alias.is_empty())
            .unwrap_or(subscribed)
    }
}

fn dispatch_ws_message(
    msg: NautilusWsMessage,
    data_sender: &tokio::sync::mpsc::UnboundedSender<DataEvent>,
    status_subs: &Arc<Mutex<AHashSet<InstrumentId>>>,
) {
    match msg {
        NautilusWsMessage::Trade(trade) => {
            if let Err(e) = data_sender.send(DataEvent::Data(Data::Trade(trade))) {
                log::error!("Failed to send trade tick: {e}");
            }
        }
        NautilusWsMessage::Quote(quote) => {
            if let Err(e) = data_sender.send(DataEvent::Data(Data::Quote(quote))) {
                log::error!("Failed to send quote tick: {e}");
            }
        }
        NautilusWsMessage::Deltas(deltas) => {
            if let Err(e) = data_sender.send(DataEvent::Data(Data::Deltas(
                OrderBookDeltas_API::new(deltas),
            ))) {
                log::error!("Failed to send order book deltas: {e}");
            }
        }
        NautilusWsMessage::Bar(bar) => {
            if let Err(e) = data_sender.send(DataEvent::Data(Data::Bar(bar))) {
                log::error!("Failed to send bar: {e}");
            }
        }
        NautilusWsMessage::InstrumentStatus(status) => {
            // Coinbase publishes status for every product on a single feed,
            // so filter to currently-subscribed instruments before emitting.
            let subscribed = status_subs
                .lock()
                .expect(MUTEX_POISONED)
                .contains(&status.instrument_id);
            if subscribed && let Err(e) = data_sender.send(DataEvent::InstrumentStatus(*status)) {
                log::error!("Failed to send instrument status: {e}");
            }
        }
        NautilusWsMessage::Reconnected => {
            log::info!("WebSocket reconnected");
        }
        NautilusWsMessage::Error(e) => {
            log::warn!("WebSocket error: {e}");
        }
        NautilusWsMessage::UserOrder(_) => {
            // User-channel execution reports are consumed by the execution client
            log::debug!("Dropping user-channel update received on the data client");
        }
        NautilusWsMessage::FuturesBalanceSummary(_) => {
            // Futures balance summary events are consumed by the execution client
            log::debug!("Dropping futures_balance_summary event received on the data client");
        }
    }
}

#[async_trait::async_trait(?Send)]
impl DataClient for CoinbaseDataClient {
    fn client_id(&self) -> ClientId {
        self.client_id
    }

    fn venue(&self) -> Option<Venue> {
        Some(Self::venue(self))
    }

    fn start(&mut self) -> anyhow::Result<()> {
        log::info!(
            "Starting Coinbase data client: client_id={}, environment={:?}",
            self.client_id,
            self.config.environment,
        );
        Ok(())
    }

    fn stop(&mut self) -> anyhow::Result<()> {
        log::info!("Stopping Coinbase data client {}", self.client_id);
        self.cancellation_token.cancel();
        self.deriv_polls.shutdown();
        self.is_connected.store(false, Ordering::Relaxed);
        Ok(())
    }

    fn reset(&mut self) -> anyhow::Result<()> {
        log::debug!("Resetting Coinbase data client {}", self.client_id);
        self.cancellation_token.cancel();
        self.deriv_polls.shutdown();
        self.is_connected.store(false, Ordering::Relaxed);
        self.cancellation_token = CancellationToken::new();
        self.tasks.clear();
        self.instrument_status_subs
            .lock()
            .expect(MUTEX_POISONED)
            .clear();
        Ok(())
    }

    fn dispose(&mut self) -> anyhow::Result<()> {
        log::debug!("Disposing Coinbase data client {}", self.client_id);
        self.stop()
    }

    fn is_connected(&self) -> bool {
        self.is_connected.load(Ordering::Acquire)
    }

    fn is_disconnected(&self) -> bool {
        !self.is_connected()
    }

    async fn connect(&mut self) -> anyhow::Result<()> {
        if self.is_connected() {
            return Ok(());
        }

        self.cancellation_token = CancellationToken::new();

        let instruments = self
            .bootstrap_instruments()
            .await
            .context("failed to bootstrap instruments")?;

        for instrument in instruments {
            if let Err(e) = self.data_sender.send(DataEvent::Instrument(instrument)) {
                log::warn!("Failed to send instrument: {e}");
            }
        }

        self.spawn_ws()
            .await
            .context("failed to spawn WebSocket client")?;

        // Re-spawn polling tasks for any derivatives subscriptions that
        // survived a previous disconnect. The data engine's client adapter
        // remembers the subscription set and suppresses duplicate subscribe
        // commands, so without this resume step index-price and
        // funding-rate streams would stay dark after a reconnect.
        self.deriv_polls.resume();

        self.is_connected.store(true, Ordering::Relaxed);
        log::info!("Connected: client_id={}", self.client_id);

        Ok(())
    }

    async fn disconnect(&mut self) -> anyhow::Result<()> {
        if !self.is_connected() {
            return Ok(());
        }

        self.cancellation_token.cancel();
        self.deriv_polls.shutdown();

        for task in self.tasks.drain(..) {
            if let Err(e) = task.await {
                log::error!("Error waiting for task to complete: {e}");
            }
        }

        self.ws_client.disconnect().await;
        self.instruments.store(ahash::AHashMap::new());
        self.is_connected.store(false, Ordering::Relaxed);
        log::info!("Disconnected: client_id={}", self.client_id);

        Ok(())
    }

    fn subscribe_instrument(&mut self, cmd: SubscribeInstrument) -> anyhow::Result<()> {
        let instruments = self.instruments.load();

        if let Some(instrument) = instruments.get(&cmd.instrument_id) {
            if let Err(e) = self
                .data_sender
                .send(DataEvent::Instrument(instrument.clone()))
            {
                log::error!("Failed to send instrument {}: {e}", cmd.instrument_id);
            }
        } else {
            log::warn!("Instrument {} not found in cache", cmd.instrument_id);
        }

        Ok(())
    }

    fn subscribe_book_deltas(&mut self, subscription: SubscribeBookDeltas) -> anyhow::Result<()> {
        log::debug!("Subscribing to book deltas: {}", subscription.instrument_id);

        if subscription.book_type != BookType::L2_MBP {
            anyhow::bail!("Coinbase only supports L2_MBP order book deltas");
        }

        let ws = self.ws_client.clone();
        let subscribed_id = Self::product_id(subscription.instrument_id);
        let wire_id = self.resolve_wire_product_id(subscribed_id);
        if wire_id != subscribed_id {
            ws.register_subscription_alias(wire_id, subscribed_id);
        }

        get_runtime().spawn(async move {
            if let Err(e) = ws.subscribe(CoinbaseWsChannel::Level2, &[wire_id]).await {
                log::error!("Failed to subscribe to book deltas: {e:?}");
            }
        });

        Ok(())
    }

    fn subscribe_quotes(&mut self, subscription: SubscribeQuotes) -> anyhow::Result<()> {
        log::debug!("Subscribing to quotes: {}", subscription.instrument_id);

        let ws = self.ws_client.clone();
        let subscribed_id = Self::product_id(subscription.instrument_id);
        let wire_id = self.resolve_wire_product_id(subscribed_id);
        if wire_id != subscribed_id {
            ws.register_subscription_alias(wire_id, subscribed_id);
        }

        get_runtime().spawn(async move {
            if let Err(e) = ws.subscribe(CoinbaseWsChannel::Ticker, &[wire_id]).await {
                log::error!("Failed to subscribe to quotes: {e:?}");
            }
        });

        Ok(())
    }

    fn subscribe_trades(&mut self, subscription: SubscribeTrades) -> anyhow::Result<()> {
        log::debug!("Subscribing to trades: {}", subscription.instrument_id);

        let ws = self.ws_client.clone();
        let subscribed_id = Self::product_id(subscription.instrument_id);
        let wire_id = self.resolve_wire_product_id(subscribed_id);
        if wire_id != subscribed_id {
            ws.register_subscription_alias(wire_id, subscribed_id);
        }

        get_runtime().spawn(async move {
            if let Err(e) = ws
                .subscribe(CoinbaseWsChannel::MarketTrades, &[wire_id])
                .await
            {
                log::error!("Failed to subscribe to trades: {e:?}");
            }
        });

        Ok(())
    }

    fn subscribe_mark_prices(&mut self, cmd: SubscribeMarkPrices) -> anyhow::Result<()> {
        // Coinbase Advanced Trade does not publish a live mark price for its
        // perpetuals on either WS or REST. `settlement_price` is the prior
        // daily settlement and drifts from the live index, so synthesizing a
        // mark from it would be misleading. Reject explicitly so callers
        // failing this subscription know why.
        anyhow::bail!(
            "Coinbase Advanced Trade does not publish mark prices; \
             cannot subscribe for {}",
            cmd.instrument_id
        )
    }

    fn subscribe_index_prices(&mut self, cmd: SubscribeIndexPrices) -> anyhow::Result<()> {
        log::debug!("Subscribing to index prices: {}", cmd.instrument_id);
        self.deriv_polls.subscribe_index(cmd.instrument_id);
        Ok(())
    }

    fn subscribe_funding_rates(&mut self, cmd: SubscribeFundingRates) -> anyhow::Result<()> {
        log::debug!("Subscribing to funding rates: {}", cmd.instrument_id);
        self.deriv_polls.subscribe_funding(cmd.instrument_id);
        Ok(())
    }

    fn subscribe_instrument_status(
        &mut self,
        cmd: SubscribeInstrumentStatus,
    ) -> anyhow::Result<()> {
        log::debug!("Subscribing to instrument status: {}", cmd.instrument_id);

        // Register the canonical-to-subscribed alias so the handler re-keys
        // inbound status events for aliased products (e.g. caller subscribed
        // to `BTC-USDC` but the venue reports the canonical `BTC-USD`).
        // Without this the filter below would drop alias-only subscriptions.
        let subscribed_id = Self::product_id(cmd.instrument_id);
        let wire_id = self.resolve_wire_product_id(subscribed_id);
        if wire_id != subscribed_id {
            self.ws_client
                .register_subscription_alias(wire_id, subscribed_id);
        }

        // Coinbase publishes a single product-wide status feed. Only subscribe
        // to the WS channel once; subsequent calls just record the instrument.
        let was_empty = {
            let mut subs = self.instrument_status_subs.lock().expect(MUTEX_POISONED);
            let was_empty = subs.is_empty();
            subs.insert(cmd.instrument_id);
            was_empty
        };

        if was_empty {
            let ws = self.ws_client.clone();
            get_runtime().spawn(async move {
                if let Err(e) = ws.subscribe(CoinbaseWsChannel::Status, &[]).await {
                    log::error!("Failed to subscribe to status channel: {e:?}");
                }
            });
        }
        Ok(())
    }

    fn subscribe_bars(&mut self, subscription: SubscribeBars) -> anyhow::Result<()> {
        log::debug!("Subscribing to bars: {}", subscription.bar_type);

        let instrument_id = subscription.bar_type.instrument_id();

        if !self.instruments.contains_key(&instrument_id) {
            anyhow::bail!(InstrumentLookupError::not_found(instrument_id));
        }

        let bar_type = subscription.bar_type;
        let subscribed_id = Self::product_id(instrument_id);
        let wire_id = self.resolve_wire_product_id(subscribed_id);
        if wire_id != subscribed_id {
            self.ws_client
                .register_subscription_alias(wire_id, subscribed_id);
        }
        let key = wire_id.to_string();

        // Register on the original client so the bar type persists across clones
        self.ws_client.register_bar_type(key.clone(), bar_type);

        let mut ws = self.ws_client.clone();

        get_runtime().spawn(async move {
            ws.add_bar_type(key, bar_type).await;

            if let Err(e) = ws.subscribe(CoinbaseWsChannel::Candles, &[wire_id]).await {
                log::error!("Failed to subscribe to bars: {e:?}");
            }
        });

        Ok(())
    }

    // Unsubscribe paths intentionally do NOT call
    // `unregister_subscription_alias`. The same canonical wire id is shared
    // across multiple data channels (ticker, market_trades, level2,
    // candles), so dropping the entry on the first unsubscribe would cause
    // every still-active channel for the same alias to mistag inbound
    // messages. The mapping is stable per product for the process lifetime
    // and the venue does not deliver messages for products that aren't
    // subscribed to, so leaving it in place is safe.

    fn unsubscribe_instrument(
        &mut self,
        _unsubscription: &UnsubscribeInstrument,
    ) -> anyhow::Result<()> {
        // `subscribe_instrument` only replays cached state; no venue subscription to tear down.
        Ok(())
    }

    fn unsubscribe_book_deltas(
        &mut self,
        unsubscription: &UnsubscribeBookDeltas,
    ) -> anyhow::Result<()> {
        log::debug!(
            "Unsubscribing from book deltas: {}",
            unsubscription.instrument_id
        );

        let ws = self.ws_client.clone();
        let subscribed_id = Self::product_id(unsubscription.instrument_id);
        let wire_id = self.resolve_wire_product_id(subscribed_id);

        get_runtime().spawn(async move {
            if let Err(e) = ws.unsubscribe(CoinbaseWsChannel::Level2, &[wire_id]).await {
                log::error!("Failed to unsubscribe from book deltas: {e:?}");
            }
        });

        Ok(())
    }

    fn unsubscribe_quotes(&mut self, unsubscription: &UnsubscribeQuotes) -> anyhow::Result<()> {
        log::debug!(
            "Unsubscribing from quotes: {}",
            unsubscription.instrument_id
        );

        let ws = self.ws_client.clone();
        let subscribed_id = Self::product_id(unsubscription.instrument_id);
        let wire_id = self.resolve_wire_product_id(subscribed_id);

        get_runtime().spawn(async move {
            if let Err(e) = ws.unsubscribe(CoinbaseWsChannel::Ticker, &[wire_id]).await {
                log::error!("Failed to unsubscribe from quotes: {e:?}");
            }
        });

        Ok(())
    }

    fn unsubscribe_trades(&mut self, unsubscription: &UnsubscribeTrades) -> anyhow::Result<()> {
        log::debug!(
            "Unsubscribing from trades: {}",
            unsubscription.instrument_id
        );

        let ws = self.ws_client.clone();
        let subscribed_id = Self::product_id(unsubscription.instrument_id);
        let wire_id = self.resolve_wire_product_id(subscribed_id);

        get_runtime().spawn(async move {
            if let Err(e) = ws
                .unsubscribe(CoinbaseWsChannel::MarketTrades, &[wire_id])
                .await
            {
                log::error!("Failed to unsubscribe from trades: {e:?}");
            }
        });

        Ok(())
    }

    fn unsubscribe_mark_prices(&mut self, _cmd: &UnsubscribeMarkPrices) -> anyhow::Result<()> {
        Ok(())
    }

    fn unsubscribe_index_prices(&mut self, cmd: &UnsubscribeIndexPrices) -> anyhow::Result<()> {
        log::debug!("Unsubscribing from index prices: {}", cmd.instrument_id);
        self.deriv_polls.unsubscribe_index(cmd.instrument_id);
        Ok(())
    }

    fn unsubscribe_funding_rates(&mut self, cmd: &UnsubscribeFundingRates) -> anyhow::Result<()> {
        log::debug!("Unsubscribing from funding rates: {}", cmd.instrument_id);
        self.deriv_polls.unsubscribe_funding(cmd.instrument_id);
        Ok(())
    }

    fn unsubscribe_instrument_status(
        &mut self,
        cmd: &UnsubscribeInstrumentStatus,
    ) -> anyhow::Result<()> {
        log::debug!(
            "Unsubscribing from instrument status: {}",
            cmd.instrument_id
        );

        let now_empty = {
            let mut subs = self.instrument_status_subs.lock().expect(MUTEX_POISONED);
            subs.remove(&cmd.instrument_id);
            subs.is_empty()
        };

        if now_empty {
            let ws = self.ws_client.clone();
            get_runtime().spawn(async move {
                if let Err(e) = ws.unsubscribe(CoinbaseWsChannel::Status, &[]).await {
                    log::error!("Failed to unsubscribe from status channel: {e:?}");
                }
            });
        }
        Ok(())
    }

    fn unsubscribe_bars(&mut self, unsubscription: &UnsubscribeBars) -> anyhow::Result<()> {
        log::debug!("Unsubscribing from bars: {}", unsubscription.bar_type);

        let instrument_id = unsubscription.bar_type.instrument_id();
        let subscribed_id = Self::product_id(instrument_id);
        let wire_id = self.resolve_wire_product_id(subscribed_id);
        let ws = self.ws_client.clone();

        get_runtime().spawn(async move {
            if let Err(e) = ws.unsubscribe(CoinbaseWsChannel::Candles, &[wire_id]).await {
                log::error!("Failed to unsubscribe from bars: {e:?}");
            }
        });

        Ok(())
    }

    fn request_instruments(&self, request: RequestInstruments) -> anyhow::Result<()> {
        log::debug!("Requesting all instruments");

        let provider = self.provider.clone();
        let sender = self.data_sender.clone();
        let instruments_cache = self.instruments.clone();
        let ws = self.ws_client.clone();
        let request_id = request.request_id;
        let client_id = request.client_id.unwrap_or(self.client_id);
        let venue = Self::venue(self);
        let start_nanos = datetime_to_unix_nanos(request.start);
        let end_nanos = datetime_to_unix_nanos(request.end);
        let params = request.params;
        let clock = self.clock;

        get_runtime().spawn(async move {
            match provider.load_all().await {
                Ok(instruments) => {
                    instruments_cache.rcu(|m| {
                        for instrument in &instruments {
                            m.insert(instrument.id(), instrument.clone());
                        }
                    });

                    for instrument in &instruments {
                        ws.update_instrument(instrument.clone()).await;
                    }

                    let response = DataResponse::Instruments(InstrumentsResponse::new(
                        request_id,
                        client_id,
                        venue,
                        instruments,
                        start_nanos,
                        end_nanos,
                        clock.get_time_ns(),
                        params,
                    ));

                    if let Err(e) = sender.send(DataEvent::Response(response)) {
                        log::error!("Failed to send instruments response: {e}");
                    }
                }
                Err(e) => {
                    log::error!("Failed to fetch instruments: {e:?}");
                }
            }
        });

        Ok(())
    }

    fn request_instrument(&self, request: RequestInstrument) -> anyhow::Result<()> {
        log::debug!("Requesting instrument: {}", request.instrument_id);

        let provider = self.provider.clone();
        let sender = self.data_sender.clone();
        let instruments_cache = self.instruments.clone();
        let ws = self.ws_client.clone();
        let instrument_id = request.instrument_id;
        let product_id = instrument_id.symbol.to_string();
        let request_id = request.request_id;
        let client_id = request.client_id.unwrap_or(self.client_id);
        let start_nanos = datetime_to_unix_nanos(request.start);
        let end_nanos = datetime_to_unix_nanos(request.end);
        let params = request.params;
        let clock = self.clock;

        get_runtime().spawn(async move {
            match provider.load(&product_id).await {
                Ok(instrument) => {
                    instruments_cache.rcu(|m| {
                        m.insert(instrument.id(), instrument.clone());
                    });
                    ws.update_instrument(instrument.clone()).await;

                    let response = DataResponse::Instrument(Box::new(InstrumentResponse::new(
                        request_id,
                        client_id,
                        instrument.id(),
                        instrument,
                        start_nanos,
                        end_nanos,
                        clock.get_time_ns(),
                        params,
                    )));

                    if let Err(e) = sender.send(DataEvent::Response(response)) {
                        log::error!("Failed to send instrument response: {e}");
                    }
                }
                Err(e) => {
                    log::error!("Failed to fetch instrument {instrument_id}: {e:?}");
                }
            }
        });

        Ok(())
    }

    fn request_book_snapshot(&self, request: RequestBookSnapshot) -> anyhow::Result<()> {
        let instrument_id = request.instrument_id;
        let product_id = instrument_id.symbol.to_string();

        let instruments = self.instruments.load();
        let instrument = instruments
            .get(&instrument_id)
            .ok_or_else(|| InstrumentLookupError::not_found(instrument_id))?;
        let price_precision = instrument.price_precision();
        let size_precision = instrument.size_precision();
        let depth = request.depth.map(|d| d.get() as u32);

        let http = self.http_client.clone();
        let sender = self.data_sender.clone();
        let client_id = request.client_id.unwrap_or(self.client_id);
        let request_id = request.request_id;
        let params = request.params;
        let clock = self.clock;

        get_runtime().spawn(async move {
            match http.get_product_book(&product_id, depth).await {
                Ok(json) => {
                    let pricebook_value = json.get("pricebook").cloned().unwrap_or(json);

                    let pricebook: PriceBook = match serde_json::from_value(pricebook_value) {
                        Ok(b) => b,
                        Err(e) => {
                            log::error!("Failed to parse product book: {e}");
                            return;
                        }
                    };

                    let ts_init = clock.get_time_ns();

                    match parse_product_book_snapshot(
                        &pricebook,
                        instrument_id,
                        price_precision,
                        size_precision,
                        ts_init,
                    ) {
                        Ok(deltas) => {
                            let mut book = OrderBook::new(instrument_id, BookType::L2_MBP);

                            for delta in &deltas.deltas {
                                if delta.order.side != OrderSide::NoOrderSide {
                                    book.add(
                                        delta.order,
                                        delta.flags,
                                        delta.sequence,
                                        delta.ts_event,
                                    );
                                }
                            }

                            let response = DataResponse::Book(BookResponse::new(
                                request_id,
                                client_id,
                                instrument_id,
                                book,
                                None,
                                None,
                                clock.get_time_ns(),
                                params,
                            ));

                            if let Err(e) = sender.send(DataEvent::Response(response)) {
                                log::error!("Failed to send book snapshot response: {e}");
                            }
                        }
                        Err(e) => {
                            log::error!("Failed to parse book snapshot for {instrument_id}: {e}");
                        }
                    }
                }
                Err(e) => {
                    log::error!("Book snapshot request failed for {instrument_id}: {e:?}");
                }
            }
        });

        Ok(())
    }

    fn request_trades(&self, request: RequestTrades) -> anyhow::Result<()> {
        log::debug!("Requesting trades for {}", request.instrument_id);

        let instrument_id = request.instrument_id;
        let product_id = instrument_id.symbol.to_string();

        let instruments = self.instruments.load();
        let instrument = instruments
            .get(&instrument_id)
            .ok_or_else(|| InstrumentLookupError::not_found(instrument_id))?;
        let price_precision = instrument.price_precision();
        let size_precision = instrument.size_precision();

        let http = self.http_client.clone();
        let sender = self.data_sender.clone();
        let request_id = request.request_id;
        let client_id = request.client_id.unwrap_or(self.client_id);
        let limit = request.limit.map_or(100, |n| n.get() as u32);
        let start_nanos = datetime_to_unix_nanos(request.start);
        let end_nanos = datetime_to_unix_nanos(request.end);
        let params = request.params;
        let clock = self.clock;

        get_runtime().spawn(async move {
            match http.get_market_trades(&product_id, limit).await {
                Ok(json) => {
                    let ticker: TickerResponse = match serde_json::from_value(json) {
                        Ok(r) => r,
                        Err(e) => {
                            log::error!("Failed to parse trades response: {e}");
                            return;
                        }
                    };

                    let ts_init = clock.get_time_ns();
                    let mut trades: Vec<_> = ticker
                        .trades
                        .iter()
                        .filter_map(|trade| {
                            parse_trade_tick(
                                trade,
                                instrument_id,
                                price_precision,
                                size_precision,
                                ts_init,
                            )
                            .map_err(|e| log::warn!("Failed to parse trade: {e}"))
                            .ok()
                        })
                        .collect();

                    // Coinbase returns newest-first; sort ascending
                    trades.sort_by_key(|t| t.ts_event);

                    let response = DataResponse::Trades(TradesResponse::new(
                        request_id,
                        client_id,
                        instrument_id,
                        trades,
                        start_nanos,
                        end_nanos,
                        clock.get_time_ns(),
                        params,
                    ));

                    if let Err(e) = sender.send(DataEvent::Response(response)) {
                        log::error!("Failed to send trades response: {e}");
                    }
                }
                Err(e) => log::error!("Trades request failed for {instrument_id}: {e:?}"),
            }
        });

        Ok(())
    }

    fn request_bars(&self, request: RequestBars) -> anyhow::Result<()> {
        log::debug!("Requesting bars for {}", request.bar_type);

        let bar_type = request.bar_type;
        let granularity = bar_type_to_granularity(&bar_type)?;
        let instrument_id = bar_type.instrument_id();
        let product_id = instrument_id.symbol.to_string();

        let instruments = self.instruments.load();
        let instrument = instruments
            .get(&instrument_id)
            .ok_or_else(|| InstrumentLookupError::not_found(instrument_id))?;
        let price_precision = instrument.price_precision();
        let size_precision = instrument.size_precision();

        let http = self.http_client.clone();
        let sender = self.data_sender.clone();
        let request_id = request.request_id;
        let client_id = request.client_id.unwrap_or(self.client_id);
        let start = request.start;
        let end = request.end;
        let limit = request.limit.map(|n| n.get());
        let start_nanos = datetime_to_unix_nanos(start);
        let end_nanos = datetime_to_unix_nanos(end);
        let params = request.params;
        let clock = self.clock;

        get_runtime().spawn(async move {
            let now = chrono::Utc::now();
            let end_secs = end.unwrap_or(now).timestamp().to_string();
            let start_secs = if let Some(s) = start {
                s.timestamp().to_string()
            } else {
                let spec = bar_type.spec();
                let step_secs = match spec.aggregation {
                    BarAggregation::Minute => spec.step.get() as i64 * 60,
                    BarAggregation::Hour => spec.step.get() as i64 * 3600,
                    BarAggregation::Day => spec.step.get() as i64 * 86400,
                    _ => 60,
                };
                let count = limit.unwrap_or(300) as i64;
                let end_ts = end.unwrap_or(now).timestamp();
                (end_ts - count * step_secs).to_string()
            };

            let granularity_str = granularity.to_string();

            match http
                .get_candles(&product_id, &start_secs, &end_secs, &granularity_str)
                .await
            {
                Ok(json) => {
                    let candles_response: CandlesResponse = match serde_json::from_value(json) {
                        Ok(r) => r,
                        Err(e) => {
                            log::error!("Failed to parse candles response: {e}");
                            return;
                        }
                    };

                    let ts_init = clock.get_time_ns();
                    let mut bars: Vec<_> = candles_response
                        .candles
                        .iter()
                        .filter_map(|candle| {
                            parse_bar(candle, bar_type, price_precision, size_precision, ts_init)
                                .map_err(|e| log::warn!("Failed to parse bar: {e}"))
                                .ok()
                        })
                        .collect();

                    bars.sort_by_key(|b| b.ts_event);

                    if let Some(limit) = limit
                        && bars.len() > limit
                    {
                        bars.drain(..bars.len() - limit);
                    }

                    let response = DataResponse::Bars(BarsResponse::new(
                        request_id,
                        client_id,
                        bar_type,
                        bars,
                        start_nanos,
                        end_nanos,
                        clock.get_time_ns(),
                        params,
                    ));

                    if let Err(e) = sender.send(DataEvent::Response(response)) {
                        log::error!("Failed to send bars response: {e}");
                    }
                }
                Err(e) => log::error!("Bar request failed: {e:?}"),
            }
        });

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use nautilus_common::{
        live::runner::set_data_event_sender, messages::data::SubscribeMarkPrices,
    };
    use nautilus_core::{UUID4, UnixNanos};
    use nautilus_model::identifiers::InstrumentId;
    use rstest::rstest;

    use super::*;
    use crate::common::consts::COINBASE_CLIENT_ID;

    // Coinbase Advanced Trade does not publish live mark prices for its
    // perpetuals, so `subscribe_mark_prices` must return an explicit error
    // naming the instrument and mentioning mark prices. A regression that
    // silently `Ok(())`s the call would mask the unsupported feature.
    #[rstest]
    #[tokio::test]
    async fn test_subscribe_mark_prices_rejects_with_explicit_error() {
        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
        set_data_event_sender(tx);

        let config = CoinbaseDataClientConfig::default();
        let mut client =
            CoinbaseDataClient::new(*COINBASE_CLIENT_ID, config).expect("client construction");

        let instrument_id = InstrumentId::from("BIP-20DEC30-CDE.COINBASE");
        let cmd = SubscribeMarkPrices::new(
            instrument_id,
            Some(*COINBASE_CLIENT_ID),
            None,
            UUID4::new(),
            UnixNanos::default(),
            None,
            None,
        );

        let err = client
            .subscribe_mark_prices(cmd)
            .expect_err("must reject mark-price subscriptions");
        let msg = err.to_string();
        assert!(
            msg.contains("mark prices"),
            "error must mention mark prices, was: {msg}"
        );
        assert!(
            msg.contains("BIP-20DEC30-CDE.COINBASE"),
            "error must name the instrument, was: {msg}"
        );
    }

    fn make_status_event(instrument_id: InstrumentId) -> NautilusWsMessage {
        use nautilus_model::{data::InstrumentStatus, enums::MarketStatusAction};

        let status = InstrumentStatus::new(
            instrument_id,
            MarketStatusAction::Trading,
            UnixNanos::from(1),
            UnixNanos::from(2),
            None,
            None,
            Some(true),
            None,
            None,
        );
        NautilusWsMessage::InstrumentStatus(Box::new(status))
    }

    // The dispatch filter is what keeps the venue-wide `status` feed from
    // leaking every product's events to a subscriber that only cares about
    // one. A regression that drops the `subs.contains(...)` guard would let
    // every product's status reach `data_sender`.
    #[rstest]
    fn test_dispatch_ws_message_status_filter_forwards_subscribed() {
        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<DataEvent>();
        let instrument_id = InstrumentId::from("BTC-USD.COINBASE");
        let mut set = AHashSet::new();
        set.insert(instrument_id);
        let subs = Arc::new(Mutex::new(set));

        dispatch_ws_message(make_status_event(instrument_id), &tx, &subs);

        match rx.try_recv() {
            Ok(DataEvent::InstrumentStatus(status)) => {
                assert_eq!(status.instrument_id, instrument_id);
            }
            other => panic!("expected DataEvent::InstrumentStatus, was {other:?}"),
        }
    }

    #[rstest]
    fn test_dispatch_ws_message_status_filter_drops_unsubscribed() {
        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<DataEvent>();
        let subscribed = InstrumentId::from("BTC-USD.COINBASE");
        let unsubscribed = InstrumentId::from("ETH-USD.COINBASE");
        let mut set = AHashSet::new();
        set.insert(subscribed);
        let subs = Arc::new(Mutex::new(set));

        dispatch_ws_message(make_status_event(unsubscribed), &tx, &subs);

        assert!(
            rx.try_recv().is_err(),
            "unsubscribed status must be dropped"
        );
    }

    // First subscribe on an empty set must populate `instrument_status_subs`;
    // a second subscribe for the same instrument must not add a duplicate or
    // re-spawn the channel-level WS subscribe. Reset must clear the field.
    #[rstest]
    #[tokio::test]
    async fn test_subscribe_instrument_status_records_and_idempotent() {
        use nautilus_common::messages::data::SubscribeInstrumentStatus;

        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
        set_data_event_sender(tx);

        let config = CoinbaseDataClientConfig::default();
        let mut client =
            CoinbaseDataClient::new(*COINBASE_CLIENT_ID, config).expect("client construction");

        let instrument_id = InstrumentId::from("BTC-USD.COINBASE");
        let cmd = SubscribeInstrumentStatus::new(
            instrument_id,
            Some(*COINBASE_CLIENT_ID),
            None,
            UUID4::new(),
            UnixNanos::default(),
            None,
            None,
        );

        client.subscribe_instrument_status(cmd.clone()).unwrap();
        assert!(
            client
                .instrument_status_subs
                .lock()
                .unwrap()
                .contains(&instrument_id)
        );

        // Duplicate subscribe keeps the set at size 1.
        client.subscribe_instrument_status(cmd).unwrap();
        assert_eq!(client.instrument_status_subs.lock().unwrap().len(), 1);

        // Reset clears the set so a subsequent connect starts clean.
        client.reset().unwrap();
        assert!(client.instrument_status_subs.lock().unwrap().is_empty());
    }

    // Unsubscribing the last instrument empties the set; intermediate
    // unsubscribes leave other entries in place.
    #[rstest]
    #[tokio::test]
    async fn test_unsubscribe_instrument_status_emptying_set() {
        use nautilus_common::messages::data::{
            SubscribeInstrumentStatus, UnsubscribeInstrumentStatus,
        };

        let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
        set_data_event_sender(tx);

        let mut client =
            CoinbaseDataClient::new(*COINBASE_CLIENT_ID, CoinbaseDataClientConfig::default())
                .expect("client construction");

        let a = InstrumentId::from("BTC-USD.COINBASE");
        let b = InstrumentId::from("ETH-USD.COINBASE");

        for id in [a, b] {
            client
                .subscribe_instrument_status(SubscribeInstrumentStatus::new(
                    id,
                    Some(*COINBASE_CLIENT_ID),
                    None,
                    UUID4::new(),
                    UnixNanos::default(),
                    None,
                    None,
                ))
                .unwrap();
        }
        assert_eq!(client.instrument_status_subs.lock().unwrap().len(), 2);

        let unsub = |id| {
            UnsubscribeInstrumentStatus::new(
                id,
                Some(*COINBASE_CLIENT_ID),
                None,
                UUID4::new(),
                UnixNanos::default(),
                None,
                None,
            )
        };

        // Intermediate unsubscribe: `a` leaves, `b` retained.
        client.unsubscribe_instrument_status(&unsub(a)).unwrap();
        {
            let subs = client.instrument_status_subs.lock().unwrap();
            assert!(!subs.contains(&a), "a removed");
            assert!(subs.contains(&b), "b retained");
            assert_eq!(subs.len(), 1);
        }

        // Last unsubscribe: set must end up empty so a future first-subscribe
        // re-arms the channel-level WS subscription.
        client.unsubscribe_instrument_status(&unsub(b)).unwrap();
        assert!(
            client.instrument_status_subs.lock().unwrap().is_empty(),
            "last unsubscribe must empty the set",
        );
    }
}