Skip to main content

nautilus_okx/websocket/
parse.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//! Functions translating raw OKX WebSocket frames into Nautilus data types.
17
18use std::{str::FromStr, sync::LazyLock};
19
20use ahash::{AHashMap, AHashSet};
21use anyhow::Context;
22use nautilus_common::cache::fifo::FifoCacheMap;
23use nautilus_core::{UUID4, nanos::UnixNanos};
24use nautilus_model::{
25    data::{
26        Bar, BarSpecification, BarType, BookOrder, Data, FundingRateUpdate, IndexPriceUpdate,
27        InstrumentStatus, MarkPriceUpdate, OptionGreekValues, OrderBookDelta, OrderBookDeltas,
28        OrderBookDepth, QuoteTick, TradeTick, option_chain::OptionGreeks,
29    },
30    enums::{
31        AggregationSource, AggressorSide, BookAction, LiquiditySide, OrderSide, OrderStatus,
32        OrderType, RecordFlag, TimeInForce, TrailingOffsetType, TriggerType,
33    },
34    events::{OrderAccepted, OrderCanceled, OrderExpired, OrderTriggered, OrderUpdated},
35    identifiers::{
36        AccountId, ClientOrderId, InstrumentId, StrategyId, TradeId, TraderId, VenueOrderId,
37    },
38    instruments::{Instrument, InstrumentAny},
39    reports::{FillReport, OrderStatusReport},
40    types::{Money, Price, Quantity},
41};
42use parking_lot::Mutex;
43use rust_decimal::Decimal;
44use ustr::Ustr;
45
46use super::{
47    enums::OKXWsChannel,
48    messages::{
49        OKXAlgoOrderMsg, OKXBookMsg, OKXCandleMsg, OKXIndexPriceMsg, OKXMarkPriceMsg,
50        OKXOptionSummaryMsg, OKXOrderMsg, OKXRpiBookMsg, OKXTickerMsg, OKXTradeMsg, OrderBookEntry,
51    },
52};
53use crate::{
54    common::{
55        consts::{OKX_POST_ONLY_CANCEL_REASON, OKX_POST_ONLY_CANCEL_SOURCE},
56        enums::{
57            OKXAlgoOrderStatus, OKXAlgoOrderType, OKXBookAction, OKXCandleConfirm, OKXGreeksType,
58            OKXInstrumentStatus, OKXInstrumentType, OKXOrderCategory, OKXOrderStatus, OKXOrderType,
59            OKXSide, OKXTargetCurrency, OKXTriggerType,
60        },
61        models::OKXInstrument,
62        parse::{
63            determine_order_type_with_alt, is_market_price, okx_channel_to_bar_spec,
64            okx_status_to_market_action, parse_fee, parse_fee_currency, parse_funding_rate_msg,
65            parse_instrument_any, parse_instrument_id, parse_message_vec,
66            parse_millisecond_timestamp, parse_parent_client_order_id, parse_price, parse_quantity,
67            parse_spread_order_status_report as parse_common_spread_order_status_report,
68            venue_position_id,
69        },
70    },
71    http::models::OKXSpreadOrder,
72    websocket::messages::{ExecutionReport, NautilusWsMessage, OKXFundingRateMsg},
73};
74
75/// Maximum terminal-order baselines retained for reconnect replay before the oldest is evicted.
76const TERMINAL_BASELINE_CAPACITY: usize = 10_000;
77
78/// Cumulative fee per venue order ID (`ordId`).
79pub type FeeCache = FillBaselineCache<Money>;
80
81/// Cumulative filled quantity per venue order ID (`ordId`).
82pub type FilledQtyCache = FillBaselineCache<Quantity>;
83
84/// Cumulative per-order baseline used to derive incremental fill values.
85///
86/// OKX reports `fee` and `accFillSz` cumulatively, so a fill's incremental commission derives
87/// from the previous message for the same `ordId`, as does its quantity whenever `fillSz` is
88/// absent. Losing an open order's baseline would charge its whole cumulative fee, and its whole
89/// accumulated quantity, to the next fill.
90///
91/// Baselines are therefore split by order lifecycle. An order that can still fill keeps its
92/// baseline in full. A terminal order keeps one only to absorb reconnect replays, so those are
93/// held in a bounded cache that evicts oldest-first and cannot grow with session length.
94#[derive(Debug)]
95pub struct FillBaselineCache<T> {
96    open: AHashMap<Ustr, T>,
97    terminal: FifoCacheMap<Ustr, T, TERMINAL_BASELINE_CAPACITY>,
98}
99
100impl<T> Default for FillBaselineCache<T> {
101    fn default() -> Self {
102        Self::new()
103    }
104}
105
106impl<T> FillBaselineCache<T> {
107    /// Creates a new empty [`FillBaselineCache`].
108    #[must_use]
109    pub fn new() -> Self {
110        Self {
111            open: AHashMap::new(),
112            terminal: FifoCacheMap::new(),
113        }
114    }
115
116    /// Returns the cumulative baseline recorded for `ord_id`.
117    #[must_use]
118    pub fn get(&self, ord_id: &Ustr) -> Option<&T> {
119        self.open.get(ord_id).or_else(|| self.terminal.get(ord_id))
120    }
121
122    /// Records the cumulative baseline for `ord_id`.
123    ///
124    /// Pass `is_terminal` for an order state the venue cannot follow with a new fill; its
125    /// baseline then becomes evictable. An open order's baseline is retained in full.
126    pub fn record(&mut self, ord_id: Ustr, value: T, is_terminal: bool) {
127        if is_terminal {
128            self.open.remove(&ord_id);
129            self.terminal.insert(ord_id, value);
130        } else if self.terminal.contains_key(&ord_id) {
131            self.terminal.insert(ord_id, value);
132        } else {
133            self.open.insert(ord_id, value);
134        }
135    }
136
137    /// Drops any baseline recorded for `ord_id`.
138    pub fn remove(&mut self, ord_id: &Ustr) {
139        self.open.remove(ord_id);
140        self.terminal.remove(ord_id);
141    }
142}
143
144/// Returns whether the venue order state admits no further fills.
145#[must_use]
146pub const fn is_terminal_order_state(state: OKXOrderStatus) -> bool {
147    matches!(
148        state,
149        OKXOrderStatus::Filled | OKXOrderStatus::Canceled | OKXOrderStatus::MmpCanceled
150    )
151}
152
153/// Extracts margin rates from a cached instrument.
154///
155/// Returns a tuple of (`margin_init`, `margin_maint`).
156/// Both values are None if the instrument type doesn't carry margins.
157pub(crate) fn extract_fees_from_cached_instrument(
158    instrument: &InstrumentAny,
159) -> (Option<Decimal>, Option<Decimal>) {
160    match instrument {
161        InstrumentAny::CurrencyPair(pair) => (Some(pair.margin_init), Some(pair.margin_maint)),
162        InstrumentAny::CryptoPerpetual(perp) => (Some(perp.margin_init), Some(perp.margin_maint)),
163        InstrumentAny::CryptoFuture(future) => {
164            (Some(future.margin_init), Some(future.margin_maint))
165        }
166        InstrumentAny::CryptoOption(option) => {
167            (Some(option.margin_init), Some(option.margin_maint))
168        }
169        _ => (None, None),
170    }
171}
172
173/// Represents the result of parsing an OKX order message into a specific event.
174#[derive(Debug, Clone)]
175pub enum ParsedOrderEvent {
176    /// Order has been accepted by the venue.
177    Accepted(OrderAccepted),
178    /// Order has been canceled.
179    Canceled(OrderCanceled),
180    /// Order has expired (e.g., GTD order reached expiration time).
181    Expired(OrderExpired),
182    /// Stop/algo order has been triggered.
183    Triggered(OrderTriggered),
184    /// Order has been modified (price, quantity, or venue order ID changed).
185    Updated(OrderUpdated),
186    /// Order fill event.
187    Fill(FillReport),
188    /// Status update that doesn't map to a specific event (for reconciliation/external orders).
189    StatusOnly(Box<OrderStatusReport>),
190    /// Duplicate message detected (e.g. reconnect replay with unchanged fill).
191    /// The dispatcher should update caches but not emit any event.
192    Skipped,
193}
194
195/// Snapshot of order state for detecting updates.
196#[derive(Debug, Clone)]
197pub struct OrderStateSnapshot {
198    pub venue_order_id: VenueOrderId,
199    pub quantity: Quantity,
200    pub price: Option<Price>,
201}
202
203/// Parses an OKX order message into a specific order event.
204///
205/// This function determines the appropriate event type based on:
206/// - Current order status from OKX
207/// - Whether there's a new fill
208/// - Whether the order was updated (price/quantity change)
209/// - Whether it's an algo order that triggered
210///
211/// # Errors
212///
213/// Returns an error if parsing order identifiers or numeric fields fails.
214#[expect(clippy::too_many_arguments)]
215pub fn parse_order_event(
216    msg: &OKXOrderMsg,
217    client_order_id: ClientOrderId,
218    account_id: AccountId,
219    trader_id: TraderId,
220    strategy_id: StrategyId,
221    instrument: &InstrumentAny,
222    previous_fee: Option<Money>,
223    previous_filled_qty: Option<Quantity>,
224    previous_state: Option<&OrderStateSnapshot>,
225    ts_init: UnixNanos,
226) -> anyhow::Result<ParsedOrderEvent> {
227    let venue_order_id = VenueOrderId::new(msg.ord_id);
228    let instrument_id = instrument.id();
229
230    let has_new_fill = (!msg.fill_sz.is_empty() && msg.fill_sz != "0")
231        || !msg.trade_id.is_empty()
232        || has_acc_fill_sz_increased(
233            msg.acc_fill_sz.as_deref(),
234            previous_filled_qty,
235            instrument.size_precision(),
236        );
237
238    warn_unrecognized_order_state(msg);
239
240    // Check for order updates, but skip when other events take precedence:
241    // - Fill events: fill data must be processed, update detection secondary
242    // - Terminal states: handled by specific branches below
243    let skip_update_check = has_new_fill
244        || matches!(
245            msg.state,
246            OKXOrderStatus::Filled | OKXOrderStatus::Canceled | OKXOrderStatus::MmpCanceled
247        );
248
249    if !skip_update_check
250        && let Some(prev) = previous_state
251        && is_order_updated_excluding_venue_id_for_live(msg, prev, instrument)?
252    {
253        let ts_event = parse_millisecond_timestamp(msg.u_time);
254        let quantity = parse_quantity(&msg.sz, instrument.size_precision())?;
255        let price = if is_market_price(&msg.px) {
256            None
257        } else {
258            Some(parse_price(&msg.px, instrument.price_precision())?)
259        };
260
261        return Ok(ParsedOrderEvent::Updated(OrderUpdated::new(
262            trader_id,
263            strategy_id,
264            instrument_id,
265            client_order_id,
266            quantity,
267            UUID4::new(),
268            ts_event,
269            ts_init,
270            false, // reconciliation
271            Some(venue_order_id),
272            Some(account_id),
273            price,
274            None,  // trigger_price
275            None,  // protection_price
276            false, // is_quote_quantity
277        )));
278    }
279
280    match msg.state {
281        OKXOrderStatus::Filled | OKXOrderStatus::PartiallyFilled | OKXOrderStatus::Unknown
282            if has_new_fill =>
283        {
284            match parse_fill_report(
285                msg,
286                instrument,
287                account_id,
288                previous_fee,
289                previous_filled_qty,
290                ts_init,
291            )? {
292                Some(mut report) => {
293                    report.client_order_id = Some(client_order_id);
294                    Ok(ParsedOrderEvent::Fill(report))
295                }
296                None => Ok(ParsedOrderEvent::Skipped),
297            }
298        }
299        OKXOrderStatus::Live => {
300            let ts_event = parse_millisecond_timestamp(msg.c_time);
301            Ok(ParsedOrderEvent::Accepted(OrderAccepted::new(
302                trader_id,
303                strategy_id,
304                instrument_id,
305                client_order_id,
306                venue_order_id,
307                account_id,
308                UUID4::new(),
309                ts_event,
310                ts_init,
311                false, // reconciliation
312            )))
313        }
314        OKXOrderStatus::Canceled | OKXOrderStatus::MmpCanceled => {
315            let ts_event = parse_millisecond_timestamp(msg.u_time);
316
317            if is_order_expired_by_reason(msg) {
318                Ok(ParsedOrderEvent::Expired(OrderExpired::new(
319                    trader_id,
320                    strategy_id,
321                    instrument_id,
322                    client_order_id,
323                    UUID4::new(),
324                    ts_event,
325                    ts_init,
326                    false,
327                    Some(venue_order_id),
328                    Some(account_id),
329                )))
330            } else {
331                Ok(ParsedOrderEvent::Canceled(OrderCanceled::new(
332                    trader_id,
333                    strategy_id,
334                    instrument_id,
335                    client_order_id,
336                    UUID4::new(),
337                    ts_event,
338                    ts_init,
339                    false,
340                    Some(venue_order_id),
341                    Some(account_id),
342                    None,
343                )))
344            }
345        }
346        _ => {
347            // PartiallyFilled without new fill or other states - use status report
348            parse_order_status_report(msg, instrument, account_id, ts_init)
349                .map(|r| ParsedOrderEvent::StatusOnly(Box::new(r)))
350        }
351    }
352}
353
354/// Parses an OKX spread order message into a specific order event.
355///
356/// # Errors
357///
358/// Returns an error if parsing order identifiers or numeric fields fails.
359#[expect(clippy::too_many_arguments)]
360pub fn parse_spread_order_event(
361    msg: &OKXSpreadOrder,
362    client_order_id: ClientOrderId,
363    account_id: AccountId,
364    trader_id: TraderId,
365    strategy_id: StrategyId,
366    instrument: &InstrumentAny,
367    previous_filled_qty: Option<Quantity>,
368    previous_state: Option<&OrderStateSnapshot>,
369    ts_init: UnixNanos,
370) -> anyhow::Result<ParsedOrderEvent> {
371    let venue_order_id = VenueOrderId::new(msg.ord_id.as_str());
372    let instrument_id = instrument.id();
373    let has_new_fill = (!msg.fill_sz.is_empty() && msg.fill_sz != "0")
374        || !msg.trade_id.is_empty()
375        || has_acc_fill_sz_increased(
376            Some(msg.acc_fill_sz.as_str()),
377            previous_filled_qty,
378            instrument.size_precision(),
379        );
380    let skip_update_check = has_new_fill
381        || matches!(
382            msg.state,
383            OKXOrderStatus::Filled | OKXOrderStatus::Canceled | OKXOrderStatus::MmpCanceled
384        );
385
386    if !skip_update_check
387        && let Some(prev) = previous_state
388        && is_spread_order_updated_excluding_venue_id_for_live(msg, prev, instrument)?
389    {
390        let ts_event = msg.u_time.map_or(ts_init, parse_millisecond_timestamp);
391        let quantity = parse_quantity(&msg.sz, instrument.size_precision())?;
392        let price = if is_market_price(&msg.px) {
393            None
394        } else {
395            Some(parse_price(&msg.px, instrument.price_precision())?)
396        };
397
398        return Ok(ParsedOrderEvent::Updated(OrderUpdated::new(
399            trader_id,
400            strategy_id,
401            instrument_id,
402            client_order_id,
403            quantity,
404            UUID4::new(),
405            ts_event,
406            ts_init,
407            false,
408            Some(venue_order_id),
409            Some(account_id),
410            price,
411            None,
412            None,
413            false,
414        )));
415    }
416
417    match msg.state {
418        OKXOrderStatus::Filled | OKXOrderStatus::PartiallyFilled if has_new_fill => {
419            match parse_spread_order_fill_report(
420                msg,
421                instrument,
422                account_id,
423                previous_filled_qty,
424                ts_init,
425            )? {
426                Some(report) => Ok(ParsedOrderEvent::Fill(report)),
427                None => Ok(ParsedOrderEvent::Skipped),
428            }
429        }
430        OKXOrderStatus::Live => {
431            let ts_event = msg.c_time.map_or(ts_init, parse_millisecond_timestamp);
432            Ok(ParsedOrderEvent::Accepted(OrderAccepted::new(
433                trader_id,
434                strategy_id,
435                instrument_id,
436                client_order_id,
437                venue_order_id,
438                account_id,
439                UUID4::new(),
440                ts_event,
441                ts_init,
442                false,
443            )))
444        }
445        OKXOrderStatus::Canceled | OKXOrderStatus::MmpCanceled => {
446            let ts_event = msg
447                .u_time
448                .or(msg.c_time)
449                .map_or(ts_init, parse_millisecond_timestamp);
450            Ok(ParsedOrderEvent::Canceled(OrderCanceled::new(
451                trader_id,
452                strategy_id,
453                instrument_id,
454                client_order_id,
455                UUID4::new(),
456                ts_event,
457                ts_init,
458                false,
459                Some(venue_order_id),
460                Some(account_id),
461                None,
462            )))
463        }
464        _ => parse_common_spread_order_status_report(
465            msg,
466            account_id,
467            instrument.id(),
468            instrument.price_precision(),
469            instrument.size_precision(),
470            ts_init,
471        )
472        .map(|report| ParsedOrderEvent::StatusOnly(Box::new(report))),
473    }
474}
475
476/// Case-insensitive substring check.
477#[inline]
478/// Builds a deterministic synthesized `TradeId` for fills where OKX omits
479/// the venue `trade_id`. Hashes the immutable fill fields with FNV-1a so
480/// the result fits inside the 36-character `TradeId` cap and stays stable
481/// across reconnect replays of the same physical fill.
482fn synthesize_trade_id(msg: &OKXOrderMsg) -> String {
483    const FNV_OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
484    const FNV_PRIME: u64 = 0x0100_0000_01b3;
485
486    let mut hasher: u64 = FNV_OFFSET;
487    let mut update = |bytes: &[u8]| {
488        for byte in bytes {
489            hasher ^= u64::from(*byte);
490            hasher = hasher.wrapping_mul(FNV_PRIME);
491        }
492        // Field separator so that "ab" + "c" doesn't hash to the same as "a" + "bc".
493        hasher ^= 0xff;
494        hasher = hasher.wrapping_mul(FNV_PRIME);
495    };
496
497    update(msg.ord_id.as_bytes());
498    update(msg.fill_time.to_string().as_bytes());
499    update(msg.fill_sz.as_bytes());
500    update(msg.fill_px.as_bytes());
501    update(msg.acc_fill_sz.as_deref().unwrap_or("").as_bytes());
502
503    format!("synth-{hasher:016x}")
504}
505
506fn contains_ignore_ascii_case(haystack: &str, needle: &str) -> bool {
507    haystack
508        .as_bytes()
509        .windows(needle.len())
510        .any(|window| window.eq_ignore_ascii_case(needle.as_bytes()))
511}
512
513/// Determines if a Canceled order is actually an Expired order based on cancel reason.
514///
515/// OKX's numeric `cancelSource` enumeration is not fully documented, so
516/// unmapped codes log once via [`log_unknown_cancel_source`] to surface
517/// candidates for the mapping.
518fn is_order_expired_by_reason(msg: &OKXOrderMsg) -> bool {
519    if let Some(ref reason) = msg.cancel_source_reason
520        && (contains_ignore_ascii_case(reason, "expir")
521            || contains_ignore_ascii_case(reason, "gtd")
522            || contains_ignore_ascii_case(reason, "timeout"))
523    {
524        return true;
525    }
526
527    if let Some(ref source) = msg.cancel_source
528        && (source == "5" || source == "time_expired" || source == "gtd_expired")
529    {
530        return true;
531    }
532
533    log_unknown_cancel_source(msg);
534    false
535}
536
537const MAX_TRACKED_CANCEL_SOURCES: usize = 64;
538
539/// Logs each unseen `(cancel_source, cancel_source_reason)` pair once,
540/// capped at [`MAX_TRACKED_CANCEL_SOURCES`].
541fn log_unknown_cancel_source(msg: &OKXOrderMsg) {
542    static SEEN: LazyLock<Mutex<AHashSet<String>>> = LazyLock::new(|| Mutex::new(AHashSet::new()));
543    log_unknown_cancel_source_inner(msg, &SEEN, MAX_TRACKED_CANCEL_SOURCES);
544}
545
546/// Test-injectable variant. Returns `true` when a new entry was recorded.
547fn log_unknown_cancel_source_inner(
548    msg: &OKXOrderMsg,
549    seen: &Mutex<AHashSet<String>>,
550    max_tracked: usize,
551) -> bool {
552    let source = msg.cancel_source.as_deref().unwrap_or("");
553    let reason = msg.cancel_source_reason.as_deref().unwrap_or("");
554
555    if source.is_empty() && reason.is_empty() {
556        return false;
557    }
558
559    if matches!(source, "5" | "31" | "time_expired" | "gtd_expired") {
560        return false;
561    }
562
563    let key = format!("{source}|{reason}");
564    let mut seen = seen.lock();
565
566    if seen.len() >= max_tracked {
567        return false;
568    }
569
570    if seen.insert(key) {
571        log::debug!("Observed unmapped OKX cancelSource: source='{source}', reason='{reason}'");
572        true
573    } else {
574        false
575    }
576}
577
578/// Checks if order parameters have been updated compared to previous state.
579///
580/// For Live status, `venue_id` changes are ignored because algo triggers create new IDs
581/// but should emit `OrderAccepted`, not `OrderUpdated`. Price/quantity changes still count.
582fn is_order_updated_excluding_venue_id_for_live(
583    msg: &OKXOrderMsg,
584    previous: &OrderStateSnapshot,
585    instrument: &InstrumentAny,
586) -> anyhow::Result<bool> {
587    // For non-Live statuses, venue_id change indicates amendment
588    if msg.state != OKXOrderStatus::Live {
589        let current_venue_id = VenueOrderId::new(msg.ord_id);
590        if previous.venue_order_id != current_venue_id {
591            return Ok(true);
592        }
593    }
594
595    let current_qty = parse_quantity(&msg.sz, instrument.size_precision())?;
596    if previous.quantity != current_qty {
597        return Ok(true);
598    }
599
600    // Price change only applies to limit orders
601    if !is_market_price(&msg.px) {
602        let current_price = parse_price(&msg.px, instrument.price_precision())?;
603
604        if let Some(prev_price) = previous.price
605            && prev_price != current_price
606        {
607            return Ok(true);
608        }
609    }
610
611    Ok(false)
612}
613
614fn is_spread_order_updated_excluding_venue_id_for_live(
615    msg: &OKXSpreadOrder,
616    previous: &OrderStateSnapshot,
617    instrument: &InstrumentAny,
618) -> anyhow::Result<bool> {
619    if msg.state != OKXOrderStatus::Live {
620        let current_venue_id = VenueOrderId::new(msg.ord_id.as_str());
621        if previous.venue_order_id != current_venue_id {
622            return Ok(true);
623        }
624    }
625
626    let current_qty = parse_quantity(&msg.sz, instrument.size_precision())?;
627    if previous.quantity != current_qty {
628        return Ok(true);
629    }
630
631    if !is_market_price(&msg.px) {
632        let current_price = parse_price(&msg.px, instrument.price_precision())?;
633
634        if let Some(prev_price) = previous.price
635            && prev_price != current_price
636        {
637            return Ok(true);
638        }
639    }
640
641    Ok(false)
642}
643
644/// Parses vector of OKX book messages into Nautilus order book deltas.
645///
646/// # Errors
647///
648/// Returns an error if any underlying book message cannot be parsed.
649pub fn parse_book_msg_vec(
650    data: Vec<OKXBookMsg>,
651    instrument_id: &InstrumentId,
652    price_precision: u8,
653    size_precision: u8,
654    action: OKXBookAction,
655    ts_init: UnixNanos,
656) -> anyhow::Result<Vec<Data>> {
657    let mut deltas = Vec::with_capacity(data.len());
658
659    for msg in data {
660        deltas.push(Data::BookDeltas(Box::new(parse_book_msg(
661            &msg,
662            *instrument_id,
663            price_precision,
664            size_precision,
665            &action,
666            ts_init,
667        )?)));
668    }
669
670    Ok(deltas)
671}
672
673/// Parses RPI book messages into Nautilus order book deltas.
674///
675/// # Errors
676///
677/// Returns an error if any RPI book message cannot be represented at the instrument precision.
678pub fn parse_rpi_book_msg_vec(
679    data: Vec<OKXRpiBookMsg>,
680    instrument_id: &InstrumentId,
681    price_precision: u8,
682    size_precision: u8,
683    action: OKXBookAction,
684    ts_init: UnixNanos,
685) -> anyhow::Result<Vec<Data>> {
686    let mut deltas = Vec::with_capacity(data.len());
687
688    for msg in data {
689        deltas.push(Data::BookDeltas(Box::new(parse_rpi_book_msg(
690            &msg,
691            *instrument_id,
692            price_precision,
693            size_precision,
694            &action,
695            ts_init,
696        )?)));
697    }
698
699    Ok(deltas)
700}
701
702/// Parses vector of OKX ticker messages into Nautilus quote ticks.
703///
704/// # Errors
705///
706/// Returns an error if any ticker message fails to parse.
707pub fn parse_ticker_msg_vec(
708    data: serde_json::Value,
709    instrument_id: &InstrumentId,
710    price_precision: u8,
711    size_precision: u8,
712    ts_init: UnixNanos,
713) -> anyhow::Result<Vec<Data>> {
714    parse_message_vec(
715        data,
716        |msg| {
717            parse_ticker_msg(
718                msg,
719                *instrument_id,
720                price_precision,
721                size_precision,
722                ts_init,
723            )
724        },
725        Data::Quote,
726    )
727}
728
729/// Parses vector of OKX book messages into Nautilus quote ticks.
730///
731/// # Errors
732///
733/// Returns an error if any quote message fails to parse.
734pub fn parse_quote_msg_vec(
735    data: serde_json::Value,
736    instrument_id: &InstrumentId,
737    price_precision: u8,
738    size_precision: u8,
739    ts_init: UnixNanos,
740) -> anyhow::Result<Vec<Data>> {
741    parse_message_vec(
742        data,
743        |msg| {
744            parse_quote_msg(
745                msg,
746                *instrument_id,
747                price_precision,
748                size_precision,
749                ts_init,
750            )
751        },
752        Data::Quote,
753    )
754}
755
756/// Parses vector of OKX trade messages into Nautilus trade ticks.
757///
758/// # Errors
759///
760/// Returns an error if any trade message fails to parse.
761pub fn parse_trade_msg_vec(
762    data: serde_json::Value,
763    instrument_id: &InstrumentId,
764    price_precision: u8,
765    size_precision: u8,
766    ts_init: UnixNanos,
767) -> anyhow::Result<Vec<Data>> {
768    parse_message_vec(
769        data,
770        |msg| {
771            parse_trade_msg(
772                msg,
773                *instrument_id,
774                price_precision,
775                size_precision,
776                ts_init,
777            )
778        },
779        Data::Trade,
780    )
781}
782
783/// Parses vector of OKX mark price messages into Nautilus mark price updates.
784///
785/// # Errors
786///
787/// Returns an error if any mark price message fails to parse.
788pub fn parse_mark_price_msg_vec(
789    data: serde_json::Value,
790    instrument_id: &InstrumentId,
791    price_precision: u8,
792    ts_init: UnixNanos,
793) -> anyhow::Result<Vec<Data>> {
794    parse_message_vec(
795        data,
796        |msg| parse_mark_price_msg(msg, *instrument_id, price_precision, ts_init),
797        Data::MarkPrice,
798    )
799}
800
801/// Parses vector of OKX index price messages into Nautilus index price updates.
802///
803/// # Errors
804///
805/// Returns an error if any index price message fails to parse.
806pub fn parse_index_price_msg_vec(
807    data: serde_json::Value,
808    instrument_id: &InstrumentId,
809    price_precision: u8,
810    ts_init: UnixNanos,
811) -> anyhow::Result<Vec<Data>> {
812    parse_message_vec(
813        data,
814        |msg| parse_index_price_msg(msg, *instrument_id, price_precision, ts_init),
815        Data::IndexPrice,
816    )
817}
818
819/// Parses vector of OKX funding rate messages into Nautilus funding rate updates.
820/// Includes caching to filter out duplicate funding rates.
821///
822/// # Errors
823///
824/// Returns an error if any funding rate message fails to parse.
825pub fn parse_funding_rate_msg_vec(
826    data: serde_json::Value,
827    instrument_id: &InstrumentId,
828    ts_init: UnixNanos,
829    funding_cache: &mut AHashMap<Ustr, (Ustr, u64)>,
830) -> anyhow::Result<Vec<FundingRateUpdate>> {
831    let msgs: Vec<OKXFundingRateMsg> = serde_json::from_value(data)?;
832
833    let mut result = Vec::with_capacity(msgs.len());
834
835    for msg in &msgs {
836        let cache_key = (msg.funding_rate, msg.funding_time);
837
838        if let Some(cached) = funding_cache.get(&msg.inst_id)
839            && *cached == cache_key
840        {
841            continue; // Skip duplicate
842        }
843
844        // New or changed funding rate, update cache and parse
845        funding_cache.insert(msg.inst_id, cache_key);
846        let funding_rate = parse_funding_rate_msg(msg, *instrument_id, ts_init)?;
847        result.push(funding_rate);
848    }
849
850    Ok(result)
851}
852
853/// Parses vector of OKX candle messages into Nautilus bars.
854///
855/// # Errors
856///
857/// Returns an error if candle messages cannot be deserialized or parsed.
858pub fn parse_candle_msg_vec(
859    data: serde_json::Value,
860    instrument_id: &InstrumentId,
861    price_precision: u8,
862    size_precision: u8,
863    spec: BarSpecification,
864    ts_init: UnixNanos,
865) -> anyhow::Result<Vec<Data>> {
866    let msgs: Vec<OKXCandleMsg> = serde_json::from_value(data)?;
867    let bar_type = BarType::new(*instrument_id, spec, AggregationSource::External);
868    let mut bars = Vec::with_capacity(msgs.len());
869
870    for msg in msgs {
871        // Only process completed candles to avoid duplicate/partial bars
872        if msg.confirm == OKXCandleConfirm::Closed {
873            let bar = parse_candle_msg(&msg, bar_type, price_precision, size_precision, ts_init)?;
874            bars.push(Data::Bar(bar));
875        }
876    }
877
878    Ok(bars)
879}
880
881/// Parses vector of OKX book messages into Nautilus depth updates.
882///
883/// # Errors
884///
885/// Returns an error if any book depth message fails to parse.
886pub fn parse_book_depth_msg_vec(
887    data: Vec<OKXBookMsg>,
888    instrument_id: &InstrumentId,
889    price_precision: u8,
890    size_precision: u8,
891    ts_init: UnixNanos,
892) -> anyhow::Result<Vec<Data>> {
893    let mut depth_updates = Vec::with_capacity(data.len());
894
895    for msg in data {
896        let depth = parse_book_depth_msg(
897            &msg,
898            *instrument_id,
899            price_precision,
900            size_precision,
901            ts_init,
902        )?;
903        depth_updates.push(Data::BookDepth(Box::new(depth)));
904    }
905
906    Ok(depth_updates)
907}
908
909/// Parses an OKX book message into Nautilus order book deltas.
910///
911/// # Errors
912///
913/// Returns an error if bid or ask levels contain values that cannot be parsed.
914pub fn parse_book_msg(
915    msg: &OKXBookMsg,
916    instrument_id: InstrumentId,
917    price_precision: u8,
918    size_precision: u8,
919    action: &OKXBookAction,
920    ts_init: UnixNanos,
921) -> anyhow::Result<OrderBookDeltas> {
922    let is_snapshot = action == &OKXBookAction::Snapshot;
923
924    let flags = if is_snapshot {
925        RecordFlag::F_SNAPSHOT as u8
926    } else {
927        0
928    };
929    let ts_event = parse_millisecond_timestamp(msg.ts);
930    let mut deltas = Vec::with_capacity(msg.asks.len() + msg.bids.len() + usize::from(is_snapshot));
931
932    if is_snapshot {
933        deltas.push(OrderBookDelta::clear(
934            instrument_id,
935            msg.seq_id,
936            ts_event,
937            ts_init,
938        ));
939    }
940
941    for bid in &msg.bids {
942        let book_action = match action {
943            OKXBookAction::Snapshot => BookAction::Add,
944            _ => match bid.size.as_str() {
945                "0" => BookAction::Delete,
946                _ => BookAction::Update,
947            },
948        };
949        let price = parse_price(&bid.price, price_precision)?;
950        let size = parse_quantity(&bid.size, size_precision)?;
951        let order_id = 0; // TBD
952        let order = BookOrder::new(OrderSide::Buy, price, size, order_id);
953        let delta = OrderBookDelta::new(
954            instrument_id,
955            book_action,
956            order,
957            flags,
958            msg.seq_id,
959            ts_event,
960            ts_init,
961        );
962        deltas.push(delta);
963    }
964
965    for ask in &msg.asks {
966        let book_action = match action {
967            OKXBookAction::Snapshot => BookAction::Add,
968            _ => match ask.size.as_str() {
969                "0" => BookAction::Delete,
970                _ => BookAction::Update,
971            },
972        };
973        let price = parse_price(&ask.price, price_precision)?;
974        let size = parse_quantity(&ask.size, size_precision)?;
975        let order_id = 0; // TBD
976        let order = BookOrder::new(OrderSide::Sell, price, size, order_id);
977        let delta = OrderBookDelta::new(
978            instrument_id,
979            book_action,
980            order,
981            flags,
982            msg.seq_id,
983            ts_event,
984            ts_init,
985        );
986        deltas.push(delta);
987    }
988
989    // The data engine only publishes a buffered batch once a delta closes the event
990    if let Some(last) = deltas.last_mut() {
991        last.flags |= RecordFlag::F_LAST as u8;
992    }
993
994    OrderBookDeltas::new_checked(instrument_id, deltas)
995}
996
997/// Parses an RPI book message into Nautilus order book deltas.
998///
999/// # Errors
1000///
1001/// Returns an error if a price or total quantity cannot be represented at the instrument precision.
1002pub fn parse_rpi_book_msg(
1003    msg: &OKXRpiBookMsg,
1004    instrument_id: InstrumentId,
1005    price_precision: u8,
1006    size_precision: u8,
1007    action: &OKXBookAction,
1008    ts_init: UnixNanos,
1009) -> anyhow::Result<OrderBookDeltas> {
1010    let is_snapshot = action == &OKXBookAction::Snapshot;
1011
1012    let flags = if is_snapshot {
1013        RecordFlag::F_SNAPSHOT as u8
1014    } else {
1015        0
1016    };
1017    let ts_event = parse_millisecond_timestamp(msg.ts);
1018    let mut deltas = Vec::with_capacity(msg.asks.len() + msg.bids.len() + usize::from(is_snapshot));
1019
1020    if is_snapshot {
1021        deltas.push(OrderBookDelta::clear(
1022            instrument_id,
1023            msg.seq_id,
1024            ts_event,
1025            ts_init,
1026        ));
1027    }
1028
1029    for bid in &msg.bids {
1030        let book_action = if action == &OKXBookAction::Snapshot {
1031            BookAction::Add
1032        } else if bid.1.is_zero() {
1033            BookAction::Delete
1034        } else {
1035            BookAction::Update
1036        };
1037        let price = Price::from_decimal_dp(bid.0, price_precision)?;
1038        let size = Quantity::from_decimal_dp(bid.1, size_precision)?;
1039        let order = BookOrder::new(OrderSide::Buy, price, size, 0);
1040        deltas.push(OrderBookDelta::new(
1041            instrument_id,
1042            book_action,
1043            order,
1044            flags,
1045            msg.seq_id,
1046            ts_event,
1047            ts_init,
1048        ));
1049    }
1050
1051    for ask in &msg.asks {
1052        let book_action = if action == &OKXBookAction::Snapshot {
1053            BookAction::Add
1054        } else if ask.1.is_zero() {
1055            BookAction::Delete
1056        } else {
1057            BookAction::Update
1058        };
1059        let price = Price::from_decimal_dp(ask.0, price_precision)?;
1060        let size = Quantity::from_decimal_dp(ask.1, size_precision)?;
1061        let order = BookOrder::new(OrderSide::Sell, price, size, 0);
1062        deltas.push(OrderBookDelta::new(
1063            instrument_id,
1064            book_action,
1065            order,
1066            flags,
1067            msg.seq_id,
1068            ts_event,
1069            ts_init,
1070        ));
1071    }
1072
1073    // The data engine only publishes a buffered batch once a delta closes the event
1074    if let Some(last) = deltas.last_mut() {
1075        last.flags |= RecordFlag::F_LAST as u8;
1076    }
1077
1078    OrderBookDeltas::new_checked(instrument_id, deltas)
1079}
1080
1081/// Parses an OKX book message into a Nautilus quote tick.
1082///
1083/// # Errors
1084///
1085/// Returns an error if any quote levels contain values that cannot be parsed.
1086pub fn parse_quote_msg(
1087    msg: &OKXBookMsg,
1088    instrument_id: InstrumentId,
1089    price_precision: u8,
1090    size_precision: u8,
1091    ts_init: UnixNanos,
1092) -> anyhow::Result<QuoteTick> {
1093    let best_bid: &OrderBookEntry = msg
1094        .bids
1095        .first()
1096        .ok_or_else(|| anyhow::anyhow!("Empty bids array for {instrument_id}"))?;
1097    let best_ask: &OrderBookEntry = msg
1098        .asks
1099        .first()
1100        .ok_or_else(|| anyhow::anyhow!("Empty asks array for {instrument_id}"))?;
1101
1102    let bid_price = parse_price(&best_bid.price, price_precision)?;
1103    let ask_price = parse_price(&best_ask.price, price_precision)?;
1104    let bid_size = parse_quantity(&best_bid.size, size_precision)?;
1105    let ask_size = parse_quantity(&best_ask.size, size_precision)?;
1106    let ts_event = parse_millisecond_timestamp(msg.ts);
1107
1108    QuoteTick::new_checked(
1109        instrument_id,
1110        bid_price,
1111        ask_price,
1112        bid_size,
1113        ask_size,
1114        ts_event,
1115        ts_init,
1116    )
1117}
1118
1119/// Parses an OKX book message into a Nautilus [`OrderBookDepth`].
1120///
1121/// Uses venue order counts for the snapshot's non-empty price levels.
1122///
1123/// # Errors
1124///
1125/// Returns an error if price, size, or order count fields cannot be parsed for any level.
1126pub fn parse_book_depth_msg(
1127    msg: &OKXBookMsg,
1128    instrument_id: InstrumentId,
1129    price_precision: u8,
1130    size_precision: u8,
1131    ts_init: UnixNanos,
1132) -> anyhow::Result<OrderBookDepth> {
1133    let mut bids = Vec::with_capacity(msg.bids.len());
1134    let mut asks = Vec::with_capacity(msg.asks.len());
1135    let mut bid_counts = Vec::with_capacity(msg.bids.len());
1136    let mut ask_counts = Vec::with_capacity(msg.asks.len());
1137
1138    for (levels, side, orders, counts) in [
1139        (&msg.bids, OrderSide::Buy, &mut bids, &mut bid_counts),
1140        (&msg.asks, OrderSide::Sell, &mut asks, &mut ask_counts),
1141    ] {
1142        for level in levels {
1143            orders.push(BookOrder::new(
1144                side,
1145                parse_price(&level.price, price_precision)?,
1146                parse_quantity(&level.size, size_precision)?,
1147                0,
1148            ));
1149            counts.push(
1150                level
1151                    .orders_count
1152                    .parse::<u32>()
1153                    .context("invalid OKX order count")?,
1154            );
1155        }
1156    }
1157
1158    let ts_event = parse_millisecond_timestamp(msg.ts);
1159
1160    Ok(OrderBookDepth::new(
1161        instrument_id,
1162        bids,
1163        asks,
1164        bid_counts,
1165        ask_counts,
1166        RecordFlag::F_SNAPSHOT as u8,
1167        msg.seq_id, // Use sequence ID for OKX L2 books
1168        ts_event,
1169        ts_init,
1170    ))
1171}
1172
1173/// Parses an OKX ticker message into a Nautilus quote tick.
1174///
1175/// # Errors
1176///
1177/// Returns an error if bid or ask values cannot be parsed from the message.
1178pub fn parse_ticker_msg(
1179    msg: &OKXTickerMsg,
1180    instrument_id: InstrumentId,
1181    price_precision: u8,
1182    size_precision: u8,
1183    ts_init: UnixNanos,
1184) -> anyhow::Result<QuoteTick> {
1185    let bid_price = parse_price(&msg.bid_px, price_precision)?;
1186    let ask_price = parse_price(&msg.ask_px, price_precision)?;
1187    let bid_size = parse_quantity(&msg.bid_sz, size_precision)?;
1188    let ask_size = parse_quantity(&msg.ask_sz, size_precision)?;
1189    let ts_event = parse_millisecond_timestamp(msg.ts);
1190
1191    QuoteTick::new_checked(
1192        instrument_id,
1193        bid_price,
1194        ask_price,
1195        bid_size,
1196        ask_size,
1197        ts_event,
1198        ts_init,
1199    )
1200}
1201
1202/// Parses an OKX trade message into a Nautilus trade tick.
1203///
1204/// # Errors
1205///
1206/// Returns an error if trade prices or sizes cannot be parsed.
1207pub fn parse_trade_msg(
1208    msg: &OKXTradeMsg,
1209    instrument_id: InstrumentId,
1210    price_precision: u8,
1211    size_precision: u8,
1212    ts_init: UnixNanos,
1213) -> anyhow::Result<TradeTick> {
1214    let price = parse_price(&msg.px, price_precision)?;
1215    let size = parse_quantity(&msg.sz, size_precision)?;
1216    let aggressor_side: AggressorSide = msg.side.into();
1217    let trade_id = TradeId::new(&msg.trade_id);
1218    let ts_event = parse_millisecond_timestamp(msg.ts);
1219
1220    TradeTick::new_checked(
1221        instrument_id,
1222        price,
1223        size,
1224        aggressor_side,
1225        trade_id,
1226        ts_event,
1227        ts_init,
1228    )
1229}
1230
1231/// Parses an OKX mark price message into a Nautilus mark price update.
1232///
1233/// # Errors
1234///
1235/// Returns an error if the mark price fails to parse.
1236pub fn parse_mark_price_msg(
1237    msg: &OKXMarkPriceMsg,
1238    instrument_id: InstrumentId,
1239    price_precision: u8,
1240    ts_init: UnixNanos,
1241) -> anyhow::Result<MarkPriceUpdate> {
1242    let price = parse_price(&msg.mark_px, price_precision)?;
1243    let ts_event = parse_millisecond_timestamp(msg.ts);
1244
1245    Ok(MarkPriceUpdate::new(
1246        instrument_id,
1247        price,
1248        ts_event,
1249        ts_init,
1250    ))
1251}
1252
1253/// Parses an OKX index price message into a Nautilus index price update.
1254///
1255/// # Errors
1256///
1257/// Returns an error if the index price fails to parse.
1258pub fn parse_index_price_msg(
1259    msg: &OKXIndexPriceMsg,
1260    instrument_id: InstrumentId,
1261    price_precision: u8,
1262    ts_init: UnixNanos,
1263) -> anyhow::Result<IndexPriceUpdate> {
1264    let price = parse_price(&msg.idx_px, price_precision)?;
1265    let ts_event = parse_millisecond_timestamp(msg.ts);
1266
1267    Ok(IndexPriceUpdate::new(
1268        instrument_id,
1269        price,
1270        ts_event,
1271        ts_init,
1272    ))
1273}
1274
1275/// Parses an OKX candle message into a Nautilus bar.
1276///
1277/// # Errors
1278///
1279/// Returns an error if candle price or volume fields cannot be parsed.
1280pub fn parse_candle_msg(
1281    msg: &OKXCandleMsg,
1282    bar_type: BarType,
1283    price_precision: u8,
1284    size_precision: u8,
1285    ts_init: UnixNanos,
1286) -> anyhow::Result<Bar> {
1287    let open = parse_price(&msg.o, price_precision)?;
1288    let high = parse_price(&msg.h, price_precision)?;
1289    let low = parse_price(&msg.l, price_precision)?;
1290    let close = parse_price(&msg.c, price_precision)?;
1291    let volume = parse_quantity(&msg.vol, size_precision)?;
1292    let ts_event = parse_millisecond_timestamp(msg.ts);
1293
1294    Bar::new_checked(bar_type, open, high, low, close, volume, ts_event, ts_init)
1295}
1296
1297/// Parses vector of OKX order messages into Nautilus execution reports.
1298///
1299/// # Errors
1300///
1301/// Returns an error if any contained order messages cannot be parsed.
1302pub fn parse_order_msg_vec(
1303    data: &[OKXOrderMsg],
1304    account_id: AccountId,
1305    instruments: &AHashMap<Ustr, InstrumentAny>,
1306    fee_cache: &mut FeeCache,
1307    filled_qty_cache: &mut FilledQtyCache,
1308    ts_init: UnixNanos,
1309) -> anyhow::Result<Vec<ExecutionReport>> {
1310    let mut order_reports = Vec::with_capacity(data.len());
1311
1312    for msg in data {
1313        match parse_order_msg(
1314            msg,
1315            account_id,
1316            instruments,
1317            fee_cache,
1318            filled_qty_cache,
1319            ts_init,
1320        ) {
1321            Ok(report) => {
1322                order_reports.push(report);
1323
1324                if let Some(instrument) = instruments.get(&msg.inst_id) {
1325                    update_fee_fill_caches(msg, instrument, fee_cache, filled_qty_cache);
1326                }
1327            }
1328            Err(e) => log::error!("Failed to parse execution report from message: {e}"),
1329        }
1330    }
1331
1332    Ok(order_reports)
1333}
1334
1335/// Updates fee and fill caches from a raw OKX order message.
1336///
1337/// Call after parsing each message so subsequent messages in the same batch
1338/// see the correct cumulative fee and filled quantity.
1339pub fn update_fee_fill_caches(
1340    msg: &OKXOrderMsg,
1341    instrument: &InstrumentAny,
1342    fee_cache: &mut FeeCache,
1343    filled_qty_cache: &mut FilledQtyCache,
1344) {
1345    let is_terminal = is_terminal_order_state(msg.state);
1346    if let Some(previous) = filled_qty_cache.get(&msg.ord_id).copied()
1347        && msg
1348            .acc_fill_sz
1349            .as_deref()
1350            .and_then(|quantity| parse_quantity(quantity, instrument.size_precision()).ok())
1351            .is_none_or(|quantity| quantity.is_zero())
1352    {
1353        if is_terminal {
1354            if let Some(fee) = fee_cache.get(&msg.ord_id).copied() {
1355                fee_cache.record(msg.ord_id, fee, true);
1356            }
1357
1358            filled_qty_cache.record(msg.ord_id, previous, true);
1359        }
1360
1361        return;
1362    }
1363
1364    if let Some(ref fee_str) = msg.fee
1365        && !fee_str.is_empty()
1366    {
1367        let fee_dec = Decimal::from_str(fee_str).unwrap_or_default();
1368        let fee_ccy = parse_fee_currency(msg.fee_ccy.as_str(), fee_dec, || {
1369            format!("update_fee_fill_caches ord_id={}", msg.ord_id)
1370        });
1371
1372        if let Ok(total_fee) = crate::common::parse::parse_fee(Some(fee_str.as_str()), fee_ccy) {
1373            fee_cache.record(msg.ord_id, total_fee, is_terminal);
1374        }
1375    }
1376
1377    if let Some(ref acc_fill_sz) = msg.acc_fill_sz
1378        && !acc_fill_sz.is_empty()
1379        && acc_fill_sz != "0"
1380        && let Ok(qty) = parse_quantity(acc_fill_sz, instrument.size_precision())
1381    {
1382        filled_qty_cache.record(msg.ord_id, qty, is_terminal);
1383    }
1384}
1385
1386/// Checks if `acc_fill_sz` has increased compared to the previous filled quantity.
1387fn has_acc_fill_sz_increased(
1388    acc_fill_sz: Option<&str>,
1389    previous_filled_qty: Option<Quantity>,
1390    size_precision: u8,
1391) -> bool {
1392    if let Some(acc_str) = acc_fill_sz {
1393        if acc_str.is_empty() || acc_str == "0" {
1394            return false;
1395        }
1396
1397        if let Ok(current_filled) = parse_quantity(acc_str, size_precision) {
1398            if let Some(prev_qty) = previous_filled_qty {
1399                return current_filled > prev_qty;
1400            }
1401            return !current_filled.is_zero();
1402        }
1403    }
1404    false
1405}
1406
1407/// Parses a single OKX order message into an [`ExecutionReport`].
1408///
1409/// # Errors
1410///
1411/// Returns an error if the instrument cannot be found or if parsing the
1412/// underlying order payload fails.
1413pub fn parse_order_msg(
1414    msg: &OKXOrderMsg,
1415    account_id: AccountId,
1416    instruments: &AHashMap<Ustr, InstrumentAny>,
1417    fee_cache: &FeeCache,
1418    filled_qty_cache: &FilledQtyCache,
1419    ts_init: UnixNanos,
1420) -> anyhow::Result<ExecutionReport> {
1421    let instrument = instruments
1422        .get(&msg.inst_id)
1423        .ok_or_else(|| anyhow::anyhow!("No instrument found for inst_id: {}", msg.inst_id))?;
1424
1425    let previous_fee = fee_cache.get(&msg.ord_id).copied();
1426    let previous_filled_qty = filled_qty_cache.get(&msg.ord_id).copied();
1427
1428    let has_new_fill = (!msg.fill_sz.is_empty() && msg.fill_sz != "0")
1429        || !msg.trade_id.is_empty()
1430        || has_acc_fill_sz_increased(
1431            msg.acc_fill_sz.as_deref(),
1432            previous_filled_qty,
1433            instrument.size_precision(),
1434        );
1435
1436    warn_unrecognized_order_state(msg);
1437
1438    match msg.state {
1439        OKXOrderStatus::Filled | OKXOrderStatus::PartiallyFilled | OKXOrderStatus::Unknown
1440            if has_new_fill =>
1441        {
1442            match parse_fill_report(
1443                msg,
1444                instrument,
1445                account_id,
1446                previous_fee,
1447                previous_filled_qty,
1448                ts_init,
1449            )? {
1450                Some(report) => Ok(ExecutionReport::Fill(report)),
1451                None => parse_order_status_report(msg, instrument, account_id, ts_init)
1452                    .map(ExecutionReport::Order),
1453            }
1454        }
1455        _ => parse_order_status_report(msg, instrument, account_id, ts_init)
1456            .map(ExecutionReport::Order),
1457    }
1458}
1459
1460/// Logs a warning when an order message carries a state this build does not
1461/// recognize. Fill data on the message is still processed; only the status
1462/// classification is skipped.
1463fn warn_unrecognized_order_state(msg: &OKXOrderMsg) {
1464    if msg.state == OKXOrderStatus::Unknown {
1465        log::warn!(
1466            "Unrecognized order state: order_id={}, inst_id={}, processing any fill data and skipping status classification",
1467            msg.ord_id,
1468            msg.inst_id,
1469        );
1470    }
1471}
1472
1473/// Parses a single OKX spread order message into an [`ExecutionReport`].
1474///
1475/// # Errors
1476///
1477/// Returns an error if the instrument cannot be found or if parsing the
1478/// underlying order payload fails.
1479pub fn parse_spread_order_msg(
1480    msg: &OKXSpreadOrder,
1481    account_id: AccountId,
1482    instruments: &AHashMap<Ustr, InstrumentAny>,
1483    filled_qty_cache: &FilledQtyCache,
1484    ts_init: UnixNanos,
1485) -> anyhow::Result<ExecutionReport> {
1486    let instrument = instruments
1487        .get(&msg.sprd_id)
1488        .ok_or_else(|| anyhow::anyhow!("No instrument found for sprd_id: {}", msg.sprd_id))?;
1489    let previous_filled_qty = filled_qty_cache.get(&msg.ord_id).copied();
1490    let has_new_fill = (!msg.fill_sz.is_empty() && msg.fill_sz != "0")
1491        || !msg.trade_id.is_empty()
1492        || has_acc_fill_sz_increased(
1493            Some(msg.acc_fill_sz.as_str()),
1494            previous_filled_qty,
1495            instrument.size_precision(),
1496        );
1497
1498    match msg.state {
1499        OKXOrderStatus::Filled | OKXOrderStatus::PartiallyFilled if has_new_fill => {
1500            match parse_spread_order_fill_report(
1501                msg,
1502                instrument,
1503                account_id,
1504                previous_filled_qty,
1505                ts_init,
1506            )? {
1507                Some(report) => Ok(ExecutionReport::Fill(report)),
1508                None => parse_common_spread_order_status_report(
1509                    msg,
1510                    account_id,
1511                    instrument.id(),
1512                    instrument.price_precision(),
1513                    instrument.size_precision(),
1514                    ts_init,
1515                )
1516                .map(ExecutionReport::Order),
1517            }
1518        }
1519        _ => parse_common_spread_order_status_report(
1520            msg,
1521            account_id,
1522            instrument.id(),
1523            instrument.price_precision(),
1524            instrument.size_precision(),
1525            ts_init,
1526        )
1527        .map(ExecutionReport::Order),
1528    }
1529}
1530
1531/// Parses an OKX algo order message into a Nautilus execution report.
1532///
1533/// # Errors
1534///
1535/// Returns an error if the instrument cannot be found or if message fields
1536/// fail to parse.
1537pub fn parse_algo_order_msg(
1538    msg: &OKXAlgoOrderMsg,
1539    account_id: AccountId,
1540    instruments: &AHashMap<Ustr, InstrumentAny>,
1541    ts_init: UnixNanos,
1542) -> anyhow::Result<Option<ExecutionReport>> {
1543    // Skip unsupported algo types (iceberg, smart_iceberg, twap, chase); their
1544    // triggered child orders still arrive on the regular orders channel
1545    if matches!(
1546        msg.ord_type,
1547        OKXAlgoOrderType::Iceberg
1548            | OKXAlgoOrderType::SmartIceberg
1549            | OKXAlgoOrderType::Twap
1550            | OKXAlgoOrderType::Chase
1551    ) {
1552        log::debug!("Skipping unsupported algo order type: {:?}", msg.ord_type);
1553        return Ok(None);
1554    }
1555
1556    if msg.ord_type == OKXAlgoOrderType::Other {
1557        log::warn!(
1558            "Skipping algo order with unrecognized order type: algo_id={}, inst_id={}",
1559            msg.algo_id,
1560            msg.inst_id,
1561        );
1562        return Ok(None);
1563    }
1564
1565    if msg.state == OKXAlgoOrderStatus::Unknown {
1566        log::warn!(
1567            "Skipping algo order with unrecognized state: algo_id={}, inst_id={}",
1568            msg.algo_id,
1569            msg.inst_id,
1570        );
1571        return Ok(None);
1572    }
1573
1574    let inst = instruments
1575        .get(&msg.inst_id)
1576        .ok_or_else(|| anyhow::anyhow!("No instrument found for inst_id: {}", msg.inst_id))?;
1577
1578    parse_algo_order_status_report(msg, inst, account_id, ts_init)
1579        .map(ExecutionReport::Order)
1580        .map(Some)
1581}
1582
1583/// Parses an OKX algo order message into a Nautilus order status report.
1584///
1585/// # Errors
1586///
1587/// Returns an error if any order identifiers or numeric fields cannot be
1588/// parsed.
1589pub fn parse_algo_order_status_report(
1590    msg: &OKXAlgoOrderMsg,
1591    instrument: &InstrumentAny,
1592    account_id: AccountId,
1593    ts_init: UnixNanos,
1594) -> anyhow::Result<OrderStatusReport> {
1595    let client_order_id = parse_parent_client_order_id(Some(&msg.algo_cl_ord_id), &msg.cl_ord_id);
1596
1597    // For algo orders that haven't triggered, ord_id will be empty, use algo_id instead
1598    let venue_order_id = if msg.ord_id.is_empty() {
1599        VenueOrderId::new(msg.algo_id.as_str())
1600    } else {
1601        VenueOrderId::new(msg.ord_id.as_str())
1602    };
1603
1604    let order_side = OrderSide::from(msg.side);
1605
1606    let algo_fields = parse_algo_order_fields(msg)?;
1607
1608    let status: OrderStatus = msg
1609        .state
1610        .try_into()
1611        .map_err(|e| anyhow::anyhow!("Unsupported OKX algo order status: {e}"))?;
1612
1613    let quantity = parse_algo_order_quantity(msg, instrument)?;
1614
1615    let filled_qty = if msg.state == OKXAlgoOrderStatus::Filled
1616        && !msg.actual_sz.is_empty()
1617        && msg.actual_sz != "0"
1618    {
1619        parse_quantity(msg.actual_sz.as_str(), instrument.size_precision())?
1620    } else {
1621        Quantity::zero(instrument.size_precision())
1622    };
1623
1624    // Parse limit price if it exists (not -1)
1625    let price = if is_market_price(algo_fields.ord_px) {
1626        None
1627    } else {
1628        Some(parse_price(
1629            algo_fields.ord_px,
1630            instrument.price_precision(),
1631        )?)
1632    };
1633
1634    let trigger_type = match algo_fields.trigger_px_type {
1635        OKXTriggerType::Last => TriggerType::LastPrice,
1636        OKXTriggerType::Mark => TriggerType::MarkPrice,
1637        OKXTriggerType::Index => TriggerType::IndexPrice,
1638        OKXTriggerType::None => TriggerType::Default,
1639    };
1640
1641    let ts_accepted = parse_millisecond_timestamp(msg.c_time);
1642    let ts_last = parse_millisecond_timestamp(msg.u_time);
1643
1644    let mut report = OrderStatusReport::new(
1645        account_id,
1646        instrument.id(),
1647        client_order_id,
1648        venue_order_id,
1649        order_side.into(),
1650        algo_fields.order_type,
1651        TimeInForce::Gtc,
1652        status,
1653        quantity,
1654        filled_qty,
1655        ts_accepted,
1656        ts_last,
1657        ts_init,
1658        None,
1659    );
1660
1661    if !algo_fields.trigger_px.is_empty() {
1662        report.trigger_price = Some(parse_price(
1663            algo_fields.trigger_px,
1664            instrument.price_precision(),
1665        )?);
1666    }
1667
1668    report.trigger_type = Some(trigger_type);
1669    report.venue_position_id = venue_position_id(instrument.id(), msg.pos_side);
1670    if let Some(limit_price) = price {
1671        report.price = Some(limit_price);
1672    }
1673
1674    if algo_fields.order_type == OrderType::TrailingStopMarket {
1675        if !msg.callback_ratio.is_empty() {
1676            // OKX ratio is e.g. "0.01" for 1%, convert to basis points
1677            let ratio = Decimal::from_str(&msg.callback_ratio)?;
1678            report.trailing_offset = Some(ratio * Decimal::new(10_000, 0));
1679            report.trailing_offset_type = Some(TrailingOffsetType::BasisPoints);
1680        } else if !msg.callback_spread.is_empty() {
1681            report.trailing_offset = Some(Decimal::from_str(&msg.callback_spread)?);
1682            report.trailing_offset_type = Some(TrailingOffsetType::Price);
1683        }
1684
1685        if !msg.active_px.is_empty() {
1686            report.activation_price =
1687                Some(parse_price(&msg.active_px, instrument.price_precision())?);
1688        }
1689    }
1690
1691    if msg.reduce_only == "true" {
1692        report = report.with_reduce_only(true);
1693    }
1694
1695    Ok(report)
1696}
1697
1698struct AlgoOrderFields<'a> {
1699    order_type: OrderType,
1700    trigger_px: &'a str,
1701    trigger_px_type: OKXTriggerType,
1702    ord_px: &'a str,
1703}
1704
1705fn parse_algo_order_fields(msg: &OKXAlgoOrderMsg) -> anyhow::Result<AlgoOrderFields<'_>> {
1706    match msg.ord_type {
1707        OKXAlgoOrderType::MoveOrderStop => Ok(AlgoOrderFields {
1708            order_type: OrderType::TrailingStopMarket,
1709            trigger_px: msg.trigger_px.as_str(),
1710            trigger_px_type: msg.trigger_px_type,
1711            ord_px: msg.ord_px.as_str(),
1712        }),
1713        OKXAlgoOrderType::Conditional | OKXAlgoOrderType::Oco => {
1714            if msg.tp_trigger_px.is_empty() {
1715                let (trigger_px, trigger_px_type, ord_px) = if msg.sl_trigger_px.is_empty() {
1716                    (
1717                        msg.trigger_px.as_str(),
1718                        msg.trigger_px_type,
1719                        msg.ord_px.as_str(),
1720                    )
1721                } else {
1722                    (
1723                        msg.sl_trigger_px.as_str(),
1724                        msg.sl_trigger_px_type,
1725                        msg.sl_ord_px.as_str(),
1726                    )
1727                };
1728
1729                Ok(AlgoOrderFields {
1730                    order_type: if is_market_price(ord_px) {
1731                        OrderType::StopMarket
1732                    } else {
1733                        OrderType::StopLimit
1734                    },
1735                    trigger_px,
1736                    trigger_px_type,
1737                    ord_px,
1738                })
1739            } else {
1740                let ord_px = msg.tp_ord_px.as_str();
1741                Ok(AlgoOrderFields {
1742                    order_type: if is_market_price(ord_px) {
1743                        OrderType::MarketIfTouched
1744                    } else {
1745                        OrderType::LimitIfTouched
1746                    },
1747                    trigger_px: msg.tp_trigger_px.as_str(),
1748                    trigger_px_type: msg.tp_trigger_px_type,
1749                    ord_px,
1750                })
1751            }
1752        }
1753        OKXAlgoOrderType::Trigger => Ok(AlgoOrderFields {
1754            order_type: if is_market_price(&msg.ord_px) {
1755                OrderType::StopMarket
1756            } else {
1757                OrderType::StopLimit
1758            },
1759            trigger_px: msg.trigger_px.as_str(),
1760            trigger_px_type: msg.trigger_px_type,
1761            ord_px: msg.ord_px.as_str(),
1762        }),
1763        _ => anyhow::bail!("Unsupported algo order type: {:?}", msg.ord_type),
1764    }
1765}
1766
1767fn parse_algo_order_quantity(
1768    msg: &OKXAlgoOrderMsg,
1769    instrument: &InstrumentAny,
1770) -> anyhow::Result<Quantity> {
1771    if !msg.sz.is_empty() {
1772        return parse_quantity(msg.sz.as_str(), instrument.size_precision());
1773    }
1774
1775    if !msg.close_fraction.is_empty()
1776        || !msg.sl_trigger_px.is_empty()
1777        || !msg.tp_trigger_px.is_empty()
1778    {
1779        return Ok(Quantity::zero(instrument.size_precision()));
1780    }
1781
1782    anyhow::bail!("Missing sz for algo order {}", msg.algo_id)
1783}
1784
1785/// Parses an OKX order message into a Nautilus order status report.
1786///
1787/// # Errors
1788///
1789/// Returns an error if order metadata or numeric values cannot be parsed.
1790pub fn parse_order_status_report(
1791    msg: &OKXOrderMsg,
1792    instrument: &InstrumentAny,
1793    account_id: AccountId,
1794    ts_init: UnixNanos,
1795) -> anyhow::Result<OrderStatusReport> {
1796    let client_order_id =
1797        parse_parent_client_order_id(msg.algo_cl_ord_id.as_deref(), &msg.cl_ord_id);
1798    let venue_order_id = VenueOrderId::new(msg.ord_id);
1799    let order_side = OrderSide::from(msg.side);
1800
1801    let okx_order_type = msg.ord_type;
1802
1803    // Determine order type based on presence of limit price for certain OKX order types
1804    let order_type = match okx_order_type {
1805        OKXOrderType::Trigger => {
1806            if is_market_price(&msg.px) {
1807                OrderType::StopMarket
1808            } else {
1809                OrderType::StopLimit
1810            }
1811        }
1812        OKXOrderType::Fok | OKXOrderType::Ioc | OKXOrderType::OptimalLimitIoc => {
1813            determine_order_type_with_alt(
1814                okx_order_type,
1815                &msg.px,
1816                msg.px_vol.as_deref().unwrap_or(""),
1817                msg.px_usd.as_deref().unwrap_or(""),
1818            )?
1819        }
1820        other => other
1821            .try_into()
1822            .map_err(|e| anyhow::anyhow!("Unsupported OKX order type: {e}"))?,
1823    };
1824    let order_status: OrderStatus = msg
1825        .state
1826        .try_into()
1827        .map_err(|e| anyhow::anyhow!("Unsupported OKX order status: {e}"))?;
1828
1829    let time_in_force = match okx_order_type {
1830        OKXOrderType::Fok | OKXOrderType::OpFok => TimeInForce::Fok,
1831        OKXOrderType::Ioc | OKXOrderType::OptimalLimitIoc => TimeInForce::Ioc,
1832        _ => TimeInForce::Gtc,
1833    };
1834
1835    let size_precision = instrument.size_precision();
1836
1837    // Parse quantities based on target currency
1838    // OKX always returns acc_fill_sz in base currency, but sz depends on tgt_ccy
1839
1840    // Determine if this is a quote-quantity order
1841    // Method 1: Explicit tgt_ccy field set to QuoteCcy
1842    let is_quote_qty_explicit = msg.tgt_ccy == Some(OKXTargetCurrency::QuoteCcy);
1843
1844    // Method 2: Use OKX defaults when tgt_ccy is None (old orders or missing field)
1845    // OKX API defaults for SPOT market orders: BUY orders use quote_ccy, SELL orders use base_ccy
1846    // Note: tgtCcy only applies to SPOT market orders (not limit orders)
1847    // For limit orders, sz is always in base currency regardless of side
1848    let is_quote_qty_heuristic = msg.tgt_ccy.is_none()
1849        && (msg.inst_type == OKXInstrumentType::Spot || msg.inst_type == OKXInstrumentType::Margin)
1850        && msg.side == OKXSide::Buy
1851        && order_type == OrderType::Market;
1852
1853    let (quantity, filled_qty) = if is_quote_qty_explicit || is_quote_qty_heuristic {
1854        // Quote-quantity order: sz is in quote currency, need to convert to base
1855        let sz_quote_dec = Decimal::from_str(&msg.sz).map_err(|e| {
1856            anyhow::anyhow!("Failed to parse sz='{}' as quote quantity: {}", msg.sz, e)
1857        })?;
1858
1859        // Determine the price to use for conversion
1860        // Priority: 1) limit price (px) for limit orders, 2) avg_px for market orders
1861        let conversion_price_dec =
1862            if !is_market_price(&msg.px) {
1863                // Limit order: use the limit price (msg.px)
1864                Some(
1865                    Decimal::from_str(&msg.px)
1866                        .map_err(|e| anyhow::anyhow!("Failed to parse px='{}': {}", msg.px, e))?,
1867                )
1868            } else if !msg.avg_px.is_empty() && msg.avg_px != "0" {
1869                // Market order with fills: use average fill price
1870                Some(Decimal::from_str(&msg.avg_px).map_err(|e| {
1871                    anyhow::anyhow!("Failed to parse avg_px='{}': {}", msg.avg_px, e)
1872                })?)
1873            } else {
1874                None
1875            };
1876
1877        // Convert quote quantity to base: quantity_base = sz_quote / price
1878        let quantity_base = if let Some(price) = conversion_price_dec {
1879            if price.is_zero() {
1880                parse_quantity(&msg.sz, size_precision)?
1881            } else {
1882                Quantity::from_decimal_dp(sz_quote_dec / price, size_precision)?
1883            }
1884        } else {
1885            // No price available, can't convert - use sz as-is temporarily
1886            // This will be corrected once the order gets filled and price is available
1887            parse_quantity(&msg.sz, size_precision)?
1888        };
1889
1890        let filled_qty = parse_quantity(msg.acc_fill_sz.as_deref().unwrap_or(""), size_precision)?;
1891
1892        (quantity_base, filled_qty)
1893    } else {
1894        // Base-quantity order: both sz and acc_fill_sz are in base currency
1895        let quantity = parse_quantity(&msg.sz, size_precision)?;
1896        let filled_qty = parse_quantity(msg.acc_fill_sz.as_deref().unwrap_or(""), size_precision)?;
1897
1898        (quantity, filled_qty)
1899    };
1900
1901    // Normalize quote conversion and base shortfalls to the venue's terminal filled size
1902    let quantity = if msg.state == OKXOrderStatus::Filled && filled_qty.is_positive() {
1903        filled_qty
1904    } else {
1905        quantity
1906    };
1907
1908    let ts_accepted = parse_millisecond_timestamp(msg.c_time);
1909    let ts_last = parse_millisecond_timestamp(msg.u_time);
1910
1911    let is_liquidation = matches!(
1912        msg.category,
1913        OKXOrderCategory::FullLiquidation | OKXOrderCategory::PartialLiquidation
1914    );
1915
1916    let is_adl = msg.category == OKXOrderCategory::Adl;
1917
1918    if is_liquidation {
1919        log::warn!(
1920            "Liquidation order status update: order_id={}, category={:?}, inst_id={}, state={:?}",
1921            msg.ord_id.as_str(),
1922            msg.category,
1923            msg.inst_id.as_str(),
1924            msg.state,
1925        );
1926    }
1927
1928    if is_adl {
1929        log::warn!(
1930            "ADL (Auto-Deleveraging) order status update: order_id={}, inst_id={}, state={:?}",
1931            msg.ord_id.as_str(),
1932            msg.inst_id.as_str(),
1933            msg.state,
1934        );
1935    }
1936
1937    let mut report = OrderStatusReport::new(
1938        account_id,
1939        instrument.id(),
1940        client_order_id,
1941        venue_order_id,
1942        order_side.into(),
1943        order_type,
1944        time_in_force,
1945        order_status,
1946        quantity,
1947        filled_qty,
1948        ts_accepted,
1949        ts_last,
1950        ts_init,
1951        None, // Generate UUID4 automatically
1952    );
1953
1954    let price_precision = instrument.price_precision();
1955
1956    report.venue_position_id = venue_position_id(instrument.id(), msg.pos_side);
1957
1958    if okx_order_type == OKXOrderType::Trigger {
1959        // For triggered orders coming through regular orders channel,
1960        // set the price if it's a stop-limit order
1961        if !is_market_price(&msg.px)
1962            && let Ok(price) = parse_price(&msg.px, price_precision)
1963        {
1964            report = report.with_price(price);
1965        }
1966    } else {
1967        // For regular orders, use px field
1968        if !is_market_price(&msg.px)
1969            && let Ok(price) = parse_price(&msg.px, price_precision)
1970        {
1971            report = report.with_price(price);
1972        }
1973    }
1974
1975    if !msg.avg_px.is_empty()
1976        && let Ok(decimal) = Decimal::from_str(&msg.avg_px)
1977    {
1978        report.avg_px = Some(decimal);
1979    }
1980
1981    if matches!(
1982        msg.ord_type,
1983        OKXOrderType::PostOnly | OKXOrderType::Rpi | OKXOrderType::MmpAndPostOnly
1984    ) || matches!(
1985        msg.cancel_source.as_deref(),
1986        Some(source) if source == OKX_POST_ONLY_CANCEL_SOURCE
1987    ) || matches!(
1988        msg.cancel_source_reason.as_deref(),
1989        Some(reason) if reason.contains("POST_ONLY")
1990    ) {
1991        report = report.with_post_only(true);
1992    }
1993
1994    if msg.reduce_only == "true" {
1995        report = report.with_reduce_only(true);
1996    }
1997
1998    let mut linked_ids = Vec::new();
1999
2000    if let Some(algo_cl_ord_id) = msg
2001        .algo_cl_ord_id
2002        .as_ref()
2003        .filter(|value| !value.is_empty())
2004    {
2005        let algo_client_id = ClientOrderId::new(algo_cl_ord_id.as_str());
2006        if report.client_order_id != Some(algo_client_id) {
2007            linked_ids.push(algo_client_id);
2008        }
2009    }
2010
2011    if let Some(attach_algo_cl_ord_id) = msg
2012        .attach_algo_cl_ord_id
2013        .as_ref()
2014        .filter(|value| !value.is_empty())
2015    {
2016        let attach_client_id = ClientOrderId::new(attach_algo_cl_ord_id.as_str());
2017        if report.client_order_id != Some(attach_client_id)
2018            && !linked_ids.contains(&attach_client_id)
2019        {
2020            linked_ids.push(attach_client_id);
2021        }
2022    }
2023
2024    for attach_algo in &msg.attach_algo_ords {
2025        if attach_algo.attach_algo_cl_ord_id.is_empty() {
2026            continue;
2027        }
2028
2029        let attach_client_id = ClientOrderId::new(attach_algo.attach_algo_cl_ord_id.as_str());
2030        if report.client_order_id != Some(attach_client_id)
2031            && !linked_ids.contains(&attach_client_id)
2032        {
2033            linked_ids.push(attach_client_id);
2034        }
2035    }
2036
2037    if !linked_ids.is_empty() {
2038        report = report.with_linked_order_ids(linked_ids);
2039    }
2040
2041    if let Some(reason) = msg
2042        .cancel_source_reason
2043        .as_ref()
2044        .filter(|reason| !reason.is_empty())
2045    {
2046        report = report.with_cancel_reason(reason.clone());
2047    } else if let Some(source) = msg
2048        .cancel_source
2049        .as_ref()
2050        .filter(|source| !source.is_empty())
2051    {
2052        let reason = if source == OKX_POST_ONLY_CANCEL_SOURCE {
2053            OKX_POST_ONLY_CANCEL_REASON.to_string()
2054        } else {
2055            format!("cancel_source={source}")
2056        };
2057        report = report.with_cancel_reason(reason);
2058    }
2059
2060    Ok(report)
2061}
2062
2063fn parse_spread_order_fill_report(
2064    msg: &OKXSpreadOrder,
2065    instrument: &InstrumentAny,
2066    _account_id: AccountId,
2067    previous_filled_qty: Option<Quantity>,
2068    _ts_init: UnixNanos,
2069) -> anyhow::Result<Option<FillReport>> {
2070    let size_precision = instrument.size_precision();
2071    if !msg.fill_sz.is_empty() && msg.fill_sz != "0" {
2072        parse_quantity(&msg.fill_sz, size_precision).map_err(|e| {
2073            anyhow::anyhow!("Failed to parse spread fill_sz='{}': {e}", msg.fill_sz)
2074        })?;
2075    } else if !msg.acc_fill_sz.is_empty() && msg.acc_fill_sz != "0" {
2076        let current_filled = parse_quantity(&msg.acc_fill_sz, size_precision).map_err(|e| {
2077            anyhow::anyhow!(
2078                "Failed to parse spread acc_fill_sz='{}': {e}",
2079                msg.acc_fill_sz
2080            )
2081        })?;
2082
2083        if let Some(prev_qty) = previous_filled_qty {
2084            if current_filled < prev_qty {
2085                anyhow::bail!(
2086                    "Cumulative spread fill went backwards: acc_fill_sz='{}' < previous_filled_qty={} \
2087                     (possible stale data after reconnect)",
2088                    msg.acc_fill_sz,
2089                    prev_qty
2090                );
2091            }
2092
2093            if (current_filled - prev_qty).is_zero() {
2094                log::debug!(
2095                    "Skipping duplicate spread fill: acc_fill_sz='{}' unchanged from previous={}",
2096                    msg.acc_fill_sz,
2097                    prev_qty
2098                );
2099                return Ok(None);
2100            }
2101        }
2102    } else {
2103        anyhow::bail!(
2104            "Cannot determine spread fill quantity: fill_sz='{}' and acc_fill_sz='{}'",
2105            msg.fill_sz,
2106            msg.acc_fill_sz
2107        );
2108    }
2109
2110    anyhow::bail!(
2111        "missing fee for spread fill report sprd_id={}; OKX sprd-orders updates omit fee",
2112        msg.sprd_id
2113    )
2114}
2115
2116/// Parses an OKX order message into a Nautilus fill report.
2117///
2118/// Requires a valid cumulative fee for subsequent fee deltas, even when per-fill fees supply the
2119/// commission.
2120///
2121/// # Errors
2122///
2123/// Returns an error if order quantities, prices, or fees cannot be parsed.
2124pub fn parse_fill_report(
2125    msg: &OKXOrderMsg,
2126    instrument: &InstrumentAny,
2127    account_id: AccountId,
2128    previous_fee: Option<Money>,
2129    previous_filled_qty: Option<Quantity>,
2130    ts_init: UnixNanos,
2131) -> anyhow::Result<Option<FillReport>> {
2132    let client_order_id =
2133        parse_parent_client_order_id(msg.algo_cl_ord_id.as_deref(), &msg.cl_ord_id);
2134    let venue_order_id = VenueOrderId::new(msg.ord_id);
2135
2136    // OKX may not provide a `trade_id` (some algo trigger payloads, manual
2137    // settlements). Derive a deterministic id from the immutable fill fields
2138    // via FNV-1a so reconnect replays of the same fill collapse to one event
2139    // in the downstream `WsDispatchState::check_and_insert_trade` dedup. A
2140    // random UUID4 here would defeat dedup, since each replay would mint a
2141    // new id. The hash output keeps the synthesized id within `TradeId`'s
2142    // 36-character cap.
2143    let trade_id = if msg.trade_id.is_empty() {
2144        let synthetic = synthesize_trade_id(msg);
2145        TradeId::new(&synthetic)
2146    } else {
2147        TradeId::new(&msg.trade_id)
2148    };
2149
2150    let order_side = OrderSide::from(msg.side);
2151
2152    let price_precision = instrument.price_precision();
2153    let size_precision = instrument.size_precision();
2154
2155    let price_str = if !msg.fill_px.is_empty() {
2156        &msg.fill_px
2157    } else if !msg.avg_px.is_empty() {
2158        &msg.avg_px
2159    } else {
2160        &msg.px
2161    };
2162    let last_px = parse_price(price_str, price_precision).map_err(|e| {
2163        anyhow::anyhow!(
2164            "Failed to parse price (fill_px='{}', avg_px='{}', px='{}'): {}",
2165            msg.fill_px,
2166            msg.avg_px,
2167            msg.px,
2168            e
2169        )
2170    })?;
2171
2172    let Some(last_qty) = parse_fill_quantity(msg, previous_filled_qty, size_precision)? else {
2173        return Ok(None);
2174    };
2175
2176    let commission = parse_fill_commission(msg, previous_fee, previous_filled_qty, last_qty)?;
2177
2178    let liquidity_side: LiquiditySide = msg.exec_type.into();
2179    let ts_event = parse_millisecond_timestamp(msg.fill_time);
2180
2181    let is_liquidation = matches!(
2182        msg.category,
2183        OKXOrderCategory::FullLiquidation | OKXOrderCategory::PartialLiquidation
2184    );
2185
2186    let is_adl = msg.category == OKXOrderCategory::Adl;
2187
2188    if is_liquidation {
2189        log::warn!(
2190            "Liquidation order detected: order_id={}, category={:?}, inst_id={}, side={:?}, fill_sz={}, fill_px={}",
2191            msg.ord_id.as_str(),
2192            msg.category,
2193            msg.inst_id.as_str(),
2194            msg.side,
2195            msg.fill_sz,
2196            msg.fill_px,
2197        );
2198    }
2199
2200    if is_adl {
2201        log::warn!(
2202            "ADL (Auto-Deleveraging) order detected: order_id={}, inst_id={}, side={:?}, fill_sz={}, fill_px={}",
2203            msg.ord_id.as_str(),
2204            msg.inst_id.as_str(),
2205            msg.side,
2206            msg.fill_sz,
2207            msg.fill_px,
2208        );
2209    }
2210
2211    let report = FillReport::new(
2212        account_id,
2213        instrument.id(),
2214        venue_order_id,
2215        trade_id,
2216        order_side,
2217        last_qty,
2218        last_px,
2219        commission,
2220        liquidity_side,
2221        client_order_id,
2222        venue_position_id(instrument.id(), msg.pos_side),
2223        ts_event,
2224        ts_init,
2225        None, // Generate UUID4 automatically
2226    );
2227
2228    Ok(Some(report))
2229}
2230
2231fn parse_fill_quantity(
2232    msg: &OKXOrderMsg,
2233    previous: Option<Quantity>,
2234    precision: u8,
2235) -> anyhow::Result<Option<Quantity>> {
2236    if !msg.fill_sz.is_empty() && msg.fill_sz != "0" {
2237        return parse_quantity(&msg.fill_sz, precision)
2238            .map(Some)
2239            .map_err(|e| anyhow::anyhow!("Failed to parse fill_sz='{}': {e}", msg.fill_sz));
2240    }
2241
2242    let Some(cumulative) = msg.acc_fill_sz.as_deref() else {
2243        anyhow::bail!(
2244            "Cannot determine fill quantity: fill_sz='{}' and acc_fill_sz is None",
2245            msg.fill_sz
2246        );
2247    };
2248
2249    anyhow::ensure!(
2250        !cumulative.is_empty() && cumulative != "0",
2251        "Cannot determine fill quantity: fill_sz is empty/zero and acc_fill_sz is empty/zero",
2252    );
2253
2254    let cumulative = parse_quantity(cumulative, precision).map_err(|e| {
2255        anyhow::anyhow!(
2256            "Failed to parse acc_fill_sz='{}': {e}",
2257            msg.acc_fill_sz.as_deref().unwrap_or_default()
2258        )
2259    })?;
2260
2261    let Some(previous) = previous else {
2262        return Ok(Some(cumulative));
2263    };
2264
2265    anyhow::ensure!(
2266        cumulative >= previous,
2267        "Cumulative fill went backwards: acc_fill_sz='{}' < previous_filled_qty={previous} (possible stale data after reconnect)",
2268        msg.acc_fill_sz.as_deref().unwrap_or_default(),
2269    );
2270    let incremental = cumulative - previous;
2271    if incremental.is_zero() {
2272        log::debug!(
2273            "Skipping duplicate fill: acc_fill_sz='{cumulative}' unchanged from previous={previous}"
2274        );
2275        return Ok(None);
2276    }
2277
2278    Ok(Some(incremental))
2279}
2280
2281fn parse_fill_commission(
2282    msg: &OKXOrderMsg,
2283    previous_fee: Option<Money>,
2284    previous_filled_qty: Option<Quantity>,
2285    last_qty: Quantity,
2286) -> anyhow::Result<Money> {
2287    let fee = msg
2288        .fee
2289        .as_deref()
2290        .filter(|fee| !fee.trim().is_empty())
2291        .ok_or_else(|| anyhow::anyhow!("missing fee for fill report inst_id={}", msg.inst_id))?;
2292    let amount =
2293        Decimal::from_str(fee).map_err(|e| anyhow::anyhow!("Failed to parse fee '{fee}': {e}"))?;
2294
2295    let currency = parse_fee_currency(msg.fee_ccy.as_str(), amount, || {
2296        format!("fill report for inst_id={}", msg.inst_id)
2297    });
2298
2299    let total = parse_fee(Some(fee), currency)
2300        .map_err(|e| anyhow::anyhow!("Failed to parse fee={:?}: {e}", msg.fee))?;
2301
2302    if !msg.fill_sz.is_empty()
2303        && msg.fill_sz != "0"
2304        && let Some(fee) = msg.fill_fee.as_deref().filter(|fee| !fee.trim().is_empty())
2305    {
2306        let amount = Decimal::from_str(fee)?;
2307        let currency = msg
2308            .fill_fee_ccy
2309            .filter(|currency| !currency.is_empty())
2310            .context("missing per-fill fee currency")?;
2311
2312        let currency = parse_fee_currency(currency.as_str(), amount, || {
2313            format!("fill report for inst_id={}", msg.inst_id)
2314        });
2315
2316        return parse_fee(Some(fee), currency);
2317    }
2318
2319    if let Some(cumulative) = msg.acc_fill_sz.as_deref().filter(|value| !value.is_empty()) {
2320        let cumulative = parse_quantity(cumulative, last_qty.precision)?;
2321        let previous = previous_filled_qty.map_or(Decimal::ZERO, |qty| qty.as_decimal());
2322        anyhow::ensure!(
2323            cumulative.as_decimal() <= previous + last_qty.as_decimal(),
2324            "missing per-fill fee across a private fill gap for {}",
2325            msg.ord_id
2326        );
2327    }
2328
2329    let Some(previous) = previous_fee else {
2330        return Ok(total);
2331    };
2332
2333    if total.currency != previous.currency {
2334        log::warn!(
2335            "Fee currency changed from {} to {} for order_id={}, using total fee as commission",
2336            previous.currency.code,
2337            total.currency.code,
2338            msg.ord_id
2339        );
2340        return Ok(total);
2341    }
2342
2343    let incremental = total - previous;
2344    if incremental < Money::zero(currency) {
2345        log::debug!(
2346            "Negative incremental fee detected - likely a maker rebate or fee refund: order_id={}, total_fee={total}, previous_fee={previous}, incremental={incremental}",
2347            msg.ord_id
2348        );
2349    }
2350
2351    if previous >= Money::zero(currency) && total > Money::zero(currency) && incremental > total {
2352        log::error!(
2353            "Incremental fee exceeds total fee - likely fee cache corruption, using total fee as fallback: order_id={}, total_fee={total}, previous_fee={previous}, incremental={incremental}",
2354            msg.ord_id
2355        );
2356        return Ok(total);
2357    }
2358
2359    Ok(incremental)
2360}
2361
2362/// Parses an option summary payload into [`OptionGreeks`].
2363///
2364/// Selects Black-Scholes (`delta_bs`, `gamma_bs`, `vega_bs`, `theta_bs`) or
2365/// price-adjusted (`delta`, `gamma`, `vega`, `theta`) greeks based on `greeks_type`.
2366/// BS greeks align with what Deribit and Bybit provide; PA greeks are denominated
2367/// in the underlying/coin units and match OKX's native contract convention.
2368///
2369/// # Errors
2370///
2371/// Returns an error if any of the greeks or volatility fields cannot be parsed as f64.
2372pub fn parse_option_summary_greeks(
2373    msg: &OKXOptionSummaryMsg,
2374    instrument_id: &InstrumentId,
2375    greeks_type: OKXGreeksType,
2376    ts_init: UnixNanos,
2377) -> anyhow::Result<OptionGreeks> {
2378    let ts_event = UnixNanos::from(msg.ts * 1_000_000);
2379
2380    let (delta_s, gamma_s, vega_s, theta_s, delta_ctx, gamma_ctx, vega_ctx, theta_ctx) =
2381        match greeks_type {
2382            OKXGreeksType::Bs => (
2383                &msg.delta_bs,
2384                &msg.gamma_bs,
2385                &msg.vega_bs,
2386                &msg.theta_bs,
2387                "invalid delta_bs",
2388                "invalid gamma_bs",
2389                "invalid vega_bs",
2390                "invalid theta_bs",
2391            ),
2392            OKXGreeksType::Pa => (
2393                &msg.delta,
2394                &msg.gamma,
2395                &msg.vega,
2396                &msg.theta,
2397                "invalid delta (pa)",
2398                "invalid gamma (pa)",
2399                "invalid vega (pa)",
2400                "invalid theta (pa)",
2401            ),
2402        };
2403
2404    let delta: f64 = delta_s.parse().context(delta_ctx)?;
2405    let gamma: f64 = gamma_s.parse().context(gamma_ctx)?;
2406    let vega: f64 = vega_s.parse().context(vega_ctx)?;
2407    let theta: f64 = theta_s.parse().context(theta_ctx)?;
2408
2409    let bid_iv: f64 = msg.bid_vol.parse().context("invalid bid_vol")?;
2410    let ask_iv: f64 = msg.ask_vol.parse().context("invalid ask_vol")?;
2411    let mark_iv: f64 = msg.mark_vol.parse().context("invalid mark_vol")?;
2412
2413    let underlying_price = msg
2414        .fwd_px
2415        .as_deref()
2416        .filter(|s| !s.is_empty())
2417        .map(str::parse::<f64>)
2418        .transpose()
2419        .context("invalid fwd_px")?;
2420
2421    Ok(OptionGreeks {
2422        instrument_id: *instrument_id,
2423        convention: greeks_type.into(),
2424        greeks: OptionGreekValues {
2425            delta,
2426            gamma,
2427            vega,
2428            theta,
2429            rho: 0.0, // OKX does not provide rho
2430        },
2431        mark_iv: Some(mark_iv),
2432        bid_iv: Some(bid_iv),
2433        ask_iv: Some(ask_iv),
2434        underlying_price,
2435        open_interest: None,
2436        ts_event,
2437        ts_init,
2438    })
2439}
2440
2441/// Parses OKX WebSocket message payloads into Nautilus data structures.
2442///
2443/// # Errors
2444///
2445/// Returns an error if the payload cannot be deserialized or if downstream
2446/// parsing routines fail.
2447///
2448/// # Panics
2449///
2450/// Panics if `okx_channel_to_bar_spec(channel)` returns `None` after a prior `is_some` check, an
2451/// unreachable scenario indicating a logic error.
2452#[expect(clippy::too_many_arguments)]
2453pub fn parse_ws_message_data(
2454    channel: &OKXWsChannel,
2455    data: serde_json::Value,
2456    instrument_id: &InstrumentId,
2457    price_precision: u8,
2458    size_precision: u8,
2459    ts_init: UnixNanos,
2460    funding_cache: &mut AHashMap<Ustr, (Ustr, u64)>,
2461    instruments_cache: &AHashMap<Ustr, InstrumentAny>,
2462) -> anyhow::Result<Option<NautilusWsMessage>> {
2463    match channel {
2464        OKXWsChannel::Instruments => {
2465            if let Ok(msg) = serde_json::from_value::<OKXInstrument>(data) {
2466                let inst_key = msg.inst_id;
2467                let cached_instrument = instruments_cache.get(&inst_key);
2468                let (margin_init, margin_maint) =
2469                    cached_instrument.map_or((None, None), extract_fees_from_cached_instrument);
2470                let instrument_id =
2471                    cached_instrument.map_or_else(|| parse_instrument_id(inst_key), Instrument::id);
2472
2473                let status_action = okx_status_to_market_action(msg.state);
2474                let status = InstrumentStatus::new(
2475                    instrument_id,
2476                    status_action,
2477                    ts_init,
2478                    ts_init,
2479                    None,
2480                    None,
2481                    Some(matches!(msg.state, OKXInstrumentStatus::Live)),
2482                    None,
2483                    None,
2484                );
2485
2486                match parse_instrument_any(&msg, margin_init, margin_maint, ts_init) {
2487                    Ok(Some(inst_any)) => Ok(Some(NautilusWsMessage::Instrument(
2488                        Box::new(inst_any),
2489                        Some(status),
2490                    ))),
2491                    Ok(None) => {
2492                        log::warn!("Empty instrument payload: {msg:?}");
2493                        Ok(Some(NautilusWsMessage::InstrumentStatus(status)))
2494                    }
2495                    Err(e) => {
2496                        log::warn!("Failed to parse instrument {inst_key}: {e}");
2497                        Ok(Some(NautilusWsMessage::InstrumentStatus(status)))
2498                    }
2499                }
2500            } else {
2501                anyhow::bail!("Failed to deserialize instrument payload")
2502            }
2503        }
2504        OKXWsChannel::BboTbt => {
2505            let data_vec = parse_quote_msg_vec(
2506                data,
2507                instrument_id,
2508                price_precision,
2509                size_precision,
2510                ts_init,
2511            )?;
2512            Ok(Some(NautilusWsMessage::Data(data_vec)))
2513        }
2514        OKXWsChannel::Tickers => {
2515            let data_vec = parse_ticker_msg_vec(
2516                data,
2517                instrument_id,
2518                price_precision,
2519                size_precision,
2520                ts_init,
2521            )?;
2522            Ok(Some(NautilusWsMessage::Data(data_vec)))
2523        }
2524        OKXWsChannel::Trades | OKXWsChannel::SprdPublicTrades => {
2525            let data_vec = parse_trade_msg_vec(
2526                data,
2527                instrument_id,
2528                price_precision,
2529                size_precision,
2530                ts_init,
2531            )?;
2532            Ok(Some(NautilusWsMessage::Data(data_vec)))
2533        }
2534        OKXWsChannel::MarkPrice => {
2535            let data_vec = parse_mark_price_msg_vec(data, instrument_id, price_precision, ts_init)?;
2536            Ok(Some(NautilusWsMessage::Data(data_vec)))
2537        }
2538        OKXWsChannel::IndexTickers => {
2539            let data_vec =
2540                parse_index_price_msg_vec(data, instrument_id, price_precision, ts_init)?;
2541            Ok(Some(NautilusWsMessage::Data(data_vec)))
2542        }
2543        OKXWsChannel::FundingRate => {
2544            let data_vec = parse_funding_rate_msg_vec(data, instrument_id, ts_init, funding_cache)?;
2545            Ok(Some(NautilusWsMessage::FundingRates(data_vec)))
2546        }
2547        OKXWsChannel::EventContractMarkets => Ok(Some(NautilusWsMessage::Raw(data))),
2548        channel if okx_channel_to_bar_spec(channel).is_some() => {
2549            let bar_spec = okx_channel_to_bar_spec(channel).expect("bar_spec checked above");
2550            let data_vec = parse_candle_msg_vec(
2551                data,
2552                instrument_id,
2553                price_precision,
2554                size_precision,
2555                bar_spec,
2556                ts_init,
2557            )?;
2558            Ok(Some(NautilusWsMessage::Data(data_vec)))
2559        }
2560        OKXWsChannel::Books
2561        | OKXWsChannel::BooksTbt
2562        | OKXWsChannel::Books5
2563        | OKXWsChannel::Books50Tbt => {
2564            if let Ok(book_msgs) = serde_json::from_value::<Vec<OKXBookMsg>>(data) {
2565                let data_vec = parse_book_depth_msg_vec(
2566                    book_msgs,
2567                    instrument_id,
2568                    price_precision,
2569                    size_precision,
2570                    ts_init,
2571                )?;
2572                Ok(Some(NautilusWsMessage::Data(data_vec)))
2573            } else {
2574                anyhow::bail!("Failed to deserialize Books channel data as Vec<OKXBookMsg>")
2575            }
2576        }
2577        _ => {
2578            log::warn!("Unsupported channel for message parsing: {channel:?}");
2579            Ok(None)
2580        }
2581    }
2582}
2583
2584#[cfg(test)]
2585mod tests {
2586    use ahash::AHashMap;
2587    use nautilus_core::nanos::UnixNanos;
2588    use nautilus_model::{
2589        data::bar::BAR_SPEC_1_DAY_LAST,
2590        enums::{AccountType, BookType, GreeksConvention},
2591        identifiers::{ClientOrderId, PositionId, Symbol, VenueOrderId},
2592        instruments::CurrencyPair,
2593        orderbook::OrderBook,
2594        types::Currency,
2595    };
2596    use rstest::rstest;
2597    use rust_decimal_macros::dec;
2598    use serde_json::Value;
2599    use ustr::Ustr;
2600
2601    use super::*;
2602    use crate::{
2603        OKXPositionSide,
2604        common::{
2605            enums::{
2606                OKXAlgoOrderStatus, OKXExecType, OKXInstrumentType, OKXMarginMode, OKXOrderType,
2607                OKXPriceType, OKXQuickMarginType, OKXSelfTradePreventionMode, OKXSide,
2608                OKXTradeMode,
2609            },
2610            parse::parse_account_state,
2611            testing::{create_stub_instrument, load_test_json},
2612        },
2613        http::models::OKXAccount,
2614        websocket::messages::{
2615            OKXAlgoOrderMsg, OKXAttachedAlgoOrd, OKXLiquidationWarningMsg, OKXWebSocketArg,
2616            OKXWsFrame,
2617        },
2618    };
2619
2620    fn is_order_updated(
2621        msg: &OKXOrderMsg,
2622        previous: &OrderStateSnapshot,
2623        instrument: &InstrumentAny,
2624    ) -> anyhow::Result<bool> {
2625        let current_venue_id = VenueOrderId::new(msg.ord_id);
2626
2627        if previous.venue_order_id != current_venue_id {
2628            return Ok(true);
2629        }
2630
2631        let current_qty = parse_quantity(&msg.sz, instrument.size_precision())?;
2632        if previous.quantity != current_qty {
2633            return Ok(true);
2634        }
2635
2636        if !is_market_price(&msg.px) {
2637            let current_price = parse_price(&msg.px, instrument.price_precision())?;
2638
2639            if let Some(prev_price) = previous.price
2640                && prev_price != current_price
2641            {
2642                return Ok(true);
2643            }
2644        }
2645
2646        Ok(false)
2647    }
2648
2649    #[rstest]
2650    fn open_order_baselines_survive_unrelated_order_churn() {
2651        let instrument = InstrumentAny::CryptoPerpetual(create_stub_instrument());
2652        let mut fee_cache = FeeCache::new();
2653        let mut filled_qty_cache = FilledQtyCache::new();
2654
2655        let mut resting = create_stub_order_msg("1.0", Some("1.0".to_string()), "ord-resting", "");
2656        resting.state = OKXOrderStatus::PartiallyFilled;
2657        update_fee_fill_caches(&resting, &instrument, &mut fee_cache, &mut filled_qty_cache);
2658
2659        for i in 0..=TERMINAL_BASELINE_CAPACITY {
2660            let mut msg =
2661                create_stub_order_msg("1.0", Some("1.0".to_string()), &format!("ord-{i}"), "");
2662            msg.state = OKXOrderStatus::Filled;
2663            update_fee_fill_caches(&msg, &instrument, &mut fee_cache, &mut filled_qty_cache);
2664        }
2665
2666        let resting_key = Ustr::from("ord-resting");
2667
2668        assert_eq!(fee_cache.get(&resting_key).unwrap().as_decimal(), dec!(1.0));
2669        assert_eq!(
2670            filled_qty_cache.get(&resting_key).unwrap().as_decimal(),
2671            dec!(1.0)
2672        );
2673        assert_eq!(fee_cache.open.len(), 1);
2674        assert_eq!(filled_qty_cache.open.len(), 1);
2675
2676        // Demotion is what bounds the open map, so prove the migration and not just the
2677        // classification: a settled order must leave `open` and expose its newer baseline.
2678        let mut settled = resting.clone();
2679        settled.state = OKXOrderStatus::Filled;
2680        settled.fee = Some("-2.5".to_string());
2681        settled.acc_fill_sz = Some("2.0".to_string());
2682        update_fee_fill_caches(&settled, &instrument, &mut fee_cache, &mut filled_qty_cache);
2683
2684        assert_eq!(fee_cache.open.len(), 0);
2685        assert_eq!(filled_qty_cache.open.len(), 0);
2686        assert_eq!(fee_cache.get(&resting_key).unwrap().as_decimal(), dec!(2.5));
2687        assert_eq!(
2688            filled_qty_cache.get(&resting_key).unwrap().as_decimal(),
2689            dec!(2.0)
2690        );
2691    }
2692
2693    #[rstest]
2694    #[case(OKXOrderStatus::Filled)]
2695    #[case(OKXOrderStatus::Canceled)]
2696    #[case(OKXOrderStatus::MmpCanceled)]
2697    fn terminal_order_baselines_stay_terminal_after_late_updates(
2698        #[case] terminal_state: OKXOrderStatus,
2699        #[values(OKXOrderStatus::Live, OKXOrderStatus::PartiallyFilled)] late_state: OKXOrderStatus,
2700    ) {
2701        let instrument = InstrumentAny::CryptoPerpetual(create_stub_instrument());
2702        let mut fee_cache = FeeCache::new();
2703        let mut filled_qty_cache = FilledQtyCache::new();
2704        let mut msg = create_stub_order_msg("1.0", Some("2.0".to_string()), "ord-late", "");
2705        msg.state = terminal_state;
2706        update_fee_fill_caches(&msg, &instrument, &mut fee_cache, &mut filled_qty_cache);
2707
2708        msg.state = late_state;
2709        msg.fee = Some("-0.5".to_string());
2710        msg.acc_fill_sz = Some("1.0".to_string());
2711        update_fee_fill_caches(&msg, &instrument, &mut fee_cache, &mut filled_qty_cache);
2712
2713        let key = msg.ord_id;
2714        let fee = Money::from_decimal(dec!(0.5), Currency::USDT()).unwrap();
2715        let quantity = Quantity::from("1.00000000");
2716
2717        assert_eq!(fee_cache.open.len(), 0);
2718        assert_eq!(filled_qty_cache.open.len(), 0);
2719        assert_eq!(fee_cache.terminal.get(&key), Some(&fee));
2720        assert_eq!(filled_qty_cache.terminal.get(&key), Some(&quantity));
2721        assert_eq!(fee_cache.get(&key), Some(&fee));
2722        assert_eq!(filled_qty_cache.get(&key), Some(&quantity));
2723    }
2724
2725    #[rstest]
2726    fn terminal_order_baselines_evict_oldest_first() {
2727        let instrument = InstrumentAny::CryptoPerpetual(create_stub_instrument());
2728        let mut fee_cache = FeeCache::new();
2729        let mut filled_qty_cache = FilledQtyCache::new();
2730
2731        for i in 0..=TERMINAL_BASELINE_CAPACITY {
2732            let mut msg =
2733                create_stub_order_msg("1.0", Some("1.0".to_string()), &format!("ord-{i}"), "");
2734            msg.state = OKXOrderStatus::Filled;
2735            update_fee_fill_caches(&msg, &instrument, &mut fee_cache, &mut filled_qty_cache);
2736        }
2737
2738        let oldest = Ustr::from("ord-0");
2739        let newest = Ustr::from(&format!("ord-{TERMINAL_BASELINE_CAPACITY}"));
2740
2741        assert_eq!(fee_cache.get(&oldest), None);
2742        assert_eq!(filled_qty_cache.get(&oldest), None);
2743        assert_eq!(fee_cache.get(&newest).unwrap().as_decimal(), dec!(1.0));
2744        assert_eq!(
2745            filled_qty_cache.get(&newest).unwrap().as_decimal(),
2746            dec!(1.0)
2747        );
2748        assert_eq!(fee_cache.open.len(), 0);
2749    }
2750
2751    fn create_stub_order_msg(
2752        fill_sz: &str,
2753        acc_fill_sz: Option<String>,
2754        order_id: &str,
2755        trade_id: &str,
2756    ) -> OKXOrderMsg {
2757        OKXOrderMsg {
2758            acc_fill_sz,
2759            algo_id: None,
2760            avg_px: "50000.0".to_string(),
2761            c_time: 1_746_947_317_401,
2762            cancel_source: None,
2763            cancel_source_reason: None,
2764            category: OKXOrderCategory::Normal,
2765            ccy: Ustr::from("USDT"),
2766            cl_ord_id: "test_order_1".to_string(),
2767            algo_cl_ord_id: None,
2768            attach_algo_cl_ord_id: None,
2769            attach_algo_ords: Vec::new(),
2770            outcome: None,
2771            fee: Some("-1.0".to_string()),
2772            fee_ccy: Ustr::from("USDT"),
2773            fill_fee: None,
2774            fill_fee_ccy: None,
2775            fill_mark_px: None,
2776            fill_mark_vol: None,
2777            fill_px_vol: None,
2778            fill_px_usd: None,
2779            fill_fwd_px: None,
2780            fill_notional_usd: None,
2781            fill_pnl: None,
2782            fill_px: "50000.0".to_string(),
2783            fill_sz: fill_sz.to_string(),
2784            fill_time: 1_746_947_317_402,
2785            inst_id: Ustr::from("BTC-USDT-SWAP"),
2786            inst_type: OKXInstrumentType::Swap,
2787            is_tp_limit: None,
2788            lever: "2.0".to_string(),
2789            linked_algo_ord: None,
2790            notional_usd: None,
2791            ord_id: Ustr::from(order_id),
2792            ord_type: OKXOrderType::Market,
2793            pnl: "0".to_string(),
2794            pos_side: OKXPositionSide::Long,
2795            px: String::new(),
2796            px_type: OKXPriceType::None,
2797            px_usd: None,
2798            px_vol: None,
2799            quick_mgn_type: OKXQuickMarginType::None,
2800            rebate: None,
2801            rebate_ccy: None,
2802            reduce_only: "false".to_string(),
2803            side: OKXSide::Buy,
2804            sl_ord_px: None,
2805            sl_trigger_px: None,
2806            sl_trigger_px_type: None,
2807            source: None,
2808            state: OKXOrderStatus::PartiallyFilled,
2809            stp_id: None,
2810            stp_mode: OKXSelfTradePreventionMode::None,
2811            exec_type: OKXExecType::Taker,
2812            sz: "0.03".to_string(),
2813            tag: None,
2814            td_mode: OKXTradeMode::Isolated,
2815            tgt_ccy: None,
2816            tp_ord_px: None,
2817            tp_trigger_px: None,
2818            tp_trigger_px_type: None,
2819            trade_id: trade_id.to_string(),
2820            u_time: 1_746_947_317_402,
2821            amend_result: None,
2822            req_id: None,
2823            code: None,
2824            msg: None,
2825        }
2826    }
2827
2828    #[rstest]
2829    #[case::standard(false)]
2830    #[case::rpi(true)]
2831    fn snapshot_replaces_existing_book(#[case] rpi: bool, #[values(false, true)] empty: bool) {
2832        let fixture = if rpi {
2833            "ws_books_rpi_snapshot.json"
2834        } else {
2835            "ws_books_snapshot.json"
2836        };
2837
2838        let mut frame: Value = serde_json::from_str(&load_test_json(fixture)).unwrap();
2839        let instrument_id = InstrumentId::from("BTC-USDT.OKX");
2840
2841        let parse = |frame: &Value| {
2842            if rpi {
2843                parse_rpi_book_msg(
2844                    &serde_json::from_value(frame["data"][0].clone()).unwrap(),
2845                    instrument_id,
2846                    7,
2847                    3,
2848                    &OKXBookAction::Snapshot,
2849                    UnixNanos::from(123),
2850                )
2851                .unwrap()
2852            } else {
2853                parse_book_msg(
2854                    &serde_json::from_value(frame["data"][0].clone()).unwrap(),
2855                    instrument_id,
2856                    2,
2857                    1,
2858                    &OKXBookAction::Snapshot,
2859                    UnixNanos::from(123),
2860                )
2861                .unwrap()
2862            }
2863        };
2864
2865        let mut actual = OrderBook::new(instrument_id, BookType::L2_MBP);
2866        actual.apply_deltas(&parse(&frame)).unwrap();
2867        for side in ["bids", "asks"] {
2868            let levels = frame["data"][0][side].as_array_mut().unwrap();
2869            if empty {
2870                levels.clear();
2871            } else {
2872                levels.remove(0);
2873            }
2874        }
2875
2876        let snapshot = parse(&frame);
2877        let mut expected = OrderBook::new(instrument_id, BookType::L2_MBP);
2878        expected.apply_deltas(&snapshot).unwrap();
2879        actual.apply_deltas(&snapshot).unwrap();
2880
2881        assert_eq!(actual.bids_as_map(None), expected.bids_as_map(None));
2882        assert_eq!(actual.asks_as_map(None), expected.asks_as_map(None));
2883
2884        let expected_clear_flags = if empty {
2885            RecordFlag::F_SNAPSHOT as u8 | RecordFlag::F_LAST as u8
2886        } else {
2887            RecordFlag::F_SNAPSHOT as u8
2888        };
2889
2890        assert_eq!(snapshot.deltas[0].action, BookAction::Clear);
2891        assert_eq!(snapshot.deltas[0].flags, expected_clear_flags);
2892        assert_eq!(snapshot.deltas[0].sequence, snapshot.sequence);
2893        assert_eq!(snapshot.deltas[0].ts_event, snapshot.ts_event);
2894        assert_eq!(snapshot.deltas[0].ts_init, UnixNanos::from(123));
2895    }
2896
2897    #[rstest]
2898    #[case::snapshot("ws_books_snapshot.json", OKXBookAction::Snapshot)]
2899    #[case::update("ws_books_update.json", OKXBookAction::Update)]
2900    #[case::rpi_snapshot("ws_books_rpi_snapshot.json", OKXBookAction::Snapshot)]
2901    #[case::rpi_update("ws_books_rpi_update.json", OKXBookAction::Update)]
2902    fn book_deltas_flag_only_the_final_delta_last(
2903        #[case] fixture: &str,
2904        #[case] action: OKXBookAction,
2905    ) {
2906        let instrument_id = InstrumentId::from("BTC-USDT.OKX");
2907        let frame: OKXWsFrame = serde_json::from_str(&load_test_json(fixture)).unwrap();
2908
2909        let deltas = match frame {
2910            OKXWsFrame::BookData { data, .. } => {
2911                parse_book_msg(&data[0], instrument_id, 2, 1, &action, UnixNanos::default())
2912            }
2913            OKXWsFrame::RpiBookData { data, .. } => {
2914                parse_rpi_book_msg(&data[0], instrument_id, 7, 3, &action, UnixNanos::default())
2915            }
2916            _ => panic!("Expected a book frame"),
2917        }
2918        .unwrap();
2919
2920        let last_count = deltas
2921            .deltas
2922            .iter()
2923            .filter(|delta| RecordFlag::F_LAST.matches(delta.flags))
2924            .count();
2925
2926        assert_eq!(last_count, 1, "exactly one delta must close the event");
2927        assert!(RecordFlag::F_LAST.matches(deltas.deltas.last().unwrap().flags));
2928        assert!(RecordFlag::F_LAST.matches(deltas.flags));
2929    }
2930
2931    #[rstest]
2932    fn empty_book_snapshot_flags_the_clear_delta_last() {
2933        let instrument_id = InstrumentId::from("BTC-USDT.OKX");
2934
2935        let msg = OKXBookMsg {
2936            bids: Vec::new(),
2937            asks: Vec::new(),
2938            ts: 1_597_026_383_085,
2939            checksum: None,
2940            prev_seq_id: None,
2941            seq_id: 123_456,
2942        };
2943
2944        let deltas = parse_book_msg(
2945            &msg,
2946            instrument_id,
2947            2,
2948            1,
2949            &OKXBookAction::Snapshot,
2950            UnixNanos::default(),
2951        )
2952        .unwrap();
2953
2954        assert_eq!(deltas.deltas.len(), 1);
2955        assert_eq!(deltas.deltas[0].action, BookAction::Clear);
2956        assert_eq!(
2957            deltas.flags,
2958            RecordFlag::F_SNAPSHOT as u8 | RecordFlag::F_LAST as u8
2959        );
2960    }
2961
2962    #[rstest]
2963    fn test_parse_books_snapshot() {
2964        let json_data = load_test_json("ws_books_snapshot.json");
2965        let msg: OKXWsFrame = serde_json::from_str(&json_data).unwrap();
2966        let (okx_books, action): (Vec<OKXBookMsg>, OKXBookAction) = match msg {
2967            OKXWsFrame::BookData { data, action, .. } => (data, action),
2968            _ => panic!("Expected a `BookData` variant"),
2969        };
2970
2971        let instrument_id = InstrumentId::from("BTC-USDT.OKX");
2972        let deltas = parse_book_msg(
2973            &okx_books[0],
2974            instrument_id,
2975            2,
2976            1,
2977            &action,
2978            UnixNanos::default(),
2979        )
2980        .unwrap();
2981
2982        assert_eq!(deltas.instrument_id, instrument_id);
2983        assert_eq!(deltas.deltas.len(), 17);
2984        assert_eq!(
2985            deltas.flags,
2986            RecordFlag::F_SNAPSHOT as u8 | RecordFlag::F_LAST as u8
2987        );
2988        assert_eq!(deltas.sequence, 123_456);
2989        assert_eq!(deltas.ts_event, UnixNanos::from(1_597_026_383_085_000_000));
2990        assert_eq!(deltas.ts_init, UnixNanos::default());
2991
2992        // Verify some individual deltas are parsed correctly
2993        assert!(!deltas.deltas.is_empty());
2994        // Snapshot should have both bid and ask deltas
2995        assert!(
2996            deltas
2997                .deltas
2998                .iter()
2999                .any(|d| d.order.side == OrderSide::Buy.into()),
3000            "Should have bid deltas"
3001        );
3002        assert!(
3003            deltas
3004                .deltas
3005                .iter()
3006                .any(|d| d.order.side == OrderSide::Sell.into()),
3007            "Should have ask deltas"
3008        );
3009    }
3010
3011    #[rstest]
3012    fn test_parse_books_update() {
3013        let json_data = load_test_json("ws_books_update.json");
3014        let msg: OKXWsFrame = serde_json::from_str(&json_data).unwrap();
3015        let instrument_id = InstrumentId::from("BTC-USDT.OKX");
3016        let (okx_books, action): (Vec<OKXBookMsg>, OKXBookAction) = match msg {
3017            OKXWsFrame::BookData { data, action, .. } => (data, action),
3018            _ => panic!("Expected a `BookData` variant"),
3019        };
3020
3021        let deltas = parse_book_msg(
3022            &okx_books[0],
3023            instrument_id,
3024            2,
3025            1,
3026            &action,
3027            UnixNanos::default(),
3028        )
3029        .unwrap();
3030
3031        assert_eq!(deltas.instrument_id, instrument_id);
3032        assert_eq!(deltas.deltas.len(), 16);
3033        assert_eq!(deltas.flags, RecordFlag::F_LAST as u8);
3034        assert_eq!(deltas.sequence, 123_457);
3035        assert_eq!(deltas.ts_event, UnixNanos::from(1_597_026_383_085_000_000));
3036        assert_eq!(deltas.ts_init, UnixNanos::default());
3037
3038        // Verify some individual deltas are parsed correctly
3039        assert!(!deltas.deltas.is_empty());
3040        // Update should also have both bid and ask deltas
3041        assert!(
3042            deltas
3043                .deltas
3044                .iter()
3045                .any(|d| d.order.side == OrderSide::Buy.into()),
3046            "Should have bid deltas"
3047        );
3048        assert!(
3049            deltas
3050                .deltas
3051                .iter()
3052                .any(|d| d.order.side == OrderSide::Sell.into()),
3053            "Should have ask deltas"
3054        );
3055    }
3056
3057    #[rstest]
3058    fn test_parse_rpi_books_update_uses_total_quantity_and_sequence() {
3059        let json_data = load_test_json("ws_books_rpi_update.json");
3060        let msg: OKXWsFrame = serde_json::from_str(&json_data).unwrap();
3061        let (data, action) = match msg {
3062            OKXWsFrame::RpiBookData { data, action, .. } => (data, action),
3063            _ => panic!("Expected an RPI book update"),
3064        };
3065        let instrument_id = InstrumentId::from("OMI-USD.OKX");
3066
3067        let deltas =
3068            parse_rpi_book_msg(&data[0], instrument_id, 7, 3, &action, UnixNanos::from(123))
3069                .unwrap();
3070
3071        assert_eq!(deltas.instrument_id, instrument_id);
3072        assert_eq!(deltas.deltas.len(), 2);
3073        assert_eq!(deltas.flags, RecordFlag::F_LAST as u8);
3074        assert_eq!(deltas.sequence, 1_082_831_230);
3075        assert_eq!(deltas.ts_event, UnixNanos::from(1_785_406_443_903_000_000));
3076        assert_eq!(deltas.ts_init, UnixNanos::from(123));
3077        assert_eq!(deltas.deltas[0].action, BookAction::Delete);
3078        assert_eq!(deltas.deltas[0].order.side, OrderSide::Sell.into());
3079        assert_eq!(deltas.deltas[0].order.price, Price::from("0.0001617"));
3080        assert_eq!(deltas.deltas[0].order.size, Quantity::from("0"));
3081        assert_eq!(deltas.deltas[1].action, BookAction::Update);
3082        assert_eq!(deltas.deltas[1].order.side, OrderSide::Sell.into());
3083        assert_eq!(deltas.deltas[1].order.price, Price::from("0.0001625"));
3084        assert_eq!(deltas.deltas[1].order.size, Quantity::from("12324367.786"));
3085    }
3086
3087    #[rstest]
3088    fn test_parse_tickers() {
3089        let json_data = load_test_json("ws_tickers.json");
3090        let msg: OKXWsFrame = serde_json::from_str(&json_data).unwrap();
3091        let okx_tickers: Vec<OKXTickerMsg> = match msg {
3092            OKXWsFrame::Data { data, .. } => serde_json::from_value(data).unwrap(),
3093            _ => panic!("Expected a `Data` variant"),
3094        };
3095
3096        let instrument_id = InstrumentId::from("BTC-USDT.OKX");
3097        let trade =
3098            parse_ticker_msg(&okx_tickers[0], instrument_id, 2, 1, UnixNanos::default()).unwrap();
3099
3100        assert_eq!(trade.instrument_id, InstrumentId::from("BTC-USDT.OKX"));
3101        assert_eq!(trade.bid_price, Price::from("8888.88"));
3102        assert_eq!(trade.ask_price, Price::from("9999.99"));
3103        assert_eq!(trade.bid_size, Quantity::from(5));
3104        assert_eq!(trade.ask_size, Quantity::from(11));
3105        assert_eq!(trade.ts_event, UnixNanos::from(1_597_026_383_085_000_000));
3106        assert_eq!(trade.ts_init, UnixNanos::default());
3107    }
3108
3109    #[rstest]
3110    fn test_parse_quotes() {
3111        let json_data = load_test_json("ws_bbo_tbt.json");
3112        let msg: OKXWsFrame = serde_json::from_str(&json_data).unwrap();
3113        let okx_quotes: Vec<OKXBookMsg> = match msg {
3114            OKXWsFrame::Data { data, .. } => serde_json::from_value(data).unwrap(),
3115            _ => panic!("Expected a `Data` variant"),
3116        };
3117        let instrument_id = InstrumentId::from("BTC-USDT.OKX");
3118
3119        let quote =
3120            parse_quote_msg(&okx_quotes[0], instrument_id, 2, 1, UnixNanos::default()).unwrap();
3121
3122        assert_eq!(quote.instrument_id, InstrumentId::from("BTC-USDT.OKX"));
3123        assert_eq!(quote.bid_price, Price::from("8476.97"));
3124        assert_eq!(quote.ask_price, Price::from("8476.98"));
3125        assert_eq!(quote.bid_size, Quantity::from(256));
3126        assert_eq!(quote.ask_size, Quantity::from(415));
3127        assert_eq!(quote.ts_event, UnixNanos::from(1_597_026_383_085_000_000));
3128        assert_eq!(quote.ts_init, UnixNanos::default());
3129    }
3130
3131    #[rstest]
3132    fn test_parse_trades() {
3133        let json_data = load_test_json("ws_trades.json");
3134        let msg: OKXWsFrame = serde_json::from_str(&json_data).unwrap();
3135        let okx_trades: Vec<OKXTradeMsg> = match msg {
3136            OKXWsFrame::Data { data, .. } => serde_json::from_value(data).unwrap(),
3137            _ => panic!("Expected a `Data` variant"),
3138        };
3139
3140        let instrument_id = InstrumentId::from("BTC-USDT.OKX");
3141        let trade =
3142            parse_trade_msg(&okx_trades[0], instrument_id, 1, 8, UnixNanos::default()).unwrap();
3143
3144        assert_eq!(trade.instrument_id, InstrumentId::from("BTC-USDT.OKX"));
3145        assert_eq!(trade.price, Price::from("42219.9"));
3146        assert_eq!(trade.size, Quantity::from("0.12060306"));
3147        assert_eq!(trade.aggressor_side, AggressorSide::Buy);
3148        assert_eq!(trade.trade_id, TradeId::from("130639474"));
3149        assert_eq!(trade.ts_event, UnixNanos::from(1_630_048_897_897_000_000));
3150        assert_eq!(trade.ts_init, UnixNanos::default());
3151    }
3152
3153    #[rstest]
3154    fn test_parse_candle() {
3155        let json_data = load_test_json("ws_candle.json");
3156        let msg: OKXWsFrame = serde_json::from_str(&json_data).unwrap();
3157        let okx_candles: Vec<OKXCandleMsg> = match msg {
3158            OKXWsFrame::Data { data, .. } => serde_json::from_value(data).unwrap(),
3159            _ => panic!("Expected a `Data` variant"),
3160        };
3161
3162        let instrument_id = InstrumentId::from("BTC-USDT.OKX");
3163        let bar_type = BarType::new(
3164            instrument_id,
3165            BAR_SPEC_1_DAY_LAST,
3166            AggregationSource::External,
3167        );
3168        let bar = parse_candle_msg(&okx_candles[0], bar_type, 2, 0, UnixNanos::default()).unwrap();
3169
3170        assert_eq!(bar.bar_type, bar_type);
3171        assert_eq!(bar.open, Price::from("8533.02"));
3172        assert_eq!(bar.high, Price::from("8553.74"));
3173        assert_eq!(bar.low, Price::from("8527.17"));
3174        assert_eq!(bar.close, Price::from("8548.26"));
3175        assert_eq!(bar.volume, Quantity::from(45247));
3176        assert_eq!(bar.ts_event, UnixNanos::from(1_597_026_383_085_000_000));
3177        assert_eq!(bar.ts_init, UnixNanos::default());
3178    }
3179
3180    #[rstest]
3181    fn test_parse_funding_rate() {
3182        let json_data = load_test_json("ws_funding_rate.json");
3183        let msg: OKXWsFrame = serde_json::from_str(&json_data).unwrap();
3184
3185        let okx_funding_rates: Vec<crate::websocket::messages::OKXFundingRateMsg> = match msg {
3186            OKXWsFrame::Data { data, .. } => serde_json::from_value(data).unwrap(),
3187            _ => panic!("Expected a `Data` variant"),
3188        };
3189
3190        let instrument_id = InstrumentId::from("BTC-USDT-SWAP.OKX");
3191        let funding_rate =
3192            parse_funding_rate_msg(&okx_funding_rates[0], instrument_id, UnixNanos::default())
3193                .unwrap();
3194
3195        assert_eq!(funding_rate.instrument_id, instrument_id);
3196        assert_eq!(funding_rate.rate, dec!(0.0001));
3197        assert_eq!(funding_rate.interval, Some(8 * 60));
3198        assert_eq!(
3199            funding_rate.next_funding_ns,
3200            Some(UnixNanos::from(1_744_590_349_506_000_000))
3201        );
3202        assert_eq!(
3203            funding_rate.ts_event,
3204            UnixNanos::from(1_744_590_349_506_000_000)
3205        );
3206        assert_eq!(funding_rate.ts_init, UnixNanos::default());
3207    }
3208
3209    #[rstest]
3210    fn test_parse_book_vec() {
3211        let json_data = load_test_json("ws_books_snapshot.json");
3212        let event: OKXWsFrame = serde_json::from_str(&json_data).unwrap();
3213        let (msgs, action): (Vec<OKXBookMsg>, OKXBookAction) = match event {
3214            OKXWsFrame::BookData { data, action, .. } => (data, action),
3215            _ => panic!("Expected BookData"),
3216        };
3217
3218        let instrument_id = InstrumentId::from("BTC-USDT.OKX");
3219        let deltas_vec =
3220            parse_book_msg_vec(msgs, &instrument_id, 8, 1, action, UnixNanos::default()).unwrap();
3221
3222        assert_eq!(deltas_vec.len(), 1);
3223
3224        if let Data::BookDeltas(d) = &deltas_vec[0] {
3225            assert_eq!(d.sequence, 123_456);
3226        } else {
3227            panic!("Expected Deltas");
3228        }
3229    }
3230
3231    #[rstest]
3232    fn test_parse_ticker_vec() {
3233        let json_data = load_test_json("ws_tickers.json");
3234        let event: OKXWsFrame = serde_json::from_str(&json_data).unwrap();
3235        let data_val: serde_json::Value = match event {
3236            OKXWsFrame::Data { data, .. } => data,
3237            _ => panic!("Expected Data"),
3238        };
3239
3240        let instrument_id = InstrumentId::from("BTC-USDT.OKX");
3241        let quotes_vec =
3242            parse_ticker_msg_vec(data_val, &instrument_id, 8, 1, UnixNanos::default()).unwrap();
3243
3244        assert_eq!(quotes_vec.len(), 1);
3245
3246        if let Data::Quote(q) = &quotes_vec[0] {
3247            assert_eq!(q.bid_price, Price::from("8888.88000000"));
3248            assert_eq!(q.ask_price, Price::from("9999.99"));
3249        } else {
3250            panic!("Expected Quote");
3251        }
3252    }
3253
3254    #[rstest]
3255    fn test_parse_trade_vec() {
3256        let json_data = load_test_json("ws_trades.json");
3257        let event: OKXWsFrame = serde_json::from_str(&json_data).unwrap();
3258        let data_val: serde_json::Value = match event {
3259            OKXWsFrame::Data { data, .. } => data,
3260            _ => panic!("Expected Data"),
3261        };
3262
3263        let instrument_id = InstrumentId::from("BTC-USDT.OKX");
3264        let trades_vec =
3265            parse_trade_msg_vec(data_val, &instrument_id, 8, 1, UnixNanos::default()).unwrap();
3266
3267        assert_eq!(trades_vec.len(), 1);
3268
3269        if let Data::Trade(t) = &trades_vec[0] {
3270            assert_eq!(t.trade_id, TradeId::new("130639474"));
3271        } else {
3272            panic!("Expected Trade");
3273        }
3274    }
3275
3276    #[rstest]
3277    fn test_parse_candle_vec() {
3278        let json_data = load_test_json("ws_candle.json");
3279        let event: OKXWsFrame = serde_json::from_str(&json_data).unwrap();
3280        let data_val: serde_json::Value = match event {
3281            OKXWsFrame::Data { data, .. } => data,
3282            _ => panic!("Expected Data"),
3283        };
3284
3285        let instrument_id = InstrumentId::from("BTC-USDT.OKX");
3286        let bars_vec = parse_candle_msg_vec(
3287            data_val,
3288            &instrument_id,
3289            2,
3290            1,
3291            BAR_SPEC_1_DAY_LAST,
3292            UnixNanos::default(),
3293        )
3294        .unwrap();
3295
3296        assert_eq!(bars_vec.len(), 1);
3297
3298        if let Data::Bar(b) = &bars_vec[0] {
3299            assert_eq!(b.open, Price::from("8533.02"));
3300        } else {
3301            panic!("Expected Bar");
3302        }
3303    }
3304
3305    #[rstest]
3306    fn test_parse_book_message() {
3307        let json_data = load_test_json("ws_bbo_tbt.json");
3308        let msg: OKXWsFrame = serde_json::from_str(&json_data).unwrap();
3309        let (okx_books, arg): (Vec<OKXBookMsg>, OKXWebSocketArg) = match msg {
3310            OKXWsFrame::Data { data, arg, .. } => (serde_json::from_value(data).unwrap(), arg),
3311            _ => panic!("Expected a `Data` variant"),
3312        };
3313
3314        assert_eq!(arg.channel, OKXWsChannel::BboTbt);
3315        assert_eq!(arg.inst_id.as_ref().unwrap(), &Ustr::from("BTC-USDT"));
3316        assert_eq!(arg.inst_type, None);
3317        assert_eq!(okx_books.len(), 1);
3318
3319        let book_msg = &okx_books[0];
3320
3321        // Check asks
3322        assert_eq!(book_msg.asks.len(), 1);
3323        let ask = &book_msg.asks[0];
3324        assert_eq!(ask.price, "8476.98");
3325        assert_eq!(ask.size, "415");
3326        assert_eq!(ask.liquidated_orders_count, "0");
3327        assert_eq!(ask.orders_count, "13");
3328
3329        // Check bids
3330        assert_eq!(book_msg.bids.len(), 1);
3331        let bid = &book_msg.bids[0];
3332        assert_eq!(bid.price, "8476.97");
3333        assert_eq!(bid.size, "256");
3334        assert_eq!(bid.liquidated_orders_count, "0");
3335        assert_eq!(bid.orders_count, "12");
3336        assert_eq!(book_msg.ts, 1_597_026_383_085);
3337        assert_eq!(book_msg.seq_id, 123_456);
3338        assert_eq!(book_msg.checksum, None);
3339        assert_eq!(book_msg.prev_seq_id, None);
3340    }
3341
3342    #[rstest]
3343    fn test_parse_ws_account_message() {
3344        let json_data = load_test_json("ws_account.json");
3345        let msg: OKXWsFrame = serde_json::from_str(&json_data).unwrap();
3346
3347        let OKXWsFrame::Data { data, .. } = msg else {
3348            panic!("Expected OKXWsFrame::Data");
3349        };
3350
3351        let accounts: Vec<OKXAccount> = serde_json::from_value(data).unwrap();
3352
3353        assert_eq!(accounts.len(), 1);
3354        let account = &accounts[0];
3355
3356        assert_eq!(account.total_eq, "100.56089404807182");
3357        assert_eq!(account.details.len(), 3);
3358
3359        let usdt_detail = &account.details[0];
3360        assert_eq!(usdt_detail.ccy, "USDT");
3361        assert_eq!(usdt_detail.avail_bal, "100.52768569797846");
3362        assert_eq!(usdt_detail.cash_bal, "100.52768569797846");
3363
3364        let btc_detail = &account.details[1];
3365        assert_eq!(btc_detail.ccy, "BTC");
3366        assert_eq!(btc_detail.avail_bal, "0.0000000051");
3367
3368        let eth_detail = &account.details[2];
3369        assert_eq!(eth_detail.ccy, "ETH");
3370        assert_eq!(eth_detail.avail_bal, "0.000000185");
3371
3372        let account_id = AccountId::new("OKX-001");
3373        let ts_init = UnixNanos::default();
3374        let account_state = parse_account_state(account, account_id, AccountType::Margin, ts_init);
3375
3376        assert!(account_state.is_ok());
3377        let state = account_state.unwrap();
3378        assert_eq!(state.account_id, account_id);
3379        assert_eq!(state.balances.len(), 3);
3380    }
3381
3382    #[rstest]
3383    fn test_parse_ws_account_message_empty_balance() {
3384        // GH-3772: OKX returns empty strings and empty details for zero-balance accounts
3385        let json_data = load_test_json("ws_account_empty.json");
3386        let msg: OKXWsFrame = serde_json::from_str(&json_data).unwrap();
3387
3388        let OKXWsFrame::Data { data, .. } = msg else {
3389            panic!("Expected OKXWsFrame::Data");
3390        };
3391
3392        let accounts: Vec<OKXAccount> = serde_json::from_value(data).unwrap();
3393        assert_eq!(accounts.len(), 1);
3394
3395        let account = &accounts[0];
3396        assert!(account.details.is_empty());
3397        assert_eq!(account.total_eq, "0");
3398
3399        let account_id = AccountId::new("OKX-001");
3400        let account_state = parse_account_state(
3401            account,
3402            account_id,
3403            AccountType::Margin,
3404            UnixNanos::default(),
3405        )
3406        .unwrap();
3407
3408        assert_eq!(account_state.account_id, account_id);
3409        assert_eq!(account_state.margins.len(), 0);
3410        assert_eq!(account_state.balances.len(), 1);
3411
3412        let balance = &account_state.balances[0];
3413        assert_eq!(balance.total, Money::new(0.0, Currency::USD()));
3414        assert_eq!(balance.free, Money::new(0.0, Currency::USD()));
3415        assert_eq!(balance.locked, Money::new(0.0, Currency::USD()));
3416    }
3417
3418    #[rstest]
3419    fn test_parse_order_msg() {
3420        let json_data = load_test_json("ws_orders.json");
3421        let ws_msg: serde_json::Value = serde_json::from_str(&json_data).unwrap();
3422
3423        let data: Vec<OKXOrderMsg> = serde_json::from_value(ws_msg["data"].clone()).unwrap();
3424
3425        let account_id = AccountId::new("OKX-001");
3426        let mut instruments = AHashMap::new();
3427
3428        // Create a mock instrument for testing
3429        let instrument_id = InstrumentId::from("BTC-USDT-SWAP.OKX");
3430        let instrument = create_stub_instrument();
3431
3432        instruments.insert(
3433            Ustr::from("BTC-USDT-SWAP"),
3434            InstrumentAny::CryptoPerpetual(instrument),
3435        );
3436
3437        let ts_init = UnixNanos::default();
3438        let mut fee_cache = FeeCache::new();
3439        let mut filled_qty_cache = FilledQtyCache::new();
3440
3441        let result = parse_order_msg_vec(
3442            &data,
3443            account_id,
3444            &instruments,
3445            &mut fee_cache,
3446            &mut filled_qty_cache,
3447            ts_init,
3448        );
3449
3450        assert!(result.is_ok());
3451        let order_reports = result.unwrap();
3452        assert_eq!(order_reports.len(), 1);
3453
3454        // Verify the parsed order report
3455        let report = &order_reports[0];
3456
3457        if let ExecutionReport::Fill(fill_report) = report {
3458            assert_eq!(fill_report.account_id, account_id);
3459            assert_eq!(fill_report.instrument_id, instrument_id);
3460            assert_eq!(
3461                fill_report.client_order_id,
3462                Some(ClientOrderId::new("001BTCUSDT20250106001"))
3463            );
3464            assert_eq!(
3465                fill_report.venue_order_id,
3466                VenueOrderId::new("2497956918703120384")
3467            );
3468            assert_eq!(fill_report.trade_id, TradeId::from("1518905529"));
3469            assert_eq!(fill_report.order_side, OrderSide::Buy);
3470            assert_eq!(fill_report.last_px, Price::from("103698.90"));
3471            assert_eq!(fill_report.last_qty, Quantity::from("0.03000000"));
3472            assert_eq!(fill_report.liquidity_side, LiquiditySide::Maker);
3473        } else {
3474            panic!("Expected Fill report for filled order");
3475        }
3476    }
3477
3478    #[rstest]
3479    fn test_parse_order_status_report() {
3480        let json_data = load_test_json("ws_orders.json");
3481        let ws_msg: serde_json::Value = serde_json::from_str(&json_data).unwrap();
3482        let data: Vec<OKXOrderMsg> = serde_json::from_value(ws_msg["data"].clone()).unwrap();
3483        let order_msg = &data[0];
3484
3485        let account_id = AccountId::new("OKX-001");
3486        let instrument_id = InstrumentId::from("BTC-USDT-SWAP.OKX");
3487        let instrument = create_stub_instrument();
3488
3489        let ts_init = UnixNanos::default();
3490
3491        let result = parse_order_status_report(
3492            order_msg,
3493            &InstrumentAny::CryptoPerpetual(instrument),
3494            account_id,
3495            ts_init,
3496        );
3497
3498        assert!(result.is_ok());
3499        let order_status_report = result.unwrap();
3500
3501        assert_eq!(order_status_report.account_id, account_id);
3502        assert_eq!(order_status_report.instrument_id, instrument_id);
3503        assert_eq!(
3504            order_status_report.client_order_id,
3505            Some(ClientOrderId::new("001BTCUSDT20250106001"))
3506        );
3507        assert_eq!(
3508            order_status_report.venue_order_id,
3509            VenueOrderId::new("2497956918703120384")
3510        );
3511        assert_eq!(order_status_report.order_side, OrderSide::Buy.into());
3512        assert_eq!(order_status_report.order_status, OrderStatus::Filled);
3513        assert_eq!(order_status_report.quantity, Quantity::from("0.03000000"));
3514        assert_eq!(order_status_report.filled_qty, Quantity::from("0.03000000"));
3515    }
3516
3517    #[rstest]
3518    #[case::base_filled(
3519        OKXOrderStatus::Filled,
3520        OKXTargetCurrency::BaseCcy,
3521        "0.00296487",
3522        "0.00296475",
3523        "0.00296475"
3524    )]
3525    #[case::base_partial(
3526        OKXOrderStatus::PartiallyFilled,
3527        OKXTargetCurrency::BaseCcy,
3528        "0.00296487",
3529        "0.00296475",
3530        "0.00296487"
3531    )]
3532    #[case::base_canceled(
3533        OKXOrderStatus::Canceled,
3534        OKXTargetCurrency::BaseCcy,
3535        "0.00296487",
3536        "0.00296475",
3537        "0.00296487"
3538    )]
3539    #[case::base_zero_fill(
3540        OKXOrderStatus::Filled,
3541        OKXTargetCurrency::BaseCcy,
3542        "0.00296487",
3543        "0",
3544        "0.00296487"
3545    )]
3546    #[case::quote_filled(
3547        OKXOrderStatus::Filled,
3548        OKXTargetCurrency::QuoteCcy,
3549        "296.487",
3550        "0.00296475",
3551        "0.00296475"
3552    )]
3553    fn test_parse_order_status_report_terminal_quantity(
3554        #[values("", "0")] price: &str,
3555        #[case] state: OKXOrderStatus,
3556        #[case] target: OKXTargetCurrency,
3557        #[case] size: &str,
3558        #[case] filled: &str,
3559        #[case] expected_quantity: &str,
3560    ) {
3561        let payload: Value = serde_json::from_str(&load_test_json("ws_orders.json")).unwrap();
3562        let mut order: OKXOrderMsg = serde_json::from_value(payload["data"][0].clone()).unwrap();
3563        order.inst_type = OKXInstrumentType::Spot;
3564        order.ord_type = OKXOrderType::Market;
3565        order.side = OKXSide::Buy;
3566        order.tgt_ccy = Some(target);
3567        order.state = state;
3568        order.sz = size.to_string();
3569        order.acc_fill_sz = Some(filled.to_string());
3570        order.px = price.to_string();
3571        order.avg_px = "100000".to_string();
3572        let instrument = CurrencyPair::builder()
3573            .instrument_id(InstrumentId::from("BTC-USDC.OKX"))
3574            .raw_symbol(Symbol::from("BTC-USDC"))
3575            .base_currency(Currency::BTC())
3576            .quote_currency(Currency::USDC())
3577            .price_precision(2)
3578            .size_precision(8)
3579            .price_increment(Price::from("0.01"))
3580            .size_increment(Quantity::from("0.00000001"))
3581            .ts_event(UnixNanos::default())
3582            .ts_init(UnixNanos::default())
3583            .build()
3584            .unwrap();
3585
3586        let report = parse_order_status_report(
3587            &order,
3588            &InstrumentAny::CurrencyPair(instrument),
3589            AccountId::from("OKX-001"),
3590            UnixNanos::default(),
3591        )
3592        .unwrap();
3593
3594        assert_eq!(report.price, None);
3595        assert_eq!(report.order_status, OrderStatus::try_from(state).unwrap());
3596        assert_eq!(report.quantity, Quantity::from(expected_quantity));
3597        assert_eq!(report.filled_qty, Quantity::from(filled));
3598    }
3599
3600    #[rstest]
3601    fn test_parse_fill_report() {
3602        let json_data = load_test_json("ws_orders.json");
3603        let ws_msg: serde_json::Value = serde_json::from_str(&json_data).unwrap();
3604        let data: Vec<OKXOrderMsg> = serde_json::from_value(ws_msg["data"].clone()).unwrap();
3605        let order_msg = &data[0];
3606
3607        let account_id = AccountId::new("OKX-001");
3608        let instrument_id = InstrumentId::from("BTC-USDT-SWAP.OKX");
3609        let instrument = create_stub_instrument();
3610
3611        let ts_init = UnixNanos::default();
3612
3613        let result = parse_fill_report(
3614            order_msg,
3615            &InstrumentAny::CryptoPerpetual(instrument),
3616            account_id,
3617            None,
3618            None,
3619            ts_init,
3620        );
3621
3622        assert!(result.is_ok());
3623        let fill_report = result.unwrap().unwrap();
3624
3625        assert_eq!(fill_report.account_id, account_id);
3626        assert_eq!(fill_report.instrument_id, instrument_id);
3627        assert_eq!(
3628            fill_report.client_order_id,
3629            Some(ClientOrderId::new("001BTCUSDT20250106001"))
3630        );
3631        assert_eq!(
3632            fill_report.venue_order_id,
3633            VenueOrderId::new("2497956918703120384")
3634        );
3635        assert_eq!(fill_report.trade_id, TradeId::from("1518905529"));
3636        assert_eq!(fill_report.order_side, OrderSide::Buy);
3637        assert_eq!(fill_report.last_px, Price::from("103698.90"));
3638        assert_eq!(fill_report.last_qty, Quantity::from("0.03000000"));
3639        assert_eq!(fill_report.liquidity_side, LiquiditySide::Maker);
3640    }
3641
3642    #[rstest]
3643    fn test_parse_fill_report_rejects_missing_fee() {
3644        let instrument = create_stub_instrument();
3645        let mut msg = create_stub_order_msg("0.01", None, "ord-1", "trade-1");
3646        msg.fee = None;
3647
3648        let error = parse_fill_report(
3649            &msg,
3650            &InstrumentAny::CryptoPerpetual(instrument),
3651            AccountId::new("OKX-001"),
3652            None,
3653            None,
3654            UnixNanos::default(),
3655        )
3656        .unwrap_err();
3657
3658        assert!(error.to_string().contains("missing fee"));
3659    }
3660
3661    #[rstest]
3662    #[case::charge("-0.03", "0.03 USD")]
3663    #[case::rebate("0.02", "-0.02 USD")]
3664    #[case::zero("0", "0 USD")]
3665    fn test_parse_fill_report_uses_per_fill_fee(#[case] fee: &str, #[case] expected: &str) {
3666        let instrument = InstrumentAny::CryptoPerpetual(create_stub_instrument());
3667        let mut msg = create_stub_order_msg("0.006", Some("0.010".into()), "ord-1", "trade-2");
3668        msg.fee = Some("-0.05".into());
3669        msg.fee_ccy = Ustr::from("BTC");
3670        msg.fill_fee = Some(fee.into());
3671        msg.fill_fee_ccy = Some(Ustr::from("USD"));
3672        let report = parse_fill_report(
3673            &msg,
3674            &instrument,
3675            AccountId::from("OKX-001"),
3676            None,
3677            None,
3678            UnixNanos::default(),
3679        )
3680        .unwrap()
3681        .unwrap();
3682        assert_eq!(report.trade_id, TradeId::from("trade-2"));
3683        assert_eq!(report.last_qty, Quantity::from("0.00600000"));
3684        assert_eq!(report.commission, Money::from(expected));
3685    }
3686
3687    #[rstest]
3688    #[case::absent(None, "missing fee for fill report inst_id=BTC-USDT-SWAP")]
3689    #[case::empty(Some(""), "missing fee for fill report inst_id=BTC-USDT-SWAP")]
3690    #[case::invalid(
3691        Some("invalid"),
3692        "Failed to parse fee 'invalid': Invalid decimal: unknown character"
3693    )]
3694    fn test_per_fill_fee_requires_valid_cumulative_fee(
3695        #[case] cumulative_fee: Option<&str>,
3696        #[case] expected: &str,
3697    ) {
3698        let instrument = InstrumentAny::CryptoPerpetual(create_stub_instrument());
3699        let mut msg = create_stub_order_msg("0.004", Some("0.004".into()), "ord-1", "trade-1");
3700        msg.fee = cumulative_fee.map(str::to_owned);
3701        msg.fill_fee = Some("-0.02".into());
3702        msg.fill_fee_ccy = Some(Ustr::from("USD"));
3703
3704        let error = parse_fill_report(
3705            &msg,
3706            &instrument,
3707            AccountId::from("OKX-001"),
3708            None,
3709            None,
3710            UnixNanos::default(),
3711        )
3712        .unwrap_err();
3713
3714        assert_eq!(error.to_string(), expected);
3715    }
3716
3717    #[rstest]
3718    fn test_per_fill_then_cumulative_fee_preserves_total(
3719        #[values(false, true)] prior_fill: bool,
3720        #[values("USD", "BTC")] currency: &str,
3721    ) {
3722        let instrument = InstrumentAny::CryptoPerpetual(create_stub_instrument());
3723        let account_id = AccountId::from("OKX-001");
3724        let mut fees = FeeCache::new();
3725        let mut quantities = FilledQtyCache::new();
3726        let zero = format!("0 {currency}");
3727        let mut total = Money::from(zero.as_str());
3728
3729        if prior_fill {
3730            let mut prior =
3731                create_stub_order_msg("0.002", Some("0.002".into()), "ord-1", "trade-0");
3732            prior.fee = Some("-0.01".into());
3733            prior.fee_ccy = Ustr::from(currency);
3734            let fill = parse_fill_report(
3735                &prior,
3736                &instrument,
3737                account_id,
3738                None,
3739                None,
3740                UnixNanos::default(),
3741            )
3742            .unwrap()
3743            .unwrap();
3744            total = total + fill.commission;
3745            update_fee_fill_caches(&prior, &instrument, &mut fees, &mut quantities);
3746        }
3747
3748        let mut first = create_stub_order_msg(
3749            "0.004",
3750            Some(if prior_fill { "0.006" } else { "0.004" }.into()),
3751            "ord-1",
3752            "trade-1",
3753        );
3754        first.fee = None;
3755        first.fee_ccy = Ustr::from(currency);
3756        first.fill_fee = Some("-0.02".into());
3757        first.fill_fee_ccy = Some(Ustr::from(currency));
3758        let mut second = create_stub_order_msg(
3759            "0.006",
3760            Some(if prior_fill { "0.012" } else { "0.010" }.into()),
3761            "ord-1",
3762            "trade-2",
3763        );
3764        second.fee = Some(if prior_fill { "-0.06" } else { "-0.05" }.into());
3765        second.fee_ccy = Ustr::from(currency);
3766
3767        let first_error = parse_fill_report(
3768            &first,
3769            &instrument,
3770            account_id,
3771            fees.get(&first.ord_id).copied(),
3772            quantities.get(&first.ord_id).copied(),
3773            UnixNanos::default(),
3774        )
3775        .unwrap_err();
3776        let second_error = parse_fill_report(
3777            &second,
3778            &instrument,
3779            account_id,
3780            fees.get(&second.ord_id).copied(),
3781            quantities.get(&second.ord_id).copied(),
3782            UnixNanos::default(),
3783        )
3784        .unwrap_err();
3785        first.fee = Some(if prior_fill { "-0.03" } else { "-0.02" }.into());
3786        let first_fill = parse_fill_report(
3787            &first,
3788            &instrument,
3789            account_id,
3790            fees.get(&first.ord_id).copied(),
3791            quantities.get(&first.ord_id).copied(),
3792            UnixNanos::default(),
3793        )
3794        .unwrap()
3795        .unwrap();
3796        update_fee_fill_caches(&first, &instrument, &mut fees, &mut quantities);
3797        let second_fill = parse_fill_report(
3798            &second,
3799            &instrument,
3800            account_id,
3801            fees.get(&second.ord_id).copied(),
3802            quantities.get(&second.ord_id).copied(),
3803            UnixNanos::default(),
3804        )
3805        .unwrap()
3806        .unwrap();
3807        total = total + first_fill.commission;
3808        total = total + second_fill.commission;
3809        let first_commission = format!("0.02 {currency}");
3810        let second_commission = format!("0.03 {currency}");
3811        let expected_total = format!("{} {currency}", if prior_fill { "0.06" } else { "0.05" });
3812
3813        assert_eq!(
3814            first_error.to_string(),
3815            "missing fee for fill report inst_id=BTC-USDT-SWAP"
3816        );
3817        assert_eq!(
3818            second_error.to_string(),
3819            "missing per-fill fee across a private fill gap for ord-1"
3820        );
3821        assert_eq!(first_fill.trade_id, TradeId::from("trade-1"));
3822        assert_eq!(first_fill.last_qty, Quantity::from("0.00400000"));
3823        assert_eq!(
3824            first_fill.commission,
3825            Money::from(first_commission.as_str())
3826        );
3827        assert_eq!(second_fill.trade_id, TradeId::from("trade-2"));
3828        assert_eq!(second_fill.last_qty, Quantity::from("0.00600000"));
3829        assert_eq!(
3830            second_fill.commission,
3831            Money::from(second_commission.as_str())
3832        );
3833        assert_eq!(total, Money::from(expected_total.as_str()));
3834    }
3835
3836    #[rstest]
3837    fn test_parse_fill_report_defers_fee_across_missing_private_fill() {
3838        let instrument = InstrumentAny::CryptoPerpetual(create_stub_instrument());
3839        let mut msg = create_stub_order_msg("0.006", Some("0.010".into()), "ord-1", "trade-2");
3840        msg.fee = Some("-0.05".into());
3841        let error = parse_fill_report(
3842            &msg,
3843            &instrument,
3844            AccountId::from("OKX-001"),
3845            None,
3846            None,
3847            UnixNanos::default(),
3848        )
3849        .unwrap_err();
3850        assert_eq!(
3851            error.to_string(),
3852            "missing per-fill fee across a private fill gap for ord-1"
3853        );
3854    }
3855
3856    #[rstest]
3857    fn test_parse_fill_report_rejects_missing_per_fill_fee_currency() {
3858        let instrument = InstrumentAny::CryptoPerpetual(create_stub_instrument());
3859        let mut msg = create_stub_order_msg("0.006", Some("0.010".into()), "ord-1", "trade-2");
3860        msg.fill_fee = Some("-0.03".into());
3861        msg.fill_fee_ccy = None;
3862        let error = parse_fill_report(
3863            &msg,
3864            &instrument,
3865            AccountId::from("OKX-001"),
3866            None,
3867            None,
3868            UnixNanos::default(),
3869        )
3870        .unwrap_err();
3871        assert_eq!(error.to_string(), "missing per-fill fee currency");
3872    }
3873
3874    #[rstest]
3875    fn test_zero_fill_terminal_update_preserves_and_retires_baselines() {
3876        let instrument = InstrumentAny::CryptoPerpetual(create_stub_instrument());
3877        let mut fees = FeeCache::new();
3878        let mut quantities = FilledQtyCache::new();
3879        let mut msg = create_stub_order_msg("0.004", Some("0.004".into()), "retired", "trade-1");
3880        msg.fee = Some("-0.02".into());
3881        update_fee_fill_caches(&msg, &instrument, &mut fees, &mut quantities);
3882        msg.acc_fill_sz = Some("0".into());
3883        msg.fee = Some("0".into());
3884        msg.state = OKXOrderStatus::Canceled;
3885        update_fee_fill_caches(&msg, &instrument, &mut fees, &mut quantities);
3886        assert_eq!(fees.get(&msg.ord_id), Some(&Money::from("0.02 USDT")));
3887        assert_eq!(
3888            quantities.get(&msg.ord_id),
3889            Some(&Quantity::from("0.00400000"))
3890        );
3891
3892        for index in 0..TERMINAL_BASELINE_CAPACITY {
3893            let mut terminal = create_stub_order_msg(
3894                "0.001",
3895                Some("0.001".into()),
3896                &format!("terminal{index}"),
3897                "trade-2",
3898            );
3899            terminal.state = OKXOrderStatus::Filled;
3900            update_fee_fill_caches(&terminal, &instrument, &mut fees, &mut quantities);
3901        }
3902
3903        assert_eq!(fees.get(&msg.ord_id), None);
3904        assert_eq!(quantities.get(&msg.ord_id), None);
3905    }
3906
3907    #[rstest]
3908    fn test_stale_acceptance_preserves_cumulative_fee_baseline(
3909        #[values(None, Some(""), Some("0"), Some("0.00000000"))] cumulative: Option<&str>,
3910    ) {
3911        let instrument = InstrumentAny::CryptoPerpetual(create_stub_instrument());
3912        let mut fees = FeeCache::new();
3913        let mut quantities = FilledQtyCache::new();
3914        let mut msg = create_stub_order_msg("0.004", Some("0.004".into()), "ord-1", "trade-1");
3915        msg.fee = Some("-0.02".into());
3916        update_fee_fill_caches(&msg, &instrument, &mut fees, &mut quantities);
3917        msg.state = OKXOrderStatus::Live;
3918        msg.acc_fill_sz = cumulative.map(str::to_string);
3919        msg.fee = Some("0".into());
3920        update_fee_fill_caches(&msg, &instrument, &mut fees, &mut quantities);
3921        let mut remainder =
3922            create_stub_order_msg("0.006", Some("0.010".into()), "ord-1", "trade-2");
3923        remainder.fee = Some("-0.05".into());
3924        let report = parse_fill_report(
3925            &remainder,
3926            &instrument,
3927            AccountId::from("OKX-001"),
3928            fees.get(&msg.ord_id).copied(),
3929            quantities.get(&msg.ord_id).copied(),
3930            UnixNanos::default(),
3931        )
3932        .unwrap()
3933        .unwrap();
3934        assert_eq!(report.commission, Money::from("0.03 USDT"));
3935        assert_eq!(report.last_qty, Quantity::from("0.00600000"));
3936    }
3937
3938    #[rstest]
3939    fn test_parse_book_depth_msg() {
3940        let json_data = load_test_json("ws_books_snapshot.json");
3941        let event: OKXWsFrame = serde_json::from_str(&json_data).unwrap();
3942        let msgs: Vec<OKXBookMsg> = match event {
3943            OKXWsFrame::BookData { data, .. } => data,
3944            _ => panic!("Expected BookData"),
3945        };
3946
3947        let instrument_id = InstrumentId::from("BTC-USDT.OKX");
3948        let depth =
3949            parse_book_depth_msg(&msgs[0], instrument_id, 2, 0, UnixNanos::default()).unwrap();
3950
3951        let expected_bids = [
3952            ("8476.97", "256"),
3953            ("8475.55", "101"),
3954            ("8475.54", "100"),
3955            ("8475.30", "1"),
3956            ("8447.32", "6"),
3957            ("8447.02", "246"),
3958            ("8446.83", "24"),
3959            ("8446.00", "95"),
3960        ];
3961        let expected_asks = [
3962            ("8476.98", "415"),
3963            ("8477.00", "7"),
3964            ("8477.34", "85"),
3965            ("8477.56", "1"),
3966            ("8505.84", "8"),
3967            ("8506.37", "85"),
3968            ("8506.49", "2"),
3969            ("8506.96", "100"),
3970        ];
3971
3972        assert_eq!(depth.instrument_id, instrument_id);
3973        assert_eq!(depth.sequence, 123_456);
3974        assert_eq!(depth.ts_event, UnixNanos::from(1_597_026_383_085_000_000));
3975        assert_eq!(depth.ts_init, UnixNanos::default());
3976        assert_eq!(depth.flags, RecordFlag::F_SNAPSHOT as u8);
3977        assert_eq!(depth.bids.len(), expected_bids.len());
3978        assert_eq!(depth.asks.len(), expected_asks.len());
3979        assert_eq!(depth.bid_counts.as_slice(), &[12, 1, 1, 1, 1, 1, 1, 3]);
3980        assert_eq!(depth.ask_counts.as_slice(), &[13, 2, 1, 1, 1, 1, 1, 2]);
3981        for (order, (price, size)) in depth.bids.iter().zip(expected_bids) {
3982            assert_eq!(order.side, Some(OrderSide::Buy));
3983            assert_eq!(order.price, Price::from(price));
3984            assert_eq!(order.size, Quantity::from(size));
3985            assert_eq!(order.order_id, 0);
3986        }
3987
3988        for (order, (price, size)) in depth.asks.iter().zip(expected_asks) {
3989            assert_eq!(order.side, Some(OrderSide::Sell));
3990            assert_eq!(order.price, Price::from(price));
3991            assert_eq!(order.size, Quantity::from(size));
3992            assert_eq!(order.order_id, 0);
3993        }
3994    }
3995
3996    #[rstest]
3997    fn test_parse_book_depth_msg_vec() {
3998        let json_data = load_test_json("ws_books_snapshot.json");
3999        let event: OKXWsFrame = serde_json::from_str(&json_data).unwrap();
4000        let msgs: Vec<OKXBookMsg> = match event {
4001            OKXWsFrame::BookData { data, .. } => data,
4002            _ => panic!("Expected BookData"),
4003        };
4004
4005        let instrument_id = InstrumentId::from("BTC-USDT.OKX");
4006        let depth_vec =
4007            parse_book_depth_msg_vec(msgs, &instrument_id, 2, 0, UnixNanos::default()).unwrap();
4008
4009        assert_eq!(depth_vec.len(), 1);
4010
4011        if let Data::BookDepth(d) = &depth_vec[0] {
4012            assert_eq!(d.instrument_id, instrument_id);
4013            assert_eq!(d.sequence, 123_456);
4014            assert_eq!(d.bids[0].price, Price::from("8476.97"));
4015            assert_eq!(d.asks[0].price, Price::from("8476.98"));
4016        } else {
4017            panic!("Expected Depth");
4018        }
4019    }
4020
4021    #[rstest]
4022    fn test_parse_fill_report_with_fee_cache() {
4023        let instrument = create_stub_instrument();
4024
4025        let account_id = AccountId::new("OKX-001");
4026        let ts_init = UnixNanos::default();
4027
4028        // First fill: 0.01 BTC out of 0.03 BTC total (1/3)
4029        let mut order_msg_1 =
4030            create_stub_order_msg("0.01", Some("0.01".to_string()), "1234567890", "trade_1");
4031        order_msg_1.exec_type = OKXExecType::Maker;
4032
4033        let fill_report_1 = parse_fill_report(
4034            &order_msg_1,
4035            &InstrumentAny::CryptoPerpetual(instrument.clone()),
4036            account_id,
4037            None,
4038            None,
4039            ts_init,
4040        )
4041        .unwrap()
4042        .unwrap();
4043
4044        // First fill should get the full fee since there's no previous fee
4045        assert_eq!(fill_report_1.commission, Money::new(1.0, Currency::USDT()));
4046
4047        // Second fill: 0.02 BTC more, now 0.03 BTC total (completely filled)
4048        let mut order_msg_2 =
4049            create_stub_order_msg("0.02", Some("0.03".to_string()), "1234567890", "trade_2");
4050        order_msg_2.fee = Some("-3.0".to_string());
4051        order_msg_2.fill_time = 1_746_947_317_403;
4052        order_msg_2.state = OKXOrderStatus::Filled;
4053        order_msg_2.exec_type = OKXExecType::Maker;
4054        order_msg_2.u_time = 1_746_947_317_403;
4055
4056        let fill_report_2 = parse_fill_report(
4057            &order_msg_2,
4058            &InstrumentAny::CryptoPerpetual(instrument),
4059            account_id,
4060            Some(fill_report_1.commission),
4061            Some(fill_report_1.last_qty),
4062            ts_init,
4063        )
4064        .unwrap()
4065        .unwrap();
4066
4067        // Second fill should get total_fee - previous_fee = 3.0 - 1.0 = 2.0
4068        assert_eq!(fill_report_2.commission, Money::new(2.0, Currency::USDT()));
4069
4070        // Test passed - fee was correctly split proportionally
4071    }
4072
4073    #[rstest]
4074    fn test_parse_fill_report_with_maker_rebates() {
4075        let instrument = create_stub_instrument();
4076
4077        let account_id = AccountId::new("OKX-001");
4078        let ts_init = UnixNanos::default();
4079
4080        // First fill: maker rebate of $0.5 (OKX sends as "0.5", parse_fee makes it -0.5)
4081        let mut order_msg_1 = create_stub_order_msg(
4082            "0.01",
4083            Some("0.01".to_string()),
4084            "rebate_order_123",
4085            "trade_rebate_1",
4086        );
4087        order_msg_1.cl_ord_id = "test_order_rebate".to_string();
4088        order_msg_1.fee = Some("0.5".to_string());
4089        order_msg_1.exec_type = OKXExecType::Maker;
4090        order_msg_1.sz = "0.02".to_string();
4091
4092        let fill_report_1 = parse_fill_report(
4093            &order_msg_1,
4094            &InstrumentAny::CryptoPerpetual(instrument.clone()),
4095            account_id,
4096            None,
4097            None,
4098            ts_init,
4099        )
4100        .unwrap()
4101        .unwrap();
4102
4103        // First fill gets the full rebate (negative commission)
4104        assert_eq!(fill_report_1.commission, Money::new(-0.5, Currency::USDT()));
4105
4106        // Second fill: another maker rebate of $0.3, cumulative now $0.8
4107        let mut order_msg_2 = create_stub_order_msg(
4108            "0.01",
4109            Some("0.02".to_string()),
4110            "rebate_order_123",
4111            "trade_rebate_2",
4112        );
4113        order_msg_2.cl_ord_id = "test_order_rebate".to_string();
4114        order_msg_2.fee = Some("0.8".to_string());
4115        order_msg_2.fill_time = 1_746_947_317_403;
4116        order_msg_2.state = OKXOrderStatus::Filled;
4117        order_msg_2.exec_type = OKXExecType::Maker;
4118        order_msg_2.sz = "0.02".to_string();
4119        order_msg_2.u_time = 1_746_947_317_403;
4120
4121        let fill_report_2 = parse_fill_report(
4122            &order_msg_2,
4123            &InstrumentAny::CryptoPerpetual(instrument),
4124            account_id,
4125            Some(fill_report_1.commission),
4126            Some(fill_report_1.last_qty),
4127            ts_init,
4128        )
4129        .unwrap()
4130        .unwrap();
4131
4132        // Second fill: incremental = -0.8 - (-0.5) = -0.3
4133        assert_eq!(fill_report_2.commission, Money::new(-0.3, Currency::USDT()));
4134    }
4135
4136    #[rstest]
4137    fn test_parse_fill_report_rebate_to_charge_transition() {
4138        let instrument = create_stub_instrument();
4139
4140        let account_id = AccountId::new("OKX-001");
4141        let ts_init = UnixNanos::default();
4142
4143        // First fill: maker rebate of $1.0
4144        let mut order_msg_1 = create_stub_order_msg(
4145            "0.01",
4146            Some("0.01".to_string()),
4147            "transition_order_456",
4148            "trade_transition_1",
4149        );
4150        order_msg_1.cl_ord_id = "test_order_transition".to_string();
4151        order_msg_1.fee = Some("1.0".to_string());
4152        order_msg_1.exec_type = OKXExecType::Maker;
4153        order_msg_1.sz = "0.02".to_string();
4154
4155        let fill_report_1 = parse_fill_report(
4156            &order_msg_1,
4157            &InstrumentAny::CryptoPerpetual(instrument.clone()),
4158            account_id,
4159            None,
4160            None,
4161            ts_init,
4162        )
4163        .unwrap()
4164        .unwrap();
4165
4166        // First fill gets rebate (negative)
4167        assert_eq!(fill_report_1.commission, Money::new(-1.0, Currency::USDT()));
4168
4169        // Second fill: taker charge of $5.0, net cumulative is now $2.0 charge
4170        // This is the edge case: incremental = 2.0 - (-1.0) = 3.0, which exceeds total (2.0)
4171        // But it's legitimate, not corruption
4172        let mut order_msg_2 = create_stub_order_msg(
4173            "0.01",
4174            Some("0.02".to_string()),
4175            "transition_order_456",
4176            "trade_transition_2",
4177        );
4178        order_msg_2.cl_ord_id = "test_order_transition".to_string();
4179        order_msg_2.fee = Some("-2.0".to_string());
4180        order_msg_2.fill_time = 1_746_947_317_403;
4181        order_msg_2.state = OKXOrderStatus::Filled;
4182        order_msg_2.sz = "0.02".to_string();
4183        order_msg_2.u_time = 1_746_947_317_403;
4184
4185        let fill_report_2 = parse_fill_report(
4186            &order_msg_2,
4187            &InstrumentAny::CryptoPerpetual(instrument),
4188            account_id,
4189            Some(fill_report_1.commission),
4190            Some(fill_report_1.last_qty),
4191            ts_init,
4192        )
4193        .unwrap()
4194        .unwrap();
4195
4196        // Second fill: incremental = 2.0 - (-1.0) = 3.0
4197        // This should NOT trigger corruption detection because previous was negative
4198        assert_eq!(fill_report_2.commission, Money::new(3.0, Currency::USDT()));
4199    }
4200
4201    #[rstest]
4202    fn test_parse_fill_report_negative_incremental() {
4203        let instrument = create_stub_instrument();
4204
4205        let account_id = AccountId::new("OKX-001");
4206        let ts_init = UnixNanos::default();
4207
4208        // First fill: charge of $2.0
4209        let mut order_msg_1 = create_stub_order_msg(
4210            "0.01",
4211            Some("0.01".to_string()),
4212            "neg_inc_order_789",
4213            "trade_neg_inc_1",
4214        );
4215        order_msg_1.cl_ord_id = "test_order_neg_inc".to_string();
4216        order_msg_1.fee = Some("-2.0".to_string());
4217        order_msg_1.sz = "0.02".to_string();
4218
4219        let fill_report_1 = parse_fill_report(
4220            &order_msg_1,
4221            &InstrumentAny::CryptoPerpetual(instrument.clone()),
4222            account_id,
4223            None,
4224            None,
4225            ts_init,
4226        )
4227        .unwrap()
4228        .unwrap();
4229
4230        assert_eq!(fill_report_1.commission, Money::new(2.0, Currency::USDT()));
4231
4232        // Second fill: charge reduced to $1.5 total (refund or maker rebate on this fill)
4233        // Incremental = 1.5 - 2.0 = -0.5 (negative incremental triggers debug log)
4234        let mut order_msg_2 = create_stub_order_msg(
4235            "0.01",
4236            Some("0.02".to_string()),
4237            "neg_inc_order_789",
4238            "trade_neg_inc_2",
4239        );
4240        order_msg_2.cl_ord_id = "test_order_neg_inc".to_string();
4241        order_msg_2.fee = Some("-1.5".to_string());
4242        order_msg_2.fill_time = 1_746_947_317_403;
4243        order_msg_2.state = OKXOrderStatus::Filled;
4244        order_msg_2.exec_type = OKXExecType::Maker;
4245        order_msg_2.sz = "0.02".to_string();
4246        order_msg_2.u_time = 1_746_947_317_403;
4247
4248        let fill_report_2 = parse_fill_report(
4249            &order_msg_2,
4250            &InstrumentAny::CryptoPerpetual(instrument),
4251            account_id,
4252            Some(fill_report_1.commission),
4253            Some(fill_report_1.last_qty),
4254            ts_init,
4255        )
4256        .unwrap()
4257        .unwrap();
4258
4259        // Incremental is negative: 1.5 - 2.0 = -0.5
4260        assert_eq!(fill_report_2.commission, Money::new(-0.5, Currency::USDT()));
4261    }
4262
4263    #[rstest]
4264    fn test_parse_fill_report_fee_currency_change_no_panic() {
4265        let instrument = create_stub_instrument();
4266        let account_id = AccountId::new("OKX-001");
4267        let ts_init = UnixNanos::default();
4268
4269        // First fill charged in USDT
4270        let previous_fee = Money::new(1.0, Currency::USDT());
4271
4272        // Second fill charged in BTC (fee currency changed)
4273        let mut order_msg =
4274            create_stub_order_msg("0.01", Some("0.02".to_string()), "1234567890", "trade_2");
4275        order_msg.fee = Some("-0.00005".to_string());
4276        order_msg.fee_ccy = Ustr::from("BTC");
4277
4278        let result = parse_fill_report(
4279            &order_msg,
4280            &InstrumentAny::CryptoPerpetual(instrument),
4281            account_id,
4282            Some(previous_fee),
4283            Some(Quantity::from("0.01")),
4284            ts_init,
4285        );
4286
4287        let fill_report = result.unwrap().unwrap();
4288        assert_eq!(fill_report.commission.currency, Currency::BTC());
4289    }
4290
4291    #[rstest]
4292    fn test_parse_fill_report_empty_fill_sz_first_fill() {
4293        let instrument = create_stub_instrument();
4294        let account_id = AccountId::new("OKX-001");
4295        let ts_init = UnixNanos::default();
4296
4297        let order_msg =
4298            create_stub_order_msg("", Some("0.01".to_string()), "1234567890", "trade_1");
4299
4300        let fill_report = parse_fill_report(
4301            &order_msg,
4302            &InstrumentAny::CryptoPerpetual(instrument),
4303            account_id,
4304            None,
4305            None,
4306            ts_init,
4307        )
4308        .unwrap()
4309        .unwrap();
4310
4311        assert_eq!(fill_report.last_qty, Quantity::from("0.01"));
4312    }
4313
4314    #[rstest]
4315    fn test_parse_fill_report_empty_fill_sz_subsequent_fills() {
4316        let instrument = create_stub_instrument();
4317        let account_id = AccountId::new("OKX-001");
4318        let ts_init = UnixNanos::default();
4319
4320        let order_msg_1 =
4321            create_stub_order_msg("", Some("0.01".to_string()), "1234567890", "trade_1");
4322
4323        let fill_report_1 = parse_fill_report(
4324            &order_msg_1,
4325            &InstrumentAny::CryptoPerpetual(instrument.clone()),
4326            account_id,
4327            None,
4328            None,
4329            ts_init,
4330        )
4331        .unwrap()
4332        .unwrap();
4333
4334        assert_eq!(fill_report_1.last_qty, Quantity::from("0.01"));
4335
4336        let order_msg_2 =
4337            create_stub_order_msg("", Some("0.03".to_string()), "1234567890", "trade_2");
4338
4339        let fill_report_2 = parse_fill_report(
4340            &order_msg_2,
4341            &InstrumentAny::CryptoPerpetual(instrument),
4342            account_id,
4343            Some(fill_report_1.commission),
4344            Some(fill_report_1.last_qty),
4345            ts_init,
4346        )
4347        .unwrap()
4348        .unwrap();
4349
4350        assert_eq!(fill_report_2.last_qty, Quantity::from("0.02"));
4351    }
4352
4353    #[rstest]
4354    fn test_parse_fill_report_error_both_empty() {
4355        let instrument = create_stub_instrument();
4356        let account_id = AccountId::new("OKX-001");
4357        let ts_init = UnixNanos::default();
4358
4359        let order_msg = create_stub_order_msg("", Some(String::new()), "1234567890", "trade_1");
4360
4361        let result = parse_fill_report(
4362            &order_msg,
4363            &InstrumentAny::CryptoPerpetual(instrument),
4364            account_id,
4365            None,
4366            None,
4367            ts_init,
4368        );
4369
4370        assert!(result.is_err());
4371        let err_msg = result.unwrap_err().to_string();
4372        assert!(err_msg.contains("Cannot determine fill quantity"));
4373        assert!(err_msg.contains("empty/zero"));
4374    }
4375
4376    #[rstest]
4377    fn test_parse_fill_report_error_acc_fill_sz_none() {
4378        let instrument = create_stub_instrument();
4379        let account_id = AccountId::new("OKX-001");
4380        let ts_init = UnixNanos::default();
4381
4382        let order_msg = create_stub_order_msg("", None, "1234567890", "trade_1");
4383
4384        let result = parse_fill_report(
4385            &order_msg,
4386            &InstrumentAny::CryptoPerpetual(instrument),
4387            account_id,
4388            None,
4389            None,
4390            ts_init,
4391        );
4392
4393        assert!(result.is_err());
4394        let err_msg = result.unwrap_err().to_string();
4395        assert!(err_msg.contains("Cannot determine fill quantity"));
4396        assert!(err_msg.contains("acc_fill_sz is None"));
4397    }
4398
4399    #[rstest]
4400    fn test_parse_fill_report_error_acc_fill_sz_less_than_previous() {
4401        let instrument = create_stub_instrument();
4402        let account_id = AccountId::new("OKX-001");
4403        let ts_init = UnixNanos::default();
4404
4405        // acc_fill_sz (0.01) < previous_filled_qty (0.03) - stale data after reconnect
4406        let order_msg =
4407            create_stub_order_msg("", Some("0.01".to_string()), "1234567890", "trade_2");
4408
4409        let result = parse_fill_report(
4410            &order_msg,
4411            &InstrumentAny::CryptoPerpetual(instrument),
4412            account_id,
4413            None,
4414            Some(Quantity::from("0.03")),
4415            ts_init,
4416        );
4417
4418        assert!(result.is_err());
4419        let err_msg = result.unwrap_err().to_string();
4420        assert!(err_msg.contains("Cumulative fill went backwards"));
4421    }
4422
4423    #[rstest]
4424    fn test_parse_order_msg_acc_fill_sz_only_update() {
4425        // Test that we emit fill reports when OKX only updates acc_fill_sz without fill_sz or trade_id
4426        let instrument = create_stub_instrument();
4427        let account_id = AccountId::new("OKX-001");
4428        let ts_init = UnixNanos::default();
4429
4430        let mut instruments = AHashMap::new();
4431        instruments.insert(
4432            Ustr::from("BTC-USDT-SWAP"),
4433            InstrumentAny::CryptoPerpetual(instrument),
4434        );
4435
4436        let fee_cache = FeeCache::new();
4437        let mut filled_qty_cache = FilledQtyCache::new();
4438
4439        // First update: acc_fill_sz = 0.01, no fill_sz, no trade_id
4440        let msg_1 = create_stub_order_msg("", Some("0.01".to_string()), "1234567890", "");
4441
4442        let report_1 = parse_order_msg(
4443            &msg_1,
4444            account_id,
4445            &instruments,
4446            &fee_cache,
4447            &filled_qty_cache,
4448            ts_init,
4449        )
4450        .unwrap();
4451
4452        // Should generate a fill report (not a status report)
4453        assert!(matches!(report_1, ExecutionReport::Fill(_)));
4454        if let ExecutionReport::Fill(fill) = &report_1 {
4455            assert_eq!(fill.last_qty, Quantity::from("0.01"));
4456        }
4457
4458        // Update cache
4459        filled_qty_cache.record(Ustr::from("1234567890"), Quantity::from("0.01"), false);
4460
4461        // Second update: acc_fill_sz increased to 0.03, still no fill_sz or trade_id
4462        let msg_2 = create_stub_order_msg("", Some("0.03".to_string()), "1234567890", "");
4463
4464        let report_2 = parse_order_msg(
4465            &msg_2,
4466            account_id,
4467            &instruments,
4468            &fee_cache,
4469            &filled_qty_cache,
4470            ts_init,
4471        )
4472        .unwrap();
4473
4474        // Should still generate a fill report for the incremental 0.02
4475        assert!(matches!(report_2, ExecutionReport::Fill(_)));
4476        if let ExecutionReport::Fill(fill) = &report_2 {
4477            assert_eq!(fill.last_qty, Quantity::from("0.02"));
4478        }
4479    }
4480
4481    #[rstest]
4482    fn test_parse_book_depth_msg_partial_levels() {
4483        let book_msg = OKXBookMsg {
4484            asks: vec![
4485                OrderBookEntry {
4486                    price: "8476.98".to_string(),
4487                    size: "415".to_string(),
4488                    liquidated_orders_count: "0".to_string(),
4489                    orders_count: "13".to_string(),
4490                },
4491                OrderBookEntry {
4492                    price: "8477.00".to_string(),
4493                    size: "7".to_string(),
4494                    liquidated_orders_count: "0".to_string(),
4495                    orders_count: "2".to_string(),
4496                },
4497            ],
4498            bids: vec![OrderBookEntry {
4499                price: "8476.97".to_string(),
4500                size: "256".to_string(),
4501                liquidated_orders_count: "0".to_string(),
4502                orders_count: "12".to_string(),
4503            }],
4504            ts: 1_597_026_383_085,
4505            checksum: None,
4506            prev_seq_id: None,
4507            seq_id: 123_456,
4508        };
4509
4510        let instrument_id = InstrumentId::from("BTC-USDT.OKX");
4511        let depth =
4512            parse_book_depth_msg(&book_msg, instrument_id, 2, 0, UnixNanos::default()).unwrap();
4513
4514        assert_eq!(depth.instrument_id, instrument_id);
4515        assert_eq!(depth.bids.len(), 1);
4516        assert_eq!(depth.asks.len(), 2);
4517        assert_eq!(depth.bids[0].price, Price::from("8476.97"));
4518        assert_eq!(depth.bids[0].size, Quantity::from("256"));
4519        assert_eq!(depth.bids[0].side, Some(OrderSide::Buy));
4520        assert_eq!(depth.bids[0].order_id, 0);
4521        assert_eq!(depth.bid_counts.as_slice(), &[12]);
4522        assert_eq!(depth.ask_counts.as_slice(), &[13, 2]);
4523        for (order, (price, size)) in depth
4524            .asks
4525            .iter()
4526            .zip([("8476.98", "415"), ("8477.00", "7")])
4527        {
4528            assert_eq!(order.price, Price::from(price));
4529            assert_eq!(order.size, Quantity::from(size));
4530            assert_eq!(order.side, Some(OrderSide::Sell));
4531            assert_eq!(order.order_id, 0);
4532        }
4533        assert_eq!(depth.sequence, 123_456);
4534        assert_eq!(depth.flags, RecordFlag::F_SNAPSHOT as u8);
4535        assert_eq!(depth.ts_event, UnixNanos::from(1_597_026_383_085_000_000));
4536        assert_eq!(depth.ts_init, UnixNanos::default());
4537    }
4538
4539    #[rstest]
4540    fn test_parse_algo_order_msg_stop_market() {
4541        let json_data = load_test_json("ws_orders_algo.json");
4542        let ws_msg: serde_json::Value = serde_json::from_str(&json_data).unwrap();
4543        let data: Vec<OKXAlgoOrderMsg> = serde_json::from_value(ws_msg["data"].clone()).unwrap();
4544
4545        // Test first algo order (stop market sell)
4546        let msg = &data[0];
4547        assert_eq!(msg.algo_id, "706620792746729472");
4548        assert_eq!(msg.algo_cl_ord_id, "STOP001BTCUSDT20250120");
4549        assert_eq!(msg.state, OKXAlgoOrderStatus::Live);
4550        assert_eq!(msg.ord_px, "-1"); // Market order indicator
4551
4552        let account_id = AccountId::new("OKX-001");
4553        let mut instruments = AHashMap::new();
4554
4555        // Create mock instrument
4556        let instrument = create_stub_instrument();
4557        instruments.insert(
4558            Ustr::from("BTC-USDT-SWAP"),
4559            InstrumentAny::CryptoPerpetual(instrument),
4560        );
4561
4562        let result = parse_algo_order_msg(msg, account_id, &instruments, UnixNanos::default());
4563
4564        let report = result.unwrap().unwrap();
4565
4566        if let ExecutionReport::Order(status_report) = report {
4567            assert_eq!(status_report.order_type, OrderType::StopMarket);
4568            assert_eq!(status_report.order_side, OrderSide::Sell.into());
4569            assert_eq!(status_report.quantity, Quantity::from("0.01000000"));
4570            assert_eq!(status_report.trigger_price, Some(Price::from("95000.00")));
4571            assert_eq!(status_report.trigger_type, Some(TriggerType::LastPrice));
4572            assert_eq!(status_report.price, None); // No limit price for market orders
4573        } else {
4574            panic!("Expected Order report");
4575        }
4576    }
4577
4578    #[rstest]
4579    fn test_parse_algo_order_msg_stop_limit() {
4580        let json_data = load_test_json("ws_orders_algo.json");
4581        let ws_msg: serde_json::Value = serde_json::from_str(&json_data).unwrap();
4582        let data: Vec<OKXAlgoOrderMsg> = serde_json::from_value(ws_msg["data"].clone()).unwrap();
4583
4584        // Test second algo order (stop limit buy)
4585        let msg = &data[1];
4586        assert_eq!(msg.algo_id, "706620792746729473");
4587        assert_eq!(msg.state, OKXAlgoOrderStatus::Live);
4588        assert_eq!(msg.ord_px, "106000"); // Limit price
4589
4590        let account_id = AccountId::new("OKX-001");
4591        let mut instruments = AHashMap::new();
4592
4593        // Create mock instrument
4594        let instrument = create_stub_instrument();
4595        instruments.insert(
4596            Ustr::from("BTC-USDT-SWAP"),
4597            InstrumentAny::CryptoPerpetual(instrument),
4598        );
4599
4600        let result = parse_algo_order_msg(msg, account_id, &instruments, UnixNanos::default());
4601
4602        let report = result.unwrap().unwrap();
4603
4604        if let ExecutionReport::Order(status_report) = report {
4605            assert_eq!(status_report.order_type, OrderType::StopLimit);
4606            assert_eq!(status_report.order_side, OrderSide::Buy.into());
4607            assert_eq!(status_report.quantity, Quantity::from("0.02000000"));
4608            assert_eq!(status_report.trigger_price, Some(Price::from("105000.00")));
4609            assert_eq!(status_report.trigger_type, Some(TriggerType::MarkPrice));
4610            assert_eq!(status_report.price, Some(Price::from("106000.00"))); // Has limit price
4611        } else {
4612            panic!("Expected Order report");
4613        }
4614    }
4615
4616    #[rstest]
4617    fn test_parse_triggered_algo_order_preserves_parent_identity() {
4618        let json_data = load_test_json("ws_orders_algo.json");
4619        let ws_msg: serde_json::Value = serde_json::from_str(&json_data).unwrap();
4620        let data: Vec<OKXAlgoOrderMsg> = serde_json::from_value(ws_msg["data"].clone()).unwrap();
4621        let msg = &data[2];
4622
4623        assert_eq!(msg.state, OKXAlgoOrderStatus::OrderPlaced);
4624        assert_eq!(msg.algo_cl_ord_id, "STOP003BTCUSDT20250120");
4625        assert_eq!(msg.cl_ord_id, "706620792746729474_0");
4626        assert_eq!(msg.actual_sz, "0.01");
4627
4628        let account_id = AccountId::new("OKX-001");
4629        let instrument = create_stub_instrument();
4630        let mut instruments = AHashMap::new();
4631        instruments.insert(
4632            Ustr::from("BTC-USDT-SWAP"),
4633            InstrumentAny::CryptoPerpetual(instrument),
4634        );
4635
4636        let report = parse_algo_order_msg(msg, account_id, &instruments, UnixNanos::default())
4637            .unwrap()
4638            .unwrap();
4639        let ExecutionReport::Order(report) = report else {
4640            panic!("Expected Order report");
4641        };
4642
4643        assert_eq!(
4644            report.client_order_id,
4645            Some(ClientOrderId::from("STOP003BTCUSDT20250120"))
4646        );
4647        assert_eq!(
4648            report.venue_order_id,
4649            VenueOrderId::from("706620792746729999")
4650        );
4651        assert_eq!(report.order_status, OrderStatus::Triggered);
4652        assert_eq!(report.filled_qty, Quantity::from("0.00000000"));
4653    }
4654
4655    #[rstest]
4656    fn test_parse_filled_algo_order_uses_actual_quantity() {
4657        let json_data = load_test_json("ws_orders_algo.json");
4658        let ws_msg: serde_json::Value = serde_json::from_str(&json_data).unwrap();
4659        let data: Vec<OKXAlgoOrderMsg> = serde_json::from_value(ws_msg["data"].clone()).unwrap();
4660        let msg = &data[4];
4661
4662        assert_eq!(msg.state, OKXAlgoOrderStatus::Filled);
4663        assert_eq!(msg.actual_sz, "0.005");
4664
4665        let instrument = create_stub_instrument();
4666        let mut instruments = AHashMap::new();
4667        instruments.insert(
4668            Ustr::from("BTC-USDT-SWAP"),
4669            InstrumentAny::CryptoPerpetual(instrument),
4670        );
4671
4672        let report = parse_algo_order_msg(
4673            msg,
4674            AccountId::new("OKX-001"),
4675            &instruments,
4676            UnixNanos::default(),
4677        )
4678        .unwrap()
4679        .unwrap();
4680        let ExecutionReport::Order(report) = report else {
4681            panic!("Expected Order report");
4682        };
4683
4684        assert_eq!(report.order_status, OrderStatus::Filled);
4685        assert_eq!(report.filled_qty, Quantity::from("0.00500000"));
4686    }
4687
4688    #[rstest]
4689    fn test_parse_trigger_order_from_regular_channel() {
4690        let json_data = load_test_json("ws_orders_trigger.json");
4691        let ws_msg: serde_json::Value = serde_json::from_str(&json_data).unwrap();
4692        let data: Vec<OKXOrderMsg> = serde_json::from_value(ws_msg["data"].clone()).unwrap();
4693
4694        // Test triggered order that came through regular orders channel
4695        let msg = &data[0];
4696        assert_eq!(msg.ord_type, OKXOrderType::Trigger);
4697        assert_eq!(msg.state, OKXOrderStatus::Filled);
4698
4699        let account_id = AccountId::new("OKX-001");
4700        let mut instruments = AHashMap::new();
4701
4702        // Create mock instrument
4703        let instrument = create_stub_instrument();
4704        instruments.insert(
4705            Ustr::from("BTC-USDT-SWAP"),
4706            InstrumentAny::CryptoPerpetual(instrument),
4707        );
4708
4709        let mut fee_cache = FeeCache::new();
4710        let mut filled_qty_cache = FilledQtyCache::new();
4711
4712        let result = parse_order_msg_vec(
4713            std::slice::from_ref(msg),
4714            account_id,
4715            &instruments,
4716            &mut fee_cache,
4717            &mut filled_qty_cache,
4718            UnixNanos::default(),
4719        );
4720
4721        assert!(result.is_ok());
4722        let reports = result.unwrap();
4723        assert_eq!(reports.len(), 1);
4724
4725        if let ExecutionReport::Fill(fill_report) = &reports[0] {
4726            assert_eq!(fill_report.order_side, OrderSide::Sell);
4727            assert_eq!(fill_report.last_qty, Quantity::from("0.01000000"));
4728            assert_eq!(fill_report.last_px, Price::from("101950.00"));
4729        } else {
4730            panic!("Expected Fill report for filled trigger order");
4731        }
4732    }
4733
4734    #[rstest]
4735    fn test_parse_liquidation_order() {
4736        let json_data = load_test_json("ws_orders_liquidation.json");
4737        let ws_msg: serde_json::Value = serde_json::from_str(&json_data).unwrap();
4738        let data: Vec<OKXOrderMsg> = serde_json::from_value(ws_msg["data"].clone()).unwrap();
4739
4740        // Test liquidation order
4741        let msg = &data[0];
4742        assert_eq!(msg.category, OKXOrderCategory::FullLiquidation);
4743        assert_eq!(msg.state, OKXOrderStatus::Filled);
4744        assert_eq!(msg.inst_id, "BTC-USDT-SWAP");
4745
4746        let account_id = AccountId::new("OKX-001");
4747        let mut instruments = AHashMap::new();
4748
4749        // Create mock instrument
4750        let instrument = create_stub_instrument();
4751        instruments.insert(
4752            Ustr::from("BTC-USDT-SWAP"),
4753            InstrumentAny::CryptoPerpetual(instrument),
4754        );
4755        let mut fee_cache = FeeCache::new();
4756        let mut filled_qty_cache = FilledQtyCache::new();
4757
4758        let result = parse_order_msg_vec(
4759            std::slice::from_ref(msg),
4760            account_id,
4761            &instruments,
4762            &mut fee_cache,
4763            &mut filled_qty_cache,
4764            UnixNanos::default(),
4765        );
4766
4767        assert!(result.is_ok());
4768        let reports = result.unwrap();
4769        assert_eq!(reports.len(), 1);
4770
4771        // Verify it's a fill report for a liquidation
4772        if let ExecutionReport::Fill(fill_report) = &reports[0] {
4773            assert_eq!(fill_report.order_side, OrderSide::Sell);
4774            assert_eq!(fill_report.last_qty, Quantity::from("0.50000000"));
4775            assert_eq!(fill_report.last_px, Price::from("40000.00"));
4776            assert_eq!(fill_report.liquidity_side, LiquiditySide::Taker);
4777        } else {
4778            panic!("Expected Fill report for liquidation order");
4779        }
4780    }
4781
4782    #[rstest]
4783    fn test_parse_adl_order() {
4784        let json_data = load_test_json("ws_orders_adl.json");
4785        let ws_msg: serde_json::Value = serde_json::from_str(&json_data).unwrap();
4786        let data: Vec<OKXOrderMsg> = serde_json::from_value(ws_msg["data"].clone()).unwrap();
4787
4788        // Test ADL order
4789        let msg = &data[0];
4790        assert_eq!(msg.category, OKXOrderCategory::Adl);
4791        assert_eq!(msg.state, OKXOrderStatus::Filled);
4792        assert_eq!(msg.inst_id, "ETH-USDT-SWAP");
4793
4794        let account_id = AccountId::new("OKX-001");
4795        let mut instruments = AHashMap::new();
4796
4797        // Create mock instrument
4798        let mut instrument = create_stub_instrument();
4799        instrument.id = InstrumentId::from("ETH-USDT-SWAP.OKX");
4800        instrument.raw_symbol = Symbol::from("ETH-USDT-SWAP");
4801        instrument.base_currency = Currency::ETH();
4802        instruments.insert(
4803            Ustr::from("ETH-USDT-SWAP"),
4804            InstrumentAny::CryptoPerpetual(instrument),
4805        );
4806
4807        let mut fee_cache = FeeCache::new();
4808        let mut filled_qty_cache = FilledQtyCache::new();
4809
4810        let result = parse_order_msg_vec(
4811            std::slice::from_ref(msg),
4812            account_id,
4813            &instruments,
4814            &mut fee_cache,
4815            &mut filled_qty_cache,
4816            UnixNanos::default(),
4817        );
4818
4819        assert!(result.is_ok());
4820        let reports = result.unwrap();
4821        assert_eq!(reports.len(), 1);
4822
4823        // Verify it's a fill report for ADL
4824        if let ExecutionReport::Fill(fill_report) = &reports[0] {
4825            assert_eq!(fill_report.order_side, OrderSide::Buy);
4826            assert_eq!(fill_report.last_qty, Quantity::from("0.30000000"));
4827            assert_eq!(fill_report.last_px, Price::from("41000.00"));
4828            assert_eq!(fill_report.liquidity_side, LiquiditySide::Taker);
4829        } else {
4830            panic!("Expected Fill report for ADL order");
4831        }
4832    }
4833
4834    #[rstest]
4835    fn test_parse_unknown_category_graceful_fallback() {
4836        // Test that unknown/future category values deserialize as Other instead of failing
4837        let json_with_unknown_category = r#"{
4838            "category": "some_future_category_we_dont_know"
4839        }"#;
4840
4841        let result: Result<serde_json::Value, _> = serde_json::from_str(json_with_unknown_category);
4842        result.unwrap();
4843
4844        // Test deserialization of the category field directly
4845        let category_result: Result<OKXOrderCategory, _> =
4846            serde_json::from_str(r#""some_future_category""#);
4847        assert!(category_result.is_ok());
4848        assert_eq!(category_result.unwrap(), OKXOrderCategory::Other);
4849
4850        // Verify known categories still work
4851        let normal: OKXOrderCategory = serde_json::from_str(r#""normal""#).unwrap();
4852        assert_eq!(normal, OKXOrderCategory::Normal);
4853
4854        let twap: OKXOrderCategory = serde_json::from_str(r#""twap""#).unwrap();
4855        assert_eq!(twap, OKXOrderCategory::Twap);
4856    }
4857
4858    #[rstest]
4859    fn test_parse_partial_liquidation_order() {
4860        // Create a test message with partial liquidation category
4861        let account_id = AccountId::new("OKX-001");
4862        let mut instruments = AHashMap::new();
4863
4864        let instrument = create_stub_instrument();
4865        instruments.insert(
4866            Ustr::from("BTC-USDT-SWAP"),
4867            InstrumentAny::CryptoPerpetual(instrument),
4868        );
4869
4870        let mut partial_liq_msg = create_stub_order_msg(
4871            "0.25",
4872            Some("0.25".to_string()),
4873            "2497956918703120888",
4874            "1518905888",
4875        );
4876        partial_liq_msg.avg_px = "39000.0".to_string();
4877        partial_liq_msg.category = OKXOrderCategory::PartialLiquidation;
4878        partial_liq_msg.cl_ord_id = String::new();
4879        partial_liq_msg.fee = Some("-9.75".to_string());
4880        partial_liq_msg.fill_px = "39000.0".to_string();
4881        partial_liq_msg.lever = "10.0".to_string();
4882        partial_liq_msg.pnl = "-2500".to_string();
4883        partial_liq_msg.side = OKXSide::Sell;
4884        partial_liq_msg.state = OKXOrderStatus::Filled;
4885        partial_liq_msg.sz = "0.25".to_string();
4886
4887        let fee_cache = FeeCache::new();
4888        let filled_qty_cache = FilledQtyCache::new();
4889        let result = parse_order_msg(
4890            &partial_liq_msg,
4891            account_id,
4892            &instruments,
4893            &fee_cache,
4894            &filled_qty_cache,
4895            UnixNanos::default(),
4896        );
4897
4898        assert!(result.is_ok());
4899        let report = result.unwrap();
4900
4901        // Verify it's a fill report for partial liquidation
4902        if let ExecutionReport::Fill(fill_report) = report {
4903            assert_eq!(fill_report.order_side, OrderSide::Sell);
4904            assert_eq!(fill_report.last_qty, Quantity::from("0.25000000"));
4905            assert_eq!(fill_report.last_px, Price::from("39000.00"));
4906        } else {
4907            panic!("Expected Fill report for partial liquidation order");
4908        }
4909    }
4910
4911    #[rstest]
4912    fn test_parse_mmp_canceled_order_message() {
4913        use nautilus_model::instruments::stubs::crypto_option_btc_deribit;
4914
4915        let json_data = load_test_json("ws_orders_mmp_canceled.json");
4916        let ws_msg: serde_json::Value = serde_json::from_str(&json_data).unwrap();
4917        let data: Vec<OKXOrderMsg> = serde_json::from_value(ws_msg["data"].clone()).unwrap();
4918
4919        let msg = &data[0];
4920        assert_eq!(msg.state, OKXOrderStatus::MmpCanceled);
4921        assert_eq!(msg.ord_type, OKXOrderType::MmpAndPostOnly);
4922
4923        let account_id = AccountId::new("OKX-001");
4924        let mut instruments = AHashMap::new();
4925        let instrument_id = InstrumentId::from("BTC-USD-250328-92000-C.OKX");
4926        let mut option =
4927            crypto_option_btc_deribit(3, 1, Price::from("0.001"), Quantity::from("0.1"));
4928        option.id = instrument_id;
4929        option.raw_symbol = Symbol::from("BTC-USD-250328-92000-C");
4930        instruments.insert(
4931            Ustr::from("BTC-USD-250328-92000-C"),
4932            InstrumentAny::CryptoOption(option),
4933        );
4934
4935        let fee_cache = FeeCache::new();
4936        let filled_qty_cache = FilledQtyCache::new();
4937        let report = parse_order_msg(
4938            msg,
4939            account_id,
4940            &instruments,
4941            &fee_cache,
4942            &filled_qty_cache,
4943            UnixNanos::default(),
4944        )
4945        .unwrap();
4946
4947        match report {
4948            ExecutionReport::Order(report) => {
4949                // MMP cancels map to Canceled with the venue reason preserved
4950                assert_eq!(report.order_status, OrderStatus::Canceled);
4951                assert_eq!(report.instrument_id, instrument_id);
4952                assert!(
4953                    report
4954                        .cancel_reason
4955                        .as_ref()
4956                        .is_some_and(|reason| reason.as_str().contains("market maker protection")),
4957                );
4958            }
4959            other => panic!("Expected Order report for MMP-canceled order, was {other:?}"),
4960        }
4961    }
4962
4963    #[rstest]
4964    fn test_parse_order_msg_unknown_state_preserves_fill() {
4965        let json_data = load_test_json("ws_orders_unknown_state_fill.json");
4966        let ws_msg: serde_json::Value = serde_json::from_str(&json_data).unwrap();
4967        let data: Vec<OKXOrderMsg> = serde_json::from_value(ws_msg["data"].clone()).unwrap();
4968
4969        // Unknown states fall back to `Unknown` instead of failing deserialization
4970        let msg = &data[0];
4971        assert_eq!(msg.state, OKXOrderStatus::Unknown);
4972
4973        let account_id = AccountId::new("OKX-001");
4974        let mut instruments = AHashMap::new();
4975        instruments.insert(
4976            Ustr::from("BTC-USDT-SWAP"),
4977            InstrumentAny::CryptoPerpetual(create_stub_instrument()),
4978        );
4979
4980        let fee_cache = FeeCache::new();
4981        let filled_qty_cache = FilledQtyCache::new();
4982        let report = parse_order_msg(
4983            msg,
4984            account_id,
4985            &instruments,
4986            &fee_cache,
4987            &filled_qty_cache,
4988            UnixNanos::default(),
4989        )
4990        .unwrap();
4991
4992        // Fill data is processed even when the state itself is unrecognized
4993        match report {
4994            ExecutionReport::Fill(fill_report) => {
4995                assert_eq!(fill_report.order_side, OrderSide::Buy);
4996                assert_eq!(fill_report.last_qty, Quantity::from("0.25000000"));
4997                assert_eq!(fill_report.last_px, Price::from("40000.00"));
4998                assert_eq!(fill_report.liquidity_side, LiquiditySide::Taker);
4999            }
5000            other => panic!("Expected Fill report for unknown-state order, was {other:?}"),
5001        }
5002    }
5003
5004    #[rstest]
5005    fn test_parse_order_msg_unknown_state_without_fill_errors() {
5006        let json_data = load_test_json("ws_orders_unknown_state_fill.json");
5007        let ws_msg: serde_json::Value = serde_json::from_str(&json_data).unwrap();
5008        let data: Vec<OKXOrderMsg> = serde_json::from_value(ws_msg["data"].clone()).unwrap();
5009
5010        let mut msg = data[0].clone();
5011        msg.fill_sz = "0".to_string();
5012        msg.trade_id = String::new();
5013        msg.acc_fill_sz = Some("0".to_string());
5014
5015        let account_id = AccountId::new("OKX-001");
5016        let mut instruments = AHashMap::new();
5017        instruments.insert(
5018            Ustr::from("BTC-USDT-SWAP"),
5019            InstrumentAny::CryptoPerpetual(create_stub_instrument()),
5020        );
5021
5022        let fee_cache = FeeCache::new();
5023        let filled_qty_cache = FilledQtyCache::new();
5024        let result = parse_order_msg(
5025            &msg,
5026            account_id,
5027            &instruments,
5028            &fee_cache,
5029            &filled_qty_cache,
5030            UnixNanos::default(),
5031        );
5032
5033        // Without fill data there is nothing safe to emit for an unrecognized state
5034        assert!(result.is_err());
5035    }
5036
5037    #[rstest]
5038    fn test_parse_order_msg_unknown_order_type_preserves_fill() {
5039        let json_data = load_test_json("ws_orders_unknown_ord_type_fill.json");
5040        let ws_msg: serde_json::Value = serde_json::from_str(&json_data).unwrap();
5041        let data: Vec<OKXOrderMsg> = serde_json::from_value(ws_msg["data"].clone()).unwrap();
5042
5043        // Unknown order types fall back to `Other` instead of failing deserialization
5044        let msg = &data[0];
5045        assert_eq!(msg.ord_type, OKXOrderType::Other);
5046
5047        let account_id = AccountId::new("OKX-001");
5048        let mut instruments = AHashMap::new();
5049        instruments.insert(
5050            Ustr::from("BTC-USDT-SWAP"),
5051            InstrumentAny::CryptoPerpetual(create_stub_instrument()),
5052        );
5053
5054        let fee_cache = FeeCache::new();
5055        let filled_qty_cache = FilledQtyCache::new();
5056        let report = parse_order_msg(
5057            msg,
5058            account_id,
5059            &instruments,
5060            &fee_cache,
5061            &filled_qty_cache,
5062            UnixNanos::default(),
5063        )
5064        .unwrap();
5065
5066        match report {
5067            ExecutionReport::Fill(fill_report) => {
5068                assert_eq!(fill_report.order_side, OrderSide::Sell);
5069                assert_eq!(fill_report.last_qty, Quantity::from("0.25000000"));
5070                assert_eq!(fill_report.last_px, Price::from("40000.00"));
5071            }
5072            other => panic!("Expected Fill report for unknown-ord-type order, was {other:?}"),
5073        }
5074    }
5075
5076    #[rstest]
5077    fn test_deserialize_liquidation_warning_message() {
5078        let json_data = load_test_json("ws_liquidation_warning.json");
5079        let payload: serde_json::Value = serde_json::from_str(&json_data).unwrap();
5080        let data: Vec<OKXLiquidationWarningMsg> =
5081            serde_json::from_value(payload["data"].clone()).unwrap();
5082
5083        assert_eq!(data.len(), 1);
5084        let warning = &data[0];
5085        assert_eq!(warning.inst_id, Ustr::from("BTC-USDT-SWAP"));
5086        assert_eq!(warning.inst_type, OKXInstrumentType::Swap);
5087        assert_eq!(warning.mgn_mode, OKXMarginMode::Cross);
5088        assert_eq!(warning.pos_side, OKXPositionSide::Long);
5089        assert_eq!(warning.pos, "0.5");
5090        assert_eq!(warning.mgn_ratio, "0.62");
5091        assert_eq!(warning.mark_px, "41250.5");
5092        assert_eq!(warning.c_time, 1_622_559_930_237);
5093        assert_eq!(warning.u_time, 1_788_000_000_001);
5094        assert_eq!(warning.p_time.as_deref(), Some("1788000000002"));
5095    }
5096
5097    #[rstest]
5098    fn test_websocket_instrument_update_preserves_cached_fees() {
5099        use nautilus_model::{identifiers::InstrumentId, instruments::InstrumentAny};
5100
5101        use crate::common::{models::OKXInstrument, parse::parse_instrument_any};
5102
5103        let ts_init = UnixNanos::default();
5104
5105        // Deserialize the initial instrument from JSON.
5106        let initial_inst_json = serde_json::json!({
5107            "instType": "SPOT",
5108            "instId": "BTC-USD",
5109            "baseCcy": "BTC",
5110            "quoteCcy": "USD",
5111            "settleCcy": "",
5112            "ctVal": "",
5113            "ctMult": "",
5114            "ctValCcy": "",
5115            "optType": "",
5116            "stk": "",
5117            "listTime": "1733454000000",
5118            "expTime": "",
5119            "lever": "",
5120            "tickSz": "0.1",
5121            "lotSz": "0.00000001",
5122            "minSz": "0.00001",
5123            "ctType": "linear",
5124            "alias": "",
5125            "state": "live",
5126            "maxLmtSz": "9999999999",
5127            "maxMktSz": "1000000",
5128            "maxTwapSz": "9999999999.0000000000000000",
5129            "maxIcebergSz": "9999999999.0000000000000000",
5130            "maxTriggerSz": "9999999999.0000000000000000",
5131            "maxStopSz": "1000000",
5132            "uly": "",
5133            "instFamily": "",
5134            "ruleType": "normal",
5135            "maxLmtAmt": "20000000",
5136            "maxMktAmt": "1000000"
5137        });
5138
5139        let initial_inst: OKXInstrument = serde_json::from_value(initial_inst_json)
5140            .expect("Failed to deserialize initial instrument");
5141
5142        // Parse the initial instrument.
5143        let parsed_initial = parse_instrument_any(&initial_inst, None, None, ts_init)
5144            .expect("Failed to parse initial instrument")
5145            .expect("Initial instrument should not be None");
5146
5147        let InstrumentAny::CurrencyPair(_) = parsed_initial else {
5148            panic!("Expected CurrencyPair instrument");
5149        };
5150
5151        // Build instrument cache with the initial instrument
5152        let mut instruments_cache = AHashMap::new();
5153        instruments_cache.insert(Ustr::from("BTC-USD"), parsed_initial);
5154
5155        // Create WebSocket update message (same structure as initial, simulating a WebSocket update)
5156        let ws_update = serde_json::json!({
5157            "instType": "SPOT",
5158            "instId": "BTC-USD",
5159            "baseCcy": "BTC",
5160            "quoteCcy": "USD",
5161            "settleCcy": "",
5162            "ctVal": "",
5163            "ctMult": "",
5164            "ctValCcy": "",
5165            "optType": "",
5166            "stk": "",
5167            "listTime": "1733454000000",
5168            "expTime": "",
5169            "lever": "",
5170            "tickSz": "0.1",
5171            "lotSz": "0.00000001",
5172            "minSz": "0.00001",
5173            "ctType": "linear",
5174            "alias": "",
5175            "state": "live",
5176            "maxLmtSz": "9999999999",
5177            "maxMktSz": "1000000",
5178            "maxTwapSz": "9999999999.0000000000000000",
5179            "maxIcebergSz": "9999999999.0000000000000000",
5180            "maxTriggerSz": "9999999999.0000000000000000",
5181            "maxStopSz": "1000000",
5182            "uly": "",
5183            "instFamily": "",
5184            "ruleType": "normal",
5185            "maxLmtAmt": "20000000",
5186            "maxMktAmt": "1000000"
5187        });
5188
5189        let instrument_id = InstrumentId::from("BTC-USD.OKX");
5190        let mut funding_cache = AHashMap::new();
5191
5192        // Parse WebSocket update with cache
5193        let result = parse_ws_message_data(
5194            &OKXWsChannel::Instruments,
5195            ws_update,
5196            &instrument_id,
5197            2,
5198            8,
5199            ts_init,
5200            &mut funding_cache,
5201            &instruments_cache,
5202        )
5203        .expect("Failed to parse WebSocket instrument update");
5204
5205        if let Some(NautilusWsMessage::Instrument(boxed_inst, _status)) = result {
5206            let InstrumentAny::CurrencyPair(_) = *boxed_inst else {
5207                panic!("Expected CurrencyPair instrument from WebSocket update");
5208            };
5209        } else {
5210            panic!("Expected Instrument message from WebSocket update");
5211        }
5212    }
5213
5214    #[rstest]
5215    #[case::fok_order(OKXOrderType::Fok, TimeInForce::Fok)]
5216    #[case::ioc_order(OKXOrderType::Ioc, TimeInForce::Ioc)]
5217    #[case::optimal_limit_ioc_order(OKXOrderType::OptimalLimitIoc, TimeInForce::Ioc)]
5218    #[case::market_order(OKXOrderType::Market, TimeInForce::Gtc)]
5219    #[case::limit_order(OKXOrderType::Limit, TimeInForce::Gtc)]
5220    fn test_parse_time_in_force_from_ord_type(
5221        #[case] okx_ord_type: OKXOrderType,
5222        #[case] expected_tif: TimeInForce,
5223    ) {
5224        let payload: Value = serde_json::from_str(&load_test_json("ws_orders.json")).unwrap();
5225        let mut msg: OKXOrderMsg = serde_json::from_value(payload["data"][0].clone()).unwrap();
5226        msg.ord_type = okx_ord_type;
5227        msg.px = if okx_ord_type == OKXOrderType::Market {
5228            String::new()
5229        } else {
5230            "50000.0".to_string()
5231        };
5232
5233        let instrument = InstrumentAny::CryptoPerpetual(create_stub_instrument());
5234
5235        let report = parse_order_status_report(
5236            &msg,
5237            &instrument,
5238            AccountId::new("OKX-001"),
5239            UnixNanos::default(),
5240        )
5241        .unwrap();
5242
5243        assert_eq!(report.time_in_force, expected_tif);
5244    }
5245
5246    #[rstest]
5247    #[case::fok("ws_orders_fok.json", OKXOrderType::Fok, "FOK-TEST-001", "BTC-USDT")]
5248    #[case::ioc("ws_orders_ioc.json", OKXOrderType::Ioc, "IOC-TEST-001", "BTC-USDT")]
5249    #[case::optimal_limit_ioc(
5250        "ws_orders_optimal_limit_ioc.json",
5251        OKXOrderType::OptimalLimitIoc,
5252        "OPTIMAL-IOC-TEST-001",
5253        "BTC-USDT-SWAP"
5254    )]
5255    fn test_deserialize_time_in_force_order_message(
5256        #[case] fixture: &str,
5257        #[case] expected_ord_type: OKXOrderType,
5258        #[case] expected_client_order_id: &str,
5259        #[case] expected_instrument: &str,
5260    ) {
5261        let json_data = load_test_json(fixture);
5262        let ws_msg: Value = serde_json::from_str(&json_data).unwrap();
5263        let data: Vec<OKXOrderMsg> = serde_json::from_value(ws_msg["data"].clone()).unwrap();
5264
5265        assert!(!data.is_empty());
5266        assert_eq!(data[0].ord_type, expected_ord_type);
5267        assert_eq!(data[0].cl_ord_id, expected_client_order_id);
5268        assert_eq!(data[0].inst_id, Ustr::from(expected_instrument));
5269    }
5270
5271    #[rstest]
5272    fn test_deserialize_regular_order_message() {
5273        let json_data = load_test_json("ws_orders.json");
5274        let payload: serde_json::Value = serde_json::from_str(&json_data).unwrap();
5275        let data: Vec<OKXOrderMsg> = serde_json::from_value(payload["data"].clone()).unwrap();
5276
5277        assert!(!data.is_empty());
5278        assert_eq!(data[0].inst_id, Ustr::from("BTC-USDT-SWAP"));
5279        assert_eq!(data[0].state, OKXOrderStatus::Filled);
5280        assert_eq!(data[0].category, OKXOrderCategory::Normal);
5281        assert_eq!(data[0].rebate.as_deref(), Some("0"));
5282        assert_eq!(data[0].rebate_ccy.as_deref(), Some("USDT"));
5283        assert_eq!(data[0].stp_mode, OKXSelfTradePreventionMode::CancelMaker);
5284        assert!(data[0].linked_algo_ord.is_some());
5285        assert_eq!(data[0].tag.as_deref(), Some(""));
5286        assert_eq!(data[0].source.as_deref(), Some(""));
5287    }
5288
5289    #[rstest]
5290    fn test_deserialize_algo_order_missing_trigger_px_type() {
5291        // algo-advance channel messages omit triggerPxType
5292        let mut value =
5293            serde_json::to_value(stub_algo_order_msg(OKXAlgoOrderType::MoveOrderStop)).unwrap();
5294        value.as_object_mut().unwrap().remove("triggerPxType");
5295        // OKX omits optional string fields rather than sending null
5296        value.as_object_mut().unwrap().retain(|_, v| !v.is_null());
5297        value["cTime"] = Value::String("1706000000000".to_string());
5298        value["uTime"] = Value::String("1706000001000".to_string());
5299
5300        let msg: OKXAlgoOrderMsg = serde_json::from_value(value).unwrap();
5301
5302        assert_eq!(msg.trigger_px_type, OKXTriggerType::None);
5303        assert_eq!(msg.ord_type, OKXAlgoOrderType::MoveOrderStop);
5304    }
5305
5306    #[rstest]
5307    fn test_deserialize_ticker_message() {
5308        let json_data = load_test_json("ws_tickers.json");
5309        let payload: serde_json::Value = serde_json::from_str(&json_data).unwrap();
5310        let data: Vec<OKXTickerMsg> = serde_json::from_value(payload["data"].clone()).unwrap();
5311
5312        assert!(!data.is_empty());
5313        assert_eq!(data[0].inst_id, Ustr::from("BTC-USDT"));
5314        assert_eq!(data[0].last_px, "9999.99");
5315    }
5316
5317    #[rstest]
5318    fn test_deserialize_funding_rate_message() {
5319        let json_data = load_test_json("ws_funding_rate.json");
5320        let payload: serde_json::Value = serde_json::from_str(&json_data).unwrap();
5321        let data: Vec<OKXFundingRateMsg> = serde_json::from_value(payload["data"].clone()).unwrap();
5322
5323        assert!(!data.is_empty());
5324        assert_eq!(data[0].inst_id, Ustr::from("BTC-USDT-SWAP"));
5325    }
5326
5327    #[rstest]
5328    fn test_deserialize_trade_message() {
5329        let json_data = load_test_json("ws_trades.json");
5330        let payload: serde_json::Value = serde_json::from_str(&json_data).unwrap();
5331        let data: Vec<OKXTradeMsg> = serde_json::from_value(payload["data"].clone()).unwrap();
5332
5333        assert!(!data.is_empty());
5334        assert_eq!(data[0].inst_id, Ustr::from("BTC-USD"));
5335    }
5336
5337    fn create_order_msg_for_event_test(
5338        state: OKXOrderStatus,
5339        cl_ord_id: &str,
5340        ord_id: &str,
5341        px: &str,
5342        sz: &str,
5343    ) -> OKXOrderMsg {
5344        let mut msg = create_stub_order_msg("", Some("0".to_string()), ord_id, "");
5345        msg.cl_ord_id = cl_ord_id.to_string();
5346        msg.fee = Some("0".to_string());
5347        msg.fill_px = String::new();
5348        msg.fill_time = 0;
5349        msg.ord_type = OKXOrderType::Limit;
5350        msg.px = px.to_string();
5351        msg.state = state;
5352        msg.sz = sz.to_string();
5353        msg
5354    }
5355
5356    fn create_spread_order_msg_for_event_test(
5357        state: OKXOrderStatus,
5358        cl_ord_id: &str,
5359        ord_id: &str,
5360        px: &str,
5361        sz: &str,
5362    ) -> OKXSpreadOrder {
5363        OKXSpreadOrder {
5364            sprd_id: Ustr::from("BTC-USDT_BTC-USDT-SWAP"),
5365            ord_id: Ustr::from(ord_id),
5366            cl_ord_id: Ustr::from(cl_ord_id),
5367            tag: String::new(),
5368            side: OKXSide::Buy,
5369            ord_type: OKXOrderType::Limit,
5370            sz: sz.to_string(),
5371            px: px.to_string(),
5372            avg_px: String::new(),
5373            state,
5374            acc_fill_sz: "0".to_string(),
5375            pending_fill_sz: "0".to_string(),
5376            pending_settle_sz: "0".to_string(),
5377            canceled_sz: "0".to_string(),
5378            fill_sz: String::new(),
5379            fill_px: String::new(),
5380            trade_id: Ustr::default(),
5381            cancel_source: String::new(),
5382            req_id: String::new(),
5383            amend_result: String::new(),
5384            code: String::new(),
5385            msg: String::new(),
5386            c_time: Some(1_746_947_317_401),
5387            u_time: Some(1_746_947_317_402),
5388        }
5389    }
5390
5391    #[rstest]
5392    fn test_deserialize_spread_orders_message() {
5393        let json_data = load_test_json("ws_sprd_orders.json");
5394        let frame: OKXWsFrame = serde_json::from_str(&json_data).unwrap();
5395
5396        match frame {
5397            OKXWsFrame::Data { arg, data } => {
5398                let orders: Vec<OKXSpreadOrder> = serde_json::from_value(data).unwrap();
5399
5400                assert_eq!(arg.channel, OKXWsChannel::SprdOrders);
5401                assert_eq!(orders.len(), 1);
5402                assert_eq!(orders[0].sprd_id, Ustr::from("BCH-USDT_BCH-USDT-SWAP"));
5403                assert_eq!(orders[0].ord_id, Ustr::from("3386544889978159104"));
5404                assert_eq!(orders[0].state, OKXOrderStatus::Live);
5405            }
5406            other => panic!("Expected Data, was {other:?}"),
5407        }
5408    }
5409
5410    #[rstest]
5411    fn test_synthesize_trade_id_is_deterministic_and_under_36_chars() {
5412        let mut msg = create_order_msg_for_event_test(
5413            OKXOrderStatus::Filled,
5414            "client-1",
5415            "venue-1",
5416            "50000.0",
5417            "0.001",
5418        );
5419        msg.fill_px = "50000.0".to_string();
5420        msg.fill_sz = "0.001".to_string();
5421        msg.fill_time = 1_746_947_317_500;
5422        msg.acc_fill_sz = Some("0.001".to_string());
5423
5424        let id1 = synthesize_trade_id(&msg);
5425        let id2 = synthesize_trade_id(&msg);
5426
5427        assert_eq!(id1, id2, "synthesized id must be deterministic");
5428        assert!(
5429            id1.len() <= 36,
5430            "synthesized id must fit in TradeId, was {}",
5431            id1.len()
5432        );
5433        assert!(id1.starts_with("synth-"));
5434    }
5435
5436    #[rstest]
5437    fn test_synthesize_trade_id_changes_with_fill_fields() {
5438        let mut msg = create_order_msg_for_event_test(
5439            OKXOrderStatus::Filled,
5440            "client-1",
5441            "venue-1",
5442            "50000.0",
5443            "0.001",
5444        );
5445        msg.fill_px = "50000.0".to_string();
5446        msg.fill_sz = "0.001".to_string();
5447        msg.fill_time = 1_746_947_317_500;
5448        msg.acc_fill_sz = Some("0.001".to_string());
5449
5450        let baseline = synthesize_trade_id(&msg);
5451
5452        msg.fill_sz = "0.002".to_string();
5453        let different_size = synthesize_trade_id(&msg);
5454        assert_ne!(baseline, different_size);
5455
5456        msg.fill_sz = "0.001".to_string();
5457        msg.fill_time = 1_746_947_317_999;
5458        let different_time = synthesize_trade_id(&msg);
5459        assert_ne!(baseline, different_time);
5460    }
5461
5462    #[rstest]
5463    fn test_empty_trade_id_fill_deduped_across_replays() {
5464        use crate::websocket::dispatch::WsDispatchState;
5465
5466        // Two identical fill messages with no venue trade_id - the dedup in
5467        // `WsDispatchState::check_and_insert_trade` must suppress the replay.
5468        // Regression lock for the empty-trade_id UUID fabrication bug: if
5469        // `synthesize_trade_id` drifts back to a non-deterministic id, the
5470        // second `check_and_insert_trade` would return false (not a dupe)
5471        // and this test fails.
5472        let mut msg = create_order_msg_for_event_test(
5473            OKXOrderStatus::Filled,
5474            "client-1",
5475            "venue-1",
5476            "50000.0",
5477            "0.001",
5478        );
5479        msg.trade_id = String::new();
5480        msg.fill_px = "50000.0".to_string();
5481        msg.fill_sz = "0.001".to_string();
5482        msg.fill_time = 1_746_947_317_500;
5483        msg.acc_fill_sz = Some("0.001".to_string());
5484
5485        let first_id = TradeId::new(synthesize_trade_id(&msg));
5486        let second_id = TradeId::new(synthesize_trade_id(&msg));
5487        assert_eq!(first_id, second_id, "synthesized id must survive replay");
5488
5489        let state = WsDispatchState::default();
5490        assert!(
5491            !state.check_and_insert_trade(first_id),
5492            "first insert is not a duplicate"
5493        );
5494        assert!(
5495            state.check_and_insert_trade(second_id),
5496            "replayed fill with empty trade_id must dedup"
5497        );
5498    }
5499
5500    #[rstest]
5501    fn test_parse_order_event_live_returns_accepted() {
5502        let instrument = create_stub_instrument();
5503        let msg = create_order_msg_for_event_test(
5504            OKXOrderStatus::Live,
5505            "test_client_123",
5506            "venue_456",
5507            "50000.0",
5508            "0.01",
5509        );
5510
5511        let client_order_id = ClientOrderId::new("test_client_123");
5512        let account_id = AccountId::new("OKX-001");
5513        let trader_id = TraderId::new("TRADER-001");
5514        let strategy_id = StrategyId::new("STRATEGY-001");
5515        let ts_init = UnixNanos::from(1_000_000_000);
5516
5517        let result = parse_order_event(
5518            &msg,
5519            client_order_id,
5520            account_id,
5521            trader_id,
5522            strategy_id,
5523            &InstrumentAny::CryptoPerpetual(instrument),
5524            None,
5525            None,
5526            None,
5527            ts_init,
5528        );
5529
5530        assert!(result.is_ok());
5531        match result.unwrap() {
5532            ParsedOrderEvent::Accepted(accepted) => {
5533                assert_eq!(accepted.client_order_id, client_order_id);
5534                assert_eq!(accepted.venue_order_id, VenueOrderId::new("venue_456"));
5535                assert_eq!(accepted.trader_id, trader_id);
5536                assert_eq!(accepted.strategy_id, strategy_id);
5537            }
5538            other => panic!("Expected Accepted, was {other:?}"),
5539        }
5540    }
5541
5542    #[rstest]
5543    fn test_parse_spread_order_event_live_returns_accepted() {
5544        let instrument = create_stub_instrument();
5545        let msg = create_spread_order_msg_for_event_test(
5546            OKXOrderStatus::Live,
5547            "test_client_123",
5548            "venue_456",
5549            "1.0",
5550            "0.01",
5551        );
5552        let client_order_id = ClientOrderId::new("test_client_123");
5553        let account_id = AccountId::new("OKX-001");
5554        let trader_id = TraderId::new("TRADER-001");
5555        let strategy_id = StrategyId::new("STRATEGY-001");
5556        let ts_init = UnixNanos::from(1_000_000_000);
5557
5558        let result = parse_spread_order_event(
5559            &msg,
5560            client_order_id,
5561            account_id,
5562            trader_id,
5563            strategy_id,
5564            &InstrumentAny::CryptoPerpetual(instrument),
5565            None,
5566            None,
5567            ts_init,
5568        );
5569
5570        match result.unwrap() {
5571            ParsedOrderEvent::Accepted(accepted) => {
5572                assert_eq!(accepted.client_order_id, client_order_id);
5573                assert_eq!(accepted.venue_order_id, VenueOrderId::new("venue_456"));
5574                assert_eq!(accepted.account_id, account_id);
5575            }
5576            other => panic!("Expected Accepted, was {other:?}"),
5577        }
5578    }
5579
5580    #[rstest]
5581    fn test_parse_spread_order_event_canceled_returns_canceled() {
5582        let instrument = create_stub_instrument();
5583        let msg = create_spread_order_msg_for_event_test(
5584            OKXOrderStatus::Canceled,
5585            "test_client_123",
5586            "venue_456",
5587            "1.0",
5588            "0.01",
5589        );
5590        let client_order_id = ClientOrderId::new("test_client_123");
5591        let account_id = AccountId::new("OKX-001");
5592        let trader_id = TraderId::new("TRADER-001");
5593        let strategy_id = StrategyId::new("STRATEGY-001");
5594        let ts_init = UnixNanos::from(1_000_000_000);
5595
5596        let result = parse_spread_order_event(
5597            &msg,
5598            client_order_id,
5599            account_id,
5600            trader_id,
5601            strategy_id,
5602            &InstrumentAny::CryptoPerpetual(instrument),
5603            None,
5604            None,
5605            ts_init,
5606        );
5607
5608        match result.unwrap() {
5609            ParsedOrderEvent::Canceled(canceled) => {
5610                assert_eq!(canceled.client_order_id, client_order_id);
5611                assert_eq!(
5612                    canceled.venue_order_id,
5613                    Some(VenueOrderId::new("venue_456"))
5614                );
5615                assert_eq!(canceled.account_id, Some(account_id));
5616            }
5617            other => panic!("Expected Canceled, was {other:?}"),
5618        }
5619    }
5620
5621    #[rstest]
5622    fn test_parse_spread_order_event_filled_returns_fill() {
5623        let instrument = create_stub_instrument();
5624        let mut msg = create_spread_order_msg_for_event_test(
5625            OKXOrderStatus::Filled,
5626            "test_client_123",
5627            "venue_456",
5628            "1.0",
5629            "0.01",
5630        );
5631        msg.fill_sz = "0.01".to_string();
5632        msg.fill_px = "1.0".to_string();
5633        msg.trade_id = Ustr::from("trade_789");
5634        msg.acc_fill_sz = "0.01".to_string();
5635
5636        let client_order_id = ClientOrderId::new("test_client_123");
5637        let account_id = AccountId::new("OKX-001");
5638        let trader_id = TraderId::new("TRADER-001");
5639        let strategy_id = StrategyId::new("STRATEGY-001");
5640        let ts_init = UnixNanos::from(1_000_000_000);
5641
5642        let result = parse_spread_order_event(
5643            &msg,
5644            client_order_id,
5645            account_id,
5646            trader_id,
5647            strategy_id,
5648            &InstrumentAny::CryptoPerpetual(instrument),
5649            None,
5650            None,
5651            ts_init,
5652        );
5653
5654        let error = result.unwrap_err();
5655        assert!(error.to_string().contains("missing fee"));
5656    }
5657
5658    #[rstest]
5659    fn test_parse_spread_order_fill_report_uses_incremental_acc_fill_sz() {
5660        let instrument = create_stub_instrument();
5661        let mut msg = create_spread_order_msg_for_event_test(
5662            OKXOrderStatus::PartiallyFilled,
5663            "test_client_123",
5664            "venue_456",
5665            "1.0",
5666            "0.03",
5667        );
5668        msg.acc_fill_sz = "0.03".to_string();
5669        msg.fill_sz = String::new();
5670        msg.fill_px = String::new();
5671
5672        let error = parse_spread_order_fill_report(
5673            &msg,
5674            &InstrumentAny::CryptoPerpetual(instrument),
5675            AccountId::new("OKX-001"),
5676            Some(Quantity::from("0.01000000")),
5677            UnixNanos::from(1_000_000_000),
5678        )
5679        .unwrap_err();
5680
5681        assert!(error.to_string().contains("missing fee"));
5682        assert!(error.to_string().contains("sprd-orders updates omit fee"));
5683    }
5684
5685    #[rstest]
5686    fn test_parse_spread_order_fill_report_skips_duplicate_acc_fill_sz() {
5687        let instrument = create_stub_instrument();
5688        let mut msg = create_spread_order_msg_for_event_test(
5689            OKXOrderStatus::PartiallyFilled,
5690            "test_client_123",
5691            "venue_456",
5692            "1.0",
5693            "0.01",
5694        );
5695        msg.acc_fill_sz = "0.01".to_string();
5696        msg.fill_sz = String::new();
5697        msg.fill_px = String::new();
5698
5699        let result = parse_spread_order_fill_report(
5700            &msg,
5701            &InstrumentAny::CryptoPerpetual(instrument),
5702            AccountId::new("OKX-001"),
5703            Some(Quantity::from("0.01000000")),
5704            UnixNanos::from(1_000_000_000),
5705        )
5706        .unwrap();
5707
5708        assert!(result.is_none());
5709    }
5710
5711    #[rstest]
5712    fn test_parse_spread_order_fill_report_rejects_regressed_acc_fill_sz() {
5713        let instrument = create_stub_instrument();
5714        let mut msg = create_spread_order_msg_for_event_test(
5715            OKXOrderStatus::PartiallyFilled,
5716            "test_client_123",
5717            "venue_456",
5718            "1.0",
5719            "0.01",
5720        );
5721        msg.acc_fill_sz = "0.01".to_string();
5722        msg.fill_sz = String::new();
5723        msg.fill_px = String::new();
5724
5725        let error = parse_spread_order_fill_report(
5726            &msg,
5727            &InstrumentAny::CryptoPerpetual(instrument),
5728            AccountId::new("OKX-001"),
5729            Some(Quantity::from("0.03000000")),
5730            UnixNanos::from(1_000_000_000),
5731        )
5732        .unwrap_err();
5733
5734        assert!(
5735            error
5736                .to_string()
5737                .contains("Cumulative spread fill went backwards")
5738        );
5739    }
5740
5741    #[rstest]
5742    fn test_parse_order_event_live_with_price_change_returns_updated() {
5743        let instrument = create_stub_instrument();
5744        let msg = create_order_msg_for_event_test(
5745            OKXOrderStatus::Live,
5746            "test_client_123",
5747            "venue_456",
5748            "51000.0",
5749            "0.01",
5750        );
5751
5752        let client_order_id = ClientOrderId::new("test_client_123");
5753        let account_id = AccountId::new("OKX-001");
5754        let trader_id = TraderId::new("TRADER-001");
5755        let strategy_id = StrategyId::new("STRATEGY-001");
5756        let ts_init = UnixNanos::from(1_000_000_000);
5757
5758        let previous_state = OrderStateSnapshot {
5759            venue_order_id: VenueOrderId::new("venue_456"),
5760            quantity: Quantity::from("0.01000000"),
5761            price: Some(Price::from("50000.00")),
5762        };
5763
5764        let result = parse_order_event(
5765            &msg,
5766            client_order_id,
5767            account_id,
5768            trader_id,
5769            strategy_id,
5770            &InstrumentAny::CryptoPerpetual(instrument),
5771            None,
5772            None,
5773            Some(&previous_state),
5774            ts_init,
5775        );
5776
5777        assert!(result.is_ok());
5778        match result.unwrap() {
5779            ParsedOrderEvent::Updated(updated) => {
5780                assert_eq!(updated.client_order_id, client_order_id);
5781                assert_eq!(updated.price, Some(Price::from("51000.00")));
5782            }
5783            other => panic!("Expected Updated, was {other:?}"),
5784        }
5785    }
5786
5787    #[rstest]
5788    fn test_parse_order_event_live_with_quantity_change_returns_updated() {
5789        let instrument = create_stub_instrument();
5790        let msg = create_order_msg_for_event_test(
5791            OKXOrderStatus::Live,
5792            "test_client_123",
5793            "venue_456",
5794            "50000.0",
5795            "0.02",
5796        );
5797
5798        let client_order_id = ClientOrderId::new("test_client_123");
5799        let account_id = AccountId::new("OKX-001");
5800        let trader_id = TraderId::new("TRADER-001");
5801        let strategy_id = StrategyId::new("STRATEGY-001");
5802        let ts_init = UnixNanos::from(1_000_000_000);
5803
5804        let previous_state = OrderStateSnapshot {
5805            venue_order_id: VenueOrderId::new("venue_456"),
5806            quantity: Quantity::from("0.01000000"),
5807            price: Some(Price::from("50000.00")),
5808        };
5809
5810        let result = parse_order_event(
5811            &msg,
5812            client_order_id,
5813            account_id,
5814            trader_id,
5815            strategy_id,
5816            &InstrumentAny::CryptoPerpetual(instrument),
5817            None,
5818            None,
5819            Some(&previous_state),
5820            ts_init,
5821        );
5822
5823        assert!(result.is_ok());
5824        match result.unwrap() {
5825            ParsedOrderEvent::Updated(updated) => {
5826                assert_eq!(updated.client_order_id, client_order_id);
5827                assert_eq!(updated.quantity, Quantity::from("0.02000000"));
5828            }
5829            other => panic!("Expected Updated, was {other:?}"),
5830        }
5831    }
5832
5833    #[rstest]
5834    fn test_parse_order_event_canceled_returns_canceled() {
5835        let instrument = create_stub_instrument();
5836        let msg = create_order_msg_for_event_test(
5837            OKXOrderStatus::Canceled,
5838            "test_client_123",
5839            "venue_456",
5840            "50000.0",
5841            "0.01",
5842        );
5843
5844        let client_order_id = ClientOrderId::new("test_client_123");
5845        let account_id = AccountId::new("OKX-001");
5846        let trader_id = TraderId::new("TRADER-001");
5847        let strategy_id = StrategyId::new("STRATEGY-001");
5848        let ts_init = UnixNanos::from(1_000_000_000);
5849
5850        let result = parse_order_event(
5851            &msg,
5852            client_order_id,
5853            account_id,
5854            trader_id,
5855            strategy_id,
5856            &InstrumentAny::CryptoPerpetual(instrument),
5857            None,
5858            None,
5859            None,
5860            ts_init,
5861        );
5862
5863        assert!(result.is_ok());
5864        match result.unwrap() {
5865            ParsedOrderEvent::Canceled(canceled) => {
5866                assert_eq!(canceled.client_order_id, client_order_id);
5867                assert_eq!(
5868                    canceled.venue_order_id,
5869                    Some(VenueOrderId::new("venue_456"))
5870                );
5871            }
5872            other => panic!("Expected Canceled, was {other:?}"),
5873        }
5874    }
5875
5876    #[rstest]
5877    fn test_parse_order_event_canceled_with_expiry_reason_returns_expired() {
5878        let instrument = create_stub_instrument();
5879        let mut msg = create_order_msg_for_event_test(
5880            OKXOrderStatus::Canceled,
5881            "test_client_123",
5882            "venue_456",
5883            "50000.0",
5884            "0.01",
5885        );
5886        msg.cancel_source_reason = Some("GTD order expired".to_string());
5887
5888        let client_order_id = ClientOrderId::new("test_client_123");
5889        let account_id = AccountId::new("OKX-001");
5890        let trader_id = TraderId::new("TRADER-001");
5891        let strategy_id = StrategyId::new("STRATEGY-001");
5892        let ts_init = UnixNanos::from(1_000_000_000);
5893
5894        let result = parse_order_event(
5895            &msg,
5896            client_order_id,
5897            account_id,
5898            trader_id,
5899            strategy_id,
5900            &InstrumentAny::CryptoPerpetual(instrument),
5901            None,
5902            None,
5903            None,
5904            ts_init,
5905        );
5906
5907        assert!(result.is_ok());
5908        match result.unwrap() {
5909            ParsedOrderEvent::Expired(expired) => {
5910                assert_eq!(expired.client_order_id, client_order_id);
5911                assert_eq!(expired.venue_order_id, Some(VenueOrderId::new("venue_456")));
5912            }
5913            other => panic!("Expected Expired, was {other:?}"),
5914        }
5915    }
5916
5917    #[rstest]
5918    fn test_parse_order_event_filled_with_fill_data_returns_fill() {
5919        let instrument = create_stub_instrument();
5920        let mut msg = create_order_msg_for_event_test(
5921            OKXOrderStatus::Filled,
5922            "test_client_123",
5923            "venue_456",
5924            "50000.0",
5925            "0.01",
5926        );
5927        msg.fill_sz = "0.01".to_string();
5928        msg.fill_px = "50000.0".to_string();
5929        msg.trade_id = "trade_789".to_string();
5930        msg.acc_fill_sz = Some("0.01".to_string());
5931
5932        let client_order_id = ClientOrderId::new("test_client_123");
5933        let account_id = AccountId::new("OKX-001");
5934        let trader_id = TraderId::new("TRADER-001");
5935        let strategy_id = StrategyId::new("STRATEGY-001");
5936        let ts_init = UnixNanos::from(1_000_000_000);
5937
5938        let result = parse_order_event(
5939            &msg,
5940            client_order_id,
5941            account_id,
5942            trader_id,
5943            strategy_id,
5944            &InstrumentAny::CryptoPerpetual(instrument),
5945            None,
5946            None,
5947            None,
5948            ts_init,
5949        );
5950
5951        assert!(result.is_ok());
5952        match result.unwrap() {
5953            ParsedOrderEvent::Fill(fill) => {
5954                assert_eq!(fill.client_order_id, Some(client_order_id));
5955                assert_eq!(fill.venue_order_id, VenueOrderId::new("venue_456"));
5956                assert_eq!(fill.trade_id, TradeId::from("trade_789"));
5957            }
5958            other => panic!("Expected Fill, was {other:?}"),
5959        }
5960    }
5961
5962    #[rstest]
5963    #[case::gtd_in_reason(None, Some("GTD order expired"), true)]
5964    #[case::timeout_in_reason(None, Some("Order timeout"), true)]
5965    #[case::expir_in_reason(None, Some("Expiration reached"), true)]
5966    #[case::source_code_5(Some("5"), None, true)]
5967    #[case::source_time_expired(Some("time_expired"), None, true)]
5968    #[case::user_cancel(Some("1"), Some("User canceled"), false)]
5969    #[case::no_reason(None, None, false)]
5970    fn test_is_order_expired_by_reason(
5971        #[case] source: Option<&str>,
5972        #[case] reason: Option<&str>,
5973        #[case] expected: bool,
5974    ) {
5975        let mut msg =
5976            create_order_msg_for_event_test(OKXOrderStatus::Canceled, "test", "123", "100", "1");
5977        msg.cancel_source = source.map(str::to_string);
5978        msg.cancel_source_reason = reason.map(str::to_string);
5979
5980        assert_eq!(is_order_expired_by_reason(&msg), expected);
5981    }
5982
5983    fn fresh_cancel_source_seen() -> Mutex<AHashSet<String>> {
5984        Mutex::new(AHashSet::new())
5985    }
5986
5987    #[rstest]
5988    fn test_log_unknown_cancel_source_records_first_observation() {
5989        let mut msg =
5990            create_order_msg_for_event_test(OKXOrderStatus::Canceled, "test", "123", "100", "1");
5991        msg.cancel_source = Some("99".to_string());
5992        msg.cancel_source_reason = Some("Unknown reason".to_string());
5993
5994        let seen = fresh_cancel_source_seen();
5995        assert!(log_unknown_cancel_source_inner(&msg, &seen, 8));
5996        assert_eq!(seen.lock().len(), 1);
5997    }
5998
5999    #[rstest]
6000    fn test_log_unknown_cancel_source_dedups_repeat_pair() {
6001        let mut msg =
6002            create_order_msg_for_event_test(OKXOrderStatus::Canceled, "test", "123", "100", "1");
6003        msg.cancel_source = Some("99".to_string());
6004        msg.cancel_source_reason = Some("Unknown reason".to_string());
6005
6006        let seen = fresh_cancel_source_seen();
6007        assert!(log_unknown_cancel_source_inner(&msg, &seen, 8));
6008        assert!(!log_unknown_cancel_source_inner(&msg, &seen, 8));
6009        assert_eq!(seen.lock().len(), 1);
6010    }
6011
6012    #[rstest]
6013    #[case::post_only("31")]
6014    #[case::known_expired("5")]
6015    #[case::sentinel_time("time_expired")]
6016    #[case::sentinel_gtd("gtd_expired")]
6017    fn test_log_unknown_cancel_source_skips_known_sources(#[case] source: &str) {
6018        let mut msg =
6019            create_order_msg_for_event_test(OKXOrderStatus::Canceled, "test", "123", "100", "1");
6020        msg.cancel_source = Some(source.to_string());
6021
6022        let seen = fresh_cancel_source_seen();
6023        assert!(!log_unknown_cancel_source_inner(&msg, &seen, 8));
6024        assert!(seen.lock().is_empty());
6025    }
6026
6027    #[rstest]
6028    fn test_log_unknown_cancel_source_skips_when_source_and_reason_empty() {
6029        let msg =
6030            create_order_msg_for_event_test(OKXOrderStatus::Canceled, "test", "123", "100", "1");
6031        let seen = fresh_cancel_source_seen();
6032        assert!(!log_unknown_cancel_source_inner(&msg, &seen, 8));
6033        assert!(seen.lock().is_empty());
6034    }
6035
6036    #[rstest]
6037    fn test_log_unknown_cancel_source_respects_capacity_cap() {
6038        let cap = 4;
6039        let seen = fresh_cancel_source_seen();
6040
6041        for i in 0..cap {
6042            let mut msg = create_order_msg_for_event_test(
6043                OKXOrderStatus::Canceled,
6044                "test",
6045                "123",
6046                "100",
6047                "1",
6048            );
6049            msg.cancel_source = Some(format!("novel_{i}"));
6050            assert!(log_unknown_cancel_source_inner(&msg, &seen, cap));
6051        }
6052
6053        let mut overflow =
6054            create_order_msg_for_event_test(OKXOrderStatus::Canceled, "test", "123", "100", "1");
6055        overflow.cancel_source = Some("novel_overflow".to_string());
6056        assert!(!log_unknown_cancel_source_inner(&overflow, &seen, cap));
6057        assert_eq!(seen.lock().len(), cap);
6058    }
6059
6060    // Regression test: PartiallyFilled order with price change should emit Updated, not StatusOnly
6061    #[rstest]
6062    fn test_parse_order_event_partially_filled_with_price_change_returns_updated() {
6063        let instrument = create_stub_instrument();
6064        let msg = create_order_msg_for_event_test(
6065            OKXOrderStatus::PartiallyFilled,
6066            "test_client_123",
6067            "venue_456",
6068            "51000.0",
6069            "0.01",
6070        );
6071
6072        let client_order_id = ClientOrderId::new("test_client_123");
6073        let account_id = AccountId::new("OKX-001");
6074        let trader_id = TraderId::new("TRADER-001");
6075        let strategy_id = StrategyId::new("STRATEGY-001");
6076        let ts_init = UnixNanos::from(1_000_000_000);
6077
6078        let previous_state = OrderStateSnapshot {
6079            venue_order_id: VenueOrderId::new("venue_456"),
6080            quantity: Quantity::from("0.01000000"),
6081            price: Some(Price::from("50000.00")),
6082        };
6083
6084        let result = parse_order_event(
6085            &msg,
6086            client_order_id,
6087            account_id,
6088            trader_id,
6089            strategy_id,
6090            &InstrumentAny::CryptoPerpetual(instrument),
6091            None,
6092            None,
6093            Some(&previous_state),
6094            ts_init,
6095        );
6096
6097        assert!(result.is_ok());
6098        match result.unwrap() {
6099            ParsedOrderEvent::Updated(updated) => {
6100                assert_eq!(updated.client_order_id, client_order_id);
6101                assert_eq!(updated.price, Some(Price::from("51000.00")));
6102            }
6103            other => {
6104                panic!("Expected Updated for PartiallyFilled with price change, was {other:?}")
6105            }
6106        }
6107    }
6108
6109    #[rstest]
6110    fn test_is_order_updated_price_change() {
6111        let instrument = create_stub_instrument();
6112        let msg = create_order_msg_for_event_test(
6113            OKXOrderStatus::Live,
6114            "test",
6115            "venue_123",
6116            "51000.0",
6117            "0.01",
6118        );
6119
6120        let previous = OrderStateSnapshot {
6121            venue_order_id: VenueOrderId::new("venue_123"),
6122            quantity: Quantity::from("0.01000000"),
6123            price: Some(Price::from("50000.00")),
6124        };
6125
6126        let result = is_order_updated(&msg, &previous, &InstrumentAny::CryptoPerpetual(instrument));
6127        assert!(result.is_ok());
6128        assert!(result.unwrap());
6129    }
6130
6131    #[rstest]
6132    fn test_is_order_updated_quantity_change() {
6133        let instrument = create_stub_instrument();
6134        let msg = create_order_msg_for_event_test(
6135            OKXOrderStatus::Live,
6136            "test",
6137            "venue_123",
6138            "50000.0",
6139            "0.02", // New quantity
6140        );
6141
6142        let previous = OrderStateSnapshot {
6143            venue_order_id: VenueOrderId::new("venue_123"),
6144            quantity: Quantity::from("0.01000000"), // Old quantity
6145            price: Some(Price::from("50000.00")),
6146        };
6147
6148        let result = is_order_updated(&msg, &previous, &InstrumentAny::CryptoPerpetual(instrument));
6149        assert!(result.is_ok());
6150        assert!(result.unwrap());
6151    }
6152
6153    #[rstest]
6154    fn test_is_order_updated_venue_id_change() {
6155        let instrument = create_stub_instrument();
6156        let msg = create_order_msg_for_event_test(
6157            OKXOrderStatus::Live,
6158            "test",
6159            "venue_456", // New venue ID
6160            "50000.0",
6161            "0.01",
6162        );
6163
6164        let previous = OrderStateSnapshot {
6165            venue_order_id: VenueOrderId::new("venue_123"), // Old venue ID
6166            quantity: Quantity::from("0.01000000"),
6167            price: Some(Price::from("50000.00")),
6168        };
6169
6170        let result = is_order_updated(&msg, &previous, &InstrumentAny::CryptoPerpetual(instrument));
6171        assert!(result.is_ok());
6172        assert!(result.unwrap());
6173    }
6174
6175    #[rstest]
6176    fn test_is_order_updated_no_change() {
6177        let instrument = create_stub_instrument();
6178        let msg = create_order_msg_for_event_test(
6179            OKXOrderStatus::Live,
6180            "test",
6181            "venue_123",
6182            "50000.0",
6183            "0.01",
6184        );
6185
6186        let previous = OrderStateSnapshot {
6187            venue_order_id: VenueOrderId::new("venue_123"),
6188            quantity: Quantity::from("0.01000000"),
6189            price: Some(Price::from("50000.00")),
6190        };
6191
6192        let result = is_order_updated(&msg, &previous, &InstrumentAny::CryptoPerpetual(instrument));
6193        assert!(result.is_ok());
6194        assert!(!result.unwrap());
6195    }
6196
6197    #[rstest]
6198    fn test_parse_order_status_report_ts_last_and_ts_init_ordering() {
6199        let instrument = create_stub_instrument();
6200        let inst = InstrumentAny::CryptoPerpetual(instrument);
6201        let account_id = AccountId::new("OKX-001");
6202        let ts_init = UnixNanos::from(999_000_000_000u64);
6203
6204        let mut msg = create_stub_order_msg("", Some("0".to_string()), "123456", "");
6205        msg.avg_px = String::new();
6206        msg.c_time = 1_706_000_000_000;
6207        msg.cl_ord_id = "test_ts_order".to_string();
6208        msg.fee = None;
6209        msg.fill_px = String::new();
6210        msg.fill_time = 0;
6211        msg.lever = String::new();
6212        msg.ord_type = OKXOrderType::Limit;
6213        msg.pnl = String::new();
6214        msg.px = "50000.00".to_string();
6215        msg.state = OKXOrderStatus::Live;
6216        msg.sz = "0.01".to_string();
6217        msg.td_mode = OKXTradeMode::Cross;
6218        msg.u_time = 1_706_000_001_000;
6219
6220        let report = parse_order_status_report(&msg, &inst, account_id, ts_init).unwrap();
6221
6222        assert_eq!(
6223            report.ts_accepted,
6224            UnixNanos::from(1_706_000_000_000_u64 * 1_000_000)
6225        );
6226        assert_eq!(
6227            report.ts_last,
6228            UnixNanos::from(1_706_000_001_000_u64 * 1_000_000)
6229        );
6230        assert_eq!(report.ts_init, ts_init);
6231    }
6232
6233    #[rstest]
6234    fn test_parse_order_status_report_preserves_attached_tp_sl_child_ids() {
6235        let instrument = create_stub_instrument();
6236        let inst = InstrumentAny::CryptoPerpetual(instrument);
6237        let account_id = AccountId::new("OKX-001");
6238        let ts_init = UnixNanos::default();
6239
6240        let mut msg = create_stub_order_msg("", Some("0".to_string()), "123456", "");
6241        msg.avg_px = String::new();
6242        msg.c_time = 1_706_000_000_000;
6243        msg.cl_ord_id = "O-attached-entry".to_string();
6244        msg.attach_algo_cl_ord_id = Some("O-attached-sl".to_string());
6245        msg.attach_algo_ords = vec![
6246            OKXAttachedAlgoOrd {
6247                attach_algo_id: "algo-sl".to_string(),
6248                attach_algo_cl_ord_id: "O-attached-sl".to_string(),
6249                sl_trigger_px: "1500".to_string(),
6250                sl_ord_px: "-1".to_string(),
6251                sl_trigger_px_type: Some(OKXTriggerType::Last),
6252                tp_trigger_px: String::new(),
6253                tp_ord_px: String::new(),
6254                tp_trigger_px_type: None,
6255                callback_ratio: String::new(),
6256                callback_spread: String::new(),
6257                active_px: String::new(),
6258            },
6259            OKXAttachedAlgoOrd {
6260                attach_algo_id: "algo-tp".to_string(),
6261                attach_algo_cl_ord_id: "O-attached-tp".to_string(),
6262                sl_trigger_px: String::new(),
6263                sl_ord_px: String::new(),
6264                sl_trigger_px_type: None,
6265                tp_trigger_px: "2500".to_string(),
6266                tp_ord_px: "-1".to_string(),
6267                tp_trigger_px_type: Some(OKXTriggerType::Last),
6268                callback_ratio: String::new(),
6269                callback_spread: String::new(),
6270                active_px: String::new(),
6271            },
6272        ];
6273        msg.fee = None;
6274        msg.fill_px = String::new();
6275        msg.fill_time = 0;
6276        msg.lever = String::new();
6277        msg.ord_type = OKXOrderType::Limit;
6278        msg.pnl = String::new();
6279        msg.px = "2000.00".to_string();
6280        msg.state = OKXOrderStatus::Live;
6281        msg.sz = "0.01".to_string();
6282        msg.td_mode = OKXTradeMode::Cross;
6283        msg.u_time = 1_706_000_001_000;
6284
6285        let report = parse_order_status_report(&msg, &inst, account_id, ts_init).unwrap();
6286        let linked_order_ids = report
6287            .linked_order_ids
6288            .expect("expected linked child order ids");
6289
6290        assert_eq!(linked_order_ids.len(), 2);
6291        assert!(linked_order_ids.contains(&ClientOrderId::from("O-attached-sl")));
6292        assert!(linked_order_ids.contains(&ClientOrderId::from("O-attached-tp")));
6293    }
6294
6295    #[rstest]
6296    fn test_parse_algo_order_timestamps_converted_from_ms_to_ns() {
6297        let instrument = create_stub_instrument();
6298        let inst = InstrumentAny::CryptoPerpetual(instrument);
6299        let account_id = AccountId::new("OKX-001");
6300        let ts_init = UnixNanos::from(999_000_000_000u64);
6301
6302        let msg = OKXAlgoOrderMsg {
6303            algo_id: "algo_1".to_string(),
6304            algo_cl_ord_id: "algo_cl_1".to_string(),
6305            cl_ord_id: String::new(),
6306            ord_id: String::new(),
6307            ord_id_list: Vec::new(),
6308            inst_id: Ustr::from("BTC-USDT-SWAP"),
6309            inst_type: OKXInstrumentType::Swap,
6310            ord_type: OKXAlgoOrderType::Trigger,
6311            state: OKXAlgoOrderStatus::Live,
6312            side: OKXSide::Buy,
6313            pos_side: OKXPositionSide::Long,
6314            sz: "0.01".to_string(),
6315            trigger_px: "45000.00".to_string(),
6316            trigger_px_type: OKXTriggerType::Last,
6317            sl_trigger_px: String::new(),
6318            sl_ord_px: String::new(),
6319            sl_trigger_px_type: OKXTriggerType::None,
6320            tp_trigger_px: String::new(),
6321            tp_ord_px: String::new(),
6322            tp_trigger_px_type: OKXTriggerType::None,
6323            ord_px: "-1".to_string(),
6324            td_mode: OKXTradeMode::Cross,
6325            lever: String::new(),
6326            reduce_only: "false".to_string(),
6327            close_fraction: String::new(),
6328            actual_px: String::new(),
6329            actual_sz: String::new(),
6330            notional_usd: String::new(),
6331            c_time: 1_706_000_000_000,
6332            u_time: 1_706_000_001_000,
6333            trigger_time: String::new(),
6334            fail_code: String::new(),
6335            tag: String::new(),
6336            callback_ratio: String::new(),
6337            callback_spread: String::new(),
6338            active_px: String::new(),
6339            ccy: None,
6340            tgt_ccy: None,
6341            fee: None,
6342            fee_ccy: None,
6343            advance_ord_type: None,
6344        };
6345
6346        let report = parse_algo_order_status_report(&msg, &inst, account_id, ts_init).unwrap();
6347
6348        let expected_accepted_ns = 1_706_000_000_000_u64 * 1_000_000;
6349        let expected_last_ns = 1_706_000_001_000_u64 * 1_000_000;
6350        assert_eq!(report.ts_accepted, UnixNanos::from(expected_accepted_ns));
6351        assert_eq!(report.ts_last, UnixNanos::from(expected_last_ns));
6352        assert_eq!(report.ts_init, ts_init);
6353    }
6354
6355    fn stub_algo_order_msg(ord_type: OKXAlgoOrderType) -> OKXAlgoOrderMsg {
6356        OKXAlgoOrderMsg {
6357            algo_id: "algo_1".to_string(),
6358            algo_cl_ord_id: "algo_cl_1".to_string(),
6359            cl_ord_id: String::new(),
6360            ord_id: String::new(),
6361            ord_id_list: Vec::new(),
6362            inst_id: Ustr::from("BTC-USDT-SWAP"),
6363            inst_type: OKXInstrumentType::Swap,
6364            ord_type,
6365            state: OKXAlgoOrderStatus::Live,
6366            side: OKXSide::Sell,
6367            pos_side: OKXPositionSide::Long,
6368            sz: "0.01".to_string(),
6369            trigger_px: "95000.00".to_string(),
6370            trigger_px_type: OKXTriggerType::Last,
6371            sl_trigger_px: String::new(),
6372            sl_ord_px: String::new(),
6373            sl_trigger_px_type: OKXTriggerType::None,
6374            tp_trigger_px: String::new(),
6375            tp_ord_px: String::new(),
6376            tp_trigger_px_type: OKXTriggerType::None,
6377            ord_px: "-1".to_string(),
6378            td_mode: OKXTradeMode::Cross,
6379            lever: String::new(),
6380            reduce_only: "false".to_string(),
6381            close_fraction: String::new(),
6382            actual_px: String::new(),
6383            actual_sz: String::new(),
6384            notional_usd: String::new(),
6385            c_time: 1_706_000_000_000,
6386            u_time: 1_706_000_001_000,
6387            trigger_time: String::new(),
6388            fail_code: String::new(),
6389            tag: String::new(),
6390            callback_ratio: String::new(),
6391            callback_spread: String::new(),
6392            active_px: String::new(),
6393            ccy: None,
6394            tgt_ccy: None,
6395            fee: None,
6396            fee_ccy: None,
6397            advance_ord_type: None,
6398        }
6399    }
6400
6401    #[rstest]
6402    fn test_parse_algo_order_trailing_stop_with_callback_ratio() {
6403        let instrument = create_stub_instrument();
6404        let inst = InstrumentAny::CryptoPerpetual(instrument);
6405        let account_id = AccountId::new("OKX-001");
6406
6407        let mut msg = stub_algo_order_msg(OKXAlgoOrderType::MoveOrderStop);
6408        msg.callback_ratio = "0.01".to_string(); // 1% = 100 basis points
6409
6410        let report =
6411            parse_algo_order_status_report(&msg, &inst, account_id, UnixNanos::default()).unwrap();
6412
6413        assert_eq!(report.order_type, OrderType::TrailingStopMarket);
6414        assert_eq!(report.trailing_offset, Some(dec!(100)));
6415        assert_eq!(
6416            report.trailing_offset_type,
6417            Some(TrailingOffsetType::BasisPoints),
6418        );
6419        assert_eq!(report.trigger_price, Some(Price::from("95000.00")));
6420    }
6421
6422    #[rstest]
6423    fn test_parse_algo_order_trailing_stop_captures_activation_price() {
6424        let instrument = create_stub_instrument();
6425        let inst = InstrumentAny::CryptoPerpetual(instrument);
6426        let account_id = AccountId::new("OKX-001");
6427
6428        let mut msg = stub_algo_order_msg(OKXAlgoOrderType::MoveOrderStop);
6429        msg.callback_ratio = "0.01".to_string();
6430        msg.active_px = "94000.5".to_string();
6431
6432        let report =
6433            parse_algo_order_status_report(&msg, &inst, account_id, UnixNanos::default()).unwrap();
6434
6435        assert_eq!(report.order_type, OrderType::TrailingStopMarket);
6436        assert_eq!(report.activation_price, Some(Price::from("94000.50")));
6437    }
6438
6439    #[rstest]
6440    fn test_parse_algo_order_trailing_stop_with_callback_spread() {
6441        let instrument = create_stub_instrument();
6442        let inst = InstrumentAny::CryptoPerpetual(instrument);
6443        let account_id = AccountId::new("OKX-001");
6444
6445        let mut msg = stub_algo_order_msg(OKXAlgoOrderType::MoveOrderStop);
6446        msg.callback_spread = "50.5".to_string();
6447
6448        let report =
6449            parse_algo_order_status_report(&msg, &inst, account_id, UnixNanos::default()).unwrap();
6450
6451        assert_eq!(report.order_type, OrderType::TrailingStopMarket);
6452        assert_eq!(report.trailing_offset, Some(dec!(50.5)));
6453        assert_eq!(report.trailing_offset_type, Some(TrailingOffsetType::Price),);
6454    }
6455
6456    #[rstest]
6457    fn test_parse_algo_order_unsupported_type_skipped() {
6458        let instrument = create_stub_instrument();
6459        let account_id = AccountId::new("OKX-001");
6460        let mut instruments = AHashMap::new();
6461        instruments.insert(
6462            Ustr::from("BTC-USDT-SWAP"),
6463            InstrumentAny::CryptoPerpetual(instrument),
6464        );
6465
6466        let msg = stub_algo_order_msg(OKXAlgoOrderType::Iceberg);
6467
6468        let result = parse_algo_order_msg(&msg, account_id, &instruments, UnixNanos::default());
6469
6470        assert!(result.unwrap().is_none());
6471    }
6472
6473    #[rstest]
6474    fn test_parse_algo_order_chase_type_skipped() {
6475        let instrument = create_stub_instrument();
6476        let account_id = AccountId::new("OKX-001");
6477        let mut instruments = AHashMap::new();
6478        instruments.insert(
6479            Ustr::from("BTC-USDT-SWAP"),
6480            InstrumentAny::CryptoPerpetual(instrument),
6481        );
6482
6483        let msg = stub_algo_order_msg(OKXAlgoOrderType::Chase);
6484
6485        let result = parse_algo_order_msg(&msg, account_id, &instruments, UnixNanos::default());
6486
6487        assert!(result.unwrap().is_none());
6488    }
6489
6490    #[rstest]
6491    fn test_parse_algo_order_unknown_type_skipped() {
6492        let instrument = create_stub_instrument();
6493        let account_id = AccountId::new("OKX-001");
6494        let mut instruments = AHashMap::new();
6495        instruments.insert(
6496            Ustr::from("BTC-USDT-SWAP"),
6497            InstrumentAny::CryptoPerpetual(instrument),
6498        );
6499
6500        let msg = stub_algo_order_msg(OKXAlgoOrderType::Other);
6501
6502        let result = parse_algo_order_msg(&msg, account_id, &instruments, UnixNanos::default());
6503
6504        assert!(result.unwrap().is_none());
6505    }
6506
6507    #[rstest]
6508    fn test_parse_algo_order_unknown_state_skipped() {
6509        let instrument = create_stub_instrument();
6510        let account_id = AccountId::new("OKX-001");
6511        let mut instruments = AHashMap::new();
6512        instruments.insert(
6513            Ustr::from("BTC-USDT-SWAP"),
6514            InstrumentAny::CryptoPerpetual(instrument),
6515        );
6516
6517        let mut msg = stub_algo_order_msg(OKXAlgoOrderType::Trigger);
6518        msg.state = OKXAlgoOrderStatus::Unknown;
6519
6520        let result = parse_algo_order_msg(&msg, account_id, &instruments, UnixNanos::default());
6521
6522        assert!(result.unwrap().is_none());
6523    }
6524
6525    #[rstest]
6526    fn test_deserialize_algo_order_states_message() {
6527        let json_data = load_test_json("ws_orders_algo_states.json");
6528        let payload: serde_json::Value = serde_json::from_str(&json_data).unwrap();
6529        let data: Vec<OKXAlgoOrderMsg> = serde_json::from_value(payload["data"].clone()).unwrap();
6530
6531        assert_eq!(data.len(), 6);
6532        assert_eq!(data[0].state, OKXAlgoOrderStatus::Effective);
6533        assert_eq!(data[1].state, OKXAlgoOrderStatus::PartiallyEffective);
6534        assert_eq!(data[2].state, OKXAlgoOrderStatus::Pause);
6535        assert_eq!(data[3].state, OKXAlgoOrderStatus::OrderFailed);
6536        assert_eq!(data[4].state, OKXAlgoOrderStatus::PartiallyFailed);
6537        assert_eq!(data[5].ord_type, OKXAlgoOrderType::Chase);
6538    }
6539
6540    #[rstest]
6541    fn test_parse_algo_order_states_map_to_nautilus_status() {
6542        let json_data = load_test_json("ws_orders_algo_states.json");
6543        let payload: serde_json::Value = serde_json::from_str(&json_data).unwrap();
6544        let data: Vec<OKXAlgoOrderMsg> = serde_json::from_value(payload["data"].clone()).unwrap();
6545
6546        let account_id = AccountId::new("OKX-001");
6547        let mut instruments = AHashMap::new();
6548        instruments.insert(
6549            Ustr::from("BTC-USDT-SWAP"),
6550            InstrumentAny::CryptoPerpetual(create_stub_instrument()),
6551        );
6552
6553        let expected = [
6554            (0_usize, OrderStatus::Triggered), // effective
6555            (1, OrderStatus::Triggered),       // partially_effective
6556            (2, OrderStatus::Accepted),        // pause
6557            (3, OrderStatus::Rejected),        // order_failed
6558            (4, OrderStatus::Rejected),        // partially_failed
6559        ];
6560
6561        for (idx, expected_status) in expected {
6562            let report =
6563                parse_algo_order_msg(&data[idx], account_id, &instruments, UnixNanos::default())
6564                    .unwrap()
6565                    .unwrap_or_else(|| panic!("Expected report for fixture index {idx}"));
6566
6567            match report {
6568                ExecutionReport::Order(report) => {
6569                    assert_eq!(report.order_status, expected_status);
6570                }
6571                other => panic!("Expected Order report for fixture index {idx}, was {other:?}"),
6572            }
6573        }
6574
6575        // Chase orders are unsupported and skipped; their triggered child orders
6576        // still arrive on the regular orders channel
6577        let chase =
6578            parse_algo_order_msg(&data[5], account_id, &instruments, UnixNanos::default()).unwrap();
6579        assert!(chase.is_none());
6580    }
6581
6582    #[rstest]
6583    fn test_parse_algo_order_missing_trigger_px_type_defaults() {
6584        let instrument = create_stub_instrument();
6585        let inst = InstrumentAny::CryptoPerpetual(instrument);
6586        let account_id = AccountId::new("OKX-001");
6587
6588        let mut msg = stub_algo_order_msg(OKXAlgoOrderType::MoveOrderStop);
6589        msg.trigger_px_type = OKXTriggerType::None;
6590        msg.callback_ratio = "0.005".to_string();
6591
6592        let report =
6593            parse_algo_order_status_report(&msg, &inst, account_id, UnixNanos::default()).unwrap();
6594
6595        assert_eq!(report.trigger_type, Some(TriggerType::Default));
6596        assert_eq!(report.order_type, OrderType::TrailingStopMarket);
6597    }
6598
6599    #[rstest]
6600    fn test_parse_algo_order_close_fraction_stop_market_without_sz() {
6601        let instrument = create_stub_instrument();
6602        let inst = InstrumentAny::CryptoPerpetual(instrument);
6603        let account_id = AccountId::new("OKX-001");
6604
6605        let mut msg = stub_algo_order_msg(OKXAlgoOrderType::Conditional);
6606        msg.sz = String::new();
6607        msg.trigger_px = String::new();
6608        msg.trigger_px_type = OKXTriggerType::None;
6609        msg.ord_px = String::new();
6610        msg.sl_trigger_px = "50000".to_string();
6611        msg.sl_ord_px = "-1".to_string();
6612        msg.sl_trigger_px_type = OKXTriggerType::Last;
6613        msg.close_fraction = "1".to_string();
6614        msg.reduce_only = "true".to_string();
6615
6616        let report =
6617            parse_algo_order_status_report(&msg, &inst, account_id, UnixNanos::default()).unwrap();
6618
6619        assert_eq!(report.order_type, OrderType::StopMarket);
6620        assert_eq!(report.trigger_price, Some(Price::from("50000.00")));
6621        assert_eq!(report.trigger_type, Some(TriggerType::LastPrice));
6622        assert_eq!(report.price, None);
6623        assert_eq!(report.quantity, Quantity::zero(inst.size_precision()));
6624        assert!(report.reduce_only);
6625    }
6626
6627    #[rstest]
6628    fn test_parse_algo_order_close_fraction_market_if_touched_without_sz() {
6629        let instrument = create_stub_instrument();
6630        let inst = InstrumentAny::CryptoPerpetual(instrument);
6631        let account_id = AccountId::new("OKX-001");
6632
6633        let mut msg = stub_algo_order_msg(OKXAlgoOrderType::Conditional);
6634        msg.sz = String::new();
6635        msg.trigger_px = String::new();
6636        msg.trigger_px_type = OKXTriggerType::None;
6637        msg.ord_px = String::new();
6638        msg.sl_trigger_px = String::new();
6639        msg.sl_ord_px = String::new();
6640        msg.tp_trigger_px = "50000".to_string();
6641        msg.tp_ord_px = "-1".to_string();
6642        msg.tp_trigger_px_type = OKXTriggerType::Last;
6643        msg.close_fraction = "1".to_string();
6644        msg.reduce_only = "true".to_string();
6645        msg.side = OKXSide::Buy;
6646
6647        let report =
6648            parse_algo_order_status_report(&msg, &inst, account_id, UnixNanos::default()).unwrap();
6649
6650        assert_eq!(report.order_type, OrderType::MarketIfTouched);
6651        assert_eq!(report.trigger_price, Some(Price::from("50000.00")));
6652        assert_eq!(report.trigger_type, Some(TriggerType::LastPrice));
6653        assert_eq!(report.price, None);
6654        assert_eq!(report.quantity, Quantity::zero(inst.size_precision()));
6655        assert!(report.reduce_only);
6656    }
6657
6658    fn stub_book_entry(price: &str, size: &str) -> OrderBookEntry {
6659        OrderBookEntry {
6660            price: price.to_string(),
6661            size: size.to_string(),
6662            liquidated_orders_count: "0".to_string(),
6663            orders_count: "1".to_string(),
6664        }
6665    }
6666
6667    fn stub_book_msg(bids: Vec<OrderBookEntry>, asks: Vec<OrderBookEntry>) -> OKXBookMsg {
6668        OKXBookMsg {
6669            bids,
6670            asks,
6671            ts: 1_706_000_000_000,
6672            seq_id: 1,
6673            prev_seq_id: Some(0),
6674            checksum: None,
6675        }
6676    }
6677
6678    #[rstest]
6679    fn test_parse_quote_msg_empty_bids_returns_error() {
6680        let msg = stub_book_msg(vec![], vec![stub_book_entry("50000.00", "1.0")]);
6681
6682        let result = parse_quote_msg(
6683            &msg,
6684            InstrumentId::from("BTC-USDT.OKX"),
6685            2,
6686            8,
6687            UnixNanos::default(),
6688        );
6689        assert!(result.is_err());
6690        assert!(result.unwrap_err().to_string().contains("Empty bids"));
6691    }
6692
6693    #[rstest]
6694    fn test_parse_quote_msg_empty_asks_returns_error() {
6695        let msg = stub_book_msg(vec![stub_book_entry("50000.00", "1.0")], vec![]);
6696
6697        let result = parse_quote_msg(
6698            &msg,
6699            InstrumentId::from("BTC-USDT.OKX"),
6700            2,
6701            8,
6702            UnixNanos::default(),
6703        );
6704        assert!(result.is_err());
6705        assert!(result.unwrap_err().to_string().contains("Empty asks"));
6706    }
6707
6708    #[rstest]
6709    fn test_quote_cache_complete_bbo_tbt_message() {
6710        use nautilus_common::cache::quote::QuoteCache;
6711
6712        let mut cache = QuoteCache::new();
6713        let instrument_id = InstrumentId::from("BTC-USD-260327-75000-C.OKX");
6714        let msg = stub_book_msg(
6715            vec![stub_book_entry("0.0035", "100")],
6716            vec![stub_book_entry("0.0040", "200")],
6717        );
6718
6719        let bid_price = Some(parse_price(&msg.bids[0].price, 4).unwrap());
6720        let bid_size = Some(parse_quantity(&msg.bids[0].size, 0).unwrap());
6721        let ask_price = Some(parse_price(&msg.asks[0].price, 4).unwrap());
6722        let ask_size = Some(parse_quantity(&msg.asks[0].size, 0).unwrap());
6723        let ts_event = parse_millisecond_timestamp(msg.ts);
6724
6725        let quote = cache
6726            .process(
6727                instrument_id,
6728                bid_price,
6729                ask_price,
6730                bid_size,
6731                ask_size,
6732                ts_event,
6733                UnixNanos::default(),
6734            )
6735            .unwrap();
6736
6737        assert_eq!(quote.bid_price, Price::from("0.0035"));
6738        assert_eq!(quote.ask_price, Price::from("0.0040"));
6739        assert_eq!(quote.bid_size, Quantity::from(100));
6740        assert_eq!(quote.ask_size, Quantity::from(200));
6741    }
6742
6743    #[rstest]
6744    fn test_quote_cache_empty_bids_uses_cached_value() {
6745        use nautilus_common::cache::quote::QuoteCache;
6746
6747        let mut cache = QuoteCache::new();
6748        let instrument_id = InstrumentId::from("BTC-USD-260327-80000-C.OKX");
6749
6750        cache
6751            .process(
6752                instrument_id,
6753                Some(Price::from("0.0010")),
6754                Some(Price::from("0.0015")),
6755                Some(Quantity::from(50)),
6756                Some(Quantity::from(75)),
6757                UnixNanos::default(),
6758                UnixNanos::default(),
6759            )
6760            .unwrap();
6761
6762        let msg = stub_book_msg(vec![], vec![stub_book_entry("0.0020", "100")]);
6763        let ask_price = Some(parse_price(&msg.asks[0].price, 4).unwrap());
6764        let ask_size = Some(parse_quantity(&msg.asks[0].size, 0).unwrap());
6765        let ts_event = parse_millisecond_timestamp(msg.ts);
6766
6767        let quote = cache
6768            .process(
6769                instrument_id,
6770                None,
6771                ask_price,
6772                None,
6773                ask_size,
6774                ts_event,
6775                UnixNanos::default(),
6776            )
6777            .unwrap();
6778
6779        assert_eq!(quote.bid_price, Price::from("0.0010"));
6780        assert_eq!(quote.bid_size, Quantity::from(50));
6781        assert_eq!(quote.ask_price, Price::from("0.0020"));
6782        assert_eq!(quote.ask_size, Quantity::from(100));
6783    }
6784
6785    #[rstest]
6786    fn test_quote_cache_empty_asks_uses_cached_value() {
6787        use nautilus_common::cache::quote::QuoteCache;
6788
6789        let mut cache = QuoteCache::new();
6790        let instrument_id = InstrumentId::from("BTC-USD-260327-79000-P.OKX");
6791
6792        cache
6793            .process(
6794                instrument_id,
6795                Some(Price::from("0.0010")),
6796                Some(Price::from("0.0015")),
6797                Some(Quantity::from(50)),
6798                Some(Quantity::from(75)),
6799                UnixNanos::default(),
6800                UnixNanos::default(),
6801            )
6802            .unwrap();
6803
6804        let msg = stub_book_msg(vec![stub_book_entry("0.0012", "60")], vec![]);
6805        let bid_price = Some(parse_price(&msg.bids[0].price, 4).unwrap());
6806        let bid_size = Some(parse_quantity(&msg.bids[0].size, 0).unwrap());
6807        let ts_event = parse_millisecond_timestamp(msg.ts);
6808
6809        let quote = cache
6810            .process(
6811                instrument_id,
6812                bid_price,
6813                None,
6814                bid_size,
6815                None,
6816                ts_event,
6817                UnixNanos::default(),
6818            )
6819            .unwrap();
6820
6821        assert_eq!(quote.bid_price, Price::from("0.0012"));
6822        assert_eq!(quote.bid_size, Quantity::from(60));
6823        assert_eq!(quote.ask_price, Price::from("0.0015"));
6824        assert_eq!(quote.ask_size, Quantity::from(75));
6825    }
6826
6827    #[rstest]
6828    fn test_quote_cache_both_sides_empty_no_cache_returns_error() {
6829        use nautilus_common::cache::quote::QuoteCache;
6830
6831        let mut cache = QuoteCache::new();
6832        let instrument_id = InstrumentId::from("BTC-USD-260327-80000-C.OKX");
6833
6834        let result = cache.process(
6835            instrument_id,
6836            None,
6837            None,
6838            None,
6839            None,
6840            UnixNanos::default(),
6841            UnixNanos::default(),
6842        );
6843
6844        result.unwrap_err();
6845    }
6846
6847    #[rstest]
6848    fn test_quote_cache_both_sides_empty_with_cache_returns_cached() {
6849        use nautilus_common::cache::quote::QuoteCache;
6850
6851        let mut cache = QuoteCache::new();
6852        let instrument_id = InstrumentId::from("BTC-USD-260327-80000-C.OKX");
6853
6854        cache
6855            .process(
6856                instrument_id,
6857                Some(Price::from("0.0010")),
6858                Some(Price::from("0.0015")),
6859                Some(Quantity::from(50)),
6860                Some(Quantity::from(75)),
6861                UnixNanos::default(),
6862                UnixNanos::default(),
6863            )
6864            .unwrap();
6865
6866        let quote = cache
6867            .process(
6868                instrument_id,
6869                None,
6870                None,
6871                None,
6872                None,
6873                UnixNanos::from(1_706_000_000_000_000_000_u64),
6874                UnixNanos::from(1_706_000_000_000_000_000_u64),
6875            )
6876            .unwrap();
6877
6878        assert_eq!(quote.bid_price, Price::from("0.0010"));
6879        assert_eq!(quote.ask_price, Price::from("0.0015"));
6880        assert_eq!(
6881            quote.ts_event,
6882            UnixNanos::from(1_706_000_000_000_000_000_u64)
6883        );
6884    }
6885
6886    #[rstest]
6887    fn test_parse_instruments_channel_produces_status() {
6888        use nautilus_model::{enums::MarketStatusAction, identifiers::InstrumentId};
6889
6890        use crate::common::{models::OKXInstrument, parse::parse_instrument_any};
6891
6892        let ts_init = UnixNanos::default();
6893
6894        // Build a cached instrument.
6895        let inst_json = serde_json::json!({
6896            "instType": "SPOT",
6897            "instId": "BTC-USD",
6898            "baseCcy": "BTC",
6899            "quoteCcy": "USD",
6900            "settleCcy": "",
6901            "ctVal": "",
6902            "ctMult": "",
6903            "ctValCcy": "",
6904            "optType": "",
6905            "stk": "",
6906            "listTime": "1733454000000",
6907            "expTime": "",
6908            "lever": "",
6909            "tickSz": "0.1",
6910            "lotSz": "0.00000001",
6911            "minSz": "0.00001",
6912            "ctType": "",
6913            "state": "live",
6914            "ruleType": "normal",
6915            "maxLmtSz": "9999999999",
6916            "maxMktSz": "1000000",
6917            "maxLmtAmt": "20000000",
6918            "maxMktAmt": "1000000",
6919            "maxTwapSz": "9999999999",
6920            "maxIcebergSz": "9999999999",
6921            "maxTriggerSz": "9999999999",
6922            "maxStopSz": "1000000",
6923            "uly": "",
6924            "instFamily": ""
6925        });
6926        let initial: OKXInstrument = serde_json::from_value(inst_json).unwrap();
6927        let parsed = parse_instrument_any(&initial, None, None, ts_init)
6928            .unwrap()
6929            .unwrap();
6930
6931        let mut instruments_cache = AHashMap::new();
6932        instruments_cache.insert(Ustr::from("BTC-USD"), parsed);
6933
6934        let ws_data = serde_json::json!({
6935            "instType": "SPOT",
6936            "instId": "BTC-USD",
6937            "baseCcy": "BTC",
6938            "quoteCcy": "USD",
6939            "settleCcy": "",
6940            "ctVal": "",
6941            "ctMult": "",
6942            "ctValCcy": "",
6943            "optType": "",
6944            "stk": "",
6945            "listTime": "1733454000000",
6946            "expTime": "",
6947            "lever": "",
6948            "tickSz": "0.1",
6949            "lotSz": "0.00000001",
6950            "minSz": "0.00001",
6951            "ctType": "",
6952            "state": "live",
6953            "ruleType": "normal",
6954            "maxLmtSz": "9999999999",
6955            "maxMktSz": "1000000",
6956            "maxLmtAmt": "20000000",
6957            "maxMktAmt": "1000000",
6958            "maxTwapSz": "9999999999",
6959            "maxIcebergSz": "9999999999",
6960            "maxTriggerSz": "9999999999",
6961            "maxStopSz": "1000000",
6962            "uly": "",
6963            "instFamily": ""
6964        });
6965
6966        let instrument_id = InstrumentId::from("BTC-USD.OKX");
6967        let mut funding_cache = AHashMap::new();
6968
6969        let result = parse_ws_message_data(
6970            &OKXWsChannel::Instruments,
6971            ws_data,
6972            &instrument_id,
6973            2,
6974            8,
6975            ts_init,
6976            &mut funding_cache,
6977            &instruments_cache,
6978        )
6979        .expect("Failed to parse instruments channel");
6980
6981        match result {
6982            Some(NautilusWsMessage::Instrument(inst, status)) => {
6983                assert_eq!(inst.id(), InstrumentId::from("BTC-USD.OKX"));
6984                let status = status.expect("Expected InstrumentStatus");
6985                assert_eq!(status.action, MarketStatusAction::Trading);
6986                assert_eq!(status.is_trading, Some(true));
6987            }
6988            other => panic!("Expected Instrument with status, was {other:?}"),
6989        }
6990    }
6991
6992    #[rstest]
6993    fn test_parse_instruments_channel_returns_status_when_definition_invalid() {
6994        use nautilus_model::{enums::MarketStatusAction, identifiers::InstrumentId};
6995
6996        let ts_init = UnixNanos::default();
6997        let ws_data = serde_json::json!({
6998            "instType": "SPOT",
6999            "instId": "USDG-SGD",
7000            "baseCcy": "USDG",
7001            "quoteCcy": "SGD",
7002            "settleCcy": "",
7003            "ctVal": "",
7004            "ctMult": "",
7005            "ctValCcy": "",
7006            "optType": "",
7007            "stk": "",
7008            "listTime": "1733454000000",
7009            "expTime": "",
7010            "lever": "",
7011            "tickSz": "",
7012            "lotSz": "0.00000001",
7013            "minSz": "0.00001",
7014            "ctType": "",
7015            "state": "live",
7016            "ruleType": "normal",
7017            "maxLmtSz": "9999999999",
7018            "maxMktSz": "1000000",
7019            "maxLmtAmt": "20000000",
7020            "maxMktAmt": "1000000",
7021            "maxTwapSz": "9999999999",
7022            "maxIcebergSz": "9999999999",
7023            "maxTriggerSz": "9999999999",
7024            "maxStopSz": "1000000",
7025            "uly": "",
7026            "instFamily": ""
7027        });
7028
7029        let mut funding_cache = AHashMap::new();
7030        let instruments_cache = AHashMap::new();
7031        let result = parse_ws_message_data(
7032            &OKXWsChannel::Instruments,
7033            ws_data,
7034            &InstrumentId::from("BTC-USD.OKX"),
7035            2,
7036            8,
7037            ts_init,
7038            &mut funding_cache,
7039            &instruments_cache,
7040        )
7041        .expect("Failed to parse instruments channel");
7042
7043        match result {
7044            Some(NautilusWsMessage::InstrumentStatus(status)) => {
7045                assert_eq!(status.instrument_id, InstrumentId::from("USDG-SGD.OKX"));
7046                assert_eq!(status.action, MarketStatusAction::Trading);
7047                assert_eq!(status.is_trading, Some(true));
7048            }
7049            other => panic!("Expected InstrumentStatus, was {other:?}"),
7050        }
7051    }
7052
7053    #[rstest]
7054    fn test_parse_instruments_channel_suspend_status() {
7055        use nautilus_model::{enums::MarketStatusAction, identifiers::InstrumentId};
7056
7057        use crate::common::{models::OKXInstrument, parse::parse_instrument_any};
7058
7059        let ts_init = UnixNanos::default();
7060
7061        let inst_json = serde_json::json!({
7062            "instType": "SPOT",
7063            "instId": "BTC-USD",
7064            "baseCcy": "BTC",
7065            "quoteCcy": "USD",
7066            "settleCcy": "",
7067            "ctVal": "",
7068            "ctMult": "",
7069            "ctValCcy": "",
7070            "optType": "",
7071            "stk": "",
7072            "listTime": "1733454000000",
7073            "expTime": "",
7074            "lever": "",
7075            "tickSz": "0.1",
7076            "lotSz": "0.00000001",
7077            "minSz": "0.00001",
7078            "ctType": "",
7079            "state": "live",
7080            "ruleType": "normal",
7081            "maxLmtSz": "9999999999",
7082            "maxMktSz": "1000000",
7083            "maxLmtAmt": "20000000",
7084            "maxMktAmt": "1000000",
7085            "maxTwapSz": "9999999999",
7086            "maxIcebergSz": "9999999999",
7087            "maxTriggerSz": "9999999999",
7088            "maxStopSz": "1000000",
7089            "uly": "",
7090            "instFamily": ""
7091        });
7092        let initial: OKXInstrument = serde_json::from_value(inst_json).unwrap();
7093        let parsed = parse_instrument_any(&initial, None, None, ts_init)
7094            .unwrap()
7095            .unwrap();
7096
7097        let mut instruments_cache = AHashMap::new();
7098        instruments_cache.insert(Ustr::from("BTC-USD"), parsed);
7099
7100        // WS update with suspend state
7101        let ws_data = serde_json::json!({
7102            "instType": "SPOT",
7103            "instId": "BTC-USD",
7104            "baseCcy": "BTC",
7105            "quoteCcy": "USD",
7106            "settleCcy": "",
7107            "ctVal": "",
7108            "ctMult": "",
7109            "ctValCcy": "",
7110            "optType": "",
7111            "stk": "",
7112            "listTime": "1733454000000",
7113            "expTime": "",
7114            "lever": "",
7115            "tickSz": "0.1",
7116            "lotSz": "0.00000001",
7117            "minSz": "0.00001",
7118            "ctType": "",
7119            "state": "suspend",
7120            "ruleType": "normal",
7121            "maxLmtSz": "9999999999",
7122            "maxMktSz": "1000000",
7123            "maxLmtAmt": "20000000",
7124            "maxMktAmt": "1000000",
7125            "maxTwapSz": "9999999999",
7126            "maxIcebergSz": "9999999999",
7127            "maxTriggerSz": "9999999999",
7128            "maxStopSz": "1000000",
7129            "uly": "",
7130            "instFamily": ""
7131        });
7132
7133        let instrument_id = InstrumentId::from("BTC-USD.OKX");
7134        let mut funding_cache = AHashMap::new();
7135
7136        let result = parse_ws_message_data(
7137            &OKXWsChannel::Instruments,
7138            ws_data,
7139            &instrument_id,
7140            2,
7141            8,
7142            ts_init,
7143            &mut funding_cache,
7144            &instruments_cache,
7145        )
7146        .expect("Failed to parse instruments channel");
7147
7148        match result {
7149            Some(NautilusWsMessage::Instrument(_, status)) => {
7150                let status = status.expect("Expected InstrumentStatus");
7151                assert_eq!(status.action, MarketStatusAction::Suspend);
7152                assert_eq!(status.is_trading, Some(false));
7153            }
7154            other => panic!("Expected Instrument with status, was {other:?}"),
7155        }
7156    }
7157
7158    #[rstest]
7159    fn test_parse_option_summary_greeks() {
7160        let json_str = load_test_json("ws_opt_summary.json");
7161        let msgs: Vec<OKXOptionSummaryMsg> =
7162            serde_json::from_str(&json_str).expect("Failed to deserialize opt-summary fixture");
7163        assert_eq!(msgs.len(), 2);
7164
7165        let instrument_id = InstrumentId::from("BTC-USD-250328-92000-C.OKX");
7166        let ts_init = UnixNanos::from(1_711_612_900_000_000_000u64);
7167        let greeks =
7168            parse_option_summary_greeks(&msgs[0], &instrument_id, OKXGreeksType::Bs, ts_init)
7169                .expect("parse failed");
7170
7171        assert_eq!(greeks.instrument_id, instrument_id);
7172        assert!((greeks.greeks.delta - 0.5312).abs() < 1e-10);
7173        assert!((greeks.greeks.gamma - 0.000_013_4).abs() < 1e-15);
7174        assert!((greeks.greeks.vega - 0.0038).abs() < 1e-10);
7175        assert!((greeks.greeks.theta - (-0.0015)).abs() < 1e-10);
7176        assert!((greeks.greeks.rho - 0.0).abs() < 1e-10);
7177        assert!((greeks.mark_iv.unwrap() - 0.53).abs() < 1e-10);
7178        assert!((greeks.bid_iv.unwrap() - 0.52).abs() < 1e-10);
7179        assert!((greeks.ask_iv.unwrap() - 0.55).abs() < 1e-10);
7180        assert!((greeks.underlying_price.unwrap() - 92150.50).abs() < 1e-10);
7181        assert!(greeks.open_interest.is_none());
7182        assert_eq!(greeks.convention, GreeksConvention::BlackScholes);
7183        assert_eq!(
7184            greeks.ts_event,
7185            UnixNanos::from(1_711_612_800_000_000_000u64)
7186        );
7187        assert_eq!(greeks.ts_init, ts_init);
7188    }
7189
7190    #[rstest]
7191    fn test_option_summary_msg_deserializes_with_uppercase_bs_alias() {
7192        let mut payload: Value =
7193            serde_json::from_str(&load_test_json("ws_opt_summary.json")).unwrap();
7194        let summary = payload[0].as_object_mut().unwrap();
7195
7196        // Preserve the original alias values while reusing the fixture's remaining fields
7197        for (key, alias, expected) in [
7198            ("deltaBs", "deltaBS", "0.53"),
7199            ("gammaBs", "gammaBS", "0.00002"),
7200            ("thetaBs", "thetaBS", "-0.002"),
7201            ("vegaBs", "vegaBS", "0.004"),
7202        ] {
7203            summary.insert(key.to_string(), Value::String(expected.to_string()));
7204            let value = summary.remove(key).unwrap();
7205            summary.insert(alias.to_string(), value);
7206        }
7207
7208        let msg: OKXOptionSummaryMsg = serde_json::from_value(payload[0].clone())
7209            .expect("deltaBS alias failed to deserialize");
7210        assert_eq!(msg.delta_bs, "0.53");
7211        assert_eq!(msg.gamma_bs, "0.00002");
7212        assert_eq!(msg.theta_bs, "-0.002");
7213        assert_eq!(msg.vega_bs, "0.004");
7214    }
7215
7216    #[rstest]
7217    fn test_parse_option_summary_greeks_put() {
7218        let json_str = load_test_json("ws_opt_summary.json");
7219        let msgs: Vec<OKXOptionSummaryMsg> =
7220            serde_json::from_str(&json_str).expect("Failed to deserialize opt-summary fixture");
7221
7222        let instrument_id = InstrumentId::from("BTC-USD-250328-92000-P.OKX");
7223        let ts_init = UnixNanos::from(1_711_612_900_000_000_000u64);
7224        let greeks =
7225            parse_option_summary_greeks(&msgs[1], &instrument_id, OKXGreeksType::Bs, ts_init)
7226                .expect("parse failed");
7227
7228        assert!((greeks.greeks.delta - (-0.4688)).abs() < 1e-10);
7229    }
7230
7231    #[rstest]
7232    fn test_parse_option_summary_greeks_pa() {
7233        let json_str = load_test_json("ws_opt_summary.json");
7234        let msgs: Vec<OKXOptionSummaryMsg> =
7235            serde_json::from_str(&json_str).expect("Failed to deserialize opt-summary fixture");
7236        assert_eq!(msgs.len(), 2);
7237
7238        let instrument_id = InstrumentId::from("BTC-USD-250328-92000-C.OKX");
7239        let ts_init = UnixNanos::from(1_711_612_900_000_000_000u64);
7240        let greeks =
7241            parse_option_summary_greeks(&msgs[0], &instrument_id, OKXGreeksType::Pa, ts_init)
7242                .expect("parse failed");
7243
7244        assert_eq!(greeks.instrument_id, instrument_id);
7245        assert!((greeks.greeks.delta - 0.5234).abs() < 1e-10);
7246        assert!((greeks.greeks.gamma - 0.000_012_3).abs() < 1e-15);
7247        assert!((greeks.greeks.vega - 0.0034).abs() < 1e-10);
7248        assert!((greeks.greeks.theta - (-0.0012)).abs() < 1e-10);
7249        assert!((greeks.greeks.rho - 0.0).abs() < 1e-10);
7250        assert!((greeks.mark_iv.unwrap() - 0.53).abs() < 1e-10);
7251        assert!((greeks.bid_iv.unwrap() - 0.52).abs() < 1e-10);
7252        assert!((greeks.ask_iv.unwrap() - 0.55).abs() < 1e-10);
7253        assert!((greeks.underlying_price.unwrap() - 92150.50).abs() < 1e-10);
7254        assert_eq!(greeks.convention, GreeksConvention::PriceAdjusted);
7255    }
7256
7257    #[rstest]
7258    fn test_parse_option_summary_greeks_pa_put() {
7259        let json_str = load_test_json("ws_opt_summary.json");
7260        let msgs: Vec<OKXOptionSummaryMsg> =
7261            serde_json::from_str(&json_str).expect("Failed to deserialize opt-summary fixture");
7262
7263        let instrument_id = InstrumentId::from("BTC-USD-250328-92000-P.OKX");
7264        let ts_init = UnixNanos::from(1_711_612_900_000_000_000u64);
7265        let greeks =
7266            parse_option_summary_greeks(&msgs[1], &instrument_id, OKXGreeksType::Pa, ts_init)
7267                .expect("parse failed");
7268
7269        assert!((greeks.greeks.delta - (-0.4766)).abs() < 1e-10);
7270    }
7271
7272    #[rstest]
7273    fn test_option_greeks_filtering_only_subscribed_instruments() {
7274        use ahash::AHashSet;
7275
7276        let json_str = load_test_json("ws_opt_summary.json");
7277        let msgs: Vec<OKXOptionSummaryMsg> =
7278            serde_json::from_str(&json_str).expect("Failed to deserialize");
7279
7280        let call_id = InstrumentId::from("BTC-USD-250328-92000-C.OKX");
7281        let put_id = InstrumentId::from("BTC-USD-250328-92000-P.OKX");
7282        let ts_init = UnixNanos::from(1_711_612_900_000_000_000u64);
7283
7284        // Subscribe to CALL only
7285        let mut subs = AHashSet::new();
7286        subs.insert(call_id);
7287
7288        let mut results = Vec::new();
7289
7290        for msg in &msgs {
7291            let inst_id_str = format!("{}.OKX", msg.inst_id);
7292            let instrument_id = InstrumentId::from(inst_id_str.as_str());
7293            if !subs.contains(&instrument_id) {
7294                continue;
7295            }
7296
7297            if let Ok(greeks) =
7298                parse_option_summary_greeks(msg, &instrument_id, OKXGreeksType::Bs, ts_init)
7299            {
7300                results.push(greeks);
7301            }
7302        }
7303
7304        assert_eq!(results.len(), 1);
7305        assert_eq!(results[0].instrument_id, call_id);
7306        assert!((results[0].greeks.delta - 0.5312).abs() < 1e-10);
7307
7308        // Now subscribe to both
7309        subs.insert(put_id);
7310
7311        let mut results = Vec::new();
7312
7313        for msg in &msgs {
7314            let inst_id_str = format!("{}.OKX", msg.inst_id);
7315            let instrument_id = InstrumentId::from(inst_id_str.as_str());
7316            if !subs.contains(&instrument_id) {
7317                continue;
7318            }
7319
7320            if let Ok(greeks) =
7321                parse_option_summary_greeks(msg, &instrument_id, OKXGreeksType::Bs, ts_init)
7322            {
7323                results.push(greeks);
7324            }
7325        }
7326
7327        assert_eq!(results.len(), 2);
7328    }
7329
7330    #[rstest]
7331    fn test_option_greeks_unsubscribed_instrument_filtered_out() {
7332        use ahash::AHashSet;
7333
7334        let json_str = load_test_json("ws_opt_summary.json");
7335        let msgs: Vec<OKXOptionSummaryMsg> =
7336            serde_json::from_str(&json_str).expect("Failed to deserialize");
7337
7338        let ts_init = UnixNanos::default();
7339
7340        // Empty subscription set
7341        let subs: AHashSet<InstrumentId> = AHashSet::new();
7342
7343        let mut results = Vec::new();
7344
7345        for msg in &msgs {
7346            let inst_id_str = format!("{}.OKX", msg.inst_id);
7347            let instrument_id = InstrumentId::from(inst_id_str.as_str());
7348            if !subs.contains(&instrument_id) {
7349                continue;
7350            }
7351
7352            if let Ok(greeks) =
7353                parse_option_summary_greeks(msg, &instrument_id, OKXGreeksType::Bs, ts_init)
7354            {
7355                results.push(greeks);
7356            }
7357        }
7358
7359        assert!(results.is_empty());
7360    }
7361
7362    #[rstest]
7363    fn test_option_greeks_family_dedup_subscribe_count() {
7364        use crate::common::parse::extract_inst_family;
7365
7366        let mut family_subs: AHashMap<Ustr, usize> = AHashMap::new();
7367
7368        let call_id = InstrumentId::from("BTC-USD-250328-92000-C.OKX");
7369        let put_id = InstrumentId::from("BTC-USD-250328-92000-P.OKX");
7370        let other_id = InstrumentId::from("BTC-USD-250328-80000-C.OKX");
7371
7372        // Subscribe first instrument: count goes to 1 (triggers WS subscribe)
7373        let family = extract_inst_family(call_id.symbol.inner().as_str()).unwrap();
7374        let count = family_subs.entry(family).or_default();
7375        *count += 1;
7376        assert_eq!(*count, 1);
7377        let should_subscribe_ws = *count == 1;
7378        assert!(should_subscribe_ws);
7379
7380        // Subscribe second instrument in same family: count goes to 2 (no WS subscribe)
7381        let family = extract_inst_family(put_id.symbol.inner().as_str()).unwrap();
7382        let count = family_subs.entry(family).or_default();
7383        *count += 1;
7384        assert_eq!(*count, 2);
7385        let should_subscribe_ws = *count == 1;
7386        assert!(!should_subscribe_ws);
7387
7388        // Subscribe third instrument in same family: count goes to 3
7389        let family = extract_inst_family(other_id.symbol.inner().as_str()).unwrap();
7390        let count = family_subs.entry(family).or_default();
7391        *count += 1;
7392        assert_eq!(*count, 3);
7393
7394        // Unsubscribe one: count goes to 2 (no WS unsubscribe)
7395        let family = extract_inst_family(call_id.symbol.inner().as_str()).unwrap();
7396        if let Some(count) = family_subs.get_mut(&family) {
7397            *count = count.saturating_sub(1);
7398            assert_eq!(*count, 2);
7399            let should_unsubscribe_ws = *count == 0;
7400            assert!(!should_unsubscribe_ws);
7401        }
7402
7403        // Unsubscribe second: count goes to 1
7404        let family = extract_inst_family(put_id.symbol.inner().as_str()).unwrap();
7405        if let Some(count) = family_subs.get_mut(&family) {
7406            *count = count.saturating_sub(1);
7407            assert_eq!(*count, 1);
7408        }
7409
7410        // Unsubscribe last: count goes to 0 (triggers WS unsubscribe)
7411        let family = extract_inst_family(other_id.symbol.inner().as_str()).unwrap();
7412        if let Some(count) = family_subs.get_mut(&family) {
7413            *count = count.saturating_sub(1);
7414            assert_eq!(*count, 0);
7415            let should_unsubscribe_ws = *count == 0;
7416            assert!(should_unsubscribe_ws);
7417        }
7418    }
7419
7420    #[rstest]
7421    fn test_parse_event_contract_markets_returns_raw_message() {
7422        let data = serde_json::json!([
7423            {
7424                "seriesId": "BTC-ABOVE-DAILY",
7425                "eventId": "BTC-ABOVE-DAILY-260224-1600",
7426                "instId": "BTC-ABOVE-DAILY-260224-1600-65000",
7427                "listTime": "1769697132335",
7428                "fixTime": "",
7429                "expTime": "1769697132335",
7430                "state": "live",
7431                "outcome": "0",
7432                "floorStrike": "120000",
7433                "capStrike": "",
7434                "settleValue": "",
7435                "disputed": false,
7436                "hitDir": ""
7437            },
7438            {
7439                "seriesId": "BTC-HIT-MONTHLY",
7440                "eventId": "BTC-HIT-MONTHLY-260831-1600",
7441                "instId": "BTC-HIT-MONTHLY-260831-1600-37500",
7442                "listTime": "1785513600000",
7443                "fixTime": "",
7444                "expTime": "1788192000000",
7445                "state": "live",
7446                "outcome": "0",
7447                "floorStrike": "37500",
7448                "capStrike": "",
7449                "settleValue": "",
7450                "disputed": false,
7451                "hitDir": "dn"
7452            }
7453        ]);
7454        let instrument_id = InstrumentId::from("BTC-ABOVE-DAILY-260224-1600-65000.OKX");
7455        let mut funding_cache = AHashMap::new();
7456        let instruments_cache = AHashMap::new();
7457
7458        let result = parse_ws_message_data(
7459            &OKXWsChannel::EventContractMarkets,
7460            data.clone(),
7461            &instrument_id,
7462            2,
7463            2,
7464            UnixNanos::default(),
7465            &mut funding_cache,
7466            &instruments_cache,
7467        )
7468        .unwrap();
7469
7470        match result {
7471            Some(NautilusWsMessage::Raw(raw)) => assert_eq!(raw, data),
7472            _ => panic!("Expected raw event contract market payload"),
7473        }
7474    }
7475
7476    #[rstest]
7477    fn test_parse_ws_message_data_spread_public_trades() {
7478        // sprd-public-trades keys the spread as `sprdId` and omits `count`; the
7479        // instrument is resolved from the channel arg, so the trade still parses.
7480        let data = serde_json::json!([{
7481            "sprdId": "ETH-USD-260925_ETH-USD-261225",
7482            "tradeId": "3392538740127301632",
7483            "px": "16.9",
7484            "sz": "100",
7485            "side": "sell",
7486            "ts": "1780047866507"
7487        }]);
7488        let instrument_id = InstrumentId::from("ETH-USD-260925_ETH-USD-261225.OKX");
7489        let mut funding_cache = AHashMap::new();
7490        let instruments_cache = AHashMap::new();
7491
7492        let result = parse_ws_message_data(
7493            &OKXWsChannel::SprdPublicTrades,
7494            data,
7495            &instrument_id,
7496            1,
7497            0,
7498            UnixNanos::default(),
7499            &mut funding_cache,
7500            &instruments_cache,
7501        )
7502        .unwrap();
7503
7504        let Some(NautilusWsMessage::Data(data_vec)) = result else {
7505            panic!("expected Data variant, was {result:?}");
7506        };
7507        assert_eq!(data_vec.len(), 1);
7508        let Data::Trade(trade) = &data_vec[0] else {
7509            panic!("expected Data::Trade, was {:?}", data_vec[0]);
7510        };
7511        assert_eq!(trade.instrument_id, instrument_id);
7512        assert_eq!(trade.price.as_decimal(), dec!(16.9));
7513        assert_eq!(trade.size.as_decimal(), dec!(100));
7514        assert_eq!(trade.aggressor_side, AggressorSide::Sell);
7515    }
7516
7517    #[rstest]
7518    fn test_parse_spread_books5_snapshot_with_three_element_levels() {
7519        // sprd-books5 pushes a full snapshot with 3-element `[price, size, count]`
7520        // levels; it is parsed as a snapshot (F_SNAPSHOT), not an incremental update.
7521        let msg: OKXBookMsg = serde_json::from_value(serde_json::json!({
7522            "asks": [["16.7", "100", "1"]],
7523            "bids": [["16.65", "100", "1"]],
7524            "ts": "1780044924909",
7525            "seqId": 1_779_935_772_619_784_u64,
7526        }))
7527        .unwrap();
7528        let instrument_id = InstrumentId::from("ETH-USD-260925_ETH-USD-261225.OKX");
7529
7530        let deltas = parse_book_msg(
7531            &msg,
7532            instrument_id,
7533            2,
7534            0,
7535            &OKXBookAction::Snapshot,
7536            UnixNanos::default(),
7537        )
7538        .unwrap();
7539
7540        assert_eq!(deltas.instrument_id, instrument_id);
7541        assert_eq!(
7542            deltas.flags,
7543            RecordFlag::F_SNAPSHOT as u8 | RecordFlag::F_LAST as u8
7544        );
7545        let bid = deltas
7546            .deltas
7547            .iter()
7548            .find(|d| d.order.side == OrderSide::Buy.into())
7549            .expect("should have a bid delta");
7550        let ask = deltas
7551            .deltas
7552            .iter()
7553            .find(|d| d.order.side == OrderSide::Sell.into())
7554            .expect("should have an ask delta");
7555        assert_eq!(bid.order.price.as_decimal(), dec!(16.65));
7556        assert_eq!(ask.order.price.as_decimal(), dec!(16.7));
7557    }
7558
7559    #[rstest]
7560    #[case(OKXPositionSide::Long, Some("BTC-USDT-SWAP.OKX-LONG"))]
7561    #[case(OKXPositionSide::Short, Some("BTC-USDT-SWAP.OKX-SHORT"))]
7562    #[case(OKXPositionSide::Net, None)]
7563    #[case(OKXPositionSide::None, None)]
7564    fn test_order_and_fill_position_ids(
7565        #[case] side: OKXPositionSide,
7566        #[case] expected: Option<&str>,
7567    ) {
7568        let payload: Value = serde_json::from_str(&load_test_json("ws_orders.json")).unwrap();
7569        let mut msg: OKXOrderMsg = serde_json::from_value(payload["data"][0].clone()).unwrap();
7570        msg.pos_side = side;
7571        let instrument = InstrumentAny::CryptoPerpetual(create_stub_instrument());
7572        let account_id = AccountId::from("OKX-001");
7573        let order =
7574            parse_order_status_report(&msg, &instrument, account_id, UnixNanos::default()).unwrap();
7575        let fill = parse_fill_report(
7576            &msg,
7577            &instrument,
7578            account_id,
7579            None,
7580            None,
7581            UnixNanos::default(),
7582        )
7583        .unwrap()
7584        .unwrap();
7585        let expected = expected.map(PositionId::from);
7586        assert_eq!(order.venue_position_id, expected);
7587        assert_eq!(fill.venue_position_id, expected);
7588    }
7589
7590    #[rstest]
7591    #[case(OKXPositionSide::Long, Some("BTC-USDT-SWAP.OKX-LONG"))]
7592    #[case(OKXPositionSide::Short, Some("BTC-USDT-SWAP.OKX-SHORT"))]
7593    #[case(OKXPositionSide::Net, None)]
7594    fn test_algo_order_position_id(#[case] side: OKXPositionSide, #[case] expected: Option<&str>) {
7595        let payload: Value = serde_json::from_str(&load_test_json("ws_orders_algo.json")).unwrap();
7596        let mut msg: OKXAlgoOrderMsg = serde_json::from_value(payload["data"][0].clone()).unwrap();
7597        msg.pos_side = side;
7598        let instrument = InstrumentAny::CryptoPerpetual(create_stub_instrument());
7599        let report = parse_algo_order_status_report(
7600            &msg,
7601            &instrument,
7602            AccountId::from("OKX-001"),
7603            UnixNanos::default(),
7604        )
7605        .unwrap();
7606        assert_eq!(report.venue_position_id, expected.map(PositionId::from));
7607    }
7608}