Skip to main content

nautilus_architect_ax/
data.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//! Live market data client implementation for the AX Exchange adapter.
17
18use std::{
19    future::Future,
20    sync::{
21        Arc,
22        atomic::{AtomicBool, Ordering},
23    },
24    time::Duration,
25};
26
27use ahash::{AHashMap, AHashSet};
28use anyhow::Context;
29use async_trait::async_trait;
30use futures_util::StreamExt;
31use jiff::{SignedDuration, Timestamp};
32use nautilus_common::{
33    clients::{DataClient, execute_bar_subscriptions, execute_instrument_subscriptions},
34    live::{dst::time::Instant, runner::get_data_event_sender, sender::EventSender},
35    messages::{
36        DataEvent, DataResponse,
37        data::{
38            BarsResponse, BookResponse, FundingRatesResponse, InstrumentResponse,
39            InstrumentsResponse, RequestBars, RequestBookSnapshot, RequestFundingRates,
40            RequestInstrument, RequestInstruments, RequestTrades, SubscribeBars,
41            SubscribeBookDeltas, SubscribeFundingRates, SubscribeIndexPrices, SubscribeInstrument,
42            SubscribeInstrumentClose, SubscribeInstrumentStatus, SubscribeInstruments,
43            SubscribeMarkPrices, SubscribeQuotes, SubscribeTrades, TradesResponse, UnsubscribeBars,
44            UnsubscribeBookDeltas, UnsubscribeFundingRates, UnsubscribeIndexPrices,
45            UnsubscribeInstrument, UnsubscribeInstrumentClose, UnsubscribeInstrumentStatus,
46            UnsubscribeInstruments, UnsubscribeMarkPrices, UnsubscribeQuotes, UnsubscribeTrades,
47        },
48    },
49};
50use nautilus_core::{
51    AtomicMap,
52    datetime::datetime_to_unix_nanos,
53    nanos::UnixNanos,
54    time::{AtomicTime, get_atomic_clock_realtime},
55};
56use nautilus_live::{
57    SocketControl,
58    task::{TaskGroup, TaskGroupGuard, TaskSpawner},
59};
60use nautilus_model::{
61    data::{Data, FundingRateUpdate, InstrumentStatus, MarkPriceUpdate, OrderBookDeltas},
62    enums::{BookType, MarketStatusAction},
63    identifiers::{ClientId, InstrumentId, Venue},
64    instruments::{Instrument, InstrumentAny},
65    types::Price,
66};
67use parking_lot::Mutex;
68use tokio_util::sync::CancellationToken;
69use ustr::Ustr;
70
71use crate::{
72    book::{self, sync::BookSyncTracker},
73    common::{
74        auth::run_auth_token_refresh,
75        consts::{AX_AUTH_TOKEN_TTL_SECS, AX_FUNDING_RATE_LOOKBACK_DAYS, AX_VENUE},
76        credential::Credential,
77        enums::{AxCandleWidth, AxInstrumentState, AxMarketDataLevel},
78        parse::{ax_timestamp_stn_to_unix_nanos, map_bar_spec_to_candle_width},
79    },
80    config::AxDataClientConfig,
81    http::client::AxHttpClient,
82    websocket::{
83        data::{
84            client::{AxMdWebSocketClient, AxWsClientError, SymbolDataTypes},
85            parse::{
86                parse_book_l1_quote, parse_book_l2_deltas, parse_book_l2_quote,
87                parse_book_l3_deltas, parse_book_l3_quote, parse_candle_bar, parse_trade_tick,
88            },
89            subscription::SubscriptionOrder,
90        },
91        messages::{AxDataWsMessage, AxMdCandle, AxMdMessage},
92    },
93};
94
95/// AX Exchange data client for live market data streaming and historical data requests.
96///
97/// This client integrates with the Nautilus DataEngine to provide:
98/// - Real-time market data via WebSocket subscriptions
99/// - Historical data via REST API requests
100/// - Automatic instrument discovery and caching
101/// - Connection lifecycle management
102#[derive(Debug)]
103pub struct AxDataClient {
104    client_id: ClientId,
105    config: AxDataClientConfig,
106    http_client: AxHttpClient,
107    ws_client: AxMdWebSocketClient,
108    is_connected: Arc<AtomicBool>,
109    cancellation_token: CancellationToken,
110    session_tasks: TaskGroup,
111    pending_tasks: TaskGroup,
112    subscription_order: SubscriptionOrder,
113    shutdown_errors: Vec<String>,
114    data_sender: EventSender<DataEvent>,
115    instruments: Arc<AtomicMap<Ustr, InstrumentAny>>,
116    clock: &'static AtomicTime,
117    funding_rate_cancellations: AHashMap<InstrumentId, CancellationToken>,
118    funding_rate_cache: Arc<Mutex<AHashMap<InstrumentId, FundingRateUpdate>>>,
119    book_sync: BookSyncTracker,
120}
121
122impl AxDataClient {
123    /// Creates a new [`AxDataClient`] instance.
124    ///
125    /// # Errors
126    ///
127    /// Returns an error if the data event sender cannot be obtained.
128    pub fn new(
129        client_id: ClientId,
130        config: AxDataClientConfig,
131        http_client: AxHttpClient,
132        ws_client: AxMdWebSocketClient,
133    ) -> anyhow::Result<Self> {
134        config
135            .validate_proxy_url()
136            .context("Invalid AX proxy URL")?;
137
138        let clock = get_atomic_clock_realtime();
139        let data_sender = get_data_event_sender();
140        let ws_client = ws_client.with_socket_control(SocketControl::new(
141            client_id,
142            Some(*AX_VENUE),
143            "architect-ax-data-streams",
144        ));
145
146        // Share instruments cache with HTTP client
147        let instruments = http_client.instruments_cache.clone();
148
149        let session_tasks = TaskGroup::new();
150        let pending_tasks = TaskGroup::new();
151
152        Ok(Self {
153            client_id,
154            config,
155            http_client,
156            ws_client,
157            is_connected: Arc::new(AtomicBool::new(false)),
158            cancellation_token: CancellationToken::new(),
159            session_tasks,
160            pending_tasks,
161            subscription_order: SubscriptionOrder::default(),
162            shutdown_errors: Vec::new(),
163            data_sender,
164            instruments,
165            clock,
166            funding_rate_cancellations: AHashMap::new(),
167            funding_rate_cache: Arc::new(Mutex::new(AHashMap::new())),
168            book_sync: BookSyncTracker::default(),
169        })
170    }
171
172    /// Returns the venue for this data client.
173    #[must_use]
174    pub fn venue(&self) -> Venue {
175        *AX_VENUE
176    }
177
178    fn map_book_type_to_market_data_level(book_type: BookType) -> AxMarketDataLevel {
179        match book_type {
180            BookType::L3_MBO => AxMarketDataLevel::Level3,
181            BookType::L1_MBP | BookType::L2_MBP => AxMarketDataLevel::Level2,
182        }
183    }
184
185    /// Returns a reference to the instruments cache.
186    #[must_use]
187    pub fn instruments(&self) -> &Arc<AtomicMap<Ustr, InstrumentAny>> {
188        &self.instruments
189    }
190
191    /// Spawns a message handler task to forward WebSocket data to the DataEngine.
192    fn spawn_message_handler(&mut self) -> anyhow::Result<()> {
193        let stream = self.ws_client.stream();
194        let data_sender = self.data_sender.clone();
195        let cancellation_token = self.cancellation_token.clone();
196        let is_connected = Arc::clone(&self.is_connected);
197        let instruments = Arc::clone(&self.instruments);
198        let symbol_data_types = self.ws_client.symbol_data_types();
199        let status_invalidations = self.ws_client.status_invalidations();
200        let clock = self.clock;
201        let book_sync = self.book_sync.clone();
202        let ws_client = self.ws_client.clone();
203        let snapshot_timeout = self.book_snapshot_timeout();
204        let book_tasks = self.pending_tasks.spawner()?;
205
206        self.session_tasks.spawn(async move {
207            tokio::pin!(stream);
208
209            let mut book_sequences: AHashMap<Ustr, u64> = AHashMap::new();
210            let mut candle_cache: AHashMap<(Ustr, AxCandleWidth), AxMdCandle> = AHashMap::new();
211            let mut instrument_states: AHashMap<Ustr, AxInstrumentState> = AHashMap::new();
212
213            loop {
214                tokio::select! {
215                    () = cancellation_token.cancelled() => {
216                        log::debug!("Message handler cancelled");
217                        break;
218                    }
219                    msg = stream.next() => {
220                        match msg {
221                            Some(ws_msg) => {
222                                drain_status_invalidations(
223                                    &status_invalidations,
224                                    &mut instrument_states,
225                                );
226
227                                handle_ws_message(
228                                    ws_msg,
229                                    &data_sender,
230                                    &instruments,
231                                    &symbol_data_types,
232                                    &mut book_sequences,
233                                    &mut candle_cache,
234                                    &mut instrument_states,
235                                    clock,
236                                    &book_sync,
237                                    &ws_client,
238                                    snapshot_timeout,
239                                    &book_tasks,
240                                );
241                            }
242                            None => {
243                                log::debug!("WebSocket stream ended");
244                                is_connected.store(false, Ordering::Release);
245                                break;
246                            }
247                        }
248                    }
249                }
250            }
251        })?;
252        Ok(())
253    }
254
255    fn book_snapshot_timeout(&self) -> Duration {
256        Duration::from_secs(self.config.book_snapshot_timeout_secs)
257    }
258
259    fn spawn_instrument_refresh(&self) -> anyhow::Result<()> {
260        let minutes = self.config.update_instruments_interval_mins;
261        if minutes == 0 {
262            return Ok(());
263        }
264
265        let interval = Duration::from_secs(minutes.saturating_mul(60));
266        let cancellation = self.cancellation_token.clone();
267        let http_client = self.http_client.clone();
268        let data_sender = self.data_sender.clone();
269        let client_id = self.client_id;
270
271        self.session_tasks.spawn(async move {
272            loop {
273                let sleep = tokio::time::sleep(interval);
274                tokio::pin!(sleep);
275                tokio::select! {
276                    () = cancellation.cancelled() => {
277                        log::debug!("Instrument refresh task cancelled");
278                        break;
279                    }
280                    () = &mut sleep => {
281                        match http_client.request_instruments().await {
282                            Ok(instruments) => {
283                                http_client.cache_instruments(&instruments);
284                                for inst in &instruments {
285                                    if let Err(e) = data_sender
286                                        .send(DataEvent::Data(inst.clone().into()))
287                                    {
288                                        log::warn!("Failed to send refreshed instrument: {e}");
289                                    }
290                                }
291                                log::debug!(
292                                    "Instruments refreshed: client_id={client_id}, count={}",
293                                    instruments.len(),
294                                );
295                            }
296                            Err(e) => {
297                                log::warn!("Failed to refresh instruments: client_id={client_id}, error={e:?}");
298                            }
299                        }
300                    }
301                }
302            }
303        })?;
304        Ok(())
305    }
306
307    #[expect(
308        clippy::unnecessary_wraps,
309        reason = "callers forward Result to trait methods"
310    )]
311    fn ws_symbol_op<F, Fut>(
312        &mut self,
313        instrument_id: InstrumentId,
314        op: F,
315        context: &'static str,
316    ) -> anyhow::Result<()>
317    where
318        F: FnOnce(AxMdWebSocketClient, String) -> Fut + Send + 'static,
319        Fut: Future<Output = Result<(), AxWsClientError>> + Send,
320    {
321        let symbol = instrument_id.symbol.to_string();
322        log::debug!("{context} for {symbol}");
323
324        let ws = self.ws_client.clone();
325        self.spawn_ws(
326            async move { op(ws, symbol).await.map_err(|e| anyhow::anyhow!(e)) },
327            context,
328        );
329
330        Ok(())
331    }
332
333    // Runs each subscription change after the earlier ones, so the venue sees command order
334    fn spawn_ws<F>(&mut self, fut: F, context: &'static str)
335    where
336        F: Future<Output = anyhow::Result<()>> + Send + 'static,
337    {
338        let mut turn = self.subscription_order.next();
339
340        let future = async move {
341            turn.wait().await;
342
343            if let Err(e) = fut.await {
344                log::error!("{context}: {e:?}");
345            }
346        };
347
348        if let Err(e) = self.pending_tasks.spawn(future) {
349            log::warn!("Skipping AX {context} after shutdown began: {e}");
350        }
351    }
352
353    fn spawn_task<F>(&self, fut: F)
354    where
355        F: Future<Output = ()> + Send + 'static,
356    {
357        if let Err(e) = self.pending_tasks.spawn(fut) {
358            log::warn!("Skipping AX data task after shutdown began: {e}");
359        }
360    }
361
362    fn abort_pending_tasks(&self) {
363        self.pending_tasks.begin_shutdown();
364    }
365
366    fn abort_all_tasks(&self) {
367        self.cancellation_token.cancel();
368        self.session_tasks.begin_shutdown();
369        self.abort_pending_tasks();
370        self.ws_client.begin_shutdown();
371
372        for cancellation in self.funding_rate_cancellations.values() {
373            cancellation.cancel();
374        }
375    }
376
377    async fn finish_all_tasks(&mut self) -> anyhow::Result<()> {
378        self.pending_tasks.begin_shutdown();
379        self.session_tasks.begin_shutdown();
380        let (pending_result, session_result) = tokio::join!(
381            self.pending_tasks
382                .finish_shutdown(Duration::from_secs(1), Duration::from_secs(2)),
383            self.session_tasks
384                .finish_shutdown(Duration::from_secs(1), Duration::from_secs(2)),
385        );
386        self.funding_rate_cancellations.clear();
387
388        pending_result.map_err(|e| anyhow::anyhow!("Failed to terminate AX data tasks: {e}"))?;
389        session_result
390            .map_err(|e| anyhow::anyhow!("Failed to terminate AX data session tasks: {e}"))?;
391        Ok(())
392    }
393
394    async fn teardown_partial_connect(&mut self) -> anyhow::Result<()> {
395        self.abort_all_tasks();
396
397        if let Err(e) = self.ws_client.close().await {
398            self.shutdown_errors.push(e.to_string());
399        }
400
401        if let Err(e) = self.finish_all_tasks().await {
402            self.shutdown_errors.push(e.to_string());
403        }
404        self.is_connected.store(false, Ordering::Release);
405
406        if !self.shutdown_errors.is_empty() {
407            anyhow::bail!(std::mem::take(&mut self.shutdown_errors).join("; "));
408        }
409        Ok(())
410    }
411}
412
413#[async_trait(?Send)]
414impl DataClient for AxDataClient {
415    fn client_id(&self) -> ClientId {
416        self.client_id
417    }
418
419    fn venue(&self) -> Option<Venue> {
420        Some(*AX_VENUE)
421    }
422
423    fn start(&mut self) -> anyhow::Result<()> {
424        log::debug!("Starting {}", self.client_id);
425        Ok(())
426    }
427
428    fn stop(&mut self) -> anyhow::Result<()> {
429        log::debug!("Stopping {}", self.client_id);
430
431        self.abort_all_tasks();
432        self.is_connected.store(false, Ordering::Release);
433        Ok(())
434    }
435
436    fn reset(&mut self) -> anyhow::Result<()> {
437        log::debug!("Resetting {}", self.client_id);
438
439        self.abort_all_tasks();
440        self.is_connected.store(false, Ordering::Release);
441        self.funding_rate_cache.lock().clear();
442        Ok(())
443    }
444
445    fn dispose(&mut self) -> anyhow::Result<()> {
446        log::debug!("Disposing {}", self.client_id);
447
448        self.abort_all_tasks();
449        self.is_connected.store(false, Ordering::Release);
450        Ok(())
451    }
452
453    fn is_connected(&self) -> bool {
454        self.is_connected.load(Ordering::Acquire)
455    }
456
457    fn is_disconnected(&self) -> bool {
458        !self.is_connected()
459    }
460
461    async fn connect(&mut self) -> anyhow::Result<()> {
462        if self.is_connected()
463            && !self.cancellation_token.is_cancelled()
464            && self.pending_tasks.is_open()
465            && self.session_tasks.is_open()
466        {
467            log::debug!("Already connected {}", self.client_id);
468            return Ok(());
469        }
470
471        log::info!("Connecting {}", self.client_id);
472
473        if self.cancellation_token.is_cancelled()
474            || !self.pending_tasks.is_open()
475            || !self.session_tasks.is_open()
476            || !self.funding_rate_cancellations.is_empty()
477        {
478            self.teardown_partial_connect().await?;
479            self.session_tasks
480                .start_generation()
481                .map_err(|e| anyhow::anyhow!("Failed to start AX data session generation: {e}"))?;
482            self.pending_tasks
483                .start_generation()
484                .map_err(|e| anyhow::anyhow!("Failed to start AX data task generation: {e}"))?;
485            self.cancellation_token = CancellationToken::new();
486        }
487        let cancellation_token = self.cancellation_token.clone();
488        let ws_client = self.ws_client.clone();
489        let setup_guard =
490            TaskGroupGuard::new(&[&self.session_tasks, &self.pending_tasks], move || {
491                cancellation_token.cancel();
492                ws_client.begin_shutdown();
493            });
494
495        let credential = Credential::resolve(
496            self.config.api_key.clone().map(|value| value.into_inner()),
497            self.config
498                .api_secret
499                .clone()
500                .map(|value| value.into_inner()),
501        )
502        .context("API credentials not configured")?;
503
504        let token = self
505            .http_client
506            .authenticate(
507                credential.api_key(),
508                credential.api_secret(),
509                AX_AUTH_TOKEN_TTL_SECS,
510            )
511            .await
512            .context("Failed to authenticate with Ax")?;
513        log::debug!("Authenticated with Ax");
514        self.ws_client.set_auth_token(token);
515
516        self.http_client
517            .request_account_fees()
518            .await
519            .context("Failed to resolve Ax account fee rates")?;
520
521        let instruments = self
522            .http_client
523            .request_instruments()
524            .await
525            .context("Failed to fetch instruments")?;
526
527        self.http_client.cache_instruments(&instruments);
528        for instrument in &instruments {
529            if let Err(e) = self
530                .data_sender
531                .send(DataEvent::Data(instrument.clone().into()))
532            {
533                log::warn!("Failed to send instrument: {e}");
534            }
535        }
536
537        log::debug!(
538            "Cached {} instruments",
539            self.http_client.get_cached_symbols().len()
540        );
541
542        self.ws_client
543            .connect()
544            .await
545            .context("Failed to connect WebSocket")?;
546        log::debug!("WebSocket connected");
547
548        let session_result = async {
549            // The client replays subscriptions on connect, so tracked books need fresh snapshots
550            book::recovery::reset_on_reconnect(
551                &self.book_sync,
552                &self.ws_client,
553                self.book_snapshot_timeout(),
554                &self.pending_tasks.spawner()?,
555            );
556            self.spawn_message_handler()?;
557            self.spawn_instrument_refresh()?;
558
559            let ws_client = self.ws_client.clone();
560            self.session_tasks.spawn(run_auth_token_refresh(
561                self.http_client.clone(),
562                credential,
563                move |token| ws_client.update_auth_token(token),
564            ))?;
565            Ok::<(), anyhow::Error>(())
566        }
567        .await;
568
569        if let Err(e) = session_result {
570            if let Err(teardown_error) = self.teardown_partial_connect().await {
571                return Err(e.context(format!("AX data startup teardown failed: {teardown_error}")));
572            }
573            return Err(e);
574        }
575
576        self.is_connected.store(true, Ordering::Release);
577        setup_guard.disarm();
578        log::info!("Connected {}", self.client_id);
579
580        Ok(())
581    }
582
583    async fn disconnect(&mut self) -> anyhow::Result<()> {
584        log::info!("Disconnecting {}", self.client_id);
585
586        self.abort_all_tasks();
587        let ws_result = self.ws_client.close().await;
588        let tasks_result = self.finish_all_tasks().await;
589        self.funding_rate_cache.lock().clear();
590
591        self.is_connected.store(false, Ordering::Release);
592        log::info!("Disconnected {}", self.client_id);
593
594        ws_result?;
595        tasks_result
596    }
597
598    fn subscribe_instruments(&mut self, _cmd: SubscribeInstruments) -> anyhow::Result<()> {
599        // AX does not have a real-time instruments channel; instruments are fetched via HTTP
600        log::debug!("Instruments subscription not applicable for AX (use request_instruments)");
601        Ok(())
602    }
603
604    fn subscribe_instrument(&mut self, _cmd: SubscribeInstrument) -> anyhow::Result<()> {
605        // AX does not have a real-time instrument channel; instruments are fetched via HTTP
606        log::debug!("Instrument subscription not applicable for AX (use request_instrument)");
607        Ok(())
608    }
609
610    fn subscribe_book_deltas(&mut self, cmd: SubscribeBookDeltas) -> anyhow::Result<()> {
611        execute_instrument_subscriptions(&cmd.instrument_ids, |instrument_id| {
612            let cmd = cmd.with_instrument_ids(instrument_id);
613            let symbol = instrument_id.symbol;
614            let level = Self::map_book_type_to_market_data_level(cmd.book_type);
615            if cmd.book_type == BookType::L1_MBP {
616                log::warn!(
617                    "Book type L1_MBP not supported by AX for deltas, downgrading {symbol} to LEVEL_2"
618                );
619            }
620
621            log::debug!("Subscribing to book deltas for {symbol} at {level:?}");
622
623            match self.pending_tasks.spawner() {
624                Ok(tasks) => book::recovery::spawn_subscription_task(
625                    instrument_id,
626                    level,
627                    self.subscription_order.next(),
628                    self.book_sync.clone(),
629                    self.ws_client.clone(),
630                    self.book_snapshot_timeout(),
631                    &tasks,
632                ),
633                Err(e) => log::warn!("Skipping AX subscribe book deltas after shutdown began: {e}"),
634            }
635
636            Ok(())
637        })
638    }
639
640    fn subscribe_quotes(&mut self, cmd: SubscribeQuotes) -> anyhow::Result<()> {
641        execute_instrument_subscriptions(&cmd.instrument_ids, |instrument_id| {
642            self.ws_symbol_op(
643                instrument_id,
644                |ws, s| async move { ws.subscribe_quotes(&s).await },
645                "Subscribing to quotes",
646            )
647        })
648    }
649
650    fn subscribe_trades(&mut self, cmd: SubscribeTrades) -> anyhow::Result<()> {
651        execute_instrument_subscriptions(&cmd.instrument_ids, |instrument_id| {
652            self.ws_symbol_op(
653                instrument_id,
654                |ws, s| async move { ws.subscribe_trades(&s).await },
655                "Subscribing to trades",
656            )
657        })
658    }
659
660    fn subscribe_mark_prices(&mut self, cmd: SubscribeMarkPrices) -> anyhow::Result<()> {
661        execute_instrument_subscriptions(&cmd.instrument_ids, |instrument_id| {
662            self.ws_symbol_op(
663                instrument_id,
664                |ws, s| async move { ws.subscribe_mark_prices(&s).await },
665                "Subscribing to mark prices",
666            )
667        })
668    }
669
670    fn subscribe_index_prices(&mut self, _cmd: SubscribeIndexPrices) -> anyhow::Result<()> {
671        log::warn!("Index price subscriptions are not supported by the Architect AX adapter");
672        Ok(())
673    }
674
675    fn subscribe_bars(&mut self, cmd: SubscribeBars) -> anyhow::Result<()> {
676        execute_bar_subscriptions(&cmd.bar_types, |bar_type| {
677            let symbol = bar_type.instrument_id().symbol.to_string();
678            let width = map_bar_spec_to_candle_width(&bar_type.spec())?;
679            log::debug!("Subscribing to bars for {bar_type} (width: {width:?})");
680
681            let ws = self.ws_client.clone();
682            self.spawn_ws(
683                async move {
684                    ws.subscribe_candles(&symbol, width)
685                        .await
686                        .map_err(|e| anyhow::anyhow!(e))
687                },
688                "subscribe bars",
689            );
690
691            Ok(())
692        })
693    }
694
695    fn subscribe_funding_rates(&mut self, cmd: SubscribeFundingRates) -> anyhow::Result<()> {
696        execute_instrument_subscriptions(&cmd.instrument_ids, |instrument_id| {
697            let poll_interval_mins = self.config.funding_rate_poll_interval_mins.max(1);
698
699            // Use 7-day lookback to capture latest rate across weekends/holidays
700            let lookback = SignedDuration::from_hours(24 * (AX_FUNDING_RATE_LOOKBACK_DAYS));
701
702            if self.funding_rate_cancellations.contains_key(&instrument_id) {
703                log::debug!("Already subscribed to funding rates for {instrument_id}");
704                return Ok(());
705            }
706
707            log::debug!("Subscribing to funding rates for {instrument_id} (HTTP polling)");
708
709            let http = self.http_client.clone();
710            let sender = self.data_sender.clone();
711            let symbol = instrument_id.symbol.inner();
712            let cancellation = self.cancellation_token.child_token();
713            let task_cancellation = cancellation.clone();
714            let cache = Arc::clone(&self.funding_rate_cache);
715            let clock = self.clock;
716
717            self.session_tasks.spawn(async move {
718                // First tick fires immediately for initial emission
719                let mut interval = tokio::time::interval(Duration::from_mins(poll_interval_mins));
720
721                loop {
722                    tokio::select! {
723                        () = task_cancellation.cancelled() => {
724                            log::debug!("Funding rate polling cancelled for {symbol}");
725                            break;
726                        }
727                        _ = interval.tick() => {
728                            let now: Timestamp = clock.get_time_ns().into();
729                            let start = now - lookback;
730
731                            match http.request_funding_rates(instrument_id, Some(start), Some(now)).await {
732                                Ok(funding_rates) => {
733                                    if funding_rates.is_empty() {
734                                        log::warn!(
735                                            "No funding rates returned for {symbol}"
736                                        );
737                                    } else if let Some(update) = funding_rates.last() {
738                                        // Only emit if rate changed
739                                        let should_emit = cache.lock()
740                                            .get(&instrument_id) != Some(update);
741
742                                        if should_emit {
743                                            log::debug!(
744                                                "Funding rate for {symbol}: {}",
745                                                update.rate,
746                                            );
747                                            let update = *update;
748                                            cache.lock()
749                                                .insert(instrument_id, update);
750
751                                            if let Err(e) = sender.send(
752                                                DataEvent::Data(Data::FundingRate(update)),
753                                            ) {
754                                                log::error!(
755                                                    "Failed to send funding rate for {symbol}: {e}"
756                                                );
757                                            }
758                                        }
759                                    }
760                                }
761                                Err(e) => {
762                                    log::error!(
763                                        "Failed to poll funding rates for {symbol}: {e}"
764                                    );
765                                }
766                            }
767                        }
768                    }
769                }
770            })?;
771
772            self.funding_rate_cancellations
773                .insert(instrument_id, cancellation);
774            Ok(())
775        })
776    }
777
778    fn subscribe_instrument_status(
779        &mut self,
780        cmd: SubscribeInstrumentStatus,
781    ) -> anyhow::Result<()> {
782        execute_instrument_subscriptions(&cmd.instrument_ids, |instrument_id| {
783            self.ws_symbol_op(
784                instrument_id,
785                |ws, s| async move { ws.subscribe_instrument_status(&s).await },
786                "Subscribing to instrument status",
787            )
788        })
789    }
790
791    fn subscribe_instrument_close(&mut self, _cmd: SubscribeInstrumentClose) -> anyhow::Result<()> {
792        log::warn!("Instrument close not supported by AX Exchange");
793        Ok(())
794    }
795
796    fn unsubscribe_instruments(&mut self, _cmd: &UnsubscribeInstruments) -> anyhow::Result<()> {
797        Ok(())
798    }
799
800    fn unsubscribe_instrument(&mut self, _cmd: &UnsubscribeInstrument) -> anyhow::Result<()> {
801        Ok(())
802    }
803
804    fn unsubscribe_book_deltas(&mut self, cmd: &UnsubscribeBookDeltas) -> anyhow::Result<()> {
805        execute_instrument_subscriptions(&cmd.instrument_ids, |instrument_id| {
806            self.book_sync.remove(instrument_id);
807
808            self.ws_symbol_op(
809                instrument_id,
810                |ws, s| async move { ws.unsubscribe_book_deltas(&s).await },
811                "Unsubscribing from book deltas",
812            )
813        })
814    }
815
816    fn unsubscribe_quotes(&mut self, cmd: &UnsubscribeQuotes) -> anyhow::Result<()> {
817        execute_instrument_subscriptions(&cmd.instrument_ids, |instrument_id| {
818            self.ws_symbol_op(
819                instrument_id,
820                |ws, s| async move { ws.unsubscribe_quotes(&s).await },
821                "Unsubscribing from quotes",
822            )
823        })
824    }
825
826    fn unsubscribe_trades(&mut self, cmd: &UnsubscribeTrades) -> anyhow::Result<()> {
827        execute_instrument_subscriptions(&cmd.instrument_ids, |instrument_id| {
828            self.ws_symbol_op(
829                instrument_id,
830                |ws, s| async move { ws.unsubscribe_trades(&s).await },
831                "Unsubscribing from trades",
832            )
833        })
834    }
835
836    fn unsubscribe_mark_prices(&mut self, cmd: &UnsubscribeMarkPrices) -> anyhow::Result<()> {
837        execute_instrument_subscriptions(&cmd.instrument_ids, |instrument_id| {
838            self.ws_symbol_op(
839                instrument_id,
840                |ws, s| async move { ws.unsubscribe_mark_prices(&s).await },
841                "Unsubscribing from mark prices",
842            )
843        })
844    }
845
846    fn unsubscribe_index_prices(&mut self, _cmd: &UnsubscribeIndexPrices) -> anyhow::Result<()> {
847        Ok(())
848    }
849
850    fn unsubscribe_bars(&mut self, cmd: &UnsubscribeBars) -> anyhow::Result<()> {
851        execute_bar_subscriptions(&cmd.bar_types, |bar_type| {
852            let symbol = bar_type.instrument_id().symbol.to_string();
853            let width = map_bar_spec_to_candle_width(&bar_type.spec())?;
854            log::debug!("Unsubscribing from bars for {bar_type}");
855
856            let ws = self.ws_client.clone();
857            self.spawn_ws(
858                async move {
859                    ws.unsubscribe_candles(&symbol, width)
860                        .await
861                        .map_err(|e| anyhow::anyhow!(e))
862                },
863                "unsubscribe bars",
864            );
865
866            Ok(())
867        })
868    }
869
870    fn unsubscribe_funding_rates(&mut self, cmd: &UnsubscribeFundingRates) -> anyhow::Result<()> {
871        execute_instrument_subscriptions(&cmd.instrument_ids, |instrument_id| {
872            if let Some(cancellation) = self.funding_rate_cancellations.remove(&instrument_id) {
873                log::debug!("Unsubscribing from funding rates for {instrument_id}");
874                cancellation.cancel();
875                self.funding_rate_cache.lock().remove(&instrument_id);
876            } else {
877                log::debug!("Not subscribed to funding rates for {instrument_id}");
878            }
879
880            Ok(())
881        })
882    }
883
884    fn unsubscribe_instrument_status(
885        &mut self,
886        cmd: &UnsubscribeInstrumentStatus,
887    ) -> anyhow::Result<()> {
888        execute_instrument_subscriptions(&cmd.instrument_ids, |instrument_id| {
889            self.ws_symbol_op(
890                instrument_id,
891                |ws, s| async move { ws.unsubscribe_instrument_status(&s).await },
892                "Unsubscribing from instrument status",
893            )
894        })
895    }
896
897    fn unsubscribe_instrument_close(
898        &mut self,
899        _cmd: &UnsubscribeInstrumentClose,
900    ) -> anyhow::Result<()> {
901        Ok(())
902    }
903
904    fn request_instruments(&self, request: RequestInstruments) -> anyhow::Result<()> {
905        let http = self.http_client.clone();
906        let sender = self.data_sender.clone();
907        let cancel = self.cancellation_token.clone();
908        let request_id = request.request_id;
909        let client_id = request.client_id.unwrap_or(self.client_id);
910        let venue = *AX_VENUE;
911        let start_nanos = datetime_to_unix_nanos(request.start);
912        let end_nanos = datetime_to_unix_nanos(request.end);
913        let params = request.params;
914        let clock = self.clock;
915
916        self.spawn_task(async move {
917            match http.request_instruments().await {
918                Ok(instruments) => {
919                    if cancel.is_cancelled() {
920                        return;
921                    }
922                    log::debug!("Fetched {} instruments from Ax", instruments.len());
923                    http.cache_instruments(&instruments);
924
925                    let response = DataResponse::Instruments(InstrumentsResponse::new(
926                        request_id,
927                        client_id,
928                        venue,
929                        instruments,
930                        start_nanos,
931                        end_nanos,
932                        clock.get_time_ns(),
933                        params,
934                    ));
935
936                    if let Err(e) = sender.send(DataEvent::Response(response)) {
937                        log::error!("Failed to send instruments response: {e}");
938                    }
939                }
940                Err(e) => {
941                    log::error!("Failed to request instruments: {e}");
942                }
943            }
944        });
945
946        Ok(())
947    }
948
949    fn request_instrument(&self, request: RequestInstrument) -> anyhow::Result<()> {
950        let instrument_id = request.single_instrument_id()?;
951
952        let http = self.http_client.clone();
953        let instruments_cache = Arc::clone(&self.instruments);
954        let sender = self.data_sender.clone();
955        let cancel = self.cancellation_token.clone();
956        let request_id = request.request_id;
957        let client_id = request.client_id.unwrap_or(self.client_id);
958        let symbol = instrument_id.symbol.inner();
959        let start_nanos = datetime_to_unix_nanos(request.start);
960        let end_nanos = datetime_to_unix_nanos(request.end);
961        let params = request.params;
962        let clock = self.clock;
963
964        self.spawn_task(async move {
965            match http.request_instrument(symbol).await {
966                Ok(instrument) => {
967                    if cancel.is_cancelled() {
968                        return;
969                    }
970                    log::debug!("Fetched instrument {symbol} from Ax");
971                    instruments_cache.insert(symbol, instrument.clone());
972                    http.cache_instrument(instrument.clone());
973
974                    let response = DataResponse::Instrument(Box::new(InstrumentResponse::new(
975                        request_id,
976                        client_id,
977                        instrument_id,
978                        instrument,
979                        start_nanos,
980                        end_nanos,
981                        clock.get_time_ns(),
982                        params,
983                    )));
984
985                    if let Err(e) = sender.send(DataEvent::Response(response)) {
986                        log::error!("Failed to send instrument response: {e}");
987                    }
988                }
989                Err(e) => {
990                    log::error!("Failed to request instrument {symbol}: {e}");
991                }
992            }
993        });
994
995        Ok(())
996    }
997
998    fn request_book_snapshot(&self, request: RequestBookSnapshot) -> anyhow::Result<()> {
999        let instrument_id = request.single_instrument_id()?;
1000
1001        let http = self.http_client.clone();
1002        let sender = self.data_sender.clone();
1003        let cancel = self.cancellation_token.clone();
1004        let request_id = request.request_id;
1005        let client_id = request.client_id.unwrap_or(self.client_id);
1006        let symbol = instrument_id.symbol.inner();
1007        let depth = request.depth.map(|n| n.get());
1008        let params = request.params;
1009        let clock = self.clock;
1010
1011        self.spawn_task(async move {
1012            match http.request_book_snapshot(symbol, depth).await {
1013                Ok(book) => {
1014                    if cancel.is_cancelled() {
1015                        return;
1016                    }
1017                    log::debug!(
1018                        "Fetched book snapshot for {symbol} ({} bids, {} asks)",
1019                        book.bids(None).count(),
1020                        book.asks(None).count(),
1021                    );
1022
1023                    let response = DataResponse::Book(BookResponse::new(
1024                        request_id,
1025                        client_id,
1026                        instrument_id,
1027                        book,
1028                        None,
1029                        None,
1030                        clock.get_time_ns(),
1031                        params,
1032                    ));
1033
1034                    if let Err(e) = sender.send(DataEvent::Response(response)) {
1035                        log::error!("Failed to send book snapshot response: {e}");
1036                    }
1037                }
1038                Err(e) => {
1039                    log::error!("Failed to request book snapshot for {symbol}: {e}");
1040                }
1041            }
1042        });
1043
1044        Ok(())
1045    }
1046
1047    fn request_trades(&self, request: RequestTrades) -> anyhow::Result<()> {
1048        let instrument_id = request.single_instrument_id()?;
1049
1050        let http = self.http_client.clone();
1051        let sender = self.data_sender.clone();
1052        let cancel = self.cancellation_token.clone();
1053        let request_id = request.request_id;
1054        let client_id = request.client_id.unwrap_or(self.client_id);
1055        let symbol = instrument_id.symbol.inner();
1056        let limit = request.limit.map(|n| n.get() as i32);
1057        let start_nanos = datetime_to_unix_nanos(request.start);
1058        let end_nanos = datetime_to_unix_nanos(request.end);
1059        let params = request.params;
1060        let clock = self.clock;
1061
1062        self.spawn_task(async move {
1063            match http
1064                .request_trade_ticks(symbol, limit, start_nanos, end_nanos)
1065                .await
1066            {
1067                Ok(ticks) => {
1068                    if cancel.is_cancelled() {
1069                        return;
1070                    }
1071                    log::debug!("Fetched {} trades for {symbol}", ticks.len());
1072
1073                    let response = DataResponse::Trades(TradesResponse::new(
1074                        request_id,
1075                        client_id,
1076                        instrument_id,
1077                        ticks,
1078                        start_nanos,
1079                        end_nanos,
1080                        clock.get_time_ns(),
1081                        params,
1082                    ));
1083
1084                    if let Err(e) = sender.send(DataEvent::Response(response)) {
1085                        log::error!("Failed to send trades response: {e}");
1086                    }
1087                }
1088                Err(e) => {
1089                    log::error!("Failed to request trades for {symbol}: {e}");
1090                }
1091            }
1092        });
1093
1094        Ok(())
1095    }
1096
1097    fn request_bars(&self, request: RequestBars) -> anyhow::Result<()> {
1098        let bar_type = request.single_bar_type()?;
1099
1100        let http = self.http_client.clone();
1101        let sender = self.data_sender.clone();
1102        let request_id = request.request_id;
1103        let client_id = request.client_id.unwrap_or(self.client_id);
1104        let symbol = bar_type.instrument_id().symbol.inner();
1105        let start = request.start;
1106        let end = request.end;
1107        let start_nanos = datetime_to_unix_nanos(start);
1108        let end_nanos = datetime_to_unix_nanos(end);
1109        let params = request.params;
1110        let clock = self.clock;
1111        let width = map_bar_spec_to_candle_width(&bar_type.spec())?;
1112
1113        let cancel = self.cancellation_token.clone();
1114
1115        self.spawn_task(async move {
1116            match http.request_bars(symbol, start, end, width).await {
1117                Ok(bars) => {
1118                    if cancel.is_cancelled() {
1119                        return;
1120                    }
1121                    log::debug!("Fetched {} bars for {symbol}", bars.len());
1122
1123                    let response = DataResponse::Bars(BarsResponse::new(
1124                        request_id,
1125                        client_id,
1126                        bar_type,
1127                        bars,
1128                        start_nanos,
1129                        end_nanos,
1130                        clock.get_time_ns(),
1131                        params,
1132                    ));
1133
1134                    if let Err(e) = sender.send(DataEvent::Response(response)) {
1135                        log::error!("Failed to send bars response: {e}");
1136                    }
1137                }
1138                Err(e) => {
1139                    log::error!("Failed to request bars for {symbol}: {e}");
1140                }
1141            }
1142        });
1143
1144        Ok(())
1145    }
1146
1147    fn request_funding_rates(&self, request: RequestFundingRates) -> anyhow::Result<()> {
1148        let instrument_id = request.single_instrument_id()?;
1149
1150        let http = self.http_client.clone();
1151        let sender = self.data_sender.clone();
1152        let cancel = self.cancellation_token.clone();
1153        let request_id = request.request_id;
1154        let client_id = request.client_id.unwrap_or(self.client_id);
1155        let symbol = instrument_id.symbol.inner();
1156        let start = request.start;
1157        let end = request.end;
1158        let start_nanos = datetime_to_unix_nanos(start);
1159        let end_nanos = datetime_to_unix_nanos(end);
1160        let params = request.params;
1161        let clock = self.clock;
1162
1163        self.spawn_task(async move {
1164            match http.request_funding_rates(instrument_id, start, end).await {
1165                Ok(funding_rates) => {
1166                    if cancel.is_cancelled() {
1167                        return;
1168                    }
1169                    log::debug!("Fetched {} funding rates for {symbol}", funding_rates.len());
1170
1171                    let ts_init = clock.get_time_ns();
1172                    let response = DataResponse::FundingRates(FundingRatesResponse::new(
1173                        request_id,
1174                        client_id,
1175                        instrument_id,
1176                        funding_rates,
1177                        start_nanos,
1178                        end_nanos,
1179                        ts_init,
1180                        params,
1181                    ));
1182
1183                    if let Err(e) = sender.send(DataEvent::Response(response)) {
1184                        log::error!("Failed to send funding rates response: {e}");
1185                    }
1186                }
1187                Err(e) => {
1188                    log::error!("Failed to request funding rates for {symbol}: {e}");
1189                }
1190            }
1191        });
1192
1193        Ok(())
1194    }
1195}
1196
1197fn drain_status_invalidations(
1198    invalidations: &Arc<Mutex<AHashSet<Ustr>>>,
1199    instrument_states: &mut AHashMap<Ustr, AxInstrumentState>,
1200) {
1201    for symbol in invalidations.lock().drain() {
1202        instrument_states.remove(&symbol);
1203    }
1204}
1205
1206#[expect(clippy::too_many_arguments)]
1207fn handle_ws_message(
1208    msg: AxDataWsMessage,
1209    sender: &EventSender<DataEvent>,
1210    instruments: &Arc<AtomicMap<Ustr, InstrumentAny>>,
1211    symbol_data_types: &Arc<AtomicMap<String, SymbolDataTypes>>,
1212    book_sequences: &mut AHashMap<Ustr, u64>,
1213    candle_cache: &mut AHashMap<(Ustr, AxCandleWidth), AxMdCandle>,
1214    instrument_states: &mut AHashMap<Ustr, AxInstrumentState>,
1215    clock: &'static AtomicTime,
1216    book_sync: &BookSyncTracker,
1217    ws_client: &AxMdWebSocketClient,
1218    snapshot_timeout: Duration,
1219    book_tasks: &TaskSpawner,
1220) {
1221    match msg {
1222        AxDataWsMessage::Reconnected => {
1223            candle_cache.clear();
1224            instrument_states.clear();
1225            log::info!("WebSocket reconnected");
1226            book::recovery::reset_on_reconnect(book_sync, ws_client, snapshot_timeout, book_tasks);
1227        }
1228        AxDataWsMessage::CandleUnsubscribed { symbol, width } => {
1229            candle_cache.remove(&(symbol, width));
1230        }
1231        AxDataWsMessage::MdMessage(md_msg) => {
1232            handle_md_message(
1233                md_msg,
1234                sender,
1235                instruments,
1236                symbol_data_types,
1237                book_sequences,
1238                candle_cache,
1239                instrument_states,
1240                clock,
1241                book_sync,
1242                ws_client,
1243                snapshot_timeout,
1244                book_tasks,
1245            );
1246        }
1247    }
1248}
1249
1250#[expect(clippy::too_many_arguments)]
1251fn handle_md_message(
1252    message: AxMdMessage,
1253    sender: &EventSender<DataEvent>,
1254    instruments: &Arc<AtomicMap<Ustr, InstrumentAny>>,
1255    symbol_data_types: &Arc<AtomicMap<String, SymbolDataTypes>>,
1256    book_sequences: &mut AHashMap<Ustr, u64>,
1257    candle_cache: &mut AHashMap<(Ustr, AxCandleWidth), AxMdCandle>,
1258    instrument_states: &mut AHashMap<Ustr, AxInstrumentState>,
1259    clock: &'static AtomicTime,
1260    book_sync: &BookSyncTracker,
1261    ws_client: &AxMdWebSocketClient,
1262    snapshot_timeout: Duration,
1263    book_tasks: &TaskSpawner,
1264) {
1265    let ts_init = || -> UnixNanos { clock.get_time_ns() };
1266
1267    let instruments_snap = instruments.load();
1268    let sdt_snap = symbol_data_types.load();
1269
1270    match message {
1271        AxMdMessage::BookL1(book) => {
1272            let l1_subscribed = sdt_snap
1273                .get(book.s.as_str())
1274                .is_some_and(|e| e.quotes || e.book_level == Some(AxMarketDataLevel::Level1));
1275
1276            if !l1_subscribed {
1277                return;
1278            }
1279
1280            let Some(instrument) = instruments_snap.get(&book.s) else {
1281                log::error!(
1282                    "No instrument cached for symbol '{}' - cannot parse L1 book",
1283                    book.s
1284                );
1285                return;
1286            };
1287
1288            match parse_book_l1_quote(&book, instrument, ts_init()) {
1289                Ok(quote) => {
1290                    let _ = sender.send(DataEvent::Data(Data::Quote(quote)));
1291                }
1292                Err(e) => log::error!("Failed to parse L1 to QuoteTick: {e}"),
1293            }
1294        }
1295        AxMdMessage::BookL2(book) => {
1296            let symbol = book.s;
1297            let seq = book_sequences.entry(symbol).or_insert(0);
1298            *seq += 1;
1299            let sequence = *seq;
1300
1301            let Some(instrument) = instruments_snap.get(&symbol) else {
1302                log::error!("No instrument cached for symbol '{symbol}' - cannot parse L2 book");
1303                return;
1304            };
1305
1306            handle_book_deltas(
1307                parse_book_l2_deltas(&book, instrument, sequence, ts_init()),
1308                instrument.id(),
1309                sender,
1310                book_sync,
1311                ws_client,
1312                snapshot_timeout,
1313                book_tasks,
1314            );
1315
1316            let quotes_subscribed = sdt_snap
1317                .get(symbol.as_str())
1318                .is_some_and(|entry| entry.quotes);
1319
1320            if quotes_subscribed {
1321                match parse_book_l2_quote(&book, instrument, ts_init()) {
1322                    Ok(quote) => {
1323                        let _ = sender.send(DataEvent::Data(Data::Quote(quote)));
1324                    }
1325                    Err(e) => log::error!("Failed to parse L2 to QuoteTick: {e}"),
1326                }
1327            }
1328        }
1329        AxMdMessage::BookL3(book) => {
1330            let symbol = book.s;
1331            let seq = book_sequences.entry(symbol).or_insert(0);
1332            *seq += 1;
1333            let sequence = *seq;
1334
1335            let Some(instrument) = instruments_snap.get(&symbol) else {
1336                log::error!("No instrument cached for symbol '{symbol}' - cannot parse L3 book");
1337                return;
1338            };
1339
1340            handle_book_deltas(
1341                parse_book_l3_deltas(&book, instrument, sequence, ts_init()),
1342                instrument.id(),
1343                sender,
1344                book_sync,
1345                ws_client,
1346                snapshot_timeout,
1347                book_tasks,
1348            );
1349
1350            let quotes_subscribed = sdt_snap
1351                .get(symbol.as_str())
1352                .is_some_and(|entry| entry.quotes);
1353
1354            if quotes_subscribed {
1355                match parse_book_l3_quote(&book, instrument, ts_init()) {
1356                    Ok(quote) => {
1357                        let _ = sender.send(DataEvent::Data(Data::Quote(quote)));
1358                    }
1359                    Err(e) => log::error!("Failed to parse L3 to QuoteTick: {e}"),
1360                }
1361            }
1362        }
1363        AxMdMessage::Ticker(ticker) => {
1364            let Some(instrument) = instruments_snap.get(&ticker.s) else {
1365                log::debug!("No instrument cached for ticker symbol '{}'", ticker.s);
1366                return;
1367            };
1368
1369            let instrument_id = instrument.id();
1370            let price_precision = instrument.price_precision();
1371            let ts_event =
1372                ax_timestamp_stn_to_unix_nanos(ticker.ts, ticker.tn).unwrap_or_else(|_| ts_init());
1373            let ts_init = ts_init();
1374
1375            let mark_prices_subscribed = sdt_snap
1376                .get(ticker.s.as_str())
1377                .is_some_and(|e| e.mark_prices);
1378
1379            if mark_prices_subscribed && let Some(mark_price) = ticker.m {
1380                match Price::from_decimal_dp(mark_price, price_precision) {
1381                    Ok(price) => {
1382                        let update = MarkPriceUpdate::new(instrument_id, price, ts_event, ts_init);
1383                        let _ = sender.send(DataEvent::Data(Data::MarkPrice(update)));
1384                    }
1385                    Err(e) => {
1386                        log::error!("Failed to parse mark price for {}: {e}", ticker.s);
1387                    }
1388                }
1389            }
1390
1391            if let Some(state) = ticker.i {
1392                let status_subscribed = sdt_snap
1393                    .get(ticker.s.as_str())
1394                    .is_some_and(|e| e.instrument_status);
1395
1396                if status_subscribed {
1397                    let prev = instrument_states.insert(ticker.s, state);
1398                    if prev != Some(state) {
1399                        let action = MarketStatusAction::from(state);
1400                        let status = InstrumentStatus::new(
1401                            instrument_id,
1402                            action,
1403                            ts_event,
1404                            ts_init,
1405                            None,
1406                            None,
1407                            Some(state == AxInstrumentState::Open),
1408                            None,
1409                            None,
1410                        );
1411                        let _ = sender.send(DataEvent::Data(Data::InstrumentStatus(status)));
1412                    }
1413                }
1414            }
1415        }
1416        AxMdMessage::Trade(trade) => {
1417            let trades_subscribed = sdt_snap.get(trade.s.as_str()).is_some_and(|e| e.trades);
1418
1419            if !trades_subscribed {
1420                return;
1421            }
1422
1423            let Some(instrument) = instruments_snap.get(&trade.s) else {
1424                log::error!(
1425                    "No instrument cached for symbol '{}' - cannot parse trade",
1426                    trade.s
1427                );
1428                return;
1429            };
1430
1431            match parse_trade_tick(&trade, instrument, ts_init()) {
1432                Ok(tick) => {
1433                    let _ = sender.send(DataEvent::Data(Data::Trade(tick)));
1434                }
1435                Err(e) => log::error!("Failed to parse trade to TradeTick: {e}"),
1436            }
1437        }
1438        AxMdMessage::Candle(candle) => {
1439            let cache_key = (candle.symbol, candle.width);
1440
1441            let closed_candle = if let Some(cached) = candle_cache.get(&cache_key) {
1442                if cached.ts == candle.ts {
1443                    None
1444                } else {
1445                    Some(cached.clone())
1446                }
1447            } else {
1448                None
1449            };
1450
1451            candle_cache.insert(cache_key, candle);
1452
1453            if let Some(closed) = closed_candle {
1454                let Some(instrument) = instruments_snap.get(&closed.symbol) else {
1455                    log::error!(
1456                        "No instrument cached for symbol '{}' - cannot parse candle",
1457                        closed.symbol
1458                    );
1459                    return;
1460                };
1461
1462                match parse_candle_bar(&closed, instrument, ts_init()) {
1463                    Ok(bar) => {
1464                        let _ = sender.send(DataEvent::Data(Data::Bar(bar)));
1465                    }
1466                    Err(e) => log::error!("Failed to parse candle to Bar: {e}"),
1467                }
1468            }
1469        }
1470        AxMdMessage::Heartbeat(_) => {
1471            log::trace!("Received heartbeat");
1472        }
1473        AxMdMessage::SubscriptionResponse(_) | AxMdMessage::Error(_) => {}
1474    }
1475}
1476
1477// Emits a book snapshot its book accepts, or recovers a book whose frame failed to parse
1478fn handle_book_deltas(
1479    deltas: anyhow::Result<OrderBookDeltas>,
1480    instrument_id: InstrumentId,
1481    sender: &EventSender<DataEvent>,
1482    book_sync: &BookSyncTracker,
1483    ws_client: &AxMdWebSocketClient,
1484    snapshot_timeout: Duration,
1485    book_tasks: &TaskSpawner,
1486) {
1487    match deltas {
1488        Ok(deltas) => {
1489            if book_sync.record_snapshot(instrument_id, Instant::now()) {
1490                let _ = sender.send(DataEvent::Data(Data::BookDeltas(Box::new(deltas))));
1491            }
1492        }
1493        Err(e) => {
1494            log::error!("Failed to parse book frame for {instrument_id}: {e}");
1495            book::recovery::reject_snapshot(
1496                instrument_id,
1497                book_sync,
1498                ws_client,
1499                snapshot_timeout,
1500                book_tasks,
1501            );
1502        }
1503    }
1504}
1505
1506#[cfg(test)]
1507mod tests {
1508    use std::sync::Arc;
1509
1510    use ahash::{AHashMap, AHashSet};
1511    use parking_lot::Mutex;
1512    use rstest::rstest;
1513    use ustr::Ustr;
1514
1515    use super::*;
1516
1517    #[rstest]
1518    fn test_drain_status_invalidations_removes_cached_state() {
1519        let invalidations = Arc::new(Mutex::new(AHashSet::new()));
1520        let mut states = AHashMap::new();
1521        let sym = Ustr::from("EURUSD-PERP");
1522
1523        states.insert(sym, AxInstrumentState::Open);
1524        invalidations.lock().insert(sym);
1525
1526        drain_status_invalidations(&invalidations, &mut states);
1527
1528        assert!(!states.contains_key(&sym));
1529        assert!(invalidations.lock().is_empty());
1530    }
1531
1532    #[rstest]
1533    fn test_drain_status_invalidations_no_op_when_empty() {
1534        let invalidations = Arc::new(Mutex::new(AHashSet::new()));
1535        let mut states = AHashMap::new();
1536        let sym = Ustr::from("EURUSD-PERP");
1537        states.insert(sym, AxInstrumentState::Open);
1538
1539        drain_status_invalidations(&invalidations, &mut states);
1540
1541        assert!(states.contains_key(&sym));
1542    }
1543}