Skip to main content

nautilus_coinbase/websocket/
handler.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//! Feed handler for parsing Coinbase WebSocket messages into Nautilus types.
17
18use std::{fmt::Debug, sync::Arc};
19
20use ahash::AHashMap;
21use nautilus_core::{
22    AtomicMap, UnixNanos,
23    string::secret::SecretString,
24    time::{AtomicTime, get_atomic_clock_realtime},
25};
26use nautilus_model::{
27    data::{Bar, BarType, InstrumentStatus, OrderBookDeltas, QuoteTick, TradeTick},
28    identifiers::{AccountId, InstrumentId, Symbol},
29    instruments::{Instrument, InstrumentAny},
30    reports::OrderStatusReport,
31};
32use nautilus_network::{RECONNECTED, websocket::WebSocketClient};
33use tokio_tungstenite::tungstenite::Message;
34use ustr::Ustr;
35
36use crate::{
37    common::consts::COINBASE_VENUE,
38    websocket::{
39        client::COINBASE_WS_SUBSCRIPTION_KEYS,
40        messages::{CoinbaseWsMessage, WsEventType, WsOrderUpdate},
41        parse::{
42            parse_ws_candle, parse_ws_l2_snapshot, parse_ws_l2_update, parse_ws_status_product,
43            parse_ws_ticker, parse_ws_trade, parse_ws_user_event_to_order_status_report,
44        },
45    },
46};
47
48fn instrument_id_from_product(product_id: &Ustr) -> InstrumentId {
49    InstrumentId::new(Symbol::new(*product_id), *COINBASE_VENUE)
50}
51
52fn resolve_instrument_id_from_aliases(
53    aliases: &AHashMap<Ustr, Ustr>,
54    product_id: &Ustr,
55) -> InstrumentId {
56    let resolved = aliases.get(product_id).copied().unwrap_or(*product_id);
57    instrument_id_from_product(&resolved)
58}
59
60/// Commands sent from [`super::client::CoinbaseWebSocketClient`] to the feed handler.
61pub enum HandlerCommand {
62    /// Provides the network-level WebSocket client.
63    SetClient(WebSocketClient),
64    /// Subscribes with a serialized payload that is zeroized on drop.
65    Subscribe {
66        channel: crate::common::enums::CoinbaseWsChannel,
67        product_ids: Vec<Ustr>,
68        payload: SecretString,
69    },
70    /// Unsubscribes with a serialized payload that is zeroized on drop.
71    Unsubscribe {
72        channel: crate::common::enums::CoinbaseWsChannel,
73        product_ids: Vec<Ustr>,
74        payload: SecretString,
75    },
76    /// Disconnects the WebSocket.
77    Disconnect,
78    /// Caches instruments for precision lookups during parsing.
79    InitializeInstruments(Vec<InstrumentAny>),
80    /// Updates a single instrument in the cache.
81    UpdateInstrument(Box<InstrumentAny>),
82    /// Registers a bar type for candle parsing.
83    AddBarType { key: String, bar_type: BarType },
84    /// Removes a bar type registration.
85    RemoveBarType { key: String },
86    /// Sets the account ID used when emitting user-channel execution reports.
87    SetAccountId(AccountId),
88}
89
90impl Debug for HandlerCommand {
91    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
92        match self {
93            Self::SetClient(_) => f.write_str("SetClient"),
94            Self::Subscribe { channel, .. } => write!(f, "Subscribe({channel:?})"),
95            Self::Unsubscribe { channel, .. } => write!(f, "Unsubscribe({channel:?})"),
96            Self::Disconnect => f.write_str("Disconnect"),
97            Self::InitializeInstruments(v) => write!(f, "InitializeInstruments({})", v.len()),
98            Self::UpdateInstrument(i) => write!(f, "UpdateInstrument({})", i.id()),
99            Self::AddBarType { key, .. } => write!(f, "AddBarType({key})"),
100            Self::RemoveBarType { key } => write!(f, "RemoveBarType({key})"),
101            Self::SetAccountId(id) => write!(f, "SetAccountId({id})"),
102        }
103    }
104}
105
106/// Carrier for a single user-channel order update.
107///
108/// Pairs the parsed [`OrderStatusReport`] with the resolved instrument and raw venue payload.
109/// The execution client uses REST fill history for authoritative trade identities and values.
110///
111/// `is_snapshot` identifies a snapshot of open orders, including snapshots after reconnect.
112/// Snapshots restate cumulative quantities rather than fresh executions. The execution client
113/// suppresses unfilled snapshot reports without order context.
114#[derive(Debug, Clone)]
115pub struct UserOrderUpdate {
116    pub report: Box<OrderStatusReport>,
117    pub update: Box<WsOrderUpdate>,
118    pub instrument: InstrumentAny,
119    pub is_snapshot: bool,
120    pub ts_event: UnixNanos,
121    pub ts_init: UnixNanos,
122}
123
124/// Nautilus-typed messages produced by the feed handler.
125#[derive(Debug, Clone)]
126pub enum NautilusWsMessage {
127    /// Trade tick from market_trades channel.
128    Trade(TradeTick),
129    /// Quote tick from ticker channel.
130    Quote(QuoteTick),
131    /// Order book deltas from l2_data channel.
132    Deltas(OrderBookDeltas),
133    /// Bar from candles channel.
134    Bar(Bar),
135    /// Order status update from the user channel.
136    UserOrder(Box<UserOrderUpdate>),
137    /// Futures balance summary snapshot from the
138    /// `futures_balance_summary` channel.
139    FuturesBalanceSummary(Box<crate::websocket::messages::WsFcmBalanceSummary>),
140    /// Instrument status update from the `status` channel. Emitted for every
141    /// product the venue reports; the data client filters by subscription.
142    InstrumentStatus(Box<InstrumentStatus>),
143    /// The connection was re-established after a drop.
144    Reconnected,
145    /// An error occurred during message processing.
146    Error(String),
147}
148
149/// Processes raw WebSocket messages into Nautilus domain types.
150#[derive(Debug)]
151pub struct FeedHandler {
152    clock: &'static AtomicTime,
153    signal: Arc<std::sync::atomic::AtomicBool>,
154    client: Option<WebSocketClient>,
155    cmd_rx: tokio::sync::mpsc::UnboundedReceiver<HandlerCommand>,
156    raw_rx: tokio::sync::mpsc::UnboundedReceiver<Message>,
157    instruments: AHashMap<InstrumentId, InstrumentAny>,
158    /// Shared with [`super::client::CoinbaseWebSocketClient`]; consulted in
159    /// `resolve_instrument_id_from_aliases` to re-key inbound messages whose wire
160    /// `product_id` is the canonical alias of a subscribed/submitted product.
161    subscription_aliases: Arc<AtomicMap<Ustr, Ustr>>,
162    bar_types: AHashMap<String, BarType>,
163    account_id: Option<AccountId>,
164    buffer: Vec<NautilusWsMessage>,
165    last_heartbeat_counter: Option<u64>,
166}
167
168impl FeedHandler {
169    /// Creates a new [`FeedHandler`] instance.
170    pub fn new(
171        signal: Arc<std::sync::atomic::AtomicBool>,
172        cmd_rx: tokio::sync::mpsc::UnboundedReceiver<HandlerCommand>,
173        raw_rx: tokio::sync::mpsc::UnboundedReceiver<Message>,
174        subscription_aliases: Arc<AtomicMap<Ustr, Ustr>>,
175    ) -> Self {
176        Self {
177            clock: get_atomic_clock_realtime(),
178            signal,
179            client: None,
180            cmd_rx,
181            raw_rx,
182            instruments: AHashMap::new(),
183            subscription_aliases,
184            bar_types: AHashMap::new(),
185            account_id: None,
186            buffer: Vec::new(),
187            last_heartbeat_counter: None,
188        }
189    }
190
191    /// Sets the account ID used to stamp user-channel execution reports.
192    pub fn set_account_id(&mut self, account_id: AccountId) {
193        self.account_id = Some(account_id);
194    }
195
196    /// Polls for the next output message, processing commands and raw messages.
197    ///
198    /// Returns `None` when the handler should shut down.
199    pub async fn next(&mut self) -> Option<NautilusWsMessage> {
200        // Check signal before draining buffer so disconnect takes
201        // priority over pending buffered messages
202        if self.signal.load(std::sync::atomic::Ordering::Acquire) {
203            self.buffer.clear();
204            return None;
205        }
206
207        if let Some(msg) = self.buffer.pop() {
208            return Some(msg);
209        }
210
211        loop {
212            if self.signal.load(std::sync::atomic::Ordering::Acquire) {
213                return None;
214            }
215
216            tokio::select! {
217                Some(cmd) = self.cmd_rx.recv() => {
218                    match cmd {
219                        HandlerCommand::SetClient(client) => {
220                            self.client = Some(client);
221                        }
222                        HandlerCommand::Subscribe { payload, .. }
223                        | HandlerCommand::Unsubscribe { payload, .. } => {
224                            self.send_subscription(&payload).await;
225                        }
226                        HandlerCommand::Disconnect => {
227                            if let Some(client) = self.client.take() {
228                                // Transition to CLOSED immediately without waiting
229                                // for ACTIVE (avoids blocking during reconnect)
230                                client.notify_closed();
231                            }
232                            return None;
233                        }
234                        HandlerCommand::InitializeInstruments(instruments) => {
235                            for inst in instruments {
236                                self.instruments.insert(inst.id(), inst);
237                            }
238                        }
239                        HandlerCommand::UpdateInstrument(inst) => {
240                            self.instruments.insert(inst.id(), *inst);
241                        }
242                        HandlerCommand::AddBarType { key, bar_type } => {
243                            self.bar_types.insert(key, bar_type);
244                        }
245                        HandlerCommand::RemoveBarType { key } => {
246                            self.bar_types.remove(&key);
247                        }
248                        HandlerCommand::SetAccountId(account_id) => {
249                            self.account_id = Some(account_id);
250                        }
251                    }
252                }
253                Some(raw) = self.raw_rx.recv() => {
254                    match raw {
255                        Message::Text(text) => {
256                            if let Some(msg) = self.handle_text(&text) {
257                                return Some(msg);
258                            }
259                        }
260                        Message::Ping(data) => {
261                            if let Some(client) = &self.client
262                                && let Err(e) = client.send_pong(data.to_vec()).await
263                            {
264                                log::warn!("Failed to send pong: {e}");
265                            }
266                        }
267                        Message::Close(_) => return None,
268                        _ => {}
269                    }
270                }
271                else => return None,
272            }
273        }
274    }
275
276    async fn send_subscription(&self, payload: &SecretString) {
277        let Some(client) = &self.client else {
278            log::warn!("Cannot send subscription, no WebSocket client set");
279            return;
280        };
281
282        if let Err(e) = client
283            .send_text(
284                payload.expose_secret().to_owned(),
285                Some(COINBASE_WS_SUBSCRIPTION_KEYS.as_slice()),
286            )
287            .await
288        {
289            log::error!("Failed to send subscription: {e}");
290        }
291    }
292
293    fn handle_text(&mut self, text: &str) -> Option<NautilusWsMessage> {
294        if text == RECONNECTED {
295            self.last_heartbeat_counter = None;
296            return Some(NautilusWsMessage::Reconnected);
297        }
298
299        let ts_init = self.clock.get_time_ns();
300
301        let msg: CoinbaseWsMessage = match serde_json::from_str(text) {
302            Ok(m) => m,
303            Err(e) => {
304                log::warn!("Failed to parse WS message: {e}");
305                return None;
306            }
307        };
308
309        match msg {
310            CoinbaseWsMessage::L2Data {
311                timestamp, events, ..
312            } => self.handle_l2_events(&events, &timestamp, ts_init),
313            CoinbaseWsMessage::MarketTrades { events, .. } => {
314                self.handle_market_trades(&events, ts_init)
315            }
316            CoinbaseWsMessage::Ticker {
317                timestamp, events, ..
318            }
319            | CoinbaseWsMessage::TickerBatch {
320                timestamp, events, ..
321            } => self.handle_ticker(&events, &timestamp, ts_init),
322            CoinbaseWsMessage::Candles { events, .. } => self.handle_candles(&events, ts_init),
323            CoinbaseWsMessage::Heartbeats { events, .. } => {
324                for event in events {
325                    if let Some((expected, actual)) =
326                        self.note_heartbeat_counter(event.heartbeat_counter)
327                    {
328                        log::warn!("Heartbeat counter gap: expected {expected}, was {actual}");
329                    }
330                }
331                None
332            }
333            CoinbaseWsMessage::Subscriptions { events, .. } => {
334                // Coinbase emits this after every subscribe and unsubscribe
335                // with the full current subscription set, so it's noisy at
336                // INFO and not strictly a "confirmation" of the latest action.
337                log::debug!("Subscription state: {events:?}");
338                None
339            }
340            CoinbaseWsMessage::User {
341                timestamp, events, ..
342            } => self.handle_user_events(&events, &timestamp, ts_init),
343            CoinbaseWsMessage::FuturesBalanceSummary { events, .. } => {
344                self.handle_futures_balance_summary(events)
345            }
346            CoinbaseWsMessage::Status {
347                timestamp, events, ..
348            } => self.handle_status_events(&events, &timestamp, ts_init),
349        }
350    }
351
352    fn note_heartbeat_counter(&mut self, counter: u64) -> Option<(u64, u64)> {
353        let gap = self.last_heartbeat_counter.and_then(|last| {
354            let expected = last.saturating_add(1);
355            (counter != expected).then_some((expected, counter))
356        });
357        self.last_heartbeat_counter = Some(counter);
358        gap
359    }
360
361    fn handle_l2_events(
362        &mut self,
363        events: &[crate::websocket::messages::WsL2DataEvent],
364        timestamp: &str,
365        ts_init: UnixNanos,
366    ) -> Option<NautilusWsMessage> {
367        let ts_event = match crate::http::parse::parse_rfc3339_timestamp(timestamp) {
368            Ok(ts) => ts,
369            Err(e) => {
370                log::warn!("Failed to parse L2 message timestamp {timestamp}: {e}");
371                ts_init
372            }
373        };
374
375        let mut first: Option<NautilusWsMessage> = None;
376        let aliases = self.subscription_aliases.load();
377
378        for event in events {
379            let instrument_id = resolve_instrument_id_from_aliases(&aliases, &event.product_id);
380
381            let instrument = match self.instruments.get(&instrument_id) {
382                Some(inst) => inst,
383                None => {
384                    log::warn!("No instrument cached for {instrument_id}");
385                    continue;
386                }
387            };
388
389            let result = match event.event_type {
390                WsEventType::Snapshot => parse_ws_l2_snapshot(event, instrument, ts_event, ts_init),
391                WsEventType::Update => parse_ws_l2_update(event, instrument, ts_event, ts_init),
392            };
393
394            match result {
395                Ok(deltas) => {
396                    let msg = NautilusWsMessage::Deltas(deltas);
397
398                    if first.is_none() {
399                        first = Some(msg);
400                    } else {
401                        self.buffer.push(msg);
402                    }
403                }
404                Err(e) => log::warn!("Failed to parse L2 event: {e}"),
405            }
406        }
407
408        if first.is_some() {
409            self.buffer.reverse();
410        }
411        first
412    }
413
414    fn handle_market_trades(
415        &mut self,
416        events: &[crate::websocket::messages::WsMarketTradesEvent],
417        ts_init: UnixNanos,
418    ) -> Option<NautilusWsMessage> {
419        let aliases = self.subscription_aliases.load();
420
421        for event in events {
422            for trade in &event.trades {
423                let instrument_id = resolve_instrument_id_from_aliases(&aliases, &trade.product_id);
424
425                let instrument = match self.instruments.get(&instrument_id) {
426                    Some(inst) => inst,
427                    None => {
428                        log::warn!("No instrument cached for {instrument_id}");
429                        continue;
430                    }
431                };
432
433                match parse_ws_trade(trade, instrument, ts_init) {
434                    Ok(tick) => {
435                        self.buffer_remaining_trades(events, event, trade, ts_init);
436                        // Reverse so pop() drains in exchange order
437                        self.buffer.reverse();
438                        return Some(NautilusWsMessage::Trade(tick));
439                    }
440                    Err(e) => log::warn!("Failed to parse trade: {e}"),
441                }
442            }
443        }
444        None
445    }
446
447    fn buffer_remaining_trades(
448        &mut self,
449        events: &[crate::websocket::messages::WsMarketTradesEvent],
450        current_event: &crate::websocket::messages::WsMarketTradesEvent,
451        current_trade: &crate::websocket::messages::WsTrade,
452        ts_init: UnixNanos,
453    ) {
454        let mut found_current = false;
455        let aliases = self.subscription_aliases.load();
456
457        for event in events {
458            let is_current_event = std::ptr::eq(event, current_event);
459
460            for trade in &event.trades {
461                if !found_current {
462                    if is_current_event && std::ptr::eq(trade, current_trade) {
463                        found_current = true;
464                    }
465                    continue;
466                }
467
468                let instrument_id = resolve_instrument_id_from_aliases(&aliases, &trade.product_id);
469
470                if let Some(instrument) = self.instruments.get(&instrument_id)
471                    && let Ok(tick) = parse_ws_trade(trade, instrument, ts_init)
472                {
473                    self.buffer.push(NautilusWsMessage::Trade(tick));
474                }
475            }
476        }
477    }
478
479    fn handle_ticker(
480        &mut self,
481        events: &[crate::websocket::messages::WsTickerEvent],
482        timestamp: &str,
483        ts_init: UnixNanos,
484    ) -> Option<NautilusWsMessage> {
485        let ts_event = crate::http::parse::parse_rfc3339_timestamp(timestamp).unwrap_or(ts_init);
486
487        let mut first: Option<NautilusWsMessage> = None;
488        let aliases = self.subscription_aliases.load();
489
490        for event in events {
491            for ticker in &event.tickers {
492                let instrument_id =
493                    resolve_instrument_id_from_aliases(&aliases, &ticker.product_id);
494
495                let instrument = match self.instruments.get(&instrument_id) {
496                    Some(inst) => inst,
497                    None => {
498                        log::warn!("No instrument cached for {instrument_id}");
499                        continue;
500                    }
501                };
502
503                match parse_ws_ticker(ticker, instrument, ts_event, ts_init) {
504                    Ok(quote) => {
505                        let msg = NautilusWsMessage::Quote(quote);
506
507                        if first.is_none() {
508                            first = Some(msg);
509                        } else {
510                            self.buffer.push(msg);
511                        }
512                    }
513                    Err(e) => log::warn!("Failed to parse ticker: {e}"),
514                }
515            }
516        }
517
518        if first.is_some() {
519            self.buffer.reverse();
520        }
521        first
522    }
523
524    fn handle_user_events(
525        &mut self,
526        events: &[crate::websocket::messages::WsUserEvent],
527        timestamp: &str,
528        ts_init: UnixNanos,
529    ) -> Option<NautilusWsMessage> {
530        let Some(account_id) = self.account_id else {
531            log::debug!(
532                "Dropping user event: account_id not set (call SetAccountId after connect)"
533            );
534            return None;
535        };
536
537        let ts_event = match crate::http::parse::parse_rfc3339_timestamp(timestamp) {
538            Ok(ts) => ts,
539            Err(e) => {
540                log::warn!("Failed to parse user message timestamp {timestamp}: {e}");
541                ts_init
542            }
543        };
544
545        let mut first: Option<NautilusWsMessage> = None;
546        let aliases = self.subscription_aliases.load();
547
548        for event in events {
549            let is_snapshot = matches!(event.event_type, WsEventType::Snapshot);
550
551            for order in &event.orders {
552                let instrument_id = resolve_instrument_id_from_aliases(&aliases, &order.product_id);
553                let instrument = match self.instruments.get(&instrument_id).cloned() {
554                    Some(inst) => inst,
555                    None => {
556                        log::warn!("No instrument cached for {instrument_id}");
557                        continue;
558                    }
559                };
560
561                self.emit_user_event_messages(
562                    order,
563                    &instrument,
564                    account_id,
565                    is_snapshot,
566                    ts_event,
567                    ts_init,
568                    &mut first,
569                );
570            }
571        }
572
573        if first.is_some() {
574            self.buffer.reverse();
575        }
576        first
577    }
578
579    #[allow(clippy::too_many_arguments)]
580    fn emit_user_event_messages(
581        &mut self,
582        order: &WsOrderUpdate,
583        instrument: &InstrumentAny,
584        account_id: AccountId,
585        is_snapshot: bool,
586        ts_event: UnixNanos,
587        ts_init: UnixNanos,
588        first: &mut Option<NautilusWsMessage>,
589    ) {
590        let report = match parse_ws_user_event_to_order_status_report(
591            order, instrument, account_id, ts_event, ts_init,
592        ) {
593            Ok(r) => r,
594            Err(e) => {
595                log::warn!("Failed to parse user order update: {e}");
596                return;
597            }
598        };
599
600        let msg = NautilusWsMessage::UserOrder(Box::new(UserOrderUpdate {
601            report: Box::new(report),
602            update: Box::new(order.clone()),
603            instrument: instrument.clone(),
604            is_snapshot,
605            ts_event,
606            ts_init,
607        }));
608
609        if first.is_none() {
610            *first = Some(msg);
611        } else {
612            self.buffer.push(msg);
613        }
614    }
615
616    fn handle_status_events(
617        &mut self,
618        events: &[crate::websocket::messages::WsStatusEvent],
619        timestamp: &str,
620        ts_init: UnixNanos,
621    ) -> Option<NautilusWsMessage> {
622        let ts_event = crate::http::parse::parse_rfc3339_timestamp(timestamp).unwrap_or(ts_init);
623
624        let mut first: Option<NautilusWsMessage> = None;
625        let aliases = self.subscription_aliases.load();
626
627        for event in events {
628            for product in &event.products {
629                let canonical = product.id;
630                let resolved = resolve_instrument_id_from_aliases(&aliases, &canonical);
631                let Some(status) = parse_ws_status_product(product, resolved, ts_event, ts_init)
632                else {
633                    continue;
634                };
635                let msg = NautilusWsMessage::InstrumentStatus(Box::new(status));
636
637                if first.is_none() {
638                    first = Some(msg);
639                } else {
640                    self.buffer.push(msg);
641                }
642            }
643        }
644
645        if first.is_some() {
646            self.buffer.reverse();
647        }
648        first
649    }
650
651    fn handle_futures_balance_summary(
652        &mut self,
653        events: Vec<crate::websocket::messages::WsFuturesBalanceSummaryEvent>,
654    ) -> Option<NautilusWsMessage> {
655        let mut first: Option<NautilusWsMessage> = None;
656
657        for event in events {
658            let msg = NautilusWsMessage::FuturesBalanceSummary(Box::new(event.fcm_balance_summary));
659
660            if first.is_none() {
661                first = Some(msg);
662            } else {
663                self.buffer.push(msg);
664            }
665        }
666
667        if first.is_some() {
668            self.buffer.reverse();
669        }
670        first
671    }
672
673    fn handle_candles(
674        &mut self,
675        events: &[crate::websocket::messages::WsCandlesEvent],
676        ts_init: UnixNanos,
677    ) -> Option<NautilusWsMessage> {
678        let mut first: Option<NautilusWsMessage> = None;
679        let aliases = self.subscription_aliases.load();
680
681        for event in events {
682            for candle in &event.candles {
683                let key = candle.product_id.as_str();
684
685                let bar_type = match self.bar_types.get(key) {
686                    Some(bt) => *bt,
687                    None => {
688                        log::debug!("No bar type registered for {key}");
689                        continue;
690                    }
691                };
692
693                let instrument_id =
694                    resolve_instrument_id_from_aliases(&aliases, &candle.product_id);
695
696                let instrument = match self.instruments.get(&instrument_id) {
697                    Some(inst) => inst,
698                    None => {
699                        log::warn!("No instrument cached for {instrument_id}");
700                        continue;
701                    }
702                };
703
704                match parse_ws_candle(candle, bar_type, instrument, ts_init) {
705                    Ok(bar) => {
706                        let msg = NautilusWsMessage::Bar(bar);
707
708                        if first.is_none() {
709                            first = Some(msg);
710                        } else {
711                            self.buffer.push(msg);
712                        }
713                    }
714                    Err(e) => log::warn!("Failed to parse candle: {e}"),
715                }
716            }
717        }
718
719        if first.is_some() {
720            self.buffer.reverse();
721        }
722        first
723    }
724}
725
726#[cfg(test)]
727mod tests {
728    use std::sync::{Arc, atomic::AtomicBool};
729
730    use nautilus_model::{
731        identifiers::Symbol,
732        instruments::CurrencyPair,
733        types::{Currency, Price, Quantity},
734    };
735    use rstest::rstest;
736
737    use super::*;
738    use crate::common::{consts::COINBASE_VENUE, testing::load_test_fixture};
739
740    fn test_handler() -> FeedHandler {
741        let (_cmd_tx, cmd_rx) = tokio::sync::mpsc::unbounded_channel();
742        let (_raw_tx, raw_rx) = tokio::sync::mpsc::unbounded_channel();
743        FeedHandler::new(
744            Arc::new(AtomicBool::new(false)),
745            cmd_rx,
746            raw_rx,
747            Arc::new(AtomicMap::new()),
748        )
749    }
750
751    fn btc_usd_instrument() -> InstrumentAny {
752        let instrument_id = InstrumentId::new(Symbol::new("BTC-USD"), *COINBASE_VENUE);
753        InstrumentAny::CurrencyPair(
754            CurrencyPair::builder()
755                .instrument_id(instrument_id)
756                .raw_symbol(Symbol::new("BTC-USD"))
757                .base_currency(Currency::get_or_create_crypto("BTC"))
758                .quote_currency(Currency::get_or_create_crypto("USD"))
759                .price_precision(2)
760                .size_precision(8)
761                .price_increment(Price::from("0.01"))
762                .size_increment(Quantity::from("0.00000001"))
763                .min_quantity(Quantity::from("0.00000001"))
764                .ts_event(UnixNanos::default())
765                .ts_init(UnixNanos::default())
766                .build()
767                .unwrap(),
768        )
769    }
770
771    #[rstest]
772    fn test_handle_text_drops_user_channel_when_account_id_unset() {
773        let json = load_test_fixture("ws_user.json");
774        let mut handler = test_handler();
775
776        // account_id is intentionally left unset; events should be dropped
777        assert!(handler.handle_text(&json).is_none());
778        assert!(handler.buffer.is_empty());
779    }
780
781    #[rstest]
782    fn test_handle_user_event_emits_user_order_update() {
783        use nautilus_model::{
784            enums::{OrderSide, OrderStatus},
785            identifiers::AccountId,
786            types::Quantity,
787        };
788
789        use crate::common::enums::CoinbaseProductType;
790
791        let json = load_test_fixture("ws_user.json");
792        let mut handler = test_handler();
793        handler.set_account_id(AccountId::new("COINBASE-001"));
794        handler
795            .instruments
796            .insert(btc_usd_instrument().id(), btc_usd_instrument());
797
798        let msg = handler
799            .handle_text(&json)
800            .expect("handler should emit a user-channel update");
801
802        match msg {
803            NautilusWsMessage::UserOrder(carrier) => {
804                // Status report fields.
805                assert_eq!(carrier.report.account_id.as_str(), "COINBASE-001");
806                assert_eq!(carrier.report.instrument_id, btc_usd_instrument().id());
807                assert_eq!(
808                    carrier.report.venue_order_id.as_str(),
809                    "a1b2c3d4-e5f6-7890-abcd-ef1234567890"
810                );
811                assert_eq!(
812                    carrier.report.client_order_id.unwrap().as_str(),
813                    "11111-000000-000001"
814                );
815                assert_eq!(carrier.report.order_side, OrderSide::Buy.into());
816                assert_eq!(carrier.report.order_status, OrderStatus::Accepted);
817                assert_eq!(carrier.report.filled_qty, Quantity::from("0.00000000"));
818                assert_eq!(carrier.report.quantity, Quantity::from("0.00100000"));
819
820                // Raw venue update fields.
821                assert_eq!(carrier.update.product_id, "BTC-USD");
822                assert_eq!(carrier.update.product_type, CoinbaseProductType::Spot);
823                assert_eq!(carrier.update.cumulative_quantity, "0");
824                assert_eq!(carrier.update.leaves_quantity, "0.001");
825
826                // Carrier metadata.
827                assert_eq!(carrier.instrument.id(), btc_usd_instrument().id());
828                assert!(carrier.ts_event.as_u64() > 0);
829            }
830            other => panic!("expected UserOrder, was {other:?}"),
831        }
832    }
833
834    #[rstest]
835    fn test_handle_text_emits_instrument_status_from_status_channel() {
836        use nautilus_model::enums::MarketStatusAction;
837
838        let json = r#"{
839          "channel": "status",
840          "client_id": "",
841          "timestamp": "2023-02-09T20:29:49.753424311Z",
842          "sequence_num": 0,
843          "events": [
844            {
845              "type": "snapshot",
846              "products": [
847                {
848                  "product_type": "SPOT",
849                  "id": "BTC-USD",
850                  "base_currency": "BTC",
851                  "quote_currency": "USD",
852                  "base_increment": "0.00000001",
853                  "quote_increment": "0.01",
854                  "display_name": "BTC/USD",
855                  "status": "online",
856                  "status_message": "",
857                  "min_market_funds": "1"
858                },
859                {
860                  "product_type": "SPOT",
861                  "id": "ETH-USD",
862                  "base_currency": "ETH",
863                  "quote_currency": "USD",
864                  "base_increment": "0.00000001",
865                  "quote_increment": "0.01",
866                  "display_name": "ETH/USD",
867                  "status": "offline",
868                  "status_message": "maintenance",
869                  "min_market_funds": "1"
870                }
871              ]
872            }
873          ]
874        }"#;
875        let mut handler = test_handler();
876
877        let first = handler
878            .handle_text(json)
879            .expect("status channel must emit InstrumentStatus");
880        let NautilusWsMessage::InstrumentStatus(status) = first else {
881            panic!("expected InstrumentStatus, was {first:?}");
882        };
883        assert_eq!(status.instrument_id, btc_usd_instrument().id());
884        assert_eq!(status.action, MarketStatusAction::Trading);
885        assert_eq!(status.is_trading, Some(true));
886        assert!(status.reason.is_none());
887
888        // The second product (ETH-USD offline) is buffered behind the BTC one.
889        assert_eq!(handler.buffer.len(), 1);
890        let NautilusWsMessage::InstrumentStatus(status) = handler.buffer.pop().unwrap() else {
891            panic!("expected buffered InstrumentStatus");
892        };
893        assert_eq!(status.action, MarketStatusAction::Halt);
894        assert_eq!(status.is_trading, Some(false));
895        assert_eq!(
896            status.reason.map(|s| s.to_string()),
897            Some("maintenance".to_string())
898        );
899    }
900
901    #[rstest]
902    fn test_handle_l2_update_uses_batch_timestamp_for_all_deltas() {
903        let json = load_test_fixture("ws_l2_data_update.json");
904        let mut handler = test_handler();
905        handler
906            .instruments
907            .insert(btc_usd_instrument().id(), btc_usd_instrument());
908
909        let msg = handler
910            .handle_text(&json)
911            .expect("handler should emit deltas for a valid L2 update");
912
913        let deltas = match msg {
914            NautilusWsMessage::Deltas(d) => d,
915            other => panic!("expected Deltas, was {other:?}"),
916        };
917
918        assert!(!deltas.deltas.is_empty());
919        let expected_ts = deltas.deltas[0].ts_event;
920        for delta in &deltas.deltas {
921            assert_eq!(
922                delta.ts_event, expected_ts,
923                "all deltas in a batch must share ts_event"
924            );
925        }
926    }
927
928    #[rstest]
929    fn test_handle_l2_update_malformed_timestamp_falls_back_to_ts_init() {
930        let json = load_test_fixture("ws_l2_data_update.json")
931            .replace("2026-04-07T14:30:01.456789Z", "not-a-valid-timestamp");
932        let mut handler = test_handler();
933        handler
934            .instruments
935            .insert(btc_usd_instrument().id(), btc_usd_instrument());
936
937        let msg = handler
938            .handle_text(&json)
939            .expect("handler should still emit deltas when timestamp is malformed");
940
941        let deltas = match msg {
942            NautilusWsMessage::Deltas(d) => d,
943            other => panic!("expected Deltas, was {other:?}"),
944        };
945
946        assert!(!deltas.deltas.is_empty());
947        for delta in &deltas.deltas {
948            assert_eq!(
949                delta.ts_event, delta.ts_init,
950                "malformed timestamp must fall back to ts_init"
951            );
952        }
953    }
954
955    #[rstest]
956    fn test_handle_text_emits_futures_balance_summary_snapshot() {
957        use rust_decimal::Decimal;
958
959        let json = r#"{
960          "channel": "futures_balance_summary",
961          "client_id": "",
962          "timestamp": "2023-02-09T20:33:57.609931463Z",
963          "sequence_num": 0,
964          "events": [
965            {
966              "type": "snapshot",
967              "fcm_balance_summary": {
968                "futures_buying_power": "100.00",
969                "total_usd_balance": "200.00",
970                "cbi_usd_balance": "300.00",
971                "cfm_usd_balance": "400.00",
972                "total_open_orders_hold_amount": "500.00",
973                "unrealized_pnl": "600.00",
974                "daily_realized_pnl": "0",
975                "initial_margin": "700.00",
976                "available_margin": "800.00",
977                "liquidation_threshold": "900.00",
978                "liquidation_buffer_amount": "1000.00",
979                "liquidation_buffer_percentage": "1000",
980                "intraday_margin_window_measure": {
981                  "margin_window_type": "FCM_MARGIN_WINDOW_TYPE_INTRADAY",
982                  "margin_level": "MARGIN_LEVEL_TYPE_BASE",
983                  "initial_margin": "100.00",
984                  "maintenance_margin": "200.00",
985                  "liquidation_buffer_percentage": "1000",
986                  "total_hold": "100.00",
987                  "futures_buying_power": "400.00"
988                },
989                "overnight_margin_window_measure": {
990                  "margin_window_type": "FCM_MARGIN_WINDOW_TYPE_OVERNIGHT",
991                  "margin_level": "MARGIN_LEVEL_TYPE_BASE",
992                  "initial_margin": "300.00",
993                  "maintenance_margin": "200.00",
994                  "liquidation_buffer_percentage": "1000",
995                  "total_hold": "-30.00",
996                  "futures_buying_power": "2000.00"
997                }
998              }
999            }
1000          ]
1001        }"#;
1002        let mut handler = test_handler();
1003
1004        let msg = handler
1005            .handle_text(json)
1006            .expect("handler should emit a futures balance summary");
1007        match msg {
1008            NautilusWsMessage::FuturesBalanceSummary(summary) => {
1009                assert_eq!(summary.futures_buying_power, Decimal::from(100));
1010                assert_eq!(summary.total_usd_balance, Decimal::from(200));
1011                assert_eq!(summary.total_open_orders_hold_amount, Decimal::from(500));
1012                assert_eq!(summary.available_margin, Decimal::from(800));
1013                let intraday = &summary.intraday_margin_window_measure;
1014                assert_eq!(intraday.initial_margin, Decimal::from(100));
1015                assert_eq!(intraday.maintenance_margin, Decimal::from(200));
1016                let overnight = &summary.overnight_margin_window_measure;
1017                assert_eq!(overnight.initial_margin, Decimal::from(300));
1018                assert_eq!(overnight.maintenance_margin, Decimal::from(200));
1019                // `total_hold` carries negative values on the wire; ensure
1020                // the signed decimal survives the round trip.
1021                assert_eq!(overnight.total_hold, "-30".parse::<Decimal>().unwrap());
1022            }
1023            other => panic!("expected FuturesBalanceSummary, was {other:?}"),
1024        }
1025    }
1026
1027    #[rstest]
1028    fn test_handle_text_routes_reconnected_sentinel() {
1029        let mut handler = test_handler();
1030        let result = handler.handle_text(RECONNECTED);
1031        assert!(matches!(result, Some(NautilusWsMessage::Reconnected)));
1032    }
1033
1034    #[rstest]
1035    fn test_heartbeat_counter_tracks_sequence_and_detects_gaps() {
1036        let mut handler = test_handler();
1037
1038        assert_eq!(handler.note_heartbeat_counter(42), None);
1039        assert_eq!(handler.last_heartbeat_counter, Some(42));
1040        assert_eq!(handler.note_heartbeat_counter(43), None);
1041        assert_eq!(handler.last_heartbeat_counter, Some(43));
1042        assert_eq!(handler.note_heartbeat_counter(45), Some((44, 45)));
1043        assert_eq!(handler.last_heartbeat_counter, Some(45));
1044        assert_eq!(handler.note_heartbeat_counter(40), Some((46, 40)));
1045        assert_eq!(handler.last_heartbeat_counter, Some(40));
1046    }
1047
1048    #[rstest]
1049    fn test_handle_text_heartbeats_updates_counter_and_reconnect_resets_it() {
1050        let json = load_test_fixture("ws_heartbeats.json");
1051        let mut handler = test_handler();
1052
1053        assert!(handler.handle_text(&json).is_none());
1054        assert_eq!(handler.last_heartbeat_counter, Some(42));
1055
1056        let next = json.replace("\"heartbeat_counter\": 42", "\"heartbeat_counter\": 43");
1057        assert!(handler.handle_text(&next).is_none());
1058        assert_eq!(handler.last_heartbeat_counter, Some(43));
1059
1060        let result = handler.handle_text(RECONNECTED);
1061        assert!(matches!(result, Some(NautilusWsMessage::Reconnected)));
1062        assert_eq!(handler.last_heartbeat_counter, None);
1063    }
1064
1065    #[rstest]
1066    fn test_signal_release_acquire_exits_handler_loop() {
1067        use std::sync::atomic::Ordering;
1068
1069        let signal = Arc::new(AtomicBool::new(false));
1070        let (_cmd_tx, cmd_rx) = tokio::sync::mpsc::unbounded_channel();
1071        let (_raw_tx, raw_rx) = tokio::sync::mpsc::unbounded_channel();
1072        let mut handler =
1073            FeedHandler::new(signal.clone(), cmd_rx, raw_rx, Arc::new(AtomicMap::new()));
1074
1075        signal.store(true, Ordering::Release);
1076
1077        let runtime = tokio::runtime::Builder::new_current_thread()
1078            .enable_all()
1079            .build()
1080            .unwrap();
1081        let result = runtime.block_on(async { handler.next().await });
1082        assert!(result.is_none(), "{result:?}");
1083    }
1084}