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        accounts::BaseAccount,
2590        data::bar::BAR_SPEC_1_DAY_LAST,
2591        enums::{AccountType, BookType, GreeksConvention},
2592        identifiers::{ClientOrderId, PositionId, Symbol, VenueOrderId},
2593        instruments::CurrencyPair,
2594        orderbook::OrderBook,
2595        types::Currency,
2596    };
2597    use rstest::rstest;
2598    use rust_decimal_macros::dec;
2599    use serde_json::Value;
2600    use ustr::Ustr;
2601
2602    use super::*;
2603    use crate::{
2604        OKXPositionSide,
2605        common::{
2606            enums::{
2607                OKXAlgoOrderStatus, OKXExecType, OKXInstrumentType, OKXMarginMode, OKXOrderType,
2608                OKXPriceType, OKXQuickMarginType, OKXSelfTradePreventionMode, OKXSide,
2609                OKXTradeMode,
2610            },
2611            parse::parse_account_state,
2612            testing::{create_stub_instrument, load_test_json},
2613        },
2614        http::models::OKXAccount,
2615        websocket::messages::{
2616            OKXAlgoOrderMsg, OKXAttachedAlgoOrd, OKXLiquidationWarningMsg, OKXWebSocketArg,
2617            OKXWsFrame,
2618        },
2619    };
2620
2621    fn is_order_updated(
2622        msg: &OKXOrderMsg,
2623        previous: &OrderStateSnapshot,
2624        instrument: &InstrumentAny,
2625    ) -> anyhow::Result<bool> {
2626        let current_venue_id = VenueOrderId::new(msg.ord_id);
2627
2628        if previous.venue_order_id != current_venue_id {
2629            return Ok(true);
2630        }
2631
2632        let current_qty = parse_quantity(&msg.sz, instrument.size_precision())?;
2633        if previous.quantity != current_qty {
2634            return Ok(true);
2635        }
2636
2637        if !is_market_price(&msg.px) {
2638            let current_price = parse_price(&msg.px, instrument.price_precision())?;
2639
2640            if let Some(prev_price) = previous.price
2641                && prev_price != current_price
2642            {
2643                return Ok(true);
2644            }
2645        }
2646
2647        Ok(false)
2648    }
2649
2650    #[rstest]
2651    fn open_order_baselines_survive_unrelated_order_churn() {
2652        let instrument = InstrumentAny::CryptoPerpetual(create_stub_instrument());
2653        let mut fee_cache = FeeCache::new();
2654        let mut filled_qty_cache = FilledQtyCache::new();
2655
2656        let mut resting = create_stub_order_msg("1.0", Some("1.0".to_string()), "ord-resting", "");
2657        resting.state = OKXOrderStatus::PartiallyFilled;
2658        update_fee_fill_caches(&resting, &instrument, &mut fee_cache, &mut filled_qty_cache);
2659
2660        for i in 0..=TERMINAL_BASELINE_CAPACITY {
2661            let mut msg =
2662                create_stub_order_msg("1.0", Some("1.0".to_string()), &format!("ord-{i}"), "");
2663            msg.state = OKXOrderStatus::Filled;
2664            update_fee_fill_caches(&msg, &instrument, &mut fee_cache, &mut filled_qty_cache);
2665        }
2666
2667        let resting_key = Ustr::from("ord-resting");
2668
2669        assert_eq!(fee_cache.get(&resting_key).unwrap().as_decimal(), dec!(1.0));
2670        assert_eq!(
2671            filled_qty_cache.get(&resting_key).unwrap().as_decimal(),
2672            dec!(1.0)
2673        );
2674        assert_eq!(fee_cache.open.len(), 1);
2675        assert_eq!(filled_qty_cache.open.len(), 1);
2676
2677        // Demotion is what bounds the open map, so prove the migration and not just the
2678        // classification: a settled order must leave `open` and expose its newer baseline.
2679        let mut settled = resting.clone();
2680        settled.state = OKXOrderStatus::Filled;
2681        settled.fee = Some("-2.5".to_string());
2682        settled.acc_fill_sz = Some("2.0".to_string());
2683        update_fee_fill_caches(&settled, &instrument, &mut fee_cache, &mut filled_qty_cache);
2684
2685        assert_eq!(fee_cache.open.len(), 0);
2686        assert_eq!(filled_qty_cache.open.len(), 0);
2687        assert_eq!(fee_cache.get(&resting_key).unwrap().as_decimal(), dec!(2.5));
2688        assert_eq!(
2689            filled_qty_cache.get(&resting_key).unwrap().as_decimal(),
2690            dec!(2.0)
2691        );
2692    }
2693
2694    #[rstest]
2695    #[case(OKXOrderStatus::Filled)]
2696    #[case(OKXOrderStatus::Canceled)]
2697    #[case(OKXOrderStatus::MmpCanceled)]
2698    fn terminal_order_baselines_stay_terminal_after_late_updates(
2699        #[case] terminal_state: OKXOrderStatus,
2700        #[values(OKXOrderStatus::Live, OKXOrderStatus::PartiallyFilled)] late_state: OKXOrderStatus,
2701    ) {
2702        let instrument = InstrumentAny::CryptoPerpetual(create_stub_instrument());
2703        let mut fee_cache = FeeCache::new();
2704        let mut filled_qty_cache = FilledQtyCache::new();
2705        let mut msg = create_stub_order_msg("1.0", Some("2.0".to_string()), "ord-late", "");
2706        msg.state = terminal_state;
2707        update_fee_fill_caches(&msg, &instrument, &mut fee_cache, &mut filled_qty_cache);
2708
2709        msg.state = late_state;
2710        msg.fee = Some("-0.5".to_string());
2711        msg.acc_fill_sz = Some("1.0".to_string());
2712        update_fee_fill_caches(&msg, &instrument, &mut fee_cache, &mut filled_qty_cache);
2713
2714        let key = msg.ord_id;
2715        let fee = Money::from_decimal(dec!(0.5), Currency::USDT()).unwrap();
2716        let quantity = Quantity::from("1.00000000");
2717
2718        assert_eq!(fee_cache.open.len(), 0);
2719        assert_eq!(filled_qty_cache.open.len(), 0);
2720        assert_eq!(fee_cache.terminal.get(&key), Some(&fee));
2721        assert_eq!(filled_qty_cache.terminal.get(&key), Some(&quantity));
2722        assert_eq!(fee_cache.get(&key), Some(&fee));
2723        assert_eq!(filled_qty_cache.get(&key), Some(&quantity));
2724    }
2725
2726    #[rstest]
2727    fn terminal_order_baselines_evict_oldest_first() {
2728        let instrument = InstrumentAny::CryptoPerpetual(create_stub_instrument());
2729        let mut fee_cache = FeeCache::new();
2730        let mut filled_qty_cache = FilledQtyCache::new();
2731
2732        for i in 0..=TERMINAL_BASELINE_CAPACITY {
2733            let mut msg =
2734                create_stub_order_msg("1.0", Some("1.0".to_string()), &format!("ord-{i}"), "");
2735            msg.state = OKXOrderStatus::Filled;
2736            update_fee_fill_caches(&msg, &instrument, &mut fee_cache, &mut filled_qty_cache);
2737        }
2738
2739        let oldest = Ustr::from("ord-0");
2740        let newest = Ustr::from(&format!("ord-{TERMINAL_BASELINE_CAPACITY}"));
2741
2742        assert_eq!(fee_cache.get(&oldest), None);
2743        assert_eq!(filled_qty_cache.get(&oldest), None);
2744        assert_eq!(fee_cache.get(&newest).unwrap().as_decimal(), dec!(1.0));
2745        assert_eq!(
2746            filled_qty_cache.get(&newest).unwrap().as_decimal(),
2747            dec!(1.0)
2748        );
2749        assert_eq!(fee_cache.open.len(), 0);
2750    }
2751
2752    fn create_stub_order_msg(
2753        fill_sz: &str,
2754        acc_fill_sz: Option<String>,
2755        order_id: &str,
2756        trade_id: &str,
2757    ) -> OKXOrderMsg {
2758        OKXOrderMsg {
2759            acc_fill_sz,
2760            algo_id: None,
2761            avg_px: "50000.0".to_string(),
2762            c_time: 1_746_947_317_401,
2763            cancel_source: None,
2764            cancel_source_reason: None,
2765            category: OKXOrderCategory::Normal,
2766            ccy: Ustr::from("USDT"),
2767            cl_ord_id: "test_order_1".to_string(),
2768            algo_cl_ord_id: None,
2769            attach_algo_cl_ord_id: None,
2770            attach_algo_ords: Vec::new(),
2771            outcome: None,
2772            fee: Some("-1.0".to_string()),
2773            fee_ccy: Ustr::from("USDT"),
2774            fill_fee: None,
2775            fill_fee_ccy: None,
2776            fill_mark_px: None,
2777            fill_mark_vol: None,
2778            fill_px_vol: None,
2779            fill_px_usd: None,
2780            fill_fwd_px: None,
2781            fill_notional_usd: None,
2782            fill_pnl: None,
2783            fill_px: "50000.0".to_string(),
2784            fill_sz: fill_sz.to_string(),
2785            fill_time: 1_746_947_317_402,
2786            inst_id: Ustr::from("BTC-USDT-SWAP"),
2787            inst_type: OKXInstrumentType::Swap,
2788            is_tp_limit: None,
2789            lever: "2.0".to_string(),
2790            linked_algo_ord: None,
2791            notional_usd: None,
2792            ord_id: Ustr::from(order_id),
2793            ord_type: OKXOrderType::Market,
2794            pnl: "0".to_string(),
2795            pos_side: OKXPositionSide::Long,
2796            px: String::new(),
2797            px_type: OKXPriceType::None,
2798            px_usd: None,
2799            px_vol: None,
2800            quick_mgn_type: OKXQuickMarginType::None,
2801            rebate: None,
2802            rebate_ccy: None,
2803            reduce_only: "false".to_string(),
2804            side: OKXSide::Buy,
2805            sl_ord_px: None,
2806            sl_trigger_px: None,
2807            sl_trigger_px_type: None,
2808            source: None,
2809            state: OKXOrderStatus::PartiallyFilled,
2810            stp_id: None,
2811            stp_mode: OKXSelfTradePreventionMode::None,
2812            exec_type: OKXExecType::Taker,
2813            sz: "0.03".to_string(),
2814            tag: None,
2815            td_mode: OKXTradeMode::Isolated,
2816            tgt_ccy: None,
2817            tp_ord_px: None,
2818            tp_trigger_px: None,
2819            tp_trigger_px_type: None,
2820            trade_id: trade_id.to_string(),
2821            u_time: 1_746_947_317_402,
2822            amend_result: None,
2823            req_id: None,
2824            code: None,
2825            msg: None,
2826        }
2827    }
2828
2829    #[rstest]
2830    #[case::standard(false)]
2831    #[case::rpi(true)]
2832    fn snapshot_replaces_existing_book(#[case] rpi: bool, #[values(false, true)] empty: bool) {
2833        let fixture = if rpi {
2834            "ws_books_rpi_snapshot.json"
2835        } else {
2836            "ws_books_snapshot.json"
2837        };
2838
2839        let mut frame: Value = serde_json::from_str(&load_test_json(fixture)).unwrap();
2840        let instrument_id = InstrumentId::from("BTC-USDT.OKX");
2841
2842        let parse = |frame: &Value| {
2843            if rpi {
2844                parse_rpi_book_msg(
2845                    &serde_json::from_value(frame["data"][0].clone()).unwrap(),
2846                    instrument_id,
2847                    7,
2848                    3,
2849                    &OKXBookAction::Snapshot,
2850                    UnixNanos::from(123),
2851                )
2852                .unwrap()
2853            } else {
2854                parse_book_msg(
2855                    &serde_json::from_value(frame["data"][0].clone()).unwrap(),
2856                    instrument_id,
2857                    2,
2858                    1,
2859                    &OKXBookAction::Snapshot,
2860                    UnixNanos::from(123),
2861                )
2862                .unwrap()
2863            }
2864        };
2865
2866        let mut actual = OrderBook::new(instrument_id, BookType::L2_MBP);
2867        actual.apply_deltas(&parse(&frame)).unwrap();
2868        for side in ["bids", "asks"] {
2869            let levels = frame["data"][0][side].as_array_mut().unwrap();
2870            if empty {
2871                levels.clear();
2872            } else {
2873                levels.remove(0);
2874            }
2875        }
2876
2877        let snapshot = parse(&frame);
2878        let mut expected = OrderBook::new(instrument_id, BookType::L2_MBP);
2879        expected.apply_deltas(&snapshot).unwrap();
2880        actual.apply_deltas(&snapshot).unwrap();
2881
2882        assert_eq!(actual.bids_as_map(None), expected.bids_as_map(None));
2883        assert_eq!(actual.asks_as_map(None), expected.asks_as_map(None));
2884
2885        let expected_clear_flags = if empty {
2886            RecordFlag::F_SNAPSHOT as u8 | RecordFlag::F_LAST as u8
2887        } else {
2888            RecordFlag::F_SNAPSHOT as u8
2889        };
2890
2891        assert_eq!(snapshot.deltas[0].action, BookAction::Clear);
2892        assert_eq!(snapshot.deltas[0].flags, expected_clear_flags);
2893        assert_eq!(snapshot.deltas[0].sequence, snapshot.sequence);
2894        assert_eq!(snapshot.deltas[0].ts_event, snapshot.ts_event);
2895        assert_eq!(snapshot.deltas[0].ts_init, UnixNanos::from(123));
2896    }
2897
2898    #[rstest]
2899    #[case::snapshot("ws_books_snapshot.json", OKXBookAction::Snapshot)]
2900    #[case::update("ws_books_update.json", OKXBookAction::Update)]
2901    #[case::rpi_snapshot("ws_books_rpi_snapshot.json", OKXBookAction::Snapshot)]
2902    #[case::rpi_update("ws_books_rpi_update.json", OKXBookAction::Update)]
2903    fn book_deltas_flag_only_the_final_delta_last(
2904        #[case] fixture: &str,
2905        #[case] action: OKXBookAction,
2906    ) {
2907        let instrument_id = InstrumentId::from("BTC-USDT.OKX");
2908        let frame: OKXWsFrame = serde_json::from_str(&load_test_json(fixture)).unwrap();
2909
2910        let deltas = match frame {
2911            OKXWsFrame::BookData { data, .. } => {
2912                parse_book_msg(&data[0], instrument_id, 2, 1, &action, UnixNanos::default())
2913            }
2914            OKXWsFrame::RpiBookData { data, .. } => {
2915                parse_rpi_book_msg(&data[0], instrument_id, 7, 3, &action, UnixNanos::default())
2916            }
2917            _ => panic!("Expected a book frame"),
2918        }
2919        .unwrap();
2920
2921        let last_count = deltas
2922            .deltas
2923            .iter()
2924            .filter(|delta| RecordFlag::F_LAST.matches(delta.flags))
2925            .count();
2926
2927        assert_eq!(last_count, 1, "exactly one delta must close the event");
2928        assert!(RecordFlag::F_LAST.matches(deltas.deltas.last().unwrap().flags));
2929        assert!(RecordFlag::F_LAST.matches(deltas.flags));
2930    }
2931
2932    #[rstest]
2933    fn empty_book_snapshot_flags_the_clear_delta_last() {
2934        let instrument_id = InstrumentId::from("BTC-USDT.OKX");
2935
2936        let msg = OKXBookMsg {
2937            bids: Vec::new(),
2938            asks: Vec::new(),
2939            ts: 1_597_026_383_085,
2940            checksum: None,
2941            prev_seq_id: None,
2942            seq_id: 123_456,
2943        };
2944
2945        let deltas = parse_book_msg(
2946            &msg,
2947            instrument_id,
2948            2,
2949            1,
2950            &OKXBookAction::Snapshot,
2951            UnixNanos::default(),
2952        )
2953        .unwrap();
2954
2955        assert_eq!(deltas.deltas.len(), 1);
2956        assert_eq!(deltas.deltas[0].action, BookAction::Clear);
2957        assert_eq!(
2958            deltas.flags,
2959            RecordFlag::F_SNAPSHOT as u8 | RecordFlag::F_LAST as u8
2960        );
2961    }
2962
2963    #[rstest]
2964    fn test_parse_books_snapshot() {
2965        let json_data = load_test_json("ws_books_snapshot.json");
2966        let msg: OKXWsFrame = serde_json::from_str(&json_data).unwrap();
2967        let (okx_books, action): (Vec<OKXBookMsg>, OKXBookAction) = match msg {
2968            OKXWsFrame::BookData { data, action, .. } => (data, action),
2969            _ => panic!("Expected a `BookData` variant"),
2970        };
2971
2972        let instrument_id = InstrumentId::from("BTC-USDT.OKX");
2973        let deltas = parse_book_msg(
2974            &okx_books[0],
2975            instrument_id,
2976            2,
2977            1,
2978            &action,
2979            UnixNanos::default(),
2980        )
2981        .unwrap();
2982
2983        assert_eq!(deltas.instrument_id, instrument_id);
2984        assert_eq!(deltas.deltas.len(), 17);
2985        assert_eq!(
2986            deltas.flags,
2987            RecordFlag::F_SNAPSHOT as u8 | RecordFlag::F_LAST as u8
2988        );
2989        assert_eq!(deltas.sequence, 123_456);
2990        assert_eq!(deltas.ts_event, UnixNanos::from(1_597_026_383_085_000_000));
2991        assert_eq!(deltas.ts_init, UnixNanos::default());
2992
2993        // Verify some individual deltas are parsed correctly
2994        assert!(!deltas.deltas.is_empty());
2995        // Snapshot should have both bid and ask deltas
2996        assert!(
2997            deltas
2998                .deltas
2999                .iter()
3000                .any(|d| d.order.side == OrderSide::Buy.into()),
3001            "Should have bid deltas"
3002        );
3003        assert!(
3004            deltas
3005                .deltas
3006                .iter()
3007                .any(|d| d.order.side == OrderSide::Sell.into()),
3008            "Should have ask deltas"
3009        );
3010    }
3011
3012    #[rstest]
3013    fn test_parse_books_update() {
3014        let json_data = load_test_json("ws_books_update.json");
3015        let msg: OKXWsFrame = serde_json::from_str(&json_data).unwrap();
3016        let instrument_id = InstrumentId::from("BTC-USDT.OKX");
3017        let (okx_books, action): (Vec<OKXBookMsg>, OKXBookAction) = match msg {
3018            OKXWsFrame::BookData { data, action, .. } => (data, action),
3019            _ => panic!("Expected a `BookData` variant"),
3020        };
3021
3022        let deltas = parse_book_msg(
3023            &okx_books[0],
3024            instrument_id,
3025            2,
3026            1,
3027            &action,
3028            UnixNanos::default(),
3029        )
3030        .unwrap();
3031
3032        assert_eq!(deltas.instrument_id, instrument_id);
3033        assert_eq!(deltas.deltas.len(), 16);
3034        assert_eq!(deltas.flags, RecordFlag::F_LAST as u8);
3035        assert_eq!(deltas.sequence, 123_457);
3036        assert_eq!(deltas.ts_event, UnixNanos::from(1_597_026_383_085_000_000));
3037        assert_eq!(deltas.ts_init, UnixNanos::default());
3038
3039        // Verify some individual deltas are parsed correctly
3040        assert!(!deltas.deltas.is_empty());
3041        // Update should also have both bid and ask deltas
3042        assert!(
3043            deltas
3044                .deltas
3045                .iter()
3046                .any(|d| d.order.side == OrderSide::Buy.into()),
3047            "Should have bid deltas"
3048        );
3049        assert!(
3050            deltas
3051                .deltas
3052                .iter()
3053                .any(|d| d.order.side == OrderSide::Sell.into()),
3054            "Should have ask deltas"
3055        );
3056    }
3057
3058    #[rstest]
3059    fn test_parse_rpi_books_update_uses_total_quantity_and_sequence() {
3060        let json_data = load_test_json("ws_books_rpi_update.json");
3061        let msg: OKXWsFrame = serde_json::from_str(&json_data).unwrap();
3062        let (data, action) = match msg {
3063            OKXWsFrame::RpiBookData { data, action, .. } => (data, action),
3064            _ => panic!("Expected an RPI book update"),
3065        };
3066        let instrument_id = InstrumentId::from("OMI-USD.OKX");
3067
3068        let deltas =
3069            parse_rpi_book_msg(&data[0], instrument_id, 7, 3, &action, UnixNanos::from(123))
3070                .unwrap();
3071
3072        assert_eq!(deltas.instrument_id, instrument_id);
3073        assert_eq!(deltas.deltas.len(), 2);
3074        assert_eq!(deltas.flags, RecordFlag::F_LAST as u8);
3075        assert_eq!(deltas.sequence, 1_082_831_230);
3076        assert_eq!(deltas.ts_event, UnixNanos::from(1_785_406_443_903_000_000));
3077        assert_eq!(deltas.ts_init, UnixNanos::from(123));
3078        assert_eq!(deltas.deltas[0].action, BookAction::Delete);
3079        assert_eq!(deltas.deltas[0].order.side, OrderSide::Sell.into());
3080        assert_eq!(deltas.deltas[0].order.price, Price::from("0.0001617"));
3081        assert_eq!(deltas.deltas[0].order.size, Quantity::from("0"));
3082        assert_eq!(deltas.deltas[1].action, BookAction::Update);
3083        assert_eq!(deltas.deltas[1].order.side, OrderSide::Sell.into());
3084        assert_eq!(deltas.deltas[1].order.price, Price::from("0.0001625"));
3085        assert_eq!(deltas.deltas[1].order.size, Quantity::from("12324367.786"));
3086    }
3087
3088    #[rstest]
3089    fn test_parse_tickers() {
3090        let json_data = load_test_json("ws_tickers.json");
3091        let msg: OKXWsFrame = serde_json::from_str(&json_data).unwrap();
3092        let okx_tickers: Vec<OKXTickerMsg> = match msg {
3093            OKXWsFrame::Data { data, .. } => serde_json::from_value(data).unwrap(),
3094            _ => panic!("Expected a `Data` variant"),
3095        };
3096
3097        let instrument_id = InstrumentId::from("BTC-USDT.OKX");
3098        let trade =
3099            parse_ticker_msg(&okx_tickers[0], instrument_id, 2, 1, UnixNanos::default()).unwrap();
3100
3101        assert_eq!(trade.instrument_id, InstrumentId::from("BTC-USDT.OKX"));
3102        assert_eq!(trade.bid_price, Price::from("8888.88"));
3103        assert_eq!(trade.ask_price, Price::from("9999.99"));
3104        assert_eq!(trade.bid_size, Quantity::from(5));
3105        assert_eq!(trade.ask_size, Quantity::from(11));
3106        assert_eq!(trade.ts_event, UnixNanos::from(1_597_026_383_085_000_000));
3107        assert_eq!(trade.ts_init, UnixNanos::default());
3108    }
3109
3110    #[rstest]
3111    fn test_parse_quotes() {
3112        let json_data = load_test_json("ws_bbo_tbt.json");
3113        let msg: OKXWsFrame = serde_json::from_str(&json_data).unwrap();
3114        let okx_quotes: Vec<OKXBookMsg> = match msg {
3115            OKXWsFrame::Data { data, .. } => serde_json::from_value(data).unwrap(),
3116            _ => panic!("Expected a `Data` variant"),
3117        };
3118        let instrument_id = InstrumentId::from("BTC-USDT.OKX");
3119
3120        let quote =
3121            parse_quote_msg(&okx_quotes[0], instrument_id, 2, 1, UnixNanos::default()).unwrap();
3122
3123        assert_eq!(quote.instrument_id, InstrumentId::from("BTC-USDT.OKX"));
3124        assert_eq!(quote.bid_price, Price::from("8476.97"));
3125        assert_eq!(quote.ask_price, Price::from("8476.98"));
3126        assert_eq!(quote.bid_size, Quantity::from(256));
3127        assert_eq!(quote.ask_size, Quantity::from(415));
3128        assert_eq!(quote.ts_event, UnixNanos::from(1_597_026_383_085_000_000));
3129        assert_eq!(quote.ts_init, UnixNanos::default());
3130    }
3131
3132    #[rstest]
3133    fn test_parse_trades() {
3134        let json_data = load_test_json("ws_trades.json");
3135        let msg: OKXWsFrame = serde_json::from_str(&json_data).unwrap();
3136        let okx_trades: Vec<OKXTradeMsg> = match msg {
3137            OKXWsFrame::Data { data, .. } => serde_json::from_value(data).unwrap(),
3138            _ => panic!("Expected a `Data` variant"),
3139        };
3140
3141        let instrument_id = InstrumentId::from("BTC-USDT.OKX");
3142        let trade =
3143            parse_trade_msg(&okx_trades[0], instrument_id, 1, 8, UnixNanos::default()).unwrap();
3144
3145        assert_eq!(trade.instrument_id, InstrumentId::from("BTC-USDT.OKX"));
3146        assert_eq!(trade.price, Price::from("42219.9"));
3147        assert_eq!(trade.size, Quantity::from("0.12060306"));
3148        assert_eq!(trade.aggressor_side, AggressorSide::Buy);
3149        assert_eq!(trade.trade_id, TradeId::from("130639474"));
3150        assert_eq!(trade.ts_event, UnixNanos::from(1_630_048_897_897_000_000));
3151        assert_eq!(trade.ts_init, UnixNanos::default());
3152    }
3153
3154    #[rstest]
3155    fn test_parse_candle() {
3156        let json_data = load_test_json("ws_candle.json");
3157        let msg: OKXWsFrame = serde_json::from_str(&json_data).unwrap();
3158        let okx_candles: Vec<OKXCandleMsg> = match msg {
3159            OKXWsFrame::Data { data, .. } => serde_json::from_value(data).unwrap(),
3160            _ => panic!("Expected a `Data` variant"),
3161        };
3162
3163        let instrument_id = InstrumentId::from("BTC-USDT.OKX");
3164        let bar_type = BarType::new(
3165            instrument_id,
3166            BAR_SPEC_1_DAY_LAST,
3167            AggregationSource::External,
3168        );
3169        let bar = parse_candle_msg(&okx_candles[0], bar_type, 2, 0, UnixNanos::default()).unwrap();
3170
3171        assert_eq!(bar.bar_type, bar_type);
3172        assert_eq!(bar.open, Price::from("8533.02"));
3173        assert_eq!(bar.high, Price::from("8553.74"));
3174        assert_eq!(bar.low, Price::from("8527.17"));
3175        assert_eq!(bar.close, Price::from("8548.26"));
3176        assert_eq!(bar.volume, Quantity::from(45247));
3177        assert_eq!(bar.ts_event, UnixNanos::from(1_597_026_383_085_000_000));
3178        assert_eq!(bar.ts_init, UnixNanos::default());
3179    }
3180
3181    #[rstest]
3182    fn test_parse_funding_rate() {
3183        let json_data = load_test_json("ws_funding_rate.json");
3184        let msg: OKXWsFrame = serde_json::from_str(&json_data).unwrap();
3185
3186        let okx_funding_rates: Vec<crate::websocket::messages::OKXFundingRateMsg> = match msg {
3187            OKXWsFrame::Data { data, .. } => serde_json::from_value(data).unwrap(),
3188            _ => panic!("Expected a `Data` variant"),
3189        };
3190
3191        let instrument_id = InstrumentId::from("BTC-USDT-SWAP.OKX");
3192        let funding_rate =
3193            parse_funding_rate_msg(&okx_funding_rates[0], instrument_id, UnixNanos::default())
3194                .unwrap();
3195
3196        assert_eq!(funding_rate.instrument_id, instrument_id);
3197        assert_eq!(funding_rate.rate, dec!(0.0001));
3198        assert_eq!(funding_rate.interval, Some(8 * 60));
3199        assert_eq!(
3200            funding_rate.next_funding_ns,
3201            Some(UnixNanos::from(1_744_590_349_506_000_000))
3202        );
3203        assert_eq!(
3204            funding_rate.ts_event,
3205            UnixNanos::from(1_744_590_349_506_000_000)
3206        );
3207        assert_eq!(funding_rate.ts_init, UnixNanos::default());
3208    }
3209
3210    #[rstest]
3211    fn test_parse_book_vec() {
3212        let json_data = load_test_json("ws_books_snapshot.json");
3213        let event: OKXWsFrame = serde_json::from_str(&json_data).unwrap();
3214        let (msgs, action): (Vec<OKXBookMsg>, OKXBookAction) = match event {
3215            OKXWsFrame::BookData { data, action, .. } => (data, action),
3216            _ => panic!("Expected BookData"),
3217        };
3218
3219        let instrument_id = InstrumentId::from("BTC-USDT.OKX");
3220        let deltas_vec =
3221            parse_book_msg_vec(msgs, &instrument_id, 8, 1, action, UnixNanos::default()).unwrap();
3222
3223        assert_eq!(deltas_vec.len(), 1);
3224
3225        if let Data::BookDeltas(d) = &deltas_vec[0] {
3226            assert_eq!(d.sequence, 123_456);
3227        } else {
3228            panic!("Expected Deltas");
3229        }
3230    }
3231
3232    #[rstest]
3233    fn test_parse_ticker_vec() {
3234        let json_data = load_test_json("ws_tickers.json");
3235        let event: OKXWsFrame = serde_json::from_str(&json_data).unwrap();
3236        let data_val: serde_json::Value = match event {
3237            OKXWsFrame::Data { data, .. } => data,
3238            _ => panic!("Expected Data"),
3239        };
3240
3241        let instrument_id = InstrumentId::from("BTC-USDT.OKX");
3242        let quotes_vec =
3243            parse_ticker_msg_vec(data_val, &instrument_id, 8, 1, UnixNanos::default()).unwrap();
3244
3245        assert_eq!(quotes_vec.len(), 1);
3246
3247        if let Data::Quote(q) = &quotes_vec[0] {
3248            assert_eq!(q.bid_price, Price::from("8888.88000000"));
3249            assert_eq!(q.ask_price, Price::from("9999.99"));
3250        } else {
3251            panic!("Expected Quote");
3252        }
3253    }
3254
3255    #[rstest]
3256    fn test_parse_trade_vec() {
3257        let json_data = load_test_json("ws_trades.json");
3258        let event: OKXWsFrame = serde_json::from_str(&json_data).unwrap();
3259        let data_val: serde_json::Value = match event {
3260            OKXWsFrame::Data { data, .. } => data,
3261            _ => panic!("Expected Data"),
3262        };
3263
3264        let instrument_id = InstrumentId::from("BTC-USDT.OKX");
3265        let trades_vec =
3266            parse_trade_msg_vec(data_val, &instrument_id, 8, 1, UnixNanos::default()).unwrap();
3267
3268        assert_eq!(trades_vec.len(), 1);
3269
3270        if let Data::Trade(t) = &trades_vec[0] {
3271            assert_eq!(t.trade_id, TradeId::new("130639474"));
3272        } else {
3273            panic!("Expected Trade");
3274        }
3275    }
3276
3277    #[rstest]
3278    fn test_parse_candle_vec() {
3279        let json_data = load_test_json("ws_candle.json");
3280        let event: OKXWsFrame = serde_json::from_str(&json_data).unwrap();
3281        let data_val: serde_json::Value = match event {
3282            OKXWsFrame::Data { data, .. } => data,
3283            _ => panic!("Expected Data"),
3284        };
3285
3286        let instrument_id = InstrumentId::from("BTC-USDT.OKX");
3287        let bars_vec = parse_candle_msg_vec(
3288            data_val,
3289            &instrument_id,
3290            2,
3291            1,
3292            BAR_SPEC_1_DAY_LAST,
3293            UnixNanos::default(),
3294        )
3295        .unwrap();
3296
3297        assert_eq!(bars_vec.len(), 1);
3298
3299        if let Data::Bar(b) = &bars_vec[0] {
3300            assert_eq!(b.open, Price::from("8533.02"));
3301        } else {
3302            panic!("Expected Bar");
3303        }
3304    }
3305
3306    #[rstest]
3307    fn test_parse_book_message() {
3308        let json_data = load_test_json("ws_bbo_tbt.json");
3309        let msg: OKXWsFrame = serde_json::from_str(&json_data).unwrap();
3310        let (okx_books, arg): (Vec<OKXBookMsg>, OKXWebSocketArg) = match msg {
3311            OKXWsFrame::Data { data, arg, .. } => (serde_json::from_value(data).unwrap(), arg),
3312            _ => panic!("Expected a `Data` variant"),
3313        };
3314
3315        assert_eq!(arg.channel, OKXWsChannel::BboTbt);
3316        assert_eq!(arg.inst_id.as_ref().unwrap(), &Ustr::from("BTC-USDT"));
3317        assert_eq!(arg.inst_type, None);
3318        assert_eq!(okx_books.len(), 1);
3319
3320        let book_msg = &okx_books[0];
3321
3322        // Check asks
3323        assert_eq!(book_msg.asks.len(), 1);
3324        let ask = &book_msg.asks[0];
3325        assert_eq!(ask.price, "8476.98");
3326        assert_eq!(ask.size, "415");
3327        assert_eq!(ask.liquidated_orders_count, "0");
3328        assert_eq!(ask.orders_count, "13");
3329
3330        // Check bids
3331        assert_eq!(book_msg.bids.len(), 1);
3332        let bid = &book_msg.bids[0];
3333        assert_eq!(bid.price, "8476.97");
3334        assert_eq!(bid.size, "256");
3335        assert_eq!(bid.liquidated_orders_count, "0");
3336        assert_eq!(bid.orders_count, "12");
3337        assert_eq!(book_msg.ts, 1_597_026_383_085);
3338        assert_eq!(book_msg.seq_id, 123_456);
3339        assert_eq!(book_msg.checksum, None);
3340        assert_eq!(book_msg.prev_seq_id, None);
3341    }
3342
3343    #[rstest]
3344    fn test_parse_ws_account_message() {
3345        let json_data = load_test_json("ws_account.json");
3346        let msg: OKXWsFrame = serde_json::from_str(&json_data).unwrap();
3347
3348        let OKXWsFrame::Data { data, .. } = msg else {
3349            panic!("Expected OKXWsFrame::Data");
3350        };
3351
3352        let accounts: Vec<OKXAccount> = serde_json::from_value(data).unwrap();
3353
3354        assert_eq!(accounts.len(), 1);
3355        let account = &accounts[0];
3356
3357        assert_eq!(account.total_eq, "100.56089404807182");
3358        assert_eq!(account.details.len(), 3);
3359
3360        let usdt_detail = &account.details[0];
3361        assert_eq!(usdt_detail.ccy, "USDT");
3362        assert_eq!(usdt_detail.avail_bal, "100.52768569797846");
3363        assert_eq!(usdt_detail.cash_bal, "100.52768569797846");
3364
3365        let btc_detail = &account.details[1];
3366        assert_eq!(btc_detail.ccy, "BTC");
3367        assert_eq!(btc_detail.avail_bal, "0.0000000051");
3368
3369        let eth_detail = &account.details[2];
3370        assert_eq!(eth_detail.ccy, "ETH");
3371        assert_eq!(eth_detail.avail_bal, "0.000000185");
3372
3373        let account_id = AccountId::new("OKX-001");
3374        let ts_init = UnixNanos::default();
3375        let account_state = parse_account_state(account, account_id, AccountType::Margin, ts_init);
3376
3377        assert!(account_state.is_ok());
3378        let state = account_state.unwrap();
3379        assert_eq!(state.account_id, account_id);
3380        assert_eq!(state.balances.len(), 3);
3381
3382        let mut base_account = BaseAccount::new(state, true);
3383        let mut partial = account.clone();
3384        partial.details.retain(|detail| detail.ccy == "BTC");
3385        partial.details[0].cash_bal = "0.25".to_string();
3386        partial.details[0].avail_bal = "0.25".to_string();
3387        let partial_state =
3388            parse_account_state(&partial, account_id, AccountType::Margin, ts_init).unwrap();
3389        assert!(partial_state.info.is_none());
3390
3391        base_account.base_apply(partial_state);
3392
3393        let usdt = base_account.base_balance(Some(Currency::USDT())).unwrap();
3394        let btc = base_account.base_balance(Some(Currency::BTC())).unwrap();
3395        assert_eq!(usdt.total, Money::from("100.52768569797846 USDT"));
3396        assert_eq!(usdt.free, Money::from("100.52768569797846 USDT"));
3397        assert_eq!(btc.total, Money::from("0.25 BTC"));
3398        assert_eq!(btc.free, Money::from("0.25 BTC"));
3399    }
3400
3401    #[rstest]
3402    fn test_parse_ws_account_message_empty_balance() {
3403        // GH-3772: OKX returns empty strings and empty details for zero-balance accounts
3404        let json_data = load_test_json("ws_account_empty.json");
3405        let msg: OKXWsFrame = serde_json::from_str(&json_data).unwrap();
3406
3407        let OKXWsFrame::Data { data, .. } = msg else {
3408            panic!("Expected OKXWsFrame::Data");
3409        };
3410
3411        let accounts: Vec<OKXAccount> = serde_json::from_value(data).unwrap();
3412        assert_eq!(accounts.len(), 1);
3413
3414        let account = &accounts[0];
3415        assert!(account.details.is_empty());
3416        assert_eq!(account.total_eq, "0");
3417
3418        let account_id = AccountId::new("OKX-001");
3419        let account_state = parse_account_state(
3420            account,
3421            account_id,
3422            AccountType::Margin,
3423            UnixNanos::default(),
3424        )
3425        .unwrap();
3426
3427        assert_eq!(account_state.account_id, account_id);
3428        assert_eq!(account_state.margins.len(), 0);
3429        assert_eq!(account_state.balances.len(), 1);
3430        assert!(account_state.info.is_none());
3431
3432        let balance = &account_state.balances[0];
3433        assert_eq!(balance.total, Money::new(0.0, Currency::USD()));
3434        assert_eq!(balance.free, Money::new(0.0, Currency::USD()));
3435        assert_eq!(balance.locked, Money::new(0.0, Currency::USD()));
3436    }
3437
3438    #[rstest]
3439    fn test_parse_order_msg() {
3440        let json_data = load_test_json("ws_orders.json");
3441        let ws_msg: serde_json::Value = serde_json::from_str(&json_data).unwrap();
3442
3443        let data: Vec<OKXOrderMsg> = serde_json::from_value(ws_msg["data"].clone()).unwrap();
3444
3445        let account_id = AccountId::new("OKX-001");
3446        let mut instruments = AHashMap::new();
3447
3448        // Create a mock instrument for testing
3449        let instrument_id = InstrumentId::from("BTC-USDT-SWAP.OKX");
3450        let instrument = create_stub_instrument();
3451
3452        instruments.insert(
3453            Ustr::from("BTC-USDT-SWAP"),
3454            InstrumentAny::CryptoPerpetual(instrument),
3455        );
3456
3457        let ts_init = UnixNanos::default();
3458        let mut fee_cache = FeeCache::new();
3459        let mut filled_qty_cache = FilledQtyCache::new();
3460
3461        let result = parse_order_msg_vec(
3462            &data,
3463            account_id,
3464            &instruments,
3465            &mut fee_cache,
3466            &mut filled_qty_cache,
3467            ts_init,
3468        );
3469
3470        assert!(result.is_ok());
3471        let order_reports = result.unwrap();
3472        assert_eq!(order_reports.len(), 1);
3473
3474        // Verify the parsed order report
3475        let report = &order_reports[0];
3476
3477        if let ExecutionReport::Fill(fill_report) = report {
3478            assert_eq!(fill_report.account_id, account_id);
3479            assert_eq!(fill_report.instrument_id, instrument_id);
3480            assert_eq!(
3481                fill_report.client_order_id,
3482                Some(ClientOrderId::new("001BTCUSDT20250106001"))
3483            );
3484            assert_eq!(
3485                fill_report.venue_order_id,
3486                VenueOrderId::new("2497956918703120384")
3487            );
3488            assert_eq!(fill_report.trade_id, TradeId::from("1518905529"));
3489            assert_eq!(fill_report.order_side, OrderSide::Buy);
3490            assert_eq!(fill_report.last_px, Price::from("103698.90"));
3491            assert_eq!(fill_report.last_qty, Quantity::from("0.03000000"));
3492            assert_eq!(fill_report.liquidity_side, LiquiditySide::Maker);
3493        } else {
3494            panic!("Expected Fill report for filled order");
3495        }
3496    }
3497
3498    #[rstest]
3499    fn test_parse_order_status_report() {
3500        let json_data = load_test_json("ws_orders.json");
3501        let ws_msg: serde_json::Value = serde_json::from_str(&json_data).unwrap();
3502        let data: Vec<OKXOrderMsg> = serde_json::from_value(ws_msg["data"].clone()).unwrap();
3503        let order_msg = &data[0];
3504
3505        let account_id = AccountId::new("OKX-001");
3506        let instrument_id = InstrumentId::from("BTC-USDT-SWAP.OKX");
3507        let instrument = create_stub_instrument();
3508
3509        let ts_init = UnixNanos::default();
3510
3511        let result = parse_order_status_report(
3512            order_msg,
3513            &InstrumentAny::CryptoPerpetual(instrument),
3514            account_id,
3515            ts_init,
3516        );
3517
3518        assert!(result.is_ok());
3519        let order_status_report = result.unwrap();
3520
3521        assert_eq!(order_status_report.account_id, account_id);
3522        assert_eq!(order_status_report.instrument_id, instrument_id);
3523        assert_eq!(
3524            order_status_report.client_order_id,
3525            Some(ClientOrderId::new("001BTCUSDT20250106001"))
3526        );
3527        assert_eq!(
3528            order_status_report.venue_order_id,
3529            VenueOrderId::new("2497956918703120384")
3530        );
3531        assert_eq!(order_status_report.order_side, OrderSide::Buy.into());
3532        assert_eq!(order_status_report.order_status, OrderStatus::Filled);
3533        assert_eq!(order_status_report.quantity, Quantity::from("0.03000000"));
3534        assert_eq!(order_status_report.filled_qty, Quantity::from("0.03000000"));
3535    }
3536
3537    #[rstest]
3538    #[case::base_filled(
3539        OKXOrderStatus::Filled,
3540        OKXTargetCurrency::BaseCcy,
3541        "0.00296487",
3542        "0.00296475",
3543        "0.00296475"
3544    )]
3545    #[case::base_partial(
3546        OKXOrderStatus::PartiallyFilled,
3547        OKXTargetCurrency::BaseCcy,
3548        "0.00296487",
3549        "0.00296475",
3550        "0.00296487"
3551    )]
3552    #[case::base_canceled(
3553        OKXOrderStatus::Canceled,
3554        OKXTargetCurrency::BaseCcy,
3555        "0.00296487",
3556        "0.00296475",
3557        "0.00296487"
3558    )]
3559    #[case::base_zero_fill(
3560        OKXOrderStatus::Filled,
3561        OKXTargetCurrency::BaseCcy,
3562        "0.00296487",
3563        "0",
3564        "0.00296487"
3565    )]
3566    #[case::quote_filled(
3567        OKXOrderStatus::Filled,
3568        OKXTargetCurrency::QuoteCcy,
3569        "296.487",
3570        "0.00296475",
3571        "0.00296475"
3572    )]
3573    fn test_parse_order_status_report_terminal_quantity(
3574        #[values("", "0")] price: &str,
3575        #[case] state: OKXOrderStatus,
3576        #[case] target: OKXTargetCurrency,
3577        #[case] size: &str,
3578        #[case] filled: &str,
3579        #[case] expected_quantity: &str,
3580    ) {
3581        let payload: Value = serde_json::from_str(&load_test_json("ws_orders.json")).unwrap();
3582        let mut order: OKXOrderMsg = serde_json::from_value(payload["data"][0].clone()).unwrap();
3583        order.inst_type = OKXInstrumentType::Spot;
3584        order.ord_type = OKXOrderType::Market;
3585        order.side = OKXSide::Buy;
3586        order.tgt_ccy = Some(target);
3587        order.state = state;
3588        order.sz = size.to_string();
3589        order.acc_fill_sz = Some(filled.to_string());
3590        order.px = price.to_string();
3591        order.avg_px = "100000".to_string();
3592        let instrument = CurrencyPair::builder()
3593            .instrument_id(InstrumentId::from("BTC-USDC.OKX"))
3594            .raw_symbol(Symbol::from("BTC-USDC"))
3595            .base_currency(Currency::BTC())
3596            .quote_currency(Currency::USDC())
3597            .price_precision(2)
3598            .size_precision(8)
3599            .price_increment(Price::from("0.01"))
3600            .size_increment(Quantity::from("0.00000001"))
3601            .ts_event(UnixNanos::default())
3602            .ts_init(UnixNanos::default())
3603            .build()
3604            .unwrap();
3605
3606        let report = parse_order_status_report(
3607            &order,
3608            &InstrumentAny::CurrencyPair(instrument),
3609            AccountId::from("OKX-001"),
3610            UnixNanos::default(),
3611        )
3612        .unwrap();
3613
3614        assert_eq!(report.price, None);
3615        assert_eq!(report.order_status, OrderStatus::try_from(state).unwrap());
3616        assert_eq!(report.quantity, Quantity::from(expected_quantity));
3617        assert_eq!(report.filled_qty, Quantity::from(filled));
3618    }
3619
3620    #[rstest]
3621    fn test_parse_fill_report() {
3622        let json_data = load_test_json("ws_orders.json");
3623        let ws_msg: serde_json::Value = serde_json::from_str(&json_data).unwrap();
3624        let data: Vec<OKXOrderMsg> = serde_json::from_value(ws_msg["data"].clone()).unwrap();
3625        let order_msg = &data[0];
3626
3627        let account_id = AccountId::new("OKX-001");
3628        let instrument_id = InstrumentId::from("BTC-USDT-SWAP.OKX");
3629        let instrument = create_stub_instrument();
3630
3631        let ts_init = UnixNanos::default();
3632
3633        let result = parse_fill_report(
3634            order_msg,
3635            &InstrumentAny::CryptoPerpetual(instrument),
3636            account_id,
3637            None,
3638            None,
3639            ts_init,
3640        );
3641
3642        assert!(result.is_ok());
3643        let fill_report = result.unwrap().unwrap();
3644
3645        assert_eq!(fill_report.account_id, account_id);
3646        assert_eq!(fill_report.instrument_id, instrument_id);
3647        assert_eq!(
3648            fill_report.client_order_id,
3649            Some(ClientOrderId::new("001BTCUSDT20250106001"))
3650        );
3651        assert_eq!(
3652            fill_report.venue_order_id,
3653            VenueOrderId::new("2497956918703120384")
3654        );
3655        assert_eq!(fill_report.trade_id, TradeId::from("1518905529"));
3656        assert_eq!(fill_report.order_side, OrderSide::Buy);
3657        assert_eq!(fill_report.last_px, Price::from("103698.90"));
3658        assert_eq!(fill_report.last_qty, Quantity::from("0.03000000"));
3659        assert_eq!(fill_report.liquidity_side, LiquiditySide::Maker);
3660    }
3661
3662    #[rstest]
3663    fn test_parse_fill_report_rejects_missing_fee() {
3664        let instrument = create_stub_instrument();
3665        let mut msg = create_stub_order_msg("0.01", None, "ord-1", "trade-1");
3666        msg.fee = None;
3667
3668        let error = parse_fill_report(
3669            &msg,
3670            &InstrumentAny::CryptoPerpetual(instrument),
3671            AccountId::new("OKX-001"),
3672            None,
3673            None,
3674            UnixNanos::default(),
3675        )
3676        .unwrap_err();
3677
3678        assert!(error.to_string().contains("missing fee"));
3679    }
3680
3681    #[rstest]
3682    #[case::charge("-0.03", "0.03 USD")]
3683    #[case::rebate("0.02", "-0.02 USD")]
3684    #[case::zero("0", "0 USD")]
3685    fn test_parse_fill_report_uses_per_fill_fee(#[case] fee: &str, #[case] expected: &str) {
3686        let instrument = InstrumentAny::CryptoPerpetual(create_stub_instrument());
3687        let mut msg = create_stub_order_msg("0.006", Some("0.010".into()), "ord-1", "trade-2");
3688        msg.fee = Some("-0.05".into());
3689        msg.fee_ccy = Ustr::from("BTC");
3690        msg.fill_fee = Some(fee.into());
3691        msg.fill_fee_ccy = Some(Ustr::from("USD"));
3692        let report = parse_fill_report(
3693            &msg,
3694            &instrument,
3695            AccountId::from("OKX-001"),
3696            None,
3697            None,
3698            UnixNanos::default(),
3699        )
3700        .unwrap()
3701        .unwrap();
3702        assert_eq!(report.trade_id, TradeId::from("trade-2"));
3703        assert_eq!(report.last_qty, Quantity::from("0.00600000"));
3704        assert_eq!(report.commission, Money::from(expected));
3705    }
3706
3707    #[rstest]
3708    #[case::absent(None, "missing fee for fill report inst_id=BTC-USDT-SWAP")]
3709    #[case::empty(Some(""), "missing fee for fill report inst_id=BTC-USDT-SWAP")]
3710    #[case::invalid(
3711        Some("invalid"),
3712        "Failed to parse fee 'invalid': Invalid decimal: unknown character"
3713    )]
3714    fn test_per_fill_fee_requires_valid_cumulative_fee(
3715        #[case] cumulative_fee: Option<&str>,
3716        #[case] expected: &str,
3717    ) {
3718        let instrument = InstrumentAny::CryptoPerpetual(create_stub_instrument());
3719        let mut msg = create_stub_order_msg("0.004", Some("0.004".into()), "ord-1", "trade-1");
3720        msg.fee = cumulative_fee.map(str::to_owned);
3721        msg.fill_fee = Some("-0.02".into());
3722        msg.fill_fee_ccy = Some(Ustr::from("USD"));
3723
3724        let error = parse_fill_report(
3725            &msg,
3726            &instrument,
3727            AccountId::from("OKX-001"),
3728            None,
3729            None,
3730            UnixNanos::default(),
3731        )
3732        .unwrap_err();
3733
3734        assert_eq!(error.to_string(), expected);
3735    }
3736
3737    #[rstest]
3738    fn test_per_fill_then_cumulative_fee_preserves_total(
3739        #[values(false, true)] prior_fill: bool,
3740        #[values("USD", "BTC")] currency: &str,
3741    ) {
3742        let instrument = InstrumentAny::CryptoPerpetual(create_stub_instrument());
3743        let account_id = AccountId::from("OKX-001");
3744        let mut fees = FeeCache::new();
3745        let mut quantities = FilledQtyCache::new();
3746        let zero = format!("0 {currency}");
3747        let mut total = Money::from(zero.as_str());
3748
3749        if prior_fill {
3750            let mut prior =
3751                create_stub_order_msg("0.002", Some("0.002".into()), "ord-1", "trade-0");
3752            prior.fee = Some("-0.01".into());
3753            prior.fee_ccy = Ustr::from(currency);
3754            let fill = parse_fill_report(
3755                &prior,
3756                &instrument,
3757                account_id,
3758                None,
3759                None,
3760                UnixNanos::default(),
3761            )
3762            .unwrap()
3763            .unwrap();
3764            total = total + fill.commission;
3765            update_fee_fill_caches(&prior, &instrument, &mut fees, &mut quantities);
3766        }
3767
3768        let mut first = create_stub_order_msg(
3769            "0.004",
3770            Some(if prior_fill { "0.006" } else { "0.004" }.into()),
3771            "ord-1",
3772            "trade-1",
3773        );
3774        first.fee = None;
3775        first.fee_ccy = Ustr::from(currency);
3776        first.fill_fee = Some("-0.02".into());
3777        first.fill_fee_ccy = Some(Ustr::from(currency));
3778        let mut second = create_stub_order_msg(
3779            "0.006",
3780            Some(if prior_fill { "0.012" } else { "0.010" }.into()),
3781            "ord-1",
3782            "trade-2",
3783        );
3784        second.fee = Some(if prior_fill { "-0.06" } else { "-0.05" }.into());
3785        second.fee_ccy = Ustr::from(currency);
3786
3787        let first_error = parse_fill_report(
3788            &first,
3789            &instrument,
3790            account_id,
3791            fees.get(&first.ord_id).copied(),
3792            quantities.get(&first.ord_id).copied(),
3793            UnixNanos::default(),
3794        )
3795        .unwrap_err();
3796        let second_error = parse_fill_report(
3797            &second,
3798            &instrument,
3799            account_id,
3800            fees.get(&second.ord_id).copied(),
3801            quantities.get(&second.ord_id).copied(),
3802            UnixNanos::default(),
3803        )
3804        .unwrap_err();
3805        first.fee = Some(if prior_fill { "-0.03" } else { "-0.02" }.into());
3806        let first_fill = parse_fill_report(
3807            &first,
3808            &instrument,
3809            account_id,
3810            fees.get(&first.ord_id).copied(),
3811            quantities.get(&first.ord_id).copied(),
3812            UnixNanos::default(),
3813        )
3814        .unwrap()
3815        .unwrap();
3816        update_fee_fill_caches(&first, &instrument, &mut fees, &mut quantities);
3817        let second_fill = parse_fill_report(
3818            &second,
3819            &instrument,
3820            account_id,
3821            fees.get(&second.ord_id).copied(),
3822            quantities.get(&second.ord_id).copied(),
3823            UnixNanos::default(),
3824        )
3825        .unwrap()
3826        .unwrap();
3827        total = total + first_fill.commission;
3828        total = total + second_fill.commission;
3829        let first_commission = format!("0.02 {currency}");
3830        let second_commission = format!("0.03 {currency}");
3831        let expected_total = format!("{} {currency}", if prior_fill { "0.06" } else { "0.05" });
3832
3833        assert_eq!(
3834            first_error.to_string(),
3835            "missing fee for fill report inst_id=BTC-USDT-SWAP"
3836        );
3837        assert_eq!(
3838            second_error.to_string(),
3839            "missing per-fill fee across a private fill gap for ord-1"
3840        );
3841        assert_eq!(first_fill.trade_id, TradeId::from("trade-1"));
3842        assert_eq!(first_fill.last_qty, Quantity::from("0.00400000"));
3843        assert_eq!(
3844            first_fill.commission,
3845            Money::from(first_commission.as_str())
3846        );
3847        assert_eq!(second_fill.trade_id, TradeId::from("trade-2"));
3848        assert_eq!(second_fill.last_qty, Quantity::from("0.00600000"));
3849        assert_eq!(
3850            second_fill.commission,
3851            Money::from(second_commission.as_str())
3852        );
3853        assert_eq!(total, Money::from(expected_total.as_str()));
3854    }
3855
3856    #[rstest]
3857    fn test_parse_fill_report_defers_fee_across_missing_private_fill() {
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.fee = Some("-0.05".into());
3861        let error = parse_fill_report(
3862            &msg,
3863            &instrument,
3864            AccountId::from("OKX-001"),
3865            None,
3866            None,
3867            UnixNanos::default(),
3868        )
3869        .unwrap_err();
3870        assert_eq!(
3871            error.to_string(),
3872            "missing per-fill fee across a private fill gap for ord-1"
3873        );
3874    }
3875
3876    #[rstest]
3877    fn test_parse_fill_report_rejects_missing_per_fill_fee_currency() {
3878        let instrument = InstrumentAny::CryptoPerpetual(create_stub_instrument());
3879        let mut msg = create_stub_order_msg("0.006", Some("0.010".into()), "ord-1", "trade-2");
3880        msg.fill_fee = Some("-0.03".into());
3881        msg.fill_fee_ccy = None;
3882        let error = parse_fill_report(
3883            &msg,
3884            &instrument,
3885            AccountId::from("OKX-001"),
3886            None,
3887            None,
3888            UnixNanos::default(),
3889        )
3890        .unwrap_err();
3891        assert_eq!(error.to_string(), "missing per-fill fee currency");
3892    }
3893
3894    #[rstest]
3895    fn test_zero_fill_terminal_update_preserves_and_retires_baselines() {
3896        let instrument = InstrumentAny::CryptoPerpetual(create_stub_instrument());
3897        let mut fees = FeeCache::new();
3898        let mut quantities = FilledQtyCache::new();
3899        let mut msg = create_stub_order_msg("0.004", Some("0.004".into()), "retired", "trade-1");
3900        msg.fee = Some("-0.02".into());
3901        update_fee_fill_caches(&msg, &instrument, &mut fees, &mut quantities);
3902        msg.acc_fill_sz = Some("0".into());
3903        msg.fee = Some("0".into());
3904        msg.state = OKXOrderStatus::Canceled;
3905        update_fee_fill_caches(&msg, &instrument, &mut fees, &mut quantities);
3906        assert_eq!(fees.get(&msg.ord_id), Some(&Money::from("0.02 USDT")));
3907        assert_eq!(
3908            quantities.get(&msg.ord_id),
3909            Some(&Quantity::from("0.00400000"))
3910        );
3911
3912        for index in 0..TERMINAL_BASELINE_CAPACITY {
3913            let mut terminal = create_stub_order_msg(
3914                "0.001",
3915                Some("0.001".into()),
3916                &format!("terminal{index}"),
3917                "trade-2",
3918            );
3919            terminal.state = OKXOrderStatus::Filled;
3920            update_fee_fill_caches(&terminal, &instrument, &mut fees, &mut quantities);
3921        }
3922
3923        assert_eq!(fees.get(&msg.ord_id), None);
3924        assert_eq!(quantities.get(&msg.ord_id), None);
3925    }
3926
3927    #[rstest]
3928    fn test_stale_acceptance_preserves_cumulative_fee_baseline(
3929        #[values(None, Some(""), Some("0"), Some("0.00000000"))] cumulative: Option<&str>,
3930    ) {
3931        let instrument = InstrumentAny::CryptoPerpetual(create_stub_instrument());
3932        let mut fees = FeeCache::new();
3933        let mut quantities = FilledQtyCache::new();
3934        let mut msg = create_stub_order_msg("0.004", Some("0.004".into()), "ord-1", "trade-1");
3935        msg.fee = Some("-0.02".into());
3936        update_fee_fill_caches(&msg, &instrument, &mut fees, &mut quantities);
3937        msg.state = OKXOrderStatus::Live;
3938        msg.acc_fill_sz = cumulative.map(str::to_string);
3939        msg.fee = Some("0".into());
3940        update_fee_fill_caches(&msg, &instrument, &mut fees, &mut quantities);
3941        let mut remainder =
3942            create_stub_order_msg("0.006", Some("0.010".into()), "ord-1", "trade-2");
3943        remainder.fee = Some("-0.05".into());
3944        let report = parse_fill_report(
3945            &remainder,
3946            &instrument,
3947            AccountId::from("OKX-001"),
3948            fees.get(&msg.ord_id).copied(),
3949            quantities.get(&msg.ord_id).copied(),
3950            UnixNanos::default(),
3951        )
3952        .unwrap()
3953        .unwrap();
3954        assert_eq!(report.commission, Money::from("0.03 USDT"));
3955        assert_eq!(report.last_qty, Quantity::from("0.00600000"));
3956    }
3957
3958    #[rstest]
3959    fn test_parse_book_depth_msg() {
3960        let json_data = load_test_json("ws_books_snapshot.json");
3961        let event: OKXWsFrame = serde_json::from_str(&json_data).unwrap();
3962        let msgs: Vec<OKXBookMsg> = match event {
3963            OKXWsFrame::BookData { data, .. } => data,
3964            _ => panic!("Expected BookData"),
3965        };
3966
3967        let instrument_id = InstrumentId::from("BTC-USDT.OKX");
3968        let depth =
3969            parse_book_depth_msg(&msgs[0], instrument_id, 2, 0, UnixNanos::default()).unwrap();
3970
3971        let expected_bids = [
3972            ("8476.97", "256"),
3973            ("8475.55", "101"),
3974            ("8475.54", "100"),
3975            ("8475.30", "1"),
3976            ("8447.32", "6"),
3977            ("8447.02", "246"),
3978            ("8446.83", "24"),
3979            ("8446.00", "95"),
3980        ];
3981        let expected_asks = [
3982            ("8476.98", "415"),
3983            ("8477.00", "7"),
3984            ("8477.34", "85"),
3985            ("8477.56", "1"),
3986            ("8505.84", "8"),
3987            ("8506.37", "85"),
3988            ("8506.49", "2"),
3989            ("8506.96", "100"),
3990        ];
3991
3992        assert_eq!(depth.instrument_id, instrument_id);
3993        assert_eq!(depth.sequence, 123_456);
3994        assert_eq!(depth.ts_event, UnixNanos::from(1_597_026_383_085_000_000));
3995        assert_eq!(depth.ts_init, UnixNanos::default());
3996        assert_eq!(depth.flags, RecordFlag::F_SNAPSHOT as u8);
3997        assert_eq!(depth.bids.len(), expected_bids.len());
3998        assert_eq!(depth.asks.len(), expected_asks.len());
3999        assert_eq!(depth.bid_counts.as_slice(), &[12, 1, 1, 1, 1, 1, 1, 3]);
4000        assert_eq!(depth.ask_counts.as_slice(), &[13, 2, 1, 1, 1, 1, 1, 2]);
4001        for (order, (price, size)) in depth.bids.iter().zip(expected_bids) {
4002            assert_eq!(order.side, Some(OrderSide::Buy));
4003            assert_eq!(order.price, Price::from(price));
4004            assert_eq!(order.size, Quantity::from(size));
4005            assert_eq!(order.order_id, 0);
4006        }
4007
4008        for (order, (price, size)) in depth.asks.iter().zip(expected_asks) {
4009            assert_eq!(order.side, Some(OrderSide::Sell));
4010            assert_eq!(order.price, Price::from(price));
4011            assert_eq!(order.size, Quantity::from(size));
4012            assert_eq!(order.order_id, 0);
4013        }
4014    }
4015
4016    #[rstest]
4017    fn test_parse_book_depth_msg_vec() {
4018        let json_data = load_test_json("ws_books_snapshot.json");
4019        let event: OKXWsFrame = serde_json::from_str(&json_data).unwrap();
4020        let msgs: Vec<OKXBookMsg> = match event {
4021            OKXWsFrame::BookData { data, .. } => data,
4022            _ => panic!("Expected BookData"),
4023        };
4024
4025        let instrument_id = InstrumentId::from("BTC-USDT.OKX");
4026        let depth_vec =
4027            parse_book_depth_msg_vec(msgs, &instrument_id, 2, 0, UnixNanos::default()).unwrap();
4028
4029        assert_eq!(depth_vec.len(), 1);
4030
4031        if let Data::BookDepth(d) = &depth_vec[0] {
4032            assert_eq!(d.instrument_id, instrument_id);
4033            assert_eq!(d.sequence, 123_456);
4034            assert_eq!(d.bids[0].price, Price::from("8476.97"));
4035            assert_eq!(d.asks[0].price, Price::from("8476.98"));
4036        } else {
4037            panic!("Expected Depth");
4038        }
4039    }
4040
4041    #[rstest]
4042    fn test_parse_fill_report_with_fee_cache() {
4043        let instrument = create_stub_instrument();
4044
4045        let account_id = AccountId::new("OKX-001");
4046        let ts_init = UnixNanos::default();
4047
4048        // First fill: 0.01 BTC out of 0.03 BTC total (1/3)
4049        let mut order_msg_1 =
4050            create_stub_order_msg("0.01", Some("0.01".to_string()), "1234567890", "trade_1");
4051        order_msg_1.exec_type = OKXExecType::Maker;
4052
4053        let fill_report_1 = parse_fill_report(
4054            &order_msg_1,
4055            &InstrumentAny::CryptoPerpetual(instrument.clone()),
4056            account_id,
4057            None,
4058            None,
4059            ts_init,
4060        )
4061        .unwrap()
4062        .unwrap();
4063
4064        // First fill should get the full fee since there's no previous fee
4065        assert_eq!(fill_report_1.commission, Money::new(1.0, Currency::USDT()));
4066
4067        // Second fill: 0.02 BTC more, now 0.03 BTC total (completely filled)
4068        let mut order_msg_2 =
4069            create_stub_order_msg("0.02", Some("0.03".to_string()), "1234567890", "trade_2");
4070        order_msg_2.fee = Some("-3.0".to_string());
4071        order_msg_2.fill_time = 1_746_947_317_403;
4072        order_msg_2.state = OKXOrderStatus::Filled;
4073        order_msg_2.exec_type = OKXExecType::Maker;
4074        order_msg_2.u_time = 1_746_947_317_403;
4075
4076        let fill_report_2 = parse_fill_report(
4077            &order_msg_2,
4078            &InstrumentAny::CryptoPerpetual(instrument),
4079            account_id,
4080            Some(fill_report_1.commission),
4081            Some(fill_report_1.last_qty),
4082            ts_init,
4083        )
4084        .unwrap()
4085        .unwrap();
4086
4087        // Second fill should get total_fee - previous_fee = 3.0 - 1.0 = 2.0
4088        assert_eq!(fill_report_2.commission, Money::new(2.0, Currency::USDT()));
4089
4090        // Test passed - fee was correctly split proportionally
4091    }
4092
4093    #[rstest]
4094    fn test_parse_fill_report_with_maker_rebates() {
4095        let instrument = create_stub_instrument();
4096
4097        let account_id = AccountId::new("OKX-001");
4098        let ts_init = UnixNanos::default();
4099
4100        // First fill: maker rebate of $0.5 (OKX sends as "0.5", parse_fee makes it -0.5)
4101        let mut order_msg_1 = create_stub_order_msg(
4102            "0.01",
4103            Some("0.01".to_string()),
4104            "rebate_order_123",
4105            "trade_rebate_1",
4106        );
4107        order_msg_1.cl_ord_id = "test_order_rebate".to_string();
4108        order_msg_1.fee = Some("0.5".to_string());
4109        order_msg_1.exec_type = OKXExecType::Maker;
4110        order_msg_1.sz = "0.02".to_string();
4111
4112        let fill_report_1 = parse_fill_report(
4113            &order_msg_1,
4114            &InstrumentAny::CryptoPerpetual(instrument.clone()),
4115            account_id,
4116            None,
4117            None,
4118            ts_init,
4119        )
4120        .unwrap()
4121        .unwrap();
4122
4123        // First fill gets the full rebate (negative commission)
4124        assert_eq!(fill_report_1.commission, Money::new(-0.5, Currency::USDT()));
4125
4126        // Second fill: another maker rebate of $0.3, cumulative now $0.8
4127        let mut order_msg_2 = create_stub_order_msg(
4128            "0.01",
4129            Some("0.02".to_string()),
4130            "rebate_order_123",
4131            "trade_rebate_2",
4132        );
4133        order_msg_2.cl_ord_id = "test_order_rebate".to_string();
4134        order_msg_2.fee = Some("0.8".to_string());
4135        order_msg_2.fill_time = 1_746_947_317_403;
4136        order_msg_2.state = OKXOrderStatus::Filled;
4137        order_msg_2.exec_type = OKXExecType::Maker;
4138        order_msg_2.sz = "0.02".to_string();
4139        order_msg_2.u_time = 1_746_947_317_403;
4140
4141        let fill_report_2 = parse_fill_report(
4142            &order_msg_2,
4143            &InstrumentAny::CryptoPerpetual(instrument),
4144            account_id,
4145            Some(fill_report_1.commission),
4146            Some(fill_report_1.last_qty),
4147            ts_init,
4148        )
4149        .unwrap()
4150        .unwrap();
4151
4152        // Second fill: incremental = -0.8 - (-0.5) = -0.3
4153        assert_eq!(fill_report_2.commission, Money::new(-0.3, Currency::USDT()));
4154    }
4155
4156    #[rstest]
4157    fn test_parse_fill_report_rebate_to_charge_transition() {
4158        let instrument = create_stub_instrument();
4159
4160        let account_id = AccountId::new("OKX-001");
4161        let ts_init = UnixNanos::default();
4162
4163        // First fill: maker rebate of $1.0
4164        let mut order_msg_1 = create_stub_order_msg(
4165            "0.01",
4166            Some("0.01".to_string()),
4167            "transition_order_456",
4168            "trade_transition_1",
4169        );
4170        order_msg_1.cl_ord_id = "test_order_transition".to_string();
4171        order_msg_1.fee = Some("1.0".to_string());
4172        order_msg_1.exec_type = OKXExecType::Maker;
4173        order_msg_1.sz = "0.02".to_string();
4174
4175        let fill_report_1 = parse_fill_report(
4176            &order_msg_1,
4177            &InstrumentAny::CryptoPerpetual(instrument.clone()),
4178            account_id,
4179            None,
4180            None,
4181            ts_init,
4182        )
4183        .unwrap()
4184        .unwrap();
4185
4186        // First fill gets rebate (negative)
4187        assert_eq!(fill_report_1.commission, Money::new(-1.0, Currency::USDT()));
4188
4189        // Second fill: taker charge of $5.0, net cumulative is now $2.0 charge
4190        // This is the edge case: incremental = 2.0 - (-1.0) = 3.0, which exceeds total (2.0)
4191        // But it's legitimate, not corruption
4192        let mut order_msg_2 = create_stub_order_msg(
4193            "0.01",
4194            Some("0.02".to_string()),
4195            "transition_order_456",
4196            "trade_transition_2",
4197        );
4198        order_msg_2.cl_ord_id = "test_order_transition".to_string();
4199        order_msg_2.fee = Some("-2.0".to_string());
4200        order_msg_2.fill_time = 1_746_947_317_403;
4201        order_msg_2.state = OKXOrderStatus::Filled;
4202        order_msg_2.sz = "0.02".to_string();
4203        order_msg_2.u_time = 1_746_947_317_403;
4204
4205        let fill_report_2 = parse_fill_report(
4206            &order_msg_2,
4207            &InstrumentAny::CryptoPerpetual(instrument),
4208            account_id,
4209            Some(fill_report_1.commission),
4210            Some(fill_report_1.last_qty),
4211            ts_init,
4212        )
4213        .unwrap()
4214        .unwrap();
4215
4216        // Second fill: incremental = 2.0 - (-1.0) = 3.0
4217        // This should NOT trigger corruption detection because previous was negative
4218        assert_eq!(fill_report_2.commission, Money::new(3.0, Currency::USDT()));
4219    }
4220
4221    #[rstest]
4222    fn test_parse_fill_report_negative_incremental() {
4223        let instrument = create_stub_instrument();
4224
4225        let account_id = AccountId::new("OKX-001");
4226        let ts_init = UnixNanos::default();
4227
4228        // First fill: charge of $2.0
4229        let mut order_msg_1 = create_stub_order_msg(
4230            "0.01",
4231            Some("0.01".to_string()),
4232            "neg_inc_order_789",
4233            "trade_neg_inc_1",
4234        );
4235        order_msg_1.cl_ord_id = "test_order_neg_inc".to_string();
4236        order_msg_1.fee = Some("-2.0".to_string());
4237        order_msg_1.sz = "0.02".to_string();
4238
4239        let fill_report_1 = parse_fill_report(
4240            &order_msg_1,
4241            &InstrumentAny::CryptoPerpetual(instrument.clone()),
4242            account_id,
4243            None,
4244            None,
4245            ts_init,
4246        )
4247        .unwrap()
4248        .unwrap();
4249
4250        assert_eq!(fill_report_1.commission, Money::new(2.0, Currency::USDT()));
4251
4252        // Second fill: charge reduced to $1.5 total (refund or maker rebate on this fill)
4253        // Incremental = 1.5 - 2.0 = -0.5 (negative incremental triggers debug log)
4254        let mut order_msg_2 = create_stub_order_msg(
4255            "0.01",
4256            Some("0.02".to_string()),
4257            "neg_inc_order_789",
4258            "trade_neg_inc_2",
4259        );
4260        order_msg_2.cl_ord_id = "test_order_neg_inc".to_string();
4261        order_msg_2.fee = Some("-1.5".to_string());
4262        order_msg_2.fill_time = 1_746_947_317_403;
4263        order_msg_2.state = OKXOrderStatus::Filled;
4264        order_msg_2.exec_type = OKXExecType::Maker;
4265        order_msg_2.sz = "0.02".to_string();
4266        order_msg_2.u_time = 1_746_947_317_403;
4267
4268        let fill_report_2 = parse_fill_report(
4269            &order_msg_2,
4270            &InstrumentAny::CryptoPerpetual(instrument),
4271            account_id,
4272            Some(fill_report_1.commission),
4273            Some(fill_report_1.last_qty),
4274            ts_init,
4275        )
4276        .unwrap()
4277        .unwrap();
4278
4279        // Incremental is negative: 1.5 - 2.0 = -0.5
4280        assert_eq!(fill_report_2.commission, Money::new(-0.5, Currency::USDT()));
4281    }
4282
4283    #[rstest]
4284    fn test_parse_fill_report_fee_currency_change_no_panic() {
4285        let instrument = create_stub_instrument();
4286        let account_id = AccountId::new("OKX-001");
4287        let ts_init = UnixNanos::default();
4288
4289        // First fill charged in USDT
4290        let previous_fee = Money::new(1.0, Currency::USDT());
4291
4292        // Second fill charged in BTC (fee currency changed)
4293        let mut order_msg =
4294            create_stub_order_msg("0.01", Some("0.02".to_string()), "1234567890", "trade_2");
4295        order_msg.fee = Some("-0.00005".to_string());
4296        order_msg.fee_ccy = Ustr::from("BTC");
4297
4298        let result = parse_fill_report(
4299            &order_msg,
4300            &InstrumentAny::CryptoPerpetual(instrument),
4301            account_id,
4302            Some(previous_fee),
4303            Some(Quantity::from("0.01")),
4304            ts_init,
4305        );
4306
4307        let fill_report = result.unwrap().unwrap();
4308        assert_eq!(fill_report.commission.currency, Currency::BTC());
4309    }
4310
4311    #[rstest]
4312    fn test_parse_fill_report_empty_fill_sz_first_fill() {
4313        let instrument = create_stub_instrument();
4314        let account_id = AccountId::new("OKX-001");
4315        let ts_init = UnixNanos::default();
4316
4317        let order_msg =
4318            create_stub_order_msg("", Some("0.01".to_string()), "1234567890", "trade_1");
4319
4320        let fill_report = parse_fill_report(
4321            &order_msg,
4322            &InstrumentAny::CryptoPerpetual(instrument),
4323            account_id,
4324            None,
4325            None,
4326            ts_init,
4327        )
4328        .unwrap()
4329        .unwrap();
4330
4331        assert_eq!(fill_report.last_qty, Quantity::from("0.01"));
4332    }
4333
4334    #[rstest]
4335    fn test_parse_fill_report_empty_fill_sz_subsequent_fills() {
4336        let instrument = create_stub_instrument();
4337        let account_id = AccountId::new("OKX-001");
4338        let ts_init = UnixNanos::default();
4339
4340        let order_msg_1 =
4341            create_stub_order_msg("", Some("0.01".to_string()), "1234567890", "trade_1");
4342
4343        let fill_report_1 = parse_fill_report(
4344            &order_msg_1,
4345            &InstrumentAny::CryptoPerpetual(instrument.clone()),
4346            account_id,
4347            None,
4348            None,
4349            ts_init,
4350        )
4351        .unwrap()
4352        .unwrap();
4353
4354        assert_eq!(fill_report_1.last_qty, Quantity::from("0.01"));
4355
4356        let order_msg_2 =
4357            create_stub_order_msg("", Some("0.03".to_string()), "1234567890", "trade_2");
4358
4359        let fill_report_2 = parse_fill_report(
4360            &order_msg_2,
4361            &InstrumentAny::CryptoPerpetual(instrument),
4362            account_id,
4363            Some(fill_report_1.commission),
4364            Some(fill_report_1.last_qty),
4365            ts_init,
4366        )
4367        .unwrap()
4368        .unwrap();
4369
4370        assert_eq!(fill_report_2.last_qty, Quantity::from("0.02"));
4371    }
4372
4373    #[rstest]
4374    fn test_parse_fill_report_error_both_empty() {
4375        let instrument = create_stub_instrument();
4376        let account_id = AccountId::new("OKX-001");
4377        let ts_init = UnixNanos::default();
4378
4379        let order_msg = create_stub_order_msg("", Some(String::new()), "1234567890", "trade_1");
4380
4381        let result = parse_fill_report(
4382            &order_msg,
4383            &InstrumentAny::CryptoPerpetual(instrument),
4384            account_id,
4385            None,
4386            None,
4387            ts_init,
4388        );
4389
4390        assert!(result.is_err());
4391        let err_msg = result.unwrap_err().to_string();
4392        assert!(err_msg.contains("Cannot determine fill quantity"));
4393        assert!(err_msg.contains("empty/zero"));
4394    }
4395
4396    #[rstest]
4397    fn test_parse_fill_report_error_acc_fill_sz_none() {
4398        let instrument = create_stub_instrument();
4399        let account_id = AccountId::new("OKX-001");
4400        let ts_init = UnixNanos::default();
4401
4402        let order_msg = create_stub_order_msg("", None, "1234567890", "trade_1");
4403
4404        let result = parse_fill_report(
4405            &order_msg,
4406            &InstrumentAny::CryptoPerpetual(instrument),
4407            account_id,
4408            None,
4409            None,
4410            ts_init,
4411        );
4412
4413        assert!(result.is_err());
4414        let err_msg = result.unwrap_err().to_string();
4415        assert!(err_msg.contains("Cannot determine fill quantity"));
4416        assert!(err_msg.contains("acc_fill_sz is None"));
4417    }
4418
4419    #[rstest]
4420    fn test_parse_fill_report_error_acc_fill_sz_less_than_previous() {
4421        let instrument = create_stub_instrument();
4422        let account_id = AccountId::new("OKX-001");
4423        let ts_init = UnixNanos::default();
4424
4425        // acc_fill_sz (0.01) < previous_filled_qty (0.03) - stale data after reconnect
4426        let order_msg =
4427            create_stub_order_msg("", Some("0.01".to_string()), "1234567890", "trade_2");
4428
4429        let result = parse_fill_report(
4430            &order_msg,
4431            &InstrumentAny::CryptoPerpetual(instrument),
4432            account_id,
4433            None,
4434            Some(Quantity::from("0.03")),
4435            ts_init,
4436        );
4437
4438        assert!(result.is_err());
4439        let err_msg = result.unwrap_err().to_string();
4440        assert!(err_msg.contains("Cumulative fill went backwards"));
4441    }
4442
4443    #[rstest]
4444    fn test_parse_order_msg_acc_fill_sz_only_update() {
4445        // Test that we emit fill reports when OKX only updates acc_fill_sz without fill_sz or trade_id
4446        let instrument = create_stub_instrument();
4447        let account_id = AccountId::new("OKX-001");
4448        let ts_init = UnixNanos::default();
4449
4450        let mut instruments = AHashMap::new();
4451        instruments.insert(
4452            Ustr::from("BTC-USDT-SWAP"),
4453            InstrumentAny::CryptoPerpetual(instrument),
4454        );
4455
4456        let fee_cache = FeeCache::new();
4457        let mut filled_qty_cache = FilledQtyCache::new();
4458
4459        // First update: acc_fill_sz = 0.01, no fill_sz, no trade_id
4460        let msg_1 = create_stub_order_msg("", Some("0.01".to_string()), "1234567890", "");
4461
4462        let report_1 = parse_order_msg(
4463            &msg_1,
4464            account_id,
4465            &instruments,
4466            &fee_cache,
4467            &filled_qty_cache,
4468            ts_init,
4469        )
4470        .unwrap();
4471
4472        // Should generate a fill report (not a status report)
4473        assert!(matches!(report_1, ExecutionReport::Fill(_)));
4474        if let ExecutionReport::Fill(fill) = &report_1 {
4475            assert_eq!(fill.last_qty, Quantity::from("0.01"));
4476        }
4477
4478        // Update cache
4479        filled_qty_cache.record(Ustr::from("1234567890"), Quantity::from("0.01"), false);
4480
4481        // Second update: acc_fill_sz increased to 0.03, still no fill_sz or trade_id
4482        let msg_2 = create_stub_order_msg("", Some("0.03".to_string()), "1234567890", "");
4483
4484        let report_2 = parse_order_msg(
4485            &msg_2,
4486            account_id,
4487            &instruments,
4488            &fee_cache,
4489            &filled_qty_cache,
4490            ts_init,
4491        )
4492        .unwrap();
4493
4494        // Should still generate a fill report for the incremental 0.02
4495        assert!(matches!(report_2, ExecutionReport::Fill(_)));
4496        if let ExecutionReport::Fill(fill) = &report_2 {
4497            assert_eq!(fill.last_qty, Quantity::from("0.02"));
4498        }
4499    }
4500
4501    #[rstest]
4502    fn test_parse_book_depth_msg_partial_levels() {
4503        let book_msg = OKXBookMsg {
4504            asks: vec![
4505                OrderBookEntry {
4506                    price: "8476.98".to_string(),
4507                    size: "415".to_string(),
4508                    liquidated_orders_count: "0".to_string(),
4509                    orders_count: "13".to_string(),
4510                },
4511                OrderBookEntry {
4512                    price: "8477.00".to_string(),
4513                    size: "7".to_string(),
4514                    liquidated_orders_count: "0".to_string(),
4515                    orders_count: "2".to_string(),
4516                },
4517            ],
4518            bids: vec![OrderBookEntry {
4519                price: "8476.97".to_string(),
4520                size: "256".to_string(),
4521                liquidated_orders_count: "0".to_string(),
4522                orders_count: "12".to_string(),
4523            }],
4524            ts: 1_597_026_383_085,
4525            checksum: None,
4526            prev_seq_id: None,
4527            seq_id: 123_456,
4528        };
4529
4530        let instrument_id = InstrumentId::from("BTC-USDT.OKX");
4531        let depth =
4532            parse_book_depth_msg(&book_msg, instrument_id, 2, 0, UnixNanos::default()).unwrap();
4533
4534        assert_eq!(depth.instrument_id, instrument_id);
4535        assert_eq!(depth.bids.len(), 1);
4536        assert_eq!(depth.asks.len(), 2);
4537        assert_eq!(depth.bids[0].price, Price::from("8476.97"));
4538        assert_eq!(depth.bids[0].size, Quantity::from("256"));
4539        assert_eq!(depth.bids[0].side, Some(OrderSide::Buy));
4540        assert_eq!(depth.bids[0].order_id, 0);
4541        assert_eq!(depth.bid_counts.as_slice(), &[12]);
4542        assert_eq!(depth.ask_counts.as_slice(), &[13, 2]);
4543        for (order, (price, size)) in depth
4544            .asks
4545            .iter()
4546            .zip([("8476.98", "415"), ("8477.00", "7")])
4547        {
4548            assert_eq!(order.price, Price::from(price));
4549            assert_eq!(order.size, Quantity::from(size));
4550            assert_eq!(order.side, Some(OrderSide::Sell));
4551            assert_eq!(order.order_id, 0);
4552        }
4553        assert_eq!(depth.sequence, 123_456);
4554        assert_eq!(depth.flags, RecordFlag::F_SNAPSHOT as u8);
4555        assert_eq!(depth.ts_event, UnixNanos::from(1_597_026_383_085_000_000));
4556        assert_eq!(depth.ts_init, UnixNanos::default());
4557    }
4558
4559    #[rstest]
4560    fn test_parse_algo_order_msg_stop_market() {
4561        let json_data = load_test_json("ws_orders_algo.json");
4562        let ws_msg: serde_json::Value = serde_json::from_str(&json_data).unwrap();
4563        let data: Vec<OKXAlgoOrderMsg> = serde_json::from_value(ws_msg["data"].clone()).unwrap();
4564
4565        // Test first algo order (stop market sell)
4566        let msg = &data[0];
4567        assert_eq!(msg.algo_id, "706620792746729472");
4568        assert_eq!(msg.algo_cl_ord_id, "STOP001BTCUSDT20250120");
4569        assert_eq!(msg.state, OKXAlgoOrderStatus::Live);
4570        assert_eq!(msg.ord_px, "-1"); // Market order indicator
4571
4572        let account_id = AccountId::new("OKX-001");
4573        let mut instruments = AHashMap::new();
4574
4575        // Create mock instrument
4576        let instrument = create_stub_instrument();
4577        instruments.insert(
4578            Ustr::from("BTC-USDT-SWAP"),
4579            InstrumentAny::CryptoPerpetual(instrument),
4580        );
4581
4582        let result = parse_algo_order_msg(msg, account_id, &instruments, UnixNanos::default());
4583
4584        let report = result.unwrap().unwrap();
4585
4586        if let ExecutionReport::Order(status_report) = report {
4587            assert_eq!(status_report.order_type, OrderType::StopMarket);
4588            assert_eq!(status_report.order_side, OrderSide::Sell.into());
4589            assert_eq!(status_report.quantity, Quantity::from("0.01000000"));
4590            assert_eq!(status_report.trigger_price, Some(Price::from("95000.00")));
4591            assert_eq!(status_report.trigger_type, Some(TriggerType::LastPrice));
4592            assert_eq!(status_report.price, None); // No limit price for market orders
4593        } else {
4594            panic!("Expected Order report");
4595        }
4596    }
4597
4598    #[rstest]
4599    fn test_parse_algo_order_msg_stop_limit() {
4600        let json_data = load_test_json("ws_orders_algo.json");
4601        let ws_msg: serde_json::Value = serde_json::from_str(&json_data).unwrap();
4602        let data: Vec<OKXAlgoOrderMsg> = serde_json::from_value(ws_msg["data"].clone()).unwrap();
4603
4604        // Test second algo order (stop limit buy)
4605        let msg = &data[1];
4606        assert_eq!(msg.algo_id, "706620792746729473");
4607        assert_eq!(msg.state, OKXAlgoOrderStatus::Live);
4608        assert_eq!(msg.ord_px, "106000"); // Limit price
4609
4610        let account_id = AccountId::new("OKX-001");
4611        let mut instruments = AHashMap::new();
4612
4613        // Create mock instrument
4614        let instrument = create_stub_instrument();
4615        instruments.insert(
4616            Ustr::from("BTC-USDT-SWAP"),
4617            InstrumentAny::CryptoPerpetual(instrument),
4618        );
4619
4620        let result = parse_algo_order_msg(msg, account_id, &instruments, UnixNanos::default());
4621
4622        let report = result.unwrap().unwrap();
4623
4624        if let ExecutionReport::Order(status_report) = report {
4625            assert_eq!(status_report.order_type, OrderType::StopLimit);
4626            assert_eq!(status_report.order_side, OrderSide::Buy.into());
4627            assert_eq!(status_report.quantity, Quantity::from("0.02000000"));
4628            assert_eq!(status_report.trigger_price, Some(Price::from("105000.00")));
4629            assert_eq!(status_report.trigger_type, Some(TriggerType::MarkPrice));
4630            assert_eq!(status_report.price, Some(Price::from("106000.00"))); // Has limit price
4631        } else {
4632            panic!("Expected Order report");
4633        }
4634    }
4635
4636    #[rstest]
4637    fn test_parse_triggered_algo_order_preserves_parent_identity() {
4638        let json_data = load_test_json("ws_orders_algo.json");
4639        let ws_msg: serde_json::Value = serde_json::from_str(&json_data).unwrap();
4640        let data: Vec<OKXAlgoOrderMsg> = serde_json::from_value(ws_msg["data"].clone()).unwrap();
4641        let msg = &data[2];
4642
4643        assert_eq!(msg.state, OKXAlgoOrderStatus::OrderPlaced);
4644        assert_eq!(msg.algo_cl_ord_id, "STOP003BTCUSDT20250120");
4645        assert_eq!(msg.cl_ord_id, "706620792746729474_0");
4646        assert_eq!(msg.actual_sz, "0.01");
4647
4648        let account_id = AccountId::new("OKX-001");
4649        let instrument = create_stub_instrument();
4650        let mut instruments = AHashMap::new();
4651        instruments.insert(
4652            Ustr::from("BTC-USDT-SWAP"),
4653            InstrumentAny::CryptoPerpetual(instrument),
4654        );
4655
4656        let report = parse_algo_order_msg(msg, account_id, &instruments, UnixNanos::default())
4657            .unwrap()
4658            .unwrap();
4659        let ExecutionReport::Order(report) = report else {
4660            panic!("Expected Order report");
4661        };
4662
4663        assert_eq!(
4664            report.client_order_id,
4665            Some(ClientOrderId::from("STOP003BTCUSDT20250120"))
4666        );
4667        assert_eq!(
4668            report.venue_order_id,
4669            VenueOrderId::from("706620792746729999")
4670        );
4671        assert_eq!(report.order_status, OrderStatus::Triggered);
4672        assert_eq!(report.filled_qty, Quantity::from("0.00000000"));
4673    }
4674
4675    #[rstest]
4676    fn test_parse_filled_algo_order_uses_actual_quantity() {
4677        let json_data = load_test_json("ws_orders_algo.json");
4678        let ws_msg: serde_json::Value = serde_json::from_str(&json_data).unwrap();
4679        let data: Vec<OKXAlgoOrderMsg> = serde_json::from_value(ws_msg["data"].clone()).unwrap();
4680        let msg = &data[4];
4681
4682        assert_eq!(msg.state, OKXAlgoOrderStatus::Filled);
4683        assert_eq!(msg.actual_sz, "0.005");
4684
4685        let instrument = create_stub_instrument();
4686        let mut instruments = AHashMap::new();
4687        instruments.insert(
4688            Ustr::from("BTC-USDT-SWAP"),
4689            InstrumentAny::CryptoPerpetual(instrument),
4690        );
4691
4692        let report = parse_algo_order_msg(
4693            msg,
4694            AccountId::new("OKX-001"),
4695            &instruments,
4696            UnixNanos::default(),
4697        )
4698        .unwrap()
4699        .unwrap();
4700        let ExecutionReport::Order(report) = report else {
4701            panic!("Expected Order report");
4702        };
4703
4704        assert_eq!(report.order_status, OrderStatus::Filled);
4705        assert_eq!(report.filled_qty, Quantity::from("0.00500000"));
4706    }
4707
4708    #[rstest]
4709    fn test_parse_trigger_order_from_regular_channel() {
4710        let json_data = load_test_json("ws_orders_trigger.json");
4711        let ws_msg: serde_json::Value = serde_json::from_str(&json_data).unwrap();
4712        let data: Vec<OKXOrderMsg> = serde_json::from_value(ws_msg["data"].clone()).unwrap();
4713
4714        // Test triggered order that came through regular orders channel
4715        let msg = &data[0];
4716        assert_eq!(msg.ord_type, OKXOrderType::Trigger);
4717        assert_eq!(msg.state, OKXOrderStatus::Filled);
4718
4719        let account_id = AccountId::new("OKX-001");
4720        let mut instruments = AHashMap::new();
4721
4722        // Create mock instrument
4723        let instrument = create_stub_instrument();
4724        instruments.insert(
4725            Ustr::from("BTC-USDT-SWAP"),
4726            InstrumentAny::CryptoPerpetual(instrument),
4727        );
4728
4729        let mut fee_cache = FeeCache::new();
4730        let mut filled_qty_cache = FilledQtyCache::new();
4731
4732        let result = parse_order_msg_vec(
4733            std::slice::from_ref(msg),
4734            account_id,
4735            &instruments,
4736            &mut fee_cache,
4737            &mut filled_qty_cache,
4738            UnixNanos::default(),
4739        );
4740
4741        assert!(result.is_ok());
4742        let reports = result.unwrap();
4743        assert_eq!(reports.len(), 1);
4744
4745        if let ExecutionReport::Fill(fill_report) = &reports[0] {
4746            assert_eq!(fill_report.order_side, OrderSide::Sell);
4747            assert_eq!(fill_report.last_qty, Quantity::from("0.01000000"));
4748            assert_eq!(fill_report.last_px, Price::from("101950.00"));
4749        } else {
4750            panic!("Expected Fill report for filled trigger order");
4751        }
4752    }
4753
4754    #[rstest]
4755    fn test_parse_liquidation_order() {
4756        let json_data = load_test_json("ws_orders_liquidation.json");
4757        let ws_msg: serde_json::Value = serde_json::from_str(&json_data).unwrap();
4758        let data: Vec<OKXOrderMsg> = serde_json::from_value(ws_msg["data"].clone()).unwrap();
4759
4760        // Test liquidation order
4761        let msg = &data[0];
4762        assert_eq!(msg.category, OKXOrderCategory::FullLiquidation);
4763        assert_eq!(msg.state, OKXOrderStatus::Filled);
4764        assert_eq!(msg.inst_id, "BTC-USDT-SWAP");
4765
4766        let account_id = AccountId::new("OKX-001");
4767        let mut instruments = AHashMap::new();
4768
4769        // Create mock instrument
4770        let instrument = create_stub_instrument();
4771        instruments.insert(
4772            Ustr::from("BTC-USDT-SWAP"),
4773            InstrumentAny::CryptoPerpetual(instrument),
4774        );
4775        let mut fee_cache = FeeCache::new();
4776        let mut filled_qty_cache = FilledQtyCache::new();
4777
4778        let result = parse_order_msg_vec(
4779            std::slice::from_ref(msg),
4780            account_id,
4781            &instruments,
4782            &mut fee_cache,
4783            &mut filled_qty_cache,
4784            UnixNanos::default(),
4785        );
4786
4787        assert!(result.is_ok());
4788        let reports = result.unwrap();
4789        assert_eq!(reports.len(), 1);
4790
4791        // Verify it's a fill report for a liquidation
4792        if let ExecutionReport::Fill(fill_report) = &reports[0] {
4793            assert_eq!(fill_report.order_side, OrderSide::Sell);
4794            assert_eq!(fill_report.last_qty, Quantity::from("0.50000000"));
4795            assert_eq!(fill_report.last_px, Price::from("40000.00"));
4796            assert_eq!(fill_report.liquidity_side, LiquiditySide::Taker);
4797        } else {
4798            panic!("Expected Fill report for liquidation order");
4799        }
4800    }
4801
4802    #[rstest]
4803    fn test_parse_adl_order() {
4804        let json_data = load_test_json("ws_orders_adl.json");
4805        let ws_msg: serde_json::Value = serde_json::from_str(&json_data).unwrap();
4806        let data: Vec<OKXOrderMsg> = serde_json::from_value(ws_msg["data"].clone()).unwrap();
4807
4808        // Test ADL order
4809        let msg = &data[0];
4810        assert_eq!(msg.category, OKXOrderCategory::Adl);
4811        assert_eq!(msg.state, OKXOrderStatus::Filled);
4812        assert_eq!(msg.inst_id, "ETH-USDT-SWAP");
4813
4814        let account_id = AccountId::new("OKX-001");
4815        let mut instruments = AHashMap::new();
4816
4817        // Create mock instrument
4818        let mut instrument = create_stub_instrument();
4819        instrument.id = InstrumentId::from("ETH-USDT-SWAP.OKX");
4820        instrument.raw_symbol = Symbol::from("ETH-USDT-SWAP");
4821        instrument.base_currency = Currency::ETH();
4822        instruments.insert(
4823            Ustr::from("ETH-USDT-SWAP"),
4824            InstrumentAny::CryptoPerpetual(instrument),
4825        );
4826
4827        let mut fee_cache = FeeCache::new();
4828        let mut filled_qty_cache = FilledQtyCache::new();
4829
4830        let result = parse_order_msg_vec(
4831            std::slice::from_ref(msg),
4832            account_id,
4833            &instruments,
4834            &mut fee_cache,
4835            &mut filled_qty_cache,
4836            UnixNanos::default(),
4837        );
4838
4839        assert!(result.is_ok());
4840        let reports = result.unwrap();
4841        assert_eq!(reports.len(), 1);
4842
4843        // Verify it's a fill report for ADL
4844        if let ExecutionReport::Fill(fill_report) = &reports[0] {
4845            assert_eq!(fill_report.order_side, OrderSide::Buy);
4846            assert_eq!(fill_report.last_qty, Quantity::from("0.30000000"));
4847            assert_eq!(fill_report.last_px, Price::from("41000.00"));
4848            assert_eq!(fill_report.liquidity_side, LiquiditySide::Taker);
4849        } else {
4850            panic!("Expected Fill report for ADL order");
4851        }
4852    }
4853
4854    #[rstest]
4855    fn test_parse_unknown_category_graceful_fallback() {
4856        // Test that unknown/future category values deserialize as Other instead of failing
4857        let json_with_unknown_category = r#"{
4858            "category": "some_future_category_we_dont_know"
4859        }"#;
4860
4861        let result: Result<serde_json::Value, _> = serde_json::from_str(json_with_unknown_category);
4862        result.unwrap();
4863
4864        // Test deserialization of the category field directly
4865        let category_result: Result<OKXOrderCategory, _> =
4866            serde_json::from_str(r#""some_future_category""#);
4867        assert!(category_result.is_ok());
4868        assert_eq!(category_result.unwrap(), OKXOrderCategory::Other);
4869
4870        // Verify known categories still work
4871        let normal: OKXOrderCategory = serde_json::from_str(r#""normal""#).unwrap();
4872        assert_eq!(normal, OKXOrderCategory::Normal);
4873
4874        let twap: OKXOrderCategory = serde_json::from_str(r#""twap""#).unwrap();
4875        assert_eq!(twap, OKXOrderCategory::Twap);
4876    }
4877
4878    #[rstest]
4879    fn test_parse_partial_liquidation_order() {
4880        // Create a test message with partial liquidation category
4881        let account_id = AccountId::new("OKX-001");
4882        let mut instruments = AHashMap::new();
4883
4884        let instrument = create_stub_instrument();
4885        instruments.insert(
4886            Ustr::from("BTC-USDT-SWAP"),
4887            InstrumentAny::CryptoPerpetual(instrument),
4888        );
4889
4890        let mut partial_liq_msg = create_stub_order_msg(
4891            "0.25",
4892            Some("0.25".to_string()),
4893            "2497956918703120888",
4894            "1518905888",
4895        );
4896        partial_liq_msg.avg_px = "39000.0".to_string();
4897        partial_liq_msg.category = OKXOrderCategory::PartialLiquidation;
4898        partial_liq_msg.cl_ord_id = String::new();
4899        partial_liq_msg.fee = Some("-9.75".to_string());
4900        partial_liq_msg.fill_px = "39000.0".to_string();
4901        partial_liq_msg.lever = "10.0".to_string();
4902        partial_liq_msg.pnl = "-2500".to_string();
4903        partial_liq_msg.side = OKXSide::Sell;
4904        partial_liq_msg.state = OKXOrderStatus::Filled;
4905        partial_liq_msg.sz = "0.25".to_string();
4906
4907        let fee_cache = FeeCache::new();
4908        let filled_qty_cache = FilledQtyCache::new();
4909        let result = parse_order_msg(
4910            &partial_liq_msg,
4911            account_id,
4912            &instruments,
4913            &fee_cache,
4914            &filled_qty_cache,
4915            UnixNanos::default(),
4916        );
4917
4918        assert!(result.is_ok());
4919        let report = result.unwrap();
4920
4921        // Verify it's a fill report for partial liquidation
4922        if let ExecutionReport::Fill(fill_report) = report {
4923            assert_eq!(fill_report.order_side, OrderSide::Sell);
4924            assert_eq!(fill_report.last_qty, Quantity::from("0.25000000"));
4925            assert_eq!(fill_report.last_px, Price::from("39000.00"));
4926        } else {
4927            panic!("Expected Fill report for partial liquidation order");
4928        }
4929    }
4930
4931    #[rstest]
4932    fn test_parse_mmp_canceled_order_message() {
4933        use nautilus_model::instruments::stubs::crypto_option_btc_deribit;
4934
4935        let json_data = load_test_json("ws_orders_mmp_canceled.json");
4936        let ws_msg: serde_json::Value = serde_json::from_str(&json_data).unwrap();
4937        let data: Vec<OKXOrderMsg> = serde_json::from_value(ws_msg["data"].clone()).unwrap();
4938
4939        let msg = &data[0];
4940        assert_eq!(msg.state, OKXOrderStatus::MmpCanceled);
4941        assert_eq!(msg.ord_type, OKXOrderType::MmpAndPostOnly);
4942
4943        let account_id = AccountId::new("OKX-001");
4944        let mut instruments = AHashMap::new();
4945        let instrument_id = InstrumentId::from("BTC-USD-250328-92000-C.OKX");
4946        let mut option =
4947            crypto_option_btc_deribit(3, 1, Price::from("0.001"), Quantity::from("0.1"));
4948        option.id = instrument_id;
4949        option.raw_symbol = Symbol::from("BTC-USD-250328-92000-C");
4950        instruments.insert(
4951            Ustr::from("BTC-USD-250328-92000-C"),
4952            InstrumentAny::CryptoOption(option),
4953        );
4954
4955        let fee_cache = FeeCache::new();
4956        let filled_qty_cache = FilledQtyCache::new();
4957        let report = parse_order_msg(
4958            msg,
4959            account_id,
4960            &instruments,
4961            &fee_cache,
4962            &filled_qty_cache,
4963            UnixNanos::default(),
4964        )
4965        .unwrap();
4966
4967        match report {
4968            ExecutionReport::Order(report) => {
4969                // MMP cancels map to Canceled with the venue reason preserved
4970                assert_eq!(report.order_status, OrderStatus::Canceled);
4971                assert_eq!(report.instrument_id, instrument_id);
4972                assert!(
4973                    report
4974                        .cancel_reason
4975                        .as_ref()
4976                        .is_some_and(|reason| reason.as_str().contains("market maker protection")),
4977                );
4978            }
4979            other => panic!("Expected Order report for MMP-canceled order, was {other:?}"),
4980        }
4981    }
4982
4983    #[rstest]
4984    fn test_parse_order_msg_unknown_state_preserves_fill() {
4985        let json_data = load_test_json("ws_orders_unknown_state_fill.json");
4986        let ws_msg: serde_json::Value = serde_json::from_str(&json_data).unwrap();
4987        let data: Vec<OKXOrderMsg> = serde_json::from_value(ws_msg["data"].clone()).unwrap();
4988
4989        // Unknown states fall back to `Unknown` instead of failing deserialization
4990        let msg = &data[0];
4991        assert_eq!(msg.state, OKXOrderStatus::Unknown);
4992
4993        let account_id = AccountId::new("OKX-001");
4994        let mut instruments = AHashMap::new();
4995        instruments.insert(
4996            Ustr::from("BTC-USDT-SWAP"),
4997            InstrumentAny::CryptoPerpetual(create_stub_instrument()),
4998        );
4999
5000        let fee_cache = FeeCache::new();
5001        let filled_qty_cache = FilledQtyCache::new();
5002        let report = parse_order_msg(
5003            msg,
5004            account_id,
5005            &instruments,
5006            &fee_cache,
5007            &filled_qty_cache,
5008            UnixNanos::default(),
5009        )
5010        .unwrap();
5011
5012        // Fill data is processed even when the state itself is unrecognized
5013        match report {
5014            ExecutionReport::Fill(fill_report) => {
5015                assert_eq!(fill_report.order_side, OrderSide::Buy);
5016                assert_eq!(fill_report.last_qty, Quantity::from("0.25000000"));
5017                assert_eq!(fill_report.last_px, Price::from("40000.00"));
5018                assert_eq!(fill_report.liquidity_side, LiquiditySide::Taker);
5019            }
5020            other => panic!("Expected Fill report for unknown-state order, was {other:?}"),
5021        }
5022    }
5023
5024    #[rstest]
5025    fn test_parse_order_msg_unknown_state_without_fill_errors() {
5026        let json_data = load_test_json("ws_orders_unknown_state_fill.json");
5027        let ws_msg: serde_json::Value = serde_json::from_str(&json_data).unwrap();
5028        let data: Vec<OKXOrderMsg> = serde_json::from_value(ws_msg["data"].clone()).unwrap();
5029
5030        let mut msg = data[0].clone();
5031        msg.fill_sz = "0".to_string();
5032        msg.trade_id = String::new();
5033        msg.acc_fill_sz = Some("0".to_string());
5034
5035        let account_id = AccountId::new("OKX-001");
5036        let mut instruments = AHashMap::new();
5037        instruments.insert(
5038            Ustr::from("BTC-USDT-SWAP"),
5039            InstrumentAny::CryptoPerpetual(create_stub_instrument()),
5040        );
5041
5042        let fee_cache = FeeCache::new();
5043        let filled_qty_cache = FilledQtyCache::new();
5044        let result = parse_order_msg(
5045            &msg,
5046            account_id,
5047            &instruments,
5048            &fee_cache,
5049            &filled_qty_cache,
5050            UnixNanos::default(),
5051        );
5052
5053        // Without fill data there is nothing safe to emit for an unrecognized state
5054        assert!(result.is_err());
5055    }
5056
5057    #[rstest]
5058    fn test_parse_order_msg_unknown_order_type_preserves_fill() {
5059        let json_data = load_test_json("ws_orders_unknown_ord_type_fill.json");
5060        let ws_msg: serde_json::Value = serde_json::from_str(&json_data).unwrap();
5061        let data: Vec<OKXOrderMsg> = serde_json::from_value(ws_msg["data"].clone()).unwrap();
5062
5063        // Unknown order types fall back to `Other` instead of failing deserialization
5064        let msg = &data[0];
5065        assert_eq!(msg.ord_type, OKXOrderType::Other);
5066
5067        let account_id = AccountId::new("OKX-001");
5068        let mut instruments = AHashMap::new();
5069        instruments.insert(
5070            Ustr::from("BTC-USDT-SWAP"),
5071            InstrumentAny::CryptoPerpetual(create_stub_instrument()),
5072        );
5073
5074        let fee_cache = FeeCache::new();
5075        let filled_qty_cache = FilledQtyCache::new();
5076        let report = parse_order_msg(
5077            msg,
5078            account_id,
5079            &instruments,
5080            &fee_cache,
5081            &filled_qty_cache,
5082            UnixNanos::default(),
5083        )
5084        .unwrap();
5085
5086        match report {
5087            ExecutionReport::Fill(fill_report) => {
5088                assert_eq!(fill_report.order_side, OrderSide::Sell);
5089                assert_eq!(fill_report.last_qty, Quantity::from("0.25000000"));
5090                assert_eq!(fill_report.last_px, Price::from("40000.00"));
5091            }
5092            other => panic!("Expected Fill report for unknown-ord-type order, was {other:?}"),
5093        }
5094    }
5095
5096    #[rstest]
5097    fn test_deserialize_liquidation_warning_message() {
5098        let json_data = load_test_json("ws_liquidation_warning.json");
5099        let payload: serde_json::Value = serde_json::from_str(&json_data).unwrap();
5100        let data: Vec<OKXLiquidationWarningMsg> =
5101            serde_json::from_value(payload["data"].clone()).unwrap();
5102
5103        assert_eq!(data.len(), 1);
5104        let warning = &data[0];
5105        assert_eq!(warning.inst_id, Ustr::from("BTC-USDT-SWAP"));
5106        assert_eq!(warning.inst_type, OKXInstrumentType::Swap);
5107        assert_eq!(warning.mgn_mode, OKXMarginMode::Cross);
5108        assert_eq!(warning.pos_side, OKXPositionSide::Long);
5109        assert_eq!(warning.pos, "0.5");
5110        assert_eq!(warning.mgn_ratio, "0.62");
5111        assert_eq!(warning.mark_px, "41250.5");
5112        assert_eq!(warning.c_time, 1_622_559_930_237);
5113        assert_eq!(warning.u_time, 1_788_000_000_001);
5114        assert_eq!(warning.p_time.as_deref(), Some("1788000000002"));
5115    }
5116
5117    #[rstest]
5118    fn test_websocket_instrument_update_preserves_cached_fees() {
5119        use nautilus_model::{identifiers::InstrumentId, instruments::InstrumentAny};
5120
5121        use crate::common::{models::OKXInstrument, parse::parse_instrument_any};
5122
5123        let ts_init = UnixNanos::default();
5124
5125        // Deserialize the initial instrument from JSON.
5126        let initial_inst_json = serde_json::json!({
5127            "instType": "SPOT",
5128            "instId": "BTC-USD",
5129            "baseCcy": "BTC",
5130            "quoteCcy": "USD",
5131            "settleCcy": "",
5132            "ctVal": "",
5133            "ctMult": "",
5134            "ctValCcy": "",
5135            "optType": "",
5136            "stk": "",
5137            "listTime": "1733454000000",
5138            "expTime": "",
5139            "lever": "",
5140            "tickSz": "0.1",
5141            "lotSz": "0.00000001",
5142            "minSz": "0.00001",
5143            "ctType": "linear",
5144            "alias": "",
5145            "state": "live",
5146            "maxLmtSz": "9999999999",
5147            "maxMktSz": "1000000",
5148            "maxTwapSz": "9999999999.0000000000000000",
5149            "maxIcebergSz": "9999999999.0000000000000000",
5150            "maxTriggerSz": "9999999999.0000000000000000",
5151            "maxStopSz": "1000000",
5152            "uly": "",
5153            "instFamily": "",
5154            "ruleType": "normal",
5155            "maxLmtAmt": "20000000",
5156            "maxMktAmt": "1000000"
5157        });
5158
5159        let initial_inst: OKXInstrument = serde_json::from_value(initial_inst_json)
5160            .expect("Failed to deserialize initial instrument");
5161
5162        // Parse the initial instrument.
5163        let parsed_initial = parse_instrument_any(&initial_inst, None, None, ts_init)
5164            .expect("Failed to parse initial instrument")
5165            .expect("Initial instrument should not be None");
5166
5167        let InstrumentAny::CurrencyPair(_) = parsed_initial else {
5168            panic!("Expected CurrencyPair instrument");
5169        };
5170
5171        // Build instrument cache with the initial instrument
5172        let mut instruments_cache = AHashMap::new();
5173        instruments_cache.insert(Ustr::from("BTC-USD"), parsed_initial);
5174
5175        // Create WebSocket update message (same structure as initial, simulating a WebSocket update)
5176        let ws_update = serde_json::json!({
5177            "instType": "SPOT",
5178            "instId": "BTC-USD",
5179            "baseCcy": "BTC",
5180            "quoteCcy": "USD",
5181            "settleCcy": "",
5182            "ctVal": "",
5183            "ctMult": "",
5184            "ctValCcy": "",
5185            "optType": "",
5186            "stk": "",
5187            "listTime": "1733454000000",
5188            "expTime": "",
5189            "lever": "",
5190            "tickSz": "0.1",
5191            "lotSz": "0.00000001",
5192            "minSz": "0.00001",
5193            "ctType": "linear",
5194            "alias": "",
5195            "state": "live",
5196            "maxLmtSz": "9999999999",
5197            "maxMktSz": "1000000",
5198            "maxTwapSz": "9999999999.0000000000000000",
5199            "maxIcebergSz": "9999999999.0000000000000000",
5200            "maxTriggerSz": "9999999999.0000000000000000",
5201            "maxStopSz": "1000000",
5202            "uly": "",
5203            "instFamily": "",
5204            "ruleType": "normal",
5205            "maxLmtAmt": "20000000",
5206            "maxMktAmt": "1000000"
5207        });
5208
5209        let instrument_id = InstrumentId::from("BTC-USD.OKX");
5210        let mut funding_cache = AHashMap::new();
5211
5212        // Parse WebSocket update with cache
5213        let result = parse_ws_message_data(
5214            &OKXWsChannel::Instruments,
5215            ws_update,
5216            &instrument_id,
5217            2,
5218            8,
5219            ts_init,
5220            &mut funding_cache,
5221            &instruments_cache,
5222        )
5223        .expect("Failed to parse WebSocket instrument update");
5224
5225        if let Some(NautilusWsMessage::Instrument(boxed_inst, _status)) = result {
5226            let InstrumentAny::CurrencyPair(_) = *boxed_inst else {
5227                panic!("Expected CurrencyPair instrument from WebSocket update");
5228            };
5229        } else {
5230            panic!("Expected Instrument message from WebSocket update");
5231        }
5232    }
5233
5234    #[rstest]
5235    #[case::fok_order(OKXOrderType::Fok, TimeInForce::Fok)]
5236    #[case::ioc_order(OKXOrderType::Ioc, TimeInForce::Ioc)]
5237    #[case::optimal_limit_ioc_order(OKXOrderType::OptimalLimitIoc, TimeInForce::Ioc)]
5238    #[case::market_order(OKXOrderType::Market, TimeInForce::Gtc)]
5239    #[case::limit_order(OKXOrderType::Limit, TimeInForce::Gtc)]
5240    fn test_parse_time_in_force_from_ord_type(
5241        #[case] okx_ord_type: OKXOrderType,
5242        #[case] expected_tif: TimeInForce,
5243    ) {
5244        let payload: Value = serde_json::from_str(&load_test_json("ws_orders.json")).unwrap();
5245        let mut msg: OKXOrderMsg = serde_json::from_value(payload["data"][0].clone()).unwrap();
5246        msg.ord_type = okx_ord_type;
5247        msg.px = if okx_ord_type == OKXOrderType::Market {
5248            String::new()
5249        } else {
5250            "50000.0".to_string()
5251        };
5252
5253        let instrument = InstrumentAny::CryptoPerpetual(create_stub_instrument());
5254
5255        let report = parse_order_status_report(
5256            &msg,
5257            &instrument,
5258            AccountId::new("OKX-001"),
5259            UnixNanos::default(),
5260        )
5261        .unwrap();
5262
5263        assert_eq!(report.time_in_force, expected_tif);
5264    }
5265
5266    #[rstest]
5267    #[case::fok("ws_orders_fok.json", OKXOrderType::Fok, "FOK-TEST-001", "BTC-USDT")]
5268    #[case::ioc("ws_orders_ioc.json", OKXOrderType::Ioc, "IOC-TEST-001", "BTC-USDT")]
5269    #[case::optimal_limit_ioc(
5270        "ws_orders_optimal_limit_ioc.json",
5271        OKXOrderType::OptimalLimitIoc,
5272        "OPTIMAL-IOC-TEST-001",
5273        "BTC-USDT-SWAP"
5274    )]
5275    fn test_deserialize_time_in_force_order_message(
5276        #[case] fixture: &str,
5277        #[case] expected_ord_type: OKXOrderType,
5278        #[case] expected_client_order_id: &str,
5279        #[case] expected_instrument: &str,
5280    ) {
5281        let json_data = load_test_json(fixture);
5282        let ws_msg: Value = serde_json::from_str(&json_data).unwrap();
5283        let data: Vec<OKXOrderMsg> = serde_json::from_value(ws_msg["data"].clone()).unwrap();
5284
5285        assert!(!data.is_empty());
5286        assert_eq!(data[0].ord_type, expected_ord_type);
5287        assert_eq!(data[0].cl_ord_id, expected_client_order_id);
5288        assert_eq!(data[0].inst_id, Ustr::from(expected_instrument));
5289    }
5290
5291    #[rstest]
5292    fn test_deserialize_regular_order_message() {
5293        let json_data = load_test_json("ws_orders.json");
5294        let payload: serde_json::Value = serde_json::from_str(&json_data).unwrap();
5295        let data: Vec<OKXOrderMsg> = serde_json::from_value(payload["data"].clone()).unwrap();
5296
5297        assert!(!data.is_empty());
5298        assert_eq!(data[0].inst_id, Ustr::from("BTC-USDT-SWAP"));
5299        assert_eq!(data[0].state, OKXOrderStatus::Filled);
5300        assert_eq!(data[0].category, OKXOrderCategory::Normal);
5301        assert_eq!(data[0].rebate.as_deref(), Some("0"));
5302        assert_eq!(data[0].rebate_ccy.as_deref(), Some("USDT"));
5303        assert_eq!(data[0].stp_mode, OKXSelfTradePreventionMode::CancelMaker);
5304        assert!(data[0].linked_algo_ord.is_some());
5305        assert_eq!(data[0].tag.as_deref(), Some(""));
5306        assert_eq!(data[0].source.as_deref(), Some(""));
5307    }
5308
5309    #[rstest]
5310    fn test_deserialize_algo_order_missing_trigger_px_type() {
5311        // algo-advance channel messages omit triggerPxType
5312        let mut value =
5313            serde_json::to_value(stub_algo_order_msg(OKXAlgoOrderType::MoveOrderStop)).unwrap();
5314        value.as_object_mut().unwrap().remove("triggerPxType");
5315        // OKX omits optional string fields rather than sending null
5316        value.as_object_mut().unwrap().retain(|_, v| !v.is_null());
5317        value["cTime"] = Value::String("1706000000000".to_string());
5318        value["uTime"] = Value::String("1706000001000".to_string());
5319
5320        let msg: OKXAlgoOrderMsg = serde_json::from_value(value).unwrap();
5321
5322        assert_eq!(msg.trigger_px_type, OKXTriggerType::None);
5323        assert_eq!(msg.ord_type, OKXAlgoOrderType::MoveOrderStop);
5324    }
5325
5326    #[rstest]
5327    fn test_deserialize_ticker_message() {
5328        let json_data = load_test_json("ws_tickers.json");
5329        let payload: serde_json::Value = serde_json::from_str(&json_data).unwrap();
5330        let data: Vec<OKXTickerMsg> = serde_json::from_value(payload["data"].clone()).unwrap();
5331
5332        assert!(!data.is_empty());
5333        assert_eq!(data[0].inst_id, Ustr::from("BTC-USDT"));
5334        assert_eq!(data[0].last_px, "9999.99");
5335    }
5336
5337    #[rstest]
5338    fn test_deserialize_funding_rate_message() {
5339        let json_data = load_test_json("ws_funding_rate.json");
5340        let payload: serde_json::Value = serde_json::from_str(&json_data).unwrap();
5341        let data: Vec<OKXFundingRateMsg> = serde_json::from_value(payload["data"].clone()).unwrap();
5342
5343        assert!(!data.is_empty());
5344        assert_eq!(data[0].inst_id, Ustr::from("BTC-USDT-SWAP"));
5345    }
5346
5347    #[rstest]
5348    fn test_deserialize_trade_message() {
5349        let json_data = load_test_json("ws_trades.json");
5350        let payload: serde_json::Value = serde_json::from_str(&json_data).unwrap();
5351        let data: Vec<OKXTradeMsg> = serde_json::from_value(payload["data"].clone()).unwrap();
5352
5353        assert!(!data.is_empty());
5354        assert_eq!(data[0].inst_id, Ustr::from("BTC-USD"));
5355    }
5356
5357    fn create_order_msg_for_event_test(
5358        state: OKXOrderStatus,
5359        cl_ord_id: &str,
5360        ord_id: &str,
5361        px: &str,
5362        sz: &str,
5363    ) -> OKXOrderMsg {
5364        let mut msg = create_stub_order_msg("", Some("0".to_string()), ord_id, "");
5365        msg.cl_ord_id = cl_ord_id.to_string();
5366        msg.fee = Some("0".to_string());
5367        msg.fill_px = String::new();
5368        msg.fill_time = 0;
5369        msg.ord_type = OKXOrderType::Limit;
5370        msg.px = px.to_string();
5371        msg.state = state;
5372        msg.sz = sz.to_string();
5373        msg
5374    }
5375
5376    fn create_spread_order_msg_for_event_test(
5377        state: OKXOrderStatus,
5378        cl_ord_id: &str,
5379        ord_id: &str,
5380        px: &str,
5381        sz: &str,
5382    ) -> OKXSpreadOrder {
5383        OKXSpreadOrder {
5384            sprd_id: Ustr::from("BTC-USDT_BTC-USDT-SWAP"),
5385            ord_id: Ustr::from(ord_id),
5386            cl_ord_id: Ustr::from(cl_ord_id),
5387            tag: String::new(),
5388            side: OKXSide::Buy,
5389            ord_type: OKXOrderType::Limit,
5390            sz: sz.to_string(),
5391            px: px.to_string(),
5392            avg_px: String::new(),
5393            state,
5394            acc_fill_sz: "0".to_string(),
5395            pending_fill_sz: "0".to_string(),
5396            pending_settle_sz: "0".to_string(),
5397            canceled_sz: "0".to_string(),
5398            fill_sz: String::new(),
5399            fill_px: String::new(),
5400            trade_id: Ustr::default(),
5401            cancel_source: String::new(),
5402            req_id: String::new(),
5403            amend_result: String::new(),
5404            code: String::new(),
5405            msg: String::new(),
5406            c_time: Some(1_746_947_317_401),
5407            u_time: Some(1_746_947_317_402),
5408        }
5409    }
5410
5411    #[rstest]
5412    fn test_deserialize_spread_orders_message() {
5413        let json_data = load_test_json("ws_sprd_orders.json");
5414        let frame: OKXWsFrame = serde_json::from_str(&json_data).unwrap();
5415
5416        match frame {
5417            OKXWsFrame::Data { arg, data } => {
5418                let orders: Vec<OKXSpreadOrder> = serde_json::from_value(data).unwrap();
5419
5420                assert_eq!(arg.channel, OKXWsChannel::SprdOrders);
5421                assert_eq!(orders.len(), 1);
5422                assert_eq!(orders[0].sprd_id, Ustr::from("BCH-USDT_BCH-USDT-SWAP"));
5423                assert_eq!(orders[0].ord_id, Ustr::from("3386544889978159104"));
5424                assert_eq!(orders[0].state, OKXOrderStatus::Live);
5425            }
5426            other => panic!("Expected Data, was {other:?}"),
5427        }
5428    }
5429
5430    #[rstest]
5431    fn test_synthesize_trade_id_is_deterministic_and_under_36_chars() {
5432        let mut msg = create_order_msg_for_event_test(
5433            OKXOrderStatus::Filled,
5434            "client-1",
5435            "venue-1",
5436            "50000.0",
5437            "0.001",
5438        );
5439        msg.fill_px = "50000.0".to_string();
5440        msg.fill_sz = "0.001".to_string();
5441        msg.fill_time = 1_746_947_317_500;
5442        msg.acc_fill_sz = Some("0.001".to_string());
5443
5444        let id1 = synthesize_trade_id(&msg);
5445        let id2 = synthesize_trade_id(&msg);
5446
5447        assert_eq!(id1, id2, "synthesized id must be deterministic");
5448        assert!(
5449            id1.len() <= 36,
5450            "synthesized id must fit in TradeId, was {}",
5451            id1.len()
5452        );
5453        assert!(id1.starts_with("synth-"));
5454    }
5455
5456    #[rstest]
5457    fn test_synthesize_trade_id_changes_with_fill_fields() {
5458        let mut msg = create_order_msg_for_event_test(
5459            OKXOrderStatus::Filled,
5460            "client-1",
5461            "venue-1",
5462            "50000.0",
5463            "0.001",
5464        );
5465        msg.fill_px = "50000.0".to_string();
5466        msg.fill_sz = "0.001".to_string();
5467        msg.fill_time = 1_746_947_317_500;
5468        msg.acc_fill_sz = Some("0.001".to_string());
5469
5470        let baseline = synthesize_trade_id(&msg);
5471
5472        msg.fill_sz = "0.002".to_string();
5473        let different_size = synthesize_trade_id(&msg);
5474        assert_ne!(baseline, different_size);
5475
5476        msg.fill_sz = "0.001".to_string();
5477        msg.fill_time = 1_746_947_317_999;
5478        let different_time = synthesize_trade_id(&msg);
5479        assert_ne!(baseline, different_time);
5480    }
5481
5482    #[rstest]
5483    fn test_empty_trade_id_fill_deduped_across_replays() {
5484        use crate::websocket::dispatch::WsDispatchState;
5485
5486        // Two identical fill messages with no venue trade_id - the dedup in
5487        // `WsDispatchState::check_and_insert_trade` must suppress the replay.
5488        // Regression lock for the empty-trade_id UUID fabrication bug: if
5489        // `synthesize_trade_id` drifts back to a non-deterministic id, the
5490        // second `check_and_insert_trade` would return false (not a dupe)
5491        // and this test fails.
5492        let mut msg = create_order_msg_for_event_test(
5493            OKXOrderStatus::Filled,
5494            "client-1",
5495            "venue-1",
5496            "50000.0",
5497            "0.001",
5498        );
5499        msg.trade_id = String::new();
5500        msg.fill_px = "50000.0".to_string();
5501        msg.fill_sz = "0.001".to_string();
5502        msg.fill_time = 1_746_947_317_500;
5503        msg.acc_fill_sz = Some("0.001".to_string());
5504
5505        let first_id = TradeId::new(synthesize_trade_id(&msg));
5506        let second_id = TradeId::new(synthesize_trade_id(&msg));
5507        assert_eq!(first_id, second_id, "synthesized id must survive replay");
5508
5509        let state = WsDispatchState::default();
5510        assert!(
5511            !state.check_and_insert_trade(first_id),
5512            "first insert is not a duplicate"
5513        );
5514        assert!(
5515            state.check_and_insert_trade(second_id),
5516            "replayed fill with empty trade_id must dedup"
5517        );
5518    }
5519
5520    #[rstest]
5521    fn test_parse_order_event_live_returns_accepted() {
5522        let instrument = create_stub_instrument();
5523        let msg = create_order_msg_for_event_test(
5524            OKXOrderStatus::Live,
5525            "test_client_123",
5526            "venue_456",
5527            "50000.0",
5528            "0.01",
5529        );
5530
5531        let client_order_id = ClientOrderId::new("test_client_123");
5532        let account_id = AccountId::new("OKX-001");
5533        let trader_id = TraderId::new("TRADER-001");
5534        let strategy_id = StrategyId::new("STRATEGY-001");
5535        let ts_init = UnixNanos::from(1_000_000_000);
5536
5537        let result = parse_order_event(
5538            &msg,
5539            client_order_id,
5540            account_id,
5541            trader_id,
5542            strategy_id,
5543            &InstrumentAny::CryptoPerpetual(instrument),
5544            None,
5545            None,
5546            None,
5547            ts_init,
5548        );
5549
5550        assert!(result.is_ok());
5551        match result.unwrap() {
5552            ParsedOrderEvent::Accepted(accepted) => {
5553                assert_eq!(accepted.client_order_id, client_order_id);
5554                assert_eq!(accepted.venue_order_id, VenueOrderId::new("venue_456"));
5555                assert_eq!(accepted.trader_id, trader_id);
5556                assert_eq!(accepted.strategy_id, strategy_id);
5557            }
5558            other => panic!("Expected Accepted, was {other:?}"),
5559        }
5560    }
5561
5562    #[rstest]
5563    fn test_parse_spread_order_event_live_returns_accepted() {
5564        let instrument = create_stub_instrument();
5565        let msg = create_spread_order_msg_for_event_test(
5566            OKXOrderStatus::Live,
5567            "test_client_123",
5568            "venue_456",
5569            "1.0",
5570            "0.01",
5571        );
5572        let client_order_id = ClientOrderId::new("test_client_123");
5573        let account_id = AccountId::new("OKX-001");
5574        let trader_id = TraderId::new("TRADER-001");
5575        let strategy_id = StrategyId::new("STRATEGY-001");
5576        let ts_init = UnixNanos::from(1_000_000_000);
5577
5578        let result = parse_spread_order_event(
5579            &msg,
5580            client_order_id,
5581            account_id,
5582            trader_id,
5583            strategy_id,
5584            &InstrumentAny::CryptoPerpetual(instrument),
5585            None,
5586            None,
5587            ts_init,
5588        );
5589
5590        match result.unwrap() {
5591            ParsedOrderEvent::Accepted(accepted) => {
5592                assert_eq!(accepted.client_order_id, client_order_id);
5593                assert_eq!(accepted.venue_order_id, VenueOrderId::new("venue_456"));
5594                assert_eq!(accepted.account_id, account_id);
5595            }
5596            other => panic!("Expected Accepted, was {other:?}"),
5597        }
5598    }
5599
5600    #[rstest]
5601    fn test_parse_spread_order_event_canceled_returns_canceled() {
5602        let instrument = create_stub_instrument();
5603        let msg = create_spread_order_msg_for_event_test(
5604            OKXOrderStatus::Canceled,
5605            "test_client_123",
5606            "venue_456",
5607            "1.0",
5608            "0.01",
5609        );
5610        let client_order_id = ClientOrderId::new("test_client_123");
5611        let account_id = AccountId::new("OKX-001");
5612        let trader_id = TraderId::new("TRADER-001");
5613        let strategy_id = StrategyId::new("STRATEGY-001");
5614        let ts_init = UnixNanos::from(1_000_000_000);
5615
5616        let result = parse_spread_order_event(
5617            &msg,
5618            client_order_id,
5619            account_id,
5620            trader_id,
5621            strategy_id,
5622            &InstrumentAny::CryptoPerpetual(instrument),
5623            None,
5624            None,
5625            ts_init,
5626        );
5627
5628        match result.unwrap() {
5629            ParsedOrderEvent::Canceled(canceled) => {
5630                assert_eq!(canceled.client_order_id, client_order_id);
5631                assert_eq!(
5632                    canceled.venue_order_id,
5633                    Some(VenueOrderId::new("venue_456"))
5634                );
5635                assert_eq!(canceled.account_id, Some(account_id));
5636            }
5637            other => panic!("Expected Canceled, was {other:?}"),
5638        }
5639    }
5640
5641    #[rstest]
5642    fn test_parse_spread_order_event_filled_returns_fill() {
5643        let instrument = create_stub_instrument();
5644        let mut msg = create_spread_order_msg_for_event_test(
5645            OKXOrderStatus::Filled,
5646            "test_client_123",
5647            "venue_456",
5648            "1.0",
5649            "0.01",
5650        );
5651        msg.fill_sz = "0.01".to_string();
5652        msg.fill_px = "1.0".to_string();
5653        msg.trade_id = Ustr::from("trade_789");
5654        msg.acc_fill_sz = "0.01".to_string();
5655
5656        let client_order_id = ClientOrderId::new("test_client_123");
5657        let account_id = AccountId::new("OKX-001");
5658        let trader_id = TraderId::new("TRADER-001");
5659        let strategy_id = StrategyId::new("STRATEGY-001");
5660        let ts_init = UnixNanos::from(1_000_000_000);
5661
5662        let result = parse_spread_order_event(
5663            &msg,
5664            client_order_id,
5665            account_id,
5666            trader_id,
5667            strategy_id,
5668            &InstrumentAny::CryptoPerpetual(instrument),
5669            None,
5670            None,
5671            ts_init,
5672        );
5673
5674        let error = result.unwrap_err();
5675        assert!(error.to_string().contains("missing fee"));
5676    }
5677
5678    #[rstest]
5679    fn test_parse_spread_order_fill_report_uses_incremental_acc_fill_sz() {
5680        let instrument = create_stub_instrument();
5681        let mut msg = create_spread_order_msg_for_event_test(
5682            OKXOrderStatus::PartiallyFilled,
5683            "test_client_123",
5684            "venue_456",
5685            "1.0",
5686            "0.03",
5687        );
5688        msg.acc_fill_sz = "0.03".to_string();
5689        msg.fill_sz = String::new();
5690        msg.fill_px = String::new();
5691
5692        let error = parse_spread_order_fill_report(
5693            &msg,
5694            &InstrumentAny::CryptoPerpetual(instrument),
5695            AccountId::new("OKX-001"),
5696            Some(Quantity::from("0.01000000")),
5697            UnixNanos::from(1_000_000_000),
5698        )
5699        .unwrap_err();
5700
5701        assert!(error.to_string().contains("missing fee"));
5702        assert!(error.to_string().contains("sprd-orders updates omit fee"));
5703    }
5704
5705    #[rstest]
5706    fn test_parse_spread_order_fill_report_skips_duplicate_acc_fill_sz() {
5707        let instrument = create_stub_instrument();
5708        let mut msg = create_spread_order_msg_for_event_test(
5709            OKXOrderStatus::PartiallyFilled,
5710            "test_client_123",
5711            "venue_456",
5712            "1.0",
5713            "0.01",
5714        );
5715        msg.acc_fill_sz = "0.01".to_string();
5716        msg.fill_sz = String::new();
5717        msg.fill_px = String::new();
5718
5719        let result = parse_spread_order_fill_report(
5720            &msg,
5721            &InstrumentAny::CryptoPerpetual(instrument),
5722            AccountId::new("OKX-001"),
5723            Some(Quantity::from("0.01000000")),
5724            UnixNanos::from(1_000_000_000),
5725        )
5726        .unwrap();
5727
5728        assert!(result.is_none());
5729    }
5730
5731    #[rstest]
5732    fn test_parse_spread_order_fill_report_rejects_regressed_acc_fill_sz() {
5733        let instrument = create_stub_instrument();
5734        let mut msg = create_spread_order_msg_for_event_test(
5735            OKXOrderStatus::PartiallyFilled,
5736            "test_client_123",
5737            "venue_456",
5738            "1.0",
5739            "0.01",
5740        );
5741        msg.acc_fill_sz = "0.01".to_string();
5742        msg.fill_sz = String::new();
5743        msg.fill_px = String::new();
5744
5745        let error = parse_spread_order_fill_report(
5746            &msg,
5747            &InstrumentAny::CryptoPerpetual(instrument),
5748            AccountId::new("OKX-001"),
5749            Some(Quantity::from("0.03000000")),
5750            UnixNanos::from(1_000_000_000),
5751        )
5752        .unwrap_err();
5753
5754        assert!(
5755            error
5756                .to_string()
5757                .contains("Cumulative spread fill went backwards")
5758        );
5759    }
5760
5761    #[rstest]
5762    fn test_parse_order_event_live_with_price_change_returns_updated() {
5763        let instrument = create_stub_instrument();
5764        let msg = create_order_msg_for_event_test(
5765            OKXOrderStatus::Live,
5766            "test_client_123",
5767            "venue_456",
5768            "51000.0",
5769            "0.01",
5770        );
5771
5772        let client_order_id = ClientOrderId::new("test_client_123");
5773        let account_id = AccountId::new("OKX-001");
5774        let trader_id = TraderId::new("TRADER-001");
5775        let strategy_id = StrategyId::new("STRATEGY-001");
5776        let ts_init = UnixNanos::from(1_000_000_000);
5777
5778        let previous_state = OrderStateSnapshot {
5779            venue_order_id: VenueOrderId::new("venue_456"),
5780            quantity: Quantity::from("0.01000000"),
5781            price: Some(Price::from("50000.00")),
5782        };
5783
5784        let result = parse_order_event(
5785            &msg,
5786            client_order_id,
5787            account_id,
5788            trader_id,
5789            strategy_id,
5790            &InstrumentAny::CryptoPerpetual(instrument),
5791            None,
5792            None,
5793            Some(&previous_state),
5794            ts_init,
5795        );
5796
5797        assert!(result.is_ok());
5798        match result.unwrap() {
5799            ParsedOrderEvent::Updated(updated) => {
5800                assert_eq!(updated.client_order_id, client_order_id);
5801                assert_eq!(updated.price, Some(Price::from("51000.00")));
5802            }
5803            other => panic!("Expected Updated, was {other:?}"),
5804        }
5805    }
5806
5807    #[rstest]
5808    fn test_parse_order_event_live_with_quantity_change_returns_updated() {
5809        let instrument = create_stub_instrument();
5810        let msg = create_order_msg_for_event_test(
5811            OKXOrderStatus::Live,
5812            "test_client_123",
5813            "venue_456",
5814            "50000.0",
5815            "0.02",
5816        );
5817
5818        let client_order_id = ClientOrderId::new("test_client_123");
5819        let account_id = AccountId::new("OKX-001");
5820        let trader_id = TraderId::new("TRADER-001");
5821        let strategy_id = StrategyId::new("STRATEGY-001");
5822        let ts_init = UnixNanos::from(1_000_000_000);
5823
5824        let previous_state = OrderStateSnapshot {
5825            venue_order_id: VenueOrderId::new("venue_456"),
5826            quantity: Quantity::from("0.01000000"),
5827            price: Some(Price::from("50000.00")),
5828        };
5829
5830        let result = parse_order_event(
5831            &msg,
5832            client_order_id,
5833            account_id,
5834            trader_id,
5835            strategy_id,
5836            &InstrumentAny::CryptoPerpetual(instrument),
5837            None,
5838            None,
5839            Some(&previous_state),
5840            ts_init,
5841        );
5842
5843        assert!(result.is_ok());
5844        match result.unwrap() {
5845            ParsedOrderEvent::Updated(updated) => {
5846                assert_eq!(updated.client_order_id, client_order_id);
5847                assert_eq!(updated.quantity, Quantity::from("0.02000000"));
5848            }
5849            other => panic!("Expected Updated, was {other:?}"),
5850        }
5851    }
5852
5853    #[rstest]
5854    fn test_parse_order_event_canceled_returns_canceled() {
5855        let instrument = create_stub_instrument();
5856        let msg = create_order_msg_for_event_test(
5857            OKXOrderStatus::Canceled,
5858            "test_client_123",
5859            "venue_456",
5860            "50000.0",
5861            "0.01",
5862        );
5863
5864        let client_order_id = ClientOrderId::new("test_client_123");
5865        let account_id = AccountId::new("OKX-001");
5866        let trader_id = TraderId::new("TRADER-001");
5867        let strategy_id = StrategyId::new("STRATEGY-001");
5868        let ts_init = UnixNanos::from(1_000_000_000);
5869
5870        let result = parse_order_event(
5871            &msg,
5872            client_order_id,
5873            account_id,
5874            trader_id,
5875            strategy_id,
5876            &InstrumentAny::CryptoPerpetual(instrument),
5877            None,
5878            None,
5879            None,
5880            ts_init,
5881        );
5882
5883        assert!(result.is_ok());
5884        match result.unwrap() {
5885            ParsedOrderEvent::Canceled(canceled) => {
5886                assert_eq!(canceled.client_order_id, client_order_id);
5887                assert_eq!(
5888                    canceled.venue_order_id,
5889                    Some(VenueOrderId::new("venue_456"))
5890                );
5891            }
5892            other => panic!("Expected Canceled, was {other:?}"),
5893        }
5894    }
5895
5896    #[rstest]
5897    fn test_parse_order_event_canceled_with_expiry_reason_returns_expired() {
5898        let instrument = create_stub_instrument();
5899        let mut msg = create_order_msg_for_event_test(
5900            OKXOrderStatus::Canceled,
5901            "test_client_123",
5902            "venue_456",
5903            "50000.0",
5904            "0.01",
5905        );
5906        msg.cancel_source_reason = Some("GTD order expired".to_string());
5907
5908        let client_order_id = ClientOrderId::new("test_client_123");
5909        let account_id = AccountId::new("OKX-001");
5910        let trader_id = TraderId::new("TRADER-001");
5911        let strategy_id = StrategyId::new("STRATEGY-001");
5912        let ts_init = UnixNanos::from(1_000_000_000);
5913
5914        let result = parse_order_event(
5915            &msg,
5916            client_order_id,
5917            account_id,
5918            trader_id,
5919            strategy_id,
5920            &InstrumentAny::CryptoPerpetual(instrument),
5921            None,
5922            None,
5923            None,
5924            ts_init,
5925        );
5926
5927        assert!(result.is_ok());
5928        match result.unwrap() {
5929            ParsedOrderEvent::Expired(expired) => {
5930                assert_eq!(expired.client_order_id, client_order_id);
5931                assert_eq!(expired.venue_order_id, Some(VenueOrderId::new("venue_456")));
5932            }
5933            other => panic!("Expected Expired, was {other:?}"),
5934        }
5935    }
5936
5937    #[rstest]
5938    fn test_parse_order_event_filled_with_fill_data_returns_fill() {
5939        let instrument = create_stub_instrument();
5940        let mut msg = create_order_msg_for_event_test(
5941            OKXOrderStatus::Filled,
5942            "test_client_123",
5943            "venue_456",
5944            "50000.0",
5945            "0.01",
5946        );
5947        msg.fill_sz = "0.01".to_string();
5948        msg.fill_px = "50000.0".to_string();
5949        msg.trade_id = "trade_789".to_string();
5950        msg.acc_fill_sz = Some("0.01".to_string());
5951
5952        let client_order_id = ClientOrderId::new("test_client_123");
5953        let account_id = AccountId::new("OKX-001");
5954        let trader_id = TraderId::new("TRADER-001");
5955        let strategy_id = StrategyId::new("STRATEGY-001");
5956        let ts_init = UnixNanos::from(1_000_000_000);
5957
5958        let result = parse_order_event(
5959            &msg,
5960            client_order_id,
5961            account_id,
5962            trader_id,
5963            strategy_id,
5964            &InstrumentAny::CryptoPerpetual(instrument),
5965            None,
5966            None,
5967            None,
5968            ts_init,
5969        );
5970
5971        assert!(result.is_ok());
5972        match result.unwrap() {
5973            ParsedOrderEvent::Fill(fill) => {
5974                assert_eq!(fill.client_order_id, Some(client_order_id));
5975                assert_eq!(fill.venue_order_id, VenueOrderId::new("venue_456"));
5976                assert_eq!(fill.trade_id, TradeId::from("trade_789"));
5977            }
5978            other => panic!("Expected Fill, was {other:?}"),
5979        }
5980    }
5981
5982    #[rstest]
5983    #[case::gtd_in_reason(None, Some("GTD order expired"), true)]
5984    #[case::timeout_in_reason(None, Some("Order timeout"), true)]
5985    #[case::expir_in_reason(None, Some("Expiration reached"), true)]
5986    #[case::source_code_5(Some("5"), None, true)]
5987    #[case::source_time_expired(Some("time_expired"), None, true)]
5988    #[case::user_cancel(Some("1"), Some("User canceled"), false)]
5989    #[case::no_reason(None, None, false)]
5990    fn test_is_order_expired_by_reason(
5991        #[case] source: Option<&str>,
5992        #[case] reason: Option<&str>,
5993        #[case] expected: bool,
5994    ) {
5995        let mut msg =
5996            create_order_msg_for_event_test(OKXOrderStatus::Canceled, "test", "123", "100", "1");
5997        msg.cancel_source = source.map(str::to_string);
5998        msg.cancel_source_reason = reason.map(str::to_string);
5999
6000        assert_eq!(is_order_expired_by_reason(&msg), expected);
6001    }
6002
6003    fn fresh_cancel_source_seen() -> Mutex<AHashSet<String>> {
6004        Mutex::new(AHashSet::new())
6005    }
6006
6007    #[rstest]
6008    fn test_log_unknown_cancel_source_records_first_observation() {
6009        let mut msg =
6010            create_order_msg_for_event_test(OKXOrderStatus::Canceled, "test", "123", "100", "1");
6011        msg.cancel_source = Some("99".to_string());
6012        msg.cancel_source_reason = Some("Unknown reason".to_string());
6013
6014        let seen = fresh_cancel_source_seen();
6015        assert!(log_unknown_cancel_source_inner(&msg, &seen, 8));
6016        assert_eq!(seen.lock().len(), 1);
6017    }
6018
6019    #[rstest]
6020    fn test_log_unknown_cancel_source_dedups_repeat_pair() {
6021        let mut msg =
6022            create_order_msg_for_event_test(OKXOrderStatus::Canceled, "test", "123", "100", "1");
6023        msg.cancel_source = Some("99".to_string());
6024        msg.cancel_source_reason = Some("Unknown reason".to_string());
6025
6026        let seen = fresh_cancel_source_seen();
6027        assert!(log_unknown_cancel_source_inner(&msg, &seen, 8));
6028        assert!(!log_unknown_cancel_source_inner(&msg, &seen, 8));
6029        assert_eq!(seen.lock().len(), 1);
6030    }
6031
6032    #[rstest]
6033    #[case::post_only("31")]
6034    #[case::known_expired("5")]
6035    #[case::sentinel_time("time_expired")]
6036    #[case::sentinel_gtd("gtd_expired")]
6037    fn test_log_unknown_cancel_source_skips_known_sources(#[case] source: &str) {
6038        let mut msg =
6039            create_order_msg_for_event_test(OKXOrderStatus::Canceled, "test", "123", "100", "1");
6040        msg.cancel_source = Some(source.to_string());
6041
6042        let seen = fresh_cancel_source_seen();
6043        assert!(!log_unknown_cancel_source_inner(&msg, &seen, 8));
6044        assert!(seen.lock().is_empty());
6045    }
6046
6047    #[rstest]
6048    fn test_log_unknown_cancel_source_skips_when_source_and_reason_empty() {
6049        let msg =
6050            create_order_msg_for_event_test(OKXOrderStatus::Canceled, "test", "123", "100", "1");
6051        let seen = fresh_cancel_source_seen();
6052        assert!(!log_unknown_cancel_source_inner(&msg, &seen, 8));
6053        assert!(seen.lock().is_empty());
6054    }
6055
6056    #[rstest]
6057    fn test_log_unknown_cancel_source_respects_capacity_cap() {
6058        let cap = 4;
6059        let seen = fresh_cancel_source_seen();
6060
6061        for i in 0..cap {
6062            let mut msg = create_order_msg_for_event_test(
6063                OKXOrderStatus::Canceled,
6064                "test",
6065                "123",
6066                "100",
6067                "1",
6068            );
6069            msg.cancel_source = Some(format!("novel_{i}"));
6070            assert!(log_unknown_cancel_source_inner(&msg, &seen, cap));
6071        }
6072
6073        let mut overflow =
6074            create_order_msg_for_event_test(OKXOrderStatus::Canceled, "test", "123", "100", "1");
6075        overflow.cancel_source = Some("novel_overflow".to_string());
6076        assert!(!log_unknown_cancel_source_inner(&overflow, &seen, cap));
6077        assert_eq!(seen.lock().len(), cap);
6078    }
6079
6080    // Regression test: PartiallyFilled order with price change should emit Updated, not StatusOnly
6081    #[rstest]
6082    fn test_parse_order_event_partially_filled_with_price_change_returns_updated() {
6083        let instrument = create_stub_instrument();
6084        let msg = create_order_msg_for_event_test(
6085            OKXOrderStatus::PartiallyFilled,
6086            "test_client_123",
6087            "venue_456",
6088            "51000.0",
6089            "0.01",
6090        );
6091
6092        let client_order_id = ClientOrderId::new("test_client_123");
6093        let account_id = AccountId::new("OKX-001");
6094        let trader_id = TraderId::new("TRADER-001");
6095        let strategy_id = StrategyId::new("STRATEGY-001");
6096        let ts_init = UnixNanos::from(1_000_000_000);
6097
6098        let previous_state = OrderStateSnapshot {
6099            venue_order_id: VenueOrderId::new("venue_456"),
6100            quantity: Quantity::from("0.01000000"),
6101            price: Some(Price::from("50000.00")),
6102        };
6103
6104        let result = parse_order_event(
6105            &msg,
6106            client_order_id,
6107            account_id,
6108            trader_id,
6109            strategy_id,
6110            &InstrumentAny::CryptoPerpetual(instrument),
6111            None,
6112            None,
6113            Some(&previous_state),
6114            ts_init,
6115        );
6116
6117        assert!(result.is_ok());
6118        match result.unwrap() {
6119            ParsedOrderEvent::Updated(updated) => {
6120                assert_eq!(updated.client_order_id, client_order_id);
6121                assert_eq!(updated.price, Some(Price::from("51000.00")));
6122            }
6123            other => {
6124                panic!("Expected Updated for PartiallyFilled with price change, was {other:?}")
6125            }
6126        }
6127    }
6128
6129    #[rstest]
6130    fn test_is_order_updated_price_change() {
6131        let instrument = create_stub_instrument();
6132        let msg = create_order_msg_for_event_test(
6133            OKXOrderStatus::Live,
6134            "test",
6135            "venue_123",
6136            "51000.0",
6137            "0.01",
6138        );
6139
6140        let previous = OrderStateSnapshot {
6141            venue_order_id: VenueOrderId::new("venue_123"),
6142            quantity: Quantity::from("0.01000000"),
6143            price: Some(Price::from("50000.00")),
6144        };
6145
6146        let result = is_order_updated(&msg, &previous, &InstrumentAny::CryptoPerpetual(instrument));
6147        assert!(result.is_ok());
6148        assert!(result.unwrap());
6149    }
6150
6151    #[rstest]
6152    fn test_is_order_updated_quantity_change() {
6153        let instrument = create_stub_instrument();
6154        let msg = create_order_msg_for_event_test(
6155            OKXOrderStatus::Live,
6156            "test",
6157            "venue_123",
6158            "50000.0",
6159            "0.02", // New quantity
6160        );
6161
6162        let previous = OrderStateSnapshot {
6163            venue_order_id: VenueOrderId::new("venue_123"),
6164            quantity: Quantity::from("0.01000000"), // Old quantity
6165            price: Some(Price::from("50000.00")),
6166        };
6167
6168        let result = is_order_updated(&msg, &previous, &InstrumentAny::CryptoPerpetual(instrument));
6169        assert!(result.is_ok());
6170        assert!(result.unwrap());
6171    }
6172
6173    #[rstest]
6174    fn test_is_order_updated_venue_id_change() {
6175        let instrument = create_stub_instrument();
6176        let msg = create_order_msg_for_event_test(
6177            OKXOrderStatus::Live,
6178            "test",
6179            "venue_456", // New venue ID
6180            "50000.0",
6181            "0.01",
6182        );
6183
6184        let previous = OrderStateSnapshot {
6185            venue_order_id: VenueOrderId::new("venue_123"), // Old venue ID
6186            quantity: Quantity::from("0.01000000"),
6187            price: Some(Price::from("50000.00")),
6188        };
6189
6190        let result = is_order_updated(&msg, &previous, &InstrumentAny::CryptoPerpetual(instrument));
6191        assert!(result.is_ok());
6192        assert!(result.unwrap());
6193    }
6194
6195    #[rstest]
6196    fn test_is_order_updated_no_change() {
6197        let instrument = create_stub_instrument();
6198        let msg = create_order_msg_for_event_test(
6199            OKXOrderStatus::Live,
6200            "test",
6201            "venue_123",
6202            "50000.0",
6203            "0.01",
6204        );
6205
6206        let previous = OrderStateSnapshot {
6207            venue_order_id: VenueOrderId::new("venue_123"),
6208            quantity: Quantity::from("0.01000000"),
6209            price: Some(Price::from("50000.00")),
6210        };
6211
6212        let result = is_order_updated(&msg, &previous, &InstrumentAny::CryptoPerpetual(instrument));
6213        assert!(result.is_ok());
6214        assert!(!result.unwrap());
6215    }
6216
6217    #[rstest]
6218    fn test_parse_order_status_report_ts_last_and_ts_init_ordering() {
6219        let instrument = create_stub_instrument();
6220        let inst = InstrumentAny::CryptoPerpetual(instrument);
6221        let account_id = AccountId::new("OKX-001");
6222        let ts_init = UnixNanos::from(999_000_000_000u64);
6223
6224        let mut msg = create_stub_order_msg("", Some("0".to_string()), "123456", "");
6225        msg.avg_px = String::new();
6226        msg.c_time = 1_706_000_000_000;
6227        msg.cl_ord_id = "test_ts_order".to_string();
6228        msg.fee = None;
6229        msg.fill_px = String::new();
6230        msg.fill_time = 0;
6231        msg.lever = String::new();
6232        msg.ord_type = OKXOrderType::Limit;
6233        msg.pnl = String::new();
6234        msg.px = "50000.00".to_string();
6235        msg.state = OKXOrderStatus::Live;
6236        msg.sz = "0.01".to_string();
6237        msg.td_mode = OKXTradeMode::Cross;
6238        msg.u_time = 1_706_000_001_000;
6239
6240        let report = parse_order_status_report(&msg, &inst, account_id, ts_init).unwrap();
6241
6242        assert_eq!(
6243            report.ts_accepted,
6244            UnixNanos::from(1_706_000_000_000_u64 * 1_000_000)
6245        );
6246        assert_eq!(
6247            report.ts_last,
6248            UnixNanos::from(1_706_000_001_000_u64 * 1_000_000)
6249        );
6250        assert_eq!(report.ts_init, ts_init);
6251    }
6252
6253    #[rstest]
6254    fn test_parse_order_status_report_preserves_attached_tp_sl_child_ids() {
6255        let instrument = create_stub_instrument();
6256        let inst = InstrumentAny::CryptoPerpetual(instrument);
6257        let account_id = AccountId::new("OKX-001");
6258        let ts_init = UnixNanos::default();
6259
6260        let mut msg = create_stub_order_msg("", Some("0".to_string()), "123456", "");
6261        msg.avg_px = String::new();
6262        msg.c_time = 1_706_000_000_000;
6263        msg.cl_ord_id = "O-attached-entry".to_string();
6264        msg.attach_algo_cl_ord_id = Some("O-attached-sl".to_string());
6265        msg.attach_algo_ords = vec![
6266            OKXAttachedAlgoOrd {
6267                attach_algo_id: "algo-sl".to_string(),
6268                attach_algo_cl_ord_id: "O-attached-sl".to_string(),
6269                sl_trigger_px: "1500".to_string(),
6270                sl_ord_px: "-1".to_string(),
6271                sl_trigger_px_type: Some(OKXTriggerType::Last),
6272                tp_trigger_px: String::new(),
6273                tp_ord_px: String::new(),
6274                tp_trigger_px_type: None,
6275                callback_ratio: String::new(),
6276                callback_spread: String::new(),
6277                active_px: String::new(),
6278            },
6279            OKXAttachedAlgoOrd {
6280                attach_algo_id: "algo-tp".to_string(),
6281                attach_algo_cl_ord_id: "O-attached-tp".to_string(),
6282                sl_trigger_px: String::new(),
6283                sl_ord_px: String::new(),
6284                sl_trigger_px_type: None,
6285                tp_trigger_px: "2500".to_string(),
6286                tp_ord_px: "-1".to_string(),
6287                tp_trigger_px_type: Some(OKXTriggerType::Last),
6288                callback_ratio: String::new(),
6289                callback_spread: String::new(),
6290                active_px: String::new(),
6291            },
6292        ];
6293        msg.fee = None;
6294        msg.fill_px = String::new();
6295        msg.fill_time = 0;
6296        msg.lever = String::new();
6297        msg.ord_type = OKXOrderType::Limit;
6298        msg.pnl = String::new();
6299        msg.px = "2000.00".to_string();
6300        msg.state = OKXOrderStatus::Live;
6301        msg.sz = "0.01".to_string();
6302        msg.td_mode = OKXTradeMode::Cross;
6303        msg.u_time = 1_706_000_001_000;
6304
6305        let report = parse_order_status_report(&msg, &inst, account_id, ts_init).unwrap();
6306        let linked_order_ids = report
6307            .linked_order_ids
6308            .expect("expected linked child order ids");
6309
6310        assert_eq!(linked_order_ids.len(), 2);
6311        assert!(linked_order_ids.contains(&ClientOrderId::from("O-attached-sl")));
6312        assert!(linked_order_ids.contains(&ClientOrderId::from("O-attached-tp")));
6313    }
6314
6315    #[rstest]
6316    fn test_parse_algo_order_timestamps_converted_from_ms_to_ns() {
6317        let instrument = create_stub_instrument();
6318        let inst = InstrumentAny::CryptoPerpetual(instrument);
6319        let account_id = AccountId::new("OKX-001");
6320        let ts_init = UnixNanos::from(999_000_000_000u64);
6321
6322        let msg = OKXAlgoOrderMsg {
6323            algo_id: "algo_1".to_string(),
6324            algo_cl_ord_id: "algo_cl_1".to_string(),
6325            cl_ord_id: String::new(),
6326            ord_id: String::new(),
6327            ord_id_list: Vec::new(),
6328            inst_id: Ustr::from("BTC-USDT-SWAP"),
6329            inst_type: OKXInstrumentType::Swap,
6330            ord_type: OKXAlgoOrderType::Trigger,
6331            state: OKXAlgoOrderStatus::Live,
6332            side: OKXSide::Buy,
6333            pos_side: OKXPositionSide::Long,
6334            sz: "0.01".to_string(),
6335            trigger_px: "45000.00".to_string(),
6336            trigger_px_type: OKXTriggerType::Last,
6337            sl_trigger_px: String::new(),
6338            sl_ord_px: String::new(),
6339            sl_trigger_px_type: OKXTriggerType::None,
6340            tp_trigger_px: String::new(),
6341            tp_ord_px: String::new(),
6342            tp_trigger_px_type: OKXTriggerType::None,
6343            ord_px: "-1".to_string(),
6344            td_mode: OKXTradeMode::Cross,
6345            lever: String::new(),
6346            reduce_only: "false".to_string(),
6347            close_fraction: String::new(),
6348            actual_px: String::new(),
6349            actual_sz: String::new(),
6350            notional_usd: String::new(),
6351            c_time: 1_706_000_000_000,
6352            u_time: 1_706_000_001_000,
6353            trigger_time: String::new(),
6354            fail_code: String::new(),
6355            tag: String::new(),
6356            callback_ratio: String::new(),
6357            callback_spread: String::new(),
6358            active_px: String::new(),
6359            ccy: None,
6360            tgt_ccy: None,
6361            fee: None,
6362            fee_ccy: None,
6363            advance_ord_type: None,
6364        };
6365
6366        let report = parse_algo_order_status_report(&msg, &inst, account_id, ts_init).unwrap();
6367
6368        let expected_accepted_ns = 1_706_000_000_000_u64 * 1_000_000;
6369        let expected_last_ns = 1_706_000_001_000_u64 * 1_000_000;
6370        assert_eq!(report.ts_accepted, UnixNanos::from(expected_accepted_ns));
6371        assert_eq!(report.ts_last, UnixNanos::from(expected_last_ns));
6372        assert_eq!(report.ts_init, ts_init);
6373    }
6374
6375    fn stub_algo_order_msg(ord_type: OKXAlgoOrderType) -> OKXAlgoOrderMsg {
6376        OKXAlgoOrderMsg {
6377            algo_id: "algo_1".to_string(),
6378            algo_cl_ord_id: "algo_cl_1".to_string(),
6379            cl_ord_id: String::new(),
6380            ord_id: String::new(),
6381            ord_id_list: Vec::new(),
6382            inst_id: Ustr::from("BTC-USDT-SWAP"),
6383            inst_type: OKXInstrumentType::Swap,
6384            ord_type,
6385            state: OKXAlgoOrderStatus::Live,
6386            side: OKXSide::Sell,
6387            pos_side: OKXPositionSide::Long,
6388            sz: "0.01".to_string(),
6389            trigger_px: "95000.00".to_string(),
6390            trigger_px_type: OKXTriggerType::Last,
6391            sl_trigger_px: String::new(),
6392            sl_ord_px: String::new(),
6393            sl_trigger_px_type: OKXTriggerType::None,
6394            tp_trigger_px: String::new(),
6395            tp_ord_px: String::new(),
6396            tp_trigger_px_type: OKXTriggerType::None,
6397            ord_px: "-1".to_string(),
6398            td_mode: OKXTradeMode::Cross,
6399            lever: String::new(),
6400            reduce_only: "false".to_string(),
6401            close_fraction: String::new(),
6402            actual_px: String::new(),
6403            actual_sz: String::new(),
6404            notional_usd: String::new(),
6405            c_time: 1_706_000_000_000,
6406            u_time: 1_706_000_001_000,
6407            trigger_time: String::new(),
6408            fail_code: String::new(),
6409            tag: String::new(),
6410            callback_ratio: String::new(),
6411            callback_spread: String::new(),
6412            active_px: String::new(),
6413            ccy: None,
6414            tgt_ccy: None,
6415            fee: None,
6416            fee_ccy: None,
6417            advance_ord_type: None,
6418        }
6419    }
6420
6421    #[rstest]
6422    fn test_parse_algo_order_trailing_stop_with_callback_ratio() {
6423        let instrument = create_stub_instrument();
6424        let inst = InstrumentAny::CryptoPerpetual(instrument);
6425        let account_id = AccountId::new("OKX-001");
6426
6427        let mut msg = stub_algo_order_msg(OKXAlgoOrderType::MoveOrderStop);
6428        msg.callback_ratio = "0.01".to_string(); // 1% = 100 basis points
6429
6430        let report =
6431            parse_algo_order_status_report(&msg, &inst, account_id, UnixNanos::default()).unwrap();
6432
6433        assert_eq!(report.order_type, OrderType::TrailingStopMarket);
6434        assert_eq!(report.trailing_offset, Some(dec!(100)));
6435        assert_eq!(
6436            report.trailing_offset_type,
6437            Some(TrailingOffsetType::BasisPoints),
6438        );
6439        assert_eq!(report.trigger_price, Some(Price::from("95000.00")));
6440    }
6441
6442    #[rstest]
6443    fn test_parse_algo_order_trailing_stop_captures_activation_price() {
6444        let instrument = create_stub_instrument();
6445        let inst = InstrumentAny::CryptoPerpetual(instrument);
6446        let account_id = AccountId::new("OKX-001");
6447
6448        let mut msg = stub_algo_order_msg(OKXAlgoOrderType::MoveOrderStop);
6449        msg.callback_ratio = "0.01".to_string();
6450        msg.active_px = "94000.5".to_string();
6451
6452        let report =
6453            parse_algo_order_status_report(&msg, &inst, account_id, UnixNanos::default()).unwrap();
6454
6455        assert_eq!(report.order_type, OrderType::TrailingStopMarket);
6456        assert_eq!(report.activation_price, Some(Price::from("94000.50")));
6457    }
6458
6459    #[rstest]
6460    fn test_parse_algo_order_trailing_stop_with_callback_spread() {
6461        let instrument = create_stub_instrument();
6462        let inst = InstrumentAny::CryptoPerpetual(instrument);
6463        let account_id = AccountId::new("OKX-001");
6464
6465        let mut msg = stub_algo_order_msg(OKXAlgoOrderType::MoveOrderStop);
6466        msg.callback_spread = "50.5".to_string();
6467
6468        let report =
6469            parse_algo_order_status_report(&msg, &inst, account_id, UnixNanos::default()).unwrap();
6470
6471        assert_eq!(report.order_type, OrderType::TrailingStopMarket);
6472        assert_eq!(report.trailing_offset, Some(dec!(50.5)));
6473        assert_eq!(report.trailing_offset_type, Some(TrailingOffsetType::Price),);
6474    }
6475
6476    #[rstest]
6477    fn test_parse_algo_order_unsupported_type_skipped() {
6478        let instrument = create_stub_instrument();
6479        let account_id = AccountId::new("OKX-001");
6480        let mut instruments = AHashMap::new();
6481        instruments.insert(
6482            Ustr::from("BTC-USDT-SWAP"),
6483            InstrumentAny::CryptoPerpetual(instrument),
6484        );
6485
6486        let msg = stub_algo_order_msg(OKXAlgoOrderType::Iceberg);
6487
6488        let result = parse_algo_order_msg(&msg, account_id, &instruments, UnixNanos::default());
6489
6490        assert!(result.unwrap().is_none());
6491    }
6492
6493    #[rstest]
6494    fn test_parse_algo_order_chase_type_skipped() {
6495        let instrument = create_stub_instrument();
6496        let account_id = AccountId::new("OKX-001");
6497        let mut instruments = AHashMap::new();
6498        instruments.insert(
6499            Ustr::from("BTC-USDT-SWAP"),
6500            InstrumentAny::CryptoPerpetual(instrument),
6501        );
6502
6503        let msg = stub_algo_order_msg(OKXAlgoOrderType::Chase);
6504
6505        let result = parse_algo_order_msg(&msg, account_id, &instruments, UnixNanos::default());
6506
6507        assert!(result.unwrap().is_none());
6508    }
6509
6510    #[rstest]
6511    fn test_parse_algo_order_unknown_type_skipped() {
6512        let instrument = create_stub_instrument();
6513        let account_id = AccountId::new("OKX-001");
6514        let mut instruments = AHashMap::new();
6515        instruments.insert(
6516            Ustr::from("BTC-USDT-SWAP"),
6517            InstrumentAny::CryptoPerpetual(instrument),
6518        );
6519
6520        let msg = stub_algo_order_msg(OKXAlgoOrderType::Other);
6521
6522        let result = parse_algo_order_msg(&msg, account_id, &instruments, UnixNanos::default());
6523
6524        assert!(result.unwrap().is_none());
6525    }
6526
6527    #[rstest]
6528    fn test_parse_algo_order_unknown_state_skipped() {
6529        let instrument = create_stub_instrument();
6530        let account_id = AccountId::new("OKX-001");
6531        let mut instruments = AHashMap::new();
6532        instruments.insert(
6533            Ustr::from("BTC-USDT-SWAP"),
6534            InstrumentAny::CryptoPerpetual(instrument),
6535        );
6536
6537        let mut msg = stub_algo_order_msg(OKXAlgoOrderType::Trigger);
6538        msg.state = OKXAlgoOrderStatus::Unknown;
6539
6540        let result = parse_algo_order_msg(&msg, account_id, &instruments, UnixNanos::default());
6541
6542        assert!(result.unwrap().is_none());
6543    }
6544
6545    #[rstest]
6546    fn test_deserialize_algo_order_states_message() {
6547        let json_data = load_test_json("ws_orders_algo_states.json");
6548        let payload: serde_json::Value = serde_json::from_str(&json_data).unwrap();
6549        let data: Vec<OKXAlgoOrderMsg> = serde_json::from_value(payload["data"].clone()).unwrap();
6550
6551        assert_eq!(data.len(), 6);
6552        assert_eq!(data[0].state, OKXAlgoOrderStatus::Effective);
6553        assert_eq!(data[1].state, OKXAlgoOrderStatus::PartiallyEffective);
6554        assert_eq!(data[2].state, OKXAlgoOrderStatus::Pause);
6555        assert_eq!(data[3].state, OKXAlgoOrderStatus::OrderFailed);
6556        assert_eq!(data[4].state, OKXAlgoOrderStatus::PartiallyFailed);
6557        assert_eq!(data[5].ord_type, OKXAlgoOrderType::Chase);
6558    }
6559
6560    #[rstest]
6561    fn test_parse_algo_order_states_map_to_nautilus_status() {
6562        let json_data = load_test_json("ws_orders_algo_states.json");
6563        let payload: serde_json::Value = serde_json::from_str(&json_data).unwrap();
6564        let data: Vec<OKXAlgoOrderMsg> = serde_json::from_value(payload["data"].clone()).unwrap();
6565
6566        let account_id = AccountId::new("OKX-001");
6567        let mut instruments = AHashMap::new();
6568        instruments.insert(
6569            Ustr::from("BTC-USDT-SWAP"),
6570            InstrumentAny::CryptoPerpetual(create_stub_instrument()),
6571        );
6572
6573        let expected = [
6574            (0_usize, OrderStatus::Triggered), // effective
6575            (1, OrderStatus::Triggered),       // partially_effective
6576            (2, OrderStatus::Accepted),        // pause
6577            (3, OrderStatus::Rejected),        // order_failed
6578            (4, OrderStatus::Rejected),        // partially_failed
6579        ];
6580
6581        for (idx, expected_status) in expected {
6582            let report =
6583                parse_algo_order_msg(&data[idx], account_id, &instruments, UnixNanos::default())
6584                    .unwrap()
6585                    .unwrap_or_else(|| panic!("Expected report for fixture index {idx}"));
6586
6587            match report {
6588                ExecutionReport::Order(report) => {
6589                    assert_eq!(report.order_status, expected_status);
6590                }
6591                other => panic!("Expected Order report for fixture index {idx}, was {other:?}"),
6592            }
6593        }
6594
6595        // Chase orders are unsupported and skipped; their triggered child orders
6596        // still arrive on the regular orders channel
6597        let chase =
6598            parse_algo_order_msg(&data[5], account_id, &instruments, UnixNanos::default()).unwrap();
6599        assert!(chase.is_none());
6600    }
6601
6602    #[rstest]
6603    fn test_parse_algo_order_missing_trigger_px_type_defaults() {
6604        let instrument = create_stub_instrument();
6605        let inst = InstrumentAny::CryptoPerpetual(instrument);
6606        let account_id = AccountId::new("OKX-001");
6607
6608        let mut msg = stub_algo_order_msg(OKXAlgoOrderType::MoveOrderStop);
6609        msg.trigger_px_type = OKXTriggerType::None;
6610        msg.callback_ratio = "0.005".to_string();
6611
6612        let report =
6613            parse_algo_order_status_report(&msg, &inst, account_id, UnixNanos::default()).unwrap();
6614
6615        assert_eq!(report.trigger_type, Some(TriggerType::Default));
6616        assert_eq!(report.order_type, OrderType::TrailingStopMarket);
6617    }
6618
6619    #[rstest]
6620    fn test_parse_algo_order_close_fraction_stop_market_without_sz() {
6621        let instrument = create_stub_instrument();
6622        let inst = InstrumentAny::CryptoPerpetual(instrument);
6623        let account_id = AccountId::new("OKX-001");
6624
6625        let mut msg = stub_algo_order_msg(OKXAlgoOrderType::Conditional);
6626        msg.sz = String::new();
6627        msg.trigger_px = String::new();
6628        msg.trigger_px_type = OKXTriggerType::None;
6629        msg.ord_px = String::new();
6630        msg.sl_trigger_px = "50000".to_string();
6631        msg.sl_ord_px = "-1".to_string();
6632        msg.sl_trigger_px_type = OKXTriggerType::Last;
6633        msg.close_fraction = "1".to_string();
6634        msg.reduce_only = "true".to_string();
6635
6636        let report =
6637            parse_algo_order_status_report(&msg, &inst, account_id, UnixNanos::default()).unwrap();
6638
6639        assert_eq!(report.order_type, OrderType::StopMarket);
6640        assert_eq!(report.trigger_price, Some(Price::from("50000.00")));
6641        assert_eq!(report.trigger_type, Some(TriggerType::LastPrice));
6642        assert_eq!(report.price, None);
6643        assert_eq!(report.quantity, Quantity::zero(inst.size_precision()));
6644        assert!(report.reduce_only);
6645    }
6646
6647    #[rstest]
6648    fn test_parse_algo_order_close_fraction_market_if_touched_without_sz() {
6649        let instrument = create_stub_instrument();
6650        let inst = InstrumentAny::CryptoPerpetual(instrument);
6651        let account_id = AccountId::new("OKX-001");
6652
6653        let mut msg = stub_algo_order_msg(OKXAlgoOrderType::Conditional);
6654        msg.sz = String::new();
6655        msg.trigger_px = String::new();
6656        msg.trigger_px_type = OKXTriggerType::None;
6657        msg.ord_px = String::new();
6658        msg.sl_trigger_px = String::new();
6659        msg.sl_ord_px = String::new();
6660        msg.tp_trigger_px = "50000".to_string();
6661        msg.tp_ord_px = "-1".to_string();
6662        msg.tp_trigger_px_type = OKXTriggerType::Last;
6663        msg.close_fraction = "1".to_string();
6664        msg.reduce_only = "true".to_string();
6665        msg.side = OKXSide::Buy;
6666
6667        let report =
6668            parse_algo_order_status_report(&msg, &inst, account_id, UnixNanos::default()).unwrap();
6669
6670        assert_eq!(report.order_type, OrderType::MarketIfTouched);
6671        assert_eq!(report.trigger_price, Some(Price::from("50000.00")));
6672        assert_eq!(report.trigger_type, Some(TriggerType::LastPrice));
6673        assert_eq!(report.price, None);
6674        assert_eq!(report.quantity, Quantity::zero(inst.size_precision()));
6675        assert!(report.reduce_only);
6676    }
6677
6678    fn stub_book_entry(price: &str, size: &str) -> OrderBookEntry {
6679        OrderBookEntry {
6680            price: price.to_string(),
6681            size: size.to_string(),
6682            liquidated_orders_count: "0".to_string(),
6683            orders_count: "1".to_string(),
6684        }
6685    }
6686
6687    fn stub_book_msg(bids: Vec<OrderBookEntry>, asks: Vec<OrderBookEntry>) -> OKXBookMsg {
6688        OKXBookMsg {
6689            bids,
6690            asks,
6691            ts: 1_706_000_000_000,
6692            seq_id: 1,
6693            prev_seq_id: Some(0),
6694            checksum: None,
6695        }
6696    }
6697
6698    #[rstest]
6699    fn test_parse_quote_msg_empty_bids_returns_error() {
6700        let msg = stub_book_msg(vec![], vec![stub_book_entry("50000.00", "1.0")]);
6701
6702        let result = parse_quote_msg(
6703            &msg,
6704            InstrumentId::from("BTC-USDT.OKX"),
6705            2,
6706            8,
6707            UnixNanos::default(),
6708        );
6709        assert!(result.is_err());
6710        assert!(result.unwrap_err().to_string().contains("Empty bids"));
6711    }
6712
6713    #[rstest]
6714    fn test_parse_quote_msg_empty_asks_returns_error() {
6715        let msg = stub_book_msg(vec![stub_book_entry("50000.00", "1.0")], vec![]);
6716
6717        let result = parse_quote_msg(
6718            &msg,
6719            InstrumentId::from("BTC-USDT.OKX"),
6720            2,
6721            8,
6722            UnixNanos::default(),
6723        );
6724        assert!(result.is_err());
6725        assert!(result.unwrap_err().to_string().contains("Empty asks"));
6726    }
6727
6728    #[rstest]
6729    fn test_quote_cache_complete_bbo_tbt_message() {
6730        use nautilus_common::cache::quote::QuoteCache;
6731
6732        let mut cache = QuoteCache::new();
6733        let instrument_id = InstrumentId::from("BTC-USD-260327-75000-C.OKX");
6734        let msg = stub_book_msg(
6735            vec![stub_book_entry("0.0035", "100")],
6736            vec![stub_book_entry("0.0040", "200")],
6737        );
6738
6739        let bid_price = Some(parse_price(&msg.bids[0].price, 4).unwrap());
6740        let bid_size = Some(parse_quantity(&msg.bids[0].size, 0).unwrap());
6741        let ask_price = Some(parse_price(&msg.asks[0].price, 4).unwrap());
6742        let ask_size = Some(parse_quantity(&msg.asks[0].size, 0).unwrap());
6743        let ts_event = parse_millisecond_timestamp(msg.ts);
6744
6745        let quote = cache
6746            .process(
6747                instrument_id,
6748                bid_price,
6749                ask_price,
6750                bid_size,
6751                ask_size,
6752                ts_event,
6753                UnixNanos::default(),
6754            )
6755            .unwrap();
6756
6757        assert_eq!(quote.bid_price, Price::from("0.0035"));
6758        assert_eq!(quote.ask_price, Price::from("0.0040"));
6759        assert_eq!(quote.bid_size, Quantity::from(100));
6760        assert_eq!(quote.ask_size, Quantity::from(200));
6761    }
6762
6763    #[rstest]
6764    fn test_quote_cache_empty_bids_uses_cached_value() {
6765        use nautilus_common::cache::quote::QuoteCache;
6766
6767        let mut cache = QuoteCache::new();
6768        let instrument_id = InstrumentId::from("BTC-USD-260327-80000-C.OKX");
6769
6770        cache
6771            .process(
6772                instrument_id,
6773                Some(Price::from("0.0010")),
6774                Some(Price::from("0.0015")),
6775                Some(Quantity::from(50)),
6776                Some(Quantity::from(75)),
6777                UnixNanos::default(),
6778                UnixNanos::default(),
6779            )
6780            .unwrap();
6781
6782        let msg = stub_book_msg(vec![], vec![stub_book_entry("0.0020", "100")]);
6783        let ask_price = Some(parse_price(&msg.asks[0].price, 4).unwrap());
6784        let ask_size = Some(parse_quantity(&msg.asks[0].size, 0).unwrap());
6785        let ts_event = parse_millisecond_timestamp(msg.ts);
6786
6787        let quote = cache
6788            .process(
6789                instrument_id,
6790                None,
6791                ask_price,
6792                None,
6793                ask_size,
6794                ts_event,
6795                UnixNanos::default(),
6796            )
6797            .unwrap();
6798
6799        assert_eq!(quote.bid_price, Price::from("0.0010"));
6800        assert_eq!(quote.bid_size, Quantity::from(50));
6801        assert_eq!(quote.ask_price, Price::from("0.0020"));
6802        assert_eq!(quote.ask_size, Quantity::from(100));
6803    }
6804
6805    #[rstest]
6806    fn test_quote_cache_empty_asks_uses_cached_value() {
6807        use nautilus_common::cache::quote::QuoteCache;
6808
6809        let mut cache = QuoteCache::new();
6810        let instrument_id = InstrumentId::from("BTC-USD-260327-79000-P.OKX");
6811
6812        cache
6813            .process(
6814                instrument_id,
6815                Some(Price::from("0.0010")),
6816                Some(Price::from("0.0015")),
6817                Some(Quantity::from(50)),
6818                Some(Quantity::from(75)),
6819                UnixNanos::default(),
6820                UnixNanos::default(),
6821            )
6822            .unwrap();
6823
6824        let msg = stub_book_msg(vec![stub_book_entry("0.0012", "60")], vec![]);
6825        let bid_price = Some(parse_price(&msg.bids[0].price, 4).unwrap());
6826        let bid_size = Some(parse_quantity(&msg.bids[0].size, 0).unwrap());
6827        let ts_event = parse_millisecond_timestamp(msg.ts);
6828
6829        let quote = cache
6830            .process(
6831                instrument_id,
6832                bid_price,
6833                None,
6834                bid_size,
6835                None,
6836                ts_event,
6837                UnixNanos::default(),
6838            )
6839            .unwrap();
6840
6841        assert_eq!(quote.bid_price, Price::from("0.0012"));
6842        assert_eq!(quote.bid_size, Quantity::from(60));
6843        assert_eq!(quote.ask_price, Price::from("0.0015"));
6844        assert_eq!(quote.ask_size, Quantity::from(75));
6845    }
6846
6847    #[rstest]
6848    fn test_quote_cache_both_sides_empty_no_cache_returns_error() {
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        let result = cache.process(
6855            instrument_id,
6856            None,
6857            None,
6858            None,
6859            None,
6860            UnixNanos::default(),
6861            UnixNanos::default(),
6862        );
6863
6864        result.unwrap_err();
6865    }
6866
6867    #[rstest]
6868    fn test_quote_cache_both_sides_empty_with_cache_returns_cached() {
6869        use nautilus_common::cache::quote::QuoteCache;
6870
6871        let mut cache = QuoteCache::new();
6872        let instrument_id = InstrumentId::from("BTC-USD-260327-80000-C.OKX");
6873
6874        cache
6875            .process(
6876                instrument_id,
6877                Some(Price::from("0.0010")),
6878                Some(Price::from("0.0015")),
6879                Some(Quantity::from(50)),
6880                Some(Quantity::from(75)),
6881                UnixNanos::default(),
6882                UnixNanos::default(),
6883            )
6884            .unwrap();
6885
6886        let quote = cache
6887            .process(
6888                instrument_id,
6889                None,
6890                None,
6891                None,
6892                None,
6893                UnixNanos::from(1_706_000_000_000_000_000_u64),
6894                UnixNanos::from(1_706_000_000_000_000_000_u64),
6895            )
6896            .unwrap();
6897
6898        assert_eq!(quote.bid_price, Price::from("0.0010"));
6899        assert_eq!(quote.ask_price, Price::from("0.0015"));
6900        assert_eq!(
6901            quote.ts_event,
6902            UnixNanos::from(1_706_000_000_000_000_000_u64)
6903        );
6904    }
6905
6906    #[rstest]
6907    fn test_parse_instruments_channel_produces_status() {
6908        use nautilus_model::{enums::MarketStatusAction, identifiers::InstrumentId};
6909
6910        use crate::common::{models::OKXInstrument, parse::parse_instrument_any};
6911
6912        let ts_init = UnixNanos::default();
6913
6914        // Build a cached instrument.
6915        let inst_json = serde_json::json!({
6916            "instType": "SPOT",
6917            "instId": "BTC-USD",
6918            "baseCcy": "BTC",
6919            "quoteCcy": "USD",
6920            "settleCcy": "",
6921            "ctVal": "",
6922            "ctMult": "",
6923            "ctValCcy": "",
6924            "optType": "",
6925            "stk": "",
6926            "listTime": "1733454000000",
6927            "expTime": "",
6928            "lever": "",
6929            "tickSz": "0.1",
6930            "lotSz": "0.00000001",
6931            "minSz": "0.00001",
6932            "ctType": "",
6933            "state": "live",
6934            "ruleType": "normal",
6935            "maxLmtSz": "9999999999",
6936            "maxMktSz": "1000000",
6937            "maxLmtAmt": "20000000",
6938            "maxMktAmt": "1000000",
6939            "maxTwapSz": "9999999999",
6940            "maxIcebergSz": "9999999999",
6941            "maxTriggerSz": "9999999999",
6942            "maxStopSz": "1000000",
6943            "uly": "",
6944            "instFamily": ""
6945        });
6946        let initial: OKXInstrument = serde_json::from_value(inst_json).unwrap();
6947        let parsed = parse_instrument_any(&initial, None, None, ts_init)
6948            .unwrap()
6949            .unwrap();
6950
6951        let mut instruments_cache = AHashMap::new();
6952        instruments_cache.insert(Ustr::from("BTC-USD"), parsed);
6953
6954        let ws_data = serde_json::json!({
6955            "instType": "SPOT",
6956            "instId": "BTC-USD",
6957            "baseCcy": "BTC",
6958            "quoteCcy": "USD",
6959            "settleCcy": "",
6960            "ctVal": "",
6961            "ctMult": "",
6962            "ctValCcy": "",
6963            "optType": "",
6964            "stk": "",
6965            "listTime": "1733454000000",
6966            "expTime": "",
6967            "lever": "",
6968            "tickSz": "0.1",
6969            "lotSz": "0.00000001",
6970            "minSz": "0.00001",
6971            "ctType": "",
6972            "state": "live",
6973            "ruleType": "normal",
6974            "maxLmtSz": "9999999999",
6975            "maxMktSz": "1000000",
6976            "maxLmtAmt": "20000000",
6977            "maxMktAmt": "1000000",
6978            "maxTwapSz": "9999999999",
6979            "maxIcebergSz": "9999999999",
6980            "maxTriggerSz": "9999999999",
6981            "maxStopSz": "1000000",
6982            "uly": "",
6983            "instFamily": ""
6984        });
6985
6986        let instrument_id = InstrumentId::from("BTC-USD.OKX");
6987        let mut funding_cache = AHashMap::new();
6988
6989        let result = parse_ws_message_data(
6990            &OKXWsChannel::Instruments,
6991            ws_data,
6992            &instrument_id,
6993            2,
6994            8,
6995            ts_init,
6996            &mut funding_cache,
6997            &instruments_cache,
6998        )
6999        .expect("Failed to parse instruments channel");
7000
7001        match result {
7002            Some(NautilusWsMessage::Instrument(inst, status)) => {
7003                assert_eq!(inst.id(), InstrumentId::from("BTC-USD.OKX"));
7004                let status = status.expect("Expected InstrumentStatus");
7005                assert_eq!(status.action, MarketStatusAction::Trading);
7006                assert_eq!(status.is_trading, Some(true));
7007            }
7008            other => panic!("Expected Instrument with status, was {other:?}"),
7009        }
7010    }
7011
7012    #[rstest]
7013    fn test_parse_instruments_channel_returns_status_when_definition_invalid() {
7014        use nautilus_model::{enums::MarketStatusAction, identifiers::InstrumentId};
7015
7016        let ts_init = UnixNanos::default();
7017        let ws_data = serde_json::json!({
7018            "instType": "SPOT",
7019            "instId": "USDG-SGD",
7020            "baseCcy": "USDG",
7021            "quoteCcy": "SGD",
7022            "settleCcy": "",
7023            "ctVal": "",
7024            "ctMult": "",
7025            "ctValCcy": "",
7026            "optType": "",
7027            "stk": "",
7028            "listTime": "1733454000000",
7029            "expTime": "",
7030            "lever": "",
7031            "tickSz": "",
7032            "lotSz": "0.00000001",
7033            "minSz": "0.00001",
7034            "ctType": "",
7035            "state": "live",
7036            "ruleType": "normal",
7037            "maxLmtSz": "9999999999",
7038            "maxMktSz": "1000000",
7039            "maxLmtAmt": "20000000",
7040            "maxMktAmt": "1000000",
7041            "maxTwapSz": "9999999999",
7042            "maxIcebergSz": "9999999999",
7043            "maxTriggerSz": "9999999999",
7044            "maxStopSz": "1000000",
7045            "uly": "",
7046            "instFamily": ""
7047        });
7048
7049        let mut funding_cache = AHashMap::new();
7050        let instruments_cache = AHashMap::new();
7051        let result = parse_ws_message_data(
7052            &OKXWsChannel::Instruments,
7053            ws_data,
7054            &InstrumentId::from("BTC-USD.OKX"),
7055            2,
7056            8,
7057            ts_init,
7058            &mut funding_cache,
7059            &instruments_cache,
7060        )
7061        .expect("Failed to parse instruments channel");
7062
7063        match result {
7064            Some(NautilusWsMessage::InstrumentStatus(status)) => {
7065                assert_eq!(status.instrument_id, InstrumentId::from("USDG-SGD.OKX"));
7066                assert_eq!(status.action, MarketStatusAction::Trading);
7067                assert_eq!(status.is_trading, Some(true));
7068            }
7069            other => panic!("Expected InstrumentStatus, was {other:?}"),
7070        }
7071    }
7072
7073    #[rstest]
7074    fn test_parse_instruments_channel_suspend_status() {
7075        use nautilus_model::{enums::MarketStatusAction, identifiers::InstrumentId};
7076
7077        use crate::common::{models::OKXInstrument, parse::parse_instrument_any};
7078
7079        let ts_init = UnixNanos::default();
7080
7081        let inst_json = serde_json::json!({
7082            "instType": "SPOT",
7083            "instId": "BTC-USD",
7084            "baseCcy": "BTC",
7085            "quoteCcy": "USD",
7086            "settleCcy": "",
7087            "ctVal": "",
7088            "ctMult": "",
7089            "ctValCcy": "",
7090            "optType": "",
7091            "stk": "",
7092            "listTime": "1733454000000",
7093            "expTime": "",
7094            "lever": "",
7095            "tickSz": "0.1",
7096            "lotSz": "0.00000001",
7097            "minSz": "0.00001",
7098            "ctType": "",
7099            "state": "live",
7100            "ruleType": "normal",
7101            "maxLmtSz": "9999999999",
7102            "maxMktSz": "1000000",
7103            "maxLmtAmt": "20000000",
7104            "maxMktAmt": "1000000",
7105            "maxTwapSz": "9999999999",
7106            "maxIcebergSz": "9999999999",
7107            "maxTriggerSz": "9999999999",
7108            "maxStopSz": "1000000",
7109            "uly": "",
7110            "instFamily": ""
7111        });
7112        let initial: OKXInstrument = serde_json::from_value(inst_json).unwrap();
7113        let parsed = parse_instrument_any(&initial, None, None, ts_init)
7114            .unwrap()
7115            .unwrap();
7116
7117        let mut instruments_cache = AHashMap::new();
7118        instruments_cache.insert(Ustr::from("BTC-USD"), parsed);
7119
7120        // WS update with suspend state
7121        let ws_data = serde_json::json!({
7122            "instType": "SPOT",
7123            "instId": "BTC-USD",
7124            "baseCcy": "BTC",
7125            "quoteCcy": "USD",
7126            "settleCcy": "",
7127            "ctVal": "",
7128            "ctMult": "",
7129            "ctValCcy": "",
7130            "optType": "",
7131            "stk": "",
7132            "listTime": "1733454000000",
7133            "expTime": "",
7134            "lever": "",
7135            "tickSz": "0.1",
7136            "lotSz": "0.00000001",
7137            "minSz": "0.00001",
7138            "ctType": "",
7139            "state": "suspend",
7140            "ruleType": "normal",
7141            "maxLmtSz": "9999999999",
7142            "maxMktSz": "1000000",
7143            "maxLmtAmt": "20000000",
7144            "maxMktAmt": "1000000",
7145            "maxTwapSz": "9999999999",
7146            "maxIcebergSz": "9999999999",
7147            "maxTriggerSz": "9999999999",
7148            "maxStopSz": "1000000",
7149            "uly": "",
7150            "instFamily": ""
7151        });
7152
7153        let instrument_id = InstrumentId::from("BTC-USD.OKX");
7154        let mut funding_cache = AHashMap::new();
7155
7156        let result = parse_ws_message_data(
7157            &OKXWsChannel::Instruments,
7158            ws_data,
7159            &instrument_id,
7160            2,
7161            8,
7162            ts_init,
7163            &mut funding_cache,
7164            &instruments_cache,
7165        )
7166        .expect("Failed to parse instruments channel");
7167
7168        match result {
7169            Some(NautilusWsMessage::Instrument(_, status)) => {
7170                let status = status.expect("Expected InstrumentStatus");
7171                assert_eq!(status.action, MarketStatusAction::Suspend);
7172                assert_eq!(status.is_trading, Some(false));
7173            }
7174            other => panic!("Expected Instrument with status, was {other:?}"),
7175        }
7176    }
7177
7178    #[rstest]
7179    fn test_parse_option_summary_greeks() {
7180        let json_str = load_test_json("ws_opt_summary.json");
7181        let msgs: Vec<OKXOptionSummaryMsg> =
7182            serde_json::from_str(&json_str).expect("Failed to deserialize opt-summary fixture");
7183        assert_eq!(msgs.len(), 2);
7184
7185        let instrument_id = InstrumentId::from("BTC-USD-250328-92000-C.OKX");
7186        let ts_init = UnixNanos::from(1_711_612_900_000_000_000u64);
7187        let greeks =
7188            parse_option_summary_greeks(&msgs[0], &instrument_id, OKXGreeksType::Bs, ts_init)
7189                .expect("parse failed");
7190
7191        assert_eq!(greeks.instrument_id, instrument_id);
7192        assert!((greeks.greeks.delta - 0.5312).abs() < 1e-10);
7193        assert!((greeks.greeks.gamma - 0.000_013_4).abs() < 1e-15);
7194        assert!((greeks.greeks.vega - 0.0038).abs() < 1e-10);
7195        assert!((greeks.greeks.theta - (-0.0015)).abs() < 1e-10);
7196        assert!((greeks.greeks.rho - 0.0).abs() < 1e-10);
7197        assert!((greeks.mark_iv.unwrap() - 0.53).abs() < 1e-10);
7198        assert!((greeks.bid_iv.unwrap() - 0.52).abs() < 1e-10);
7199        assert!((greeks.ask_iv.unwrap() - 0.55).abs() < 1e-10);
7200        assert!((greeks.underlying_price.unwrap() - 92150.50).abs() < 1e-10);
7201        assert!(greeks.open_interest.is_none());
7202        assert_eq!(greeks.convention, GreeksConvention::BlackScholes);
7203        assert_eq!(
7204            greeks.ts_event,
7205            UnixNanos::from(1_711_612_800_000_000_000u64)
7206        );
7207        assert_eq!(greeks.ts_init, ts_init);
7208    }
7209
7210    #[rstest]
7211    fn test_option_summary_msg_deserializes_with_uppercase_bs_alias() {
7212        let mut payload: Value =
7213            serde_json::from_str(&load_test_json("ws_opt_summary.json")).unwrap();
7214        let summary = payload[0].as_object_mut().unwrap();
7215
7216        // Preserve the original alias values while reusing the fixture's remaining fields
7217        for (key, alias, expected) in [
7218            ("deltaBs", "deltaBS", "0.53"),
7219            ("gammaBs", "gammaBS", "0.00002"),
7220            ("thetaBs", "thetaBS", "-0.002"),
7221            ("vegaBs", "vegaBS", "0.004"),
7222        ] {
7223            summary.insert(key.to_string(), Value::String(expected.to_string()));
7224            let value = summary.remove(key).unwrap();
7225            summary.insert(alias.to_string(), value);
7226        }
7227
7228        let msg: OKXOptionSummaryMsg = serde_json::from_value(payload[0].clone())
7229            .expect("deltaBS alias failed to deserialize");
7230        assert_eq!(msg.delta_bs, "0.53");
7231        assert_eq!(msg.gamma_bs, "0.00002");
7232        assert_eq!(msg.theta_bs, "-0.002");
7233        assert_eq!(msg.vega_bs, "0.004");
7234    }
7235
7236    #[rstest]
7237    fn test_parse_option_summary_greeks_put() {
7238        let json_str = load_test_json("ws_opt_summary.json");
7239        let msgs: Vec<OKXOptionSummaryMsg> =
7240            serde_json::from_str(&json_str).expect("Failed to deserialize opt-summary fixture");
7241
7242        let instrument_id = InstrumentId::from("BTC-USD-250328-92000-P.OKX");
7243        let ts_init = UnixNanos::from(1_711_612_900_000_000_000u64);
7244        let greeks =
7245            parse_option_summary_greeks(&msgs[1], &instrument_id, OKXGreeksType::Bs, ts_init)
7246                .expect("parse failed");
7247
7248        assert!((greeks.greeks.delta - (-0.4688)).abs() < 1e-10);
7249    }
7250
7251    #[rstest]
7252    fn test_parse_option_summary_greeks_pa() {
7253        let json_str = load_test_json("ws_opt_summary.json");
7254        let msgs: Vec<OKXOptionSummaryMsg> =
7255            serde_json::from_str(&json_str).expect("Failed to deserialize opt-summary fixture");
7256        assert_eq!(msgs.len(), 2);
7257
7258        let instrument_id = InstrumentId::from("BTC-USD-250328-92000-C.OKX");
7259        let ts_init = UnixNanos::from(1_711_612_900_000_000_000u64);
7260        let greeks =
7261            parse_option_summary_greeks(&msgs[0], &instrument_id, OKXGreeksType::Pa, ts_init)
7262                .expect("parse failed");
7263
7264        assert_eq!(greeks.instrument_id, instrument_id);
7265        assert!((greeks.greeks.delta - 0.5234).abs() < 1e-10);
7266        assert!((greeks.greeks.gamma - 0.000_012_3).abs() < 1e-15);
7267        assert!((greeks.greeks.vega - 0.0034).abs() < 1e-10);
7268        assert!((greeks.greeks.theta - (-0.0012)).abs() < 1e-10);
7269        assert!((greeks.greeks.rho - 0.0).abs() < 1e-10);
7270        assert!((greeks.mark_iv.unwrap() - 0.53).abs() < 1e-10);
7271        assert!((greeks.bid_iv.unwrap() - 0.52).abs() < 1e-10);
7272        assert!((greeks.ask_iv.unwrap() - 0.55).abs() < 1e-10);
7273        assert!((greeks.underlying_price.unwrap() - 92150.50).abs() < 1e-10);
7274        assert_eq!(greeks.convention, GreeksConvention::PriceAdjusted);
7275    }
7276
7277    #[rstest]
7278    fn test_parse_option_summary_greeks_pa_put() {
7279        let json_str = load_test_json("ws_opt_summary.json");
7280        let msgs: Vec<OKXOptionSummaryMsg> =
7281            serde_json::from_str(&json_str).expect("Failed to deserialize opt-summary fixture");
7282
7283        let instrument_id = InstrumentId::from("BTC-USD-250328-92000-P.OKX");
7284        let ts_init = UnixNanos::from(1_711_612_900_000_000_000u64);
7285        let greeks =
7286            parse_option_summary_greeks(&msgs[1], &instrument_id, OKXGreeksType::Pa, ts_init)
7287                .expect("parse failed");
7288
7289        assert!((greeks.greeks.delta - (-0.4766)).abs() < 1e-10);
7290    }
7291
7292    #[rstest]
7293    fn test_option_greeks_filtering_only_subscribed_instruments() {
7294        use ahash::AHashSet;
7295
7296        let json_str = load_test_json("ws_opt_summary.json");
7297        let msgs: Vec<OKXOptionSummaryMsg> =
7298            serde_json::from_str(&json_str).expect("Failed to deserialize");
7299
7300        let call_id = InstrumentId::from("BTC-USD-250328-92000-C.OKX");
7301        let put_id = InstrumentId::from("BTC-USD-250328-92000-P.OKX");
7302        let ts_init = UnixNanos::from(1_711_612_900_000_000_000u64);
7303
7304        // Subscribe to CALL only
7305        let mut subs = AHashSet::new();
7306        subs.insert(call_id);
7307
7308        let mut results = Vec::new();
7309
7310        for msg in &msgs {
7311            let inst_id_str = format!("{}.OKX", msg.inst_id);
7312            let instrument_id = InstrumentId::from(inst_id_str.as_str());
7313            if !subs.contains(&instrument_id) {
7314                continue;
7315            }
7316
7317            if let Ok(greeks) =
7318                parse_option_summary_greeks(msg, &instrument_id, OKXGreeksType::Bs, ts_init)
7319            {
7320                results.push(greeks);
7321            }
7322        }
7323
7324        assert_eq!(results.len(), 1);
7325        assert_eq!(results[0].instrument_id, call_id);
7326        assert!((results[0].greeks.delta - 0.5312).abs() < 1e-10);
7327
7328        // Now subscribe to both
7329        subs.insert(put_id);
7330
7331        let mut results = Vec::new();
7332
7333        for msg in &msgs {
7334            let inst_id_str = format!("{}.OKX", msg.inst_id);
7335            let instrument_id = InstrumentId::from(inst_id_str.as_str());
7336            if !subs.contains(&instrument_id) {
7337                continue;
7338            }
7339
7340            if let Ok(greeks) =
7341                parse_option_summary_greeks(msg, &instrument_id, OKXGreeksType::Bs, ts_init)
7342            {
7343                results.push(greeks);
7344            }
7345        }
7346
7347        assert_eq!(results.len(), 2);
7348    }
7349
7350    #[rstest]
7351    fn test_option_greeks_unsubscribed_instrument_filtered_out() {
7352        use ahash::AHashSet;
7353
7354        let json_str = load_test_json("ws_opt_summary.json");
7355        let msgs: Vec<OKXOptionSummaryMsg> =
7356            serde_json::from_str(&json_str).expect("Failed to deserialize");
7357
7358        let ts_init = UnixNanos::default();
7359
7360        // Empty subscription set
7361        let subs: AHashSet<InstrumentId> = AHashSet::new();
7362
7363        let mut results = Vec::new();
7364
7365        for msg in &msgs {
7366            let inst_id_str = format!("{}.OKX", msg.inst_id);
7367            let instrument_id = InstrumentId::from(inst_id_str.as_str());
7368            if !subs.contains(&instrument_id) {
7369                continue;
7370            }
7371
7372            if let Ok(greeks) =
7373                parse_option_summary_greeks(msg, &instrument_id, OKXGreeksType::Bs, ts_init)
7374            {
7375                results.push(greeks);
7376            }
7377        }
7378
7379        assert!(results.is_empty());
7380    }
7381
7382    #[rstest]
7383    fn test_option_greeks_family_dedup_subscribe_count() {
7384        use crate::common::parse::extract_inst_family;
7385
7386        let mut family_subs: AHashMap<Ustr, usize> = AHashMap::new();
7387
7388        let call_id = InstrumentId::from("BTC-USD-250328-92000-C.OKX");
7389        let put_id = InstrumentId::from("BTC-USD-250328-92000-P.OKX");
7390        let other_id = InstrumentId::from("BTC-USD-250328-80000-C.OKX");
7391
7392        // Subscribe first instrument: count goes to 1 (triggers WS subscribe)
7393        let family = extract_inst_family(call_id.symbol.inner().as_str()).unwrap();
7394        let count = family_subs.entry(family).or_default();
7395        *count += 1;
7396        assert_eq!(*count, 1);
7397        let should_subscribe_ws = *count == 1;
7398        assert!(should_subscribe_ws);
7399
7400        // Subscribe second instrument in same family: count goes to 2 (no WS subscribe)
7401        let family = extract_inst_family(put_id.symbol.inner().as_str()).unwrap();
7402        let count = family_subs.entry(family).or_default();
7403        *count += 1;
7404        assert_eq!(*count, 2);
7405        let should_subscribe_ws = *count == 1;
7406        assert!(!should_subscribe_ws);
7407
7408        // Subscribe third instrument in same family: count goes to 3
7409        let family = extract_inst_family(other_id.symbol.inner().as_str()).unwrap();
7410        let count = family_subs.entry(family).or_default();
7411        *count += 1;
7412        assert_eq!(*count, 3);
7413
7414        // Unsubscribe one: count goes to 2 (no WS unsubscribe)
7415        let family = extract_inst_family(call_id.symbol.inner().as_str()).unwrap();
7416        if let Some(count) = family_subs.get_mut(&family) {
7417            *count = count.saturating_sub(1);
7418            assert_eq!(*count, 2);
7419            let should_unsubscribe_ws = *count == 0;
7420            assert!(!should_unsubscribe_ws);
7421        }
7422
7423        // Unsubscribe second: count goes to 1
7424        let family = extract_inst_family(put_id.symbol.inner().as_str()).unwrap();
7425        if let Some(count) = family_subs.get_mut(&family) {
7426            *count = count.saturating_sub(1);
7427            assert_eq!(*count, 1);
7428        }
7429
7430        // Unsubscribe last: count goes to 0 (triggers WS unsubscribe)
7431        let family = extract_inst_family(other_id.symbol.inner().as_str()).unwrap();
7432        if let Some(count) = family_subs.get_mut(&family) {
7433            *count = count.saturating_sub(1);
7434            assert_eq!(*count, 0);
7435            let should_unsubscribe_ws = *count == 0;
7436            assert!(should_unsubscribe_ws);
7437        }
7438    }
7439
7440    #[rstest]
7441    fn test_parse_event_contract_markets_returns_raw_message() {
7442        let data = serde_json::json!([
7443            {
7444                "seriesId": "BTC-ABOVE-DAILY",
7445                "eventId": "BTC-ABOVE-DAILY-260224-1600",
7446                "instId": "BTC-ABOVE-DAILY-260224-1600-65000",
7447                "listTime": "1769697132335",
7448                "fixTime": "",
7449                "expTime": "1769697132335",
7450                "state": "live",
7451                "outcome": "0",
7452                "floorStrike": "120000",
7453                "capStrike": "",
7454                "settleValue": "",
7455                "disputed": false,
7456                "hitDir": ""
7457            },
7458            {
7459                "seriesId": "BTC-HIT-MONTHLY",
7460                "eventId": "BTC-HIT-MONTHLY-260831-1600",
7461                "instId": "BTC-HIT-MONTHLY-260831-1600-37500",
7462                "listTime": "1785513600000",
7463                "fixTime": "",
7464                "expTime": "1788192000000",
7465                "state": "live",
7466                "outcome": "0",
7467                "floorStrike": "37500",
7468                "capStrike": "",
7469                "settleValue": "",
7470                "disputed": false,
7471                "hitDir": "dn"
7472            }
7473        ]);
7474        let instrument_id = InstrumentId::from("BTC-ABOVE-DAILY-260224-1600-65000.OKX");
7475        let mut funding_cache = AHashMap::new();
7476        let instruments_cache = AHashMap::new();
7477
7478        let result = parse_ws_message_data(
7479            &OKXWsChannel::EventContractMarkets,
7480            data.clone(),
7481            &instrument_id,
7482            2,
7483            2,
7484            UnixNanos::default(),
7485            &mut funding_cache,
7486            &instruments_cache,
7487        )
7488        .unwrap();
7489
7490        match result {
7491            Some(NautilusWsMessage::Raw(raw)) => assert_eq!(raw, data),
7492            _ => panic!("Expected raw event contract market payload"),
7493        }
7494    }
7495
7496    #[rstest]
7497    fn test_parse_ws_message_data_spread_public_trades() {
7498        // sprd-public-trades keys the spread as `sprdId` and omits `count`; the
7499        // instrument is resolved from the channel arg, so the trade still parses.
7500        let data = serde_json::json!([{
7501            "sprdId": "ETH-USD-260925_ETH-USD-261225",
7502            "tradeId": "3392538740127301632",
7503            "px": "16.9",
7504            "sz": "100",
7505            "side": "sell",
7506            "ts": "1780047866507"
7507        }]);
7508        let instrument_id = InstrumentId::from("ETH-USD-260925_ETH-USD-261225.OKX");
7509        let mut funding_cache = AHashMap::new();
7510        let instruments_cache = AHashMap::new();
7511
7512        let result = parse_ws_message_data(
7513            &OKXWsChannel::SprdPublicTrades,
7514            data,
7515            &instrument_id,
7516            1,
7517            0,
7518            UnixNanos::default(),
7519            &mut funding_cache,
7520            &instruments_cache,
7521        )
7522        .unwrap();
7523
7524        let Some(NautilusWsMessage::Data(data_vec)) = result else {
7525            panic!("expected Data variant, was {result:?}");
7526        };
7527        assert_eq!(data_vec.len(), 1);
7528        let Data::Trade(trade) = &data_vec[0] else {
7529            panic!("expected Data::Trade, was {:?}", data_vec[0]);
7530        };
7531        assert_eq!(trade.instrument_id, instrument_id);
7532        assert_eq!(trade.price.as_decimal(), dec!(16.9));
7533        assert_eq!(trade.size.as_decimal(), dec!(100));
7534        assert_eq!(trade.aggressor_side, AggressorSide::Sell);
7535    }
7536
7537    #[rstest]
7538    fn test_parse_spread_books5_snapshot_with_three_element_levels() {
7539        // sprd-books5 pushes a full snapshot with 3-element `[price, size, count]`
7540        // levels; it is parsed as a snapshot (F_SNAPSHOT), not an incremental update.
7541        let msg: OKXBookMsg = serde_json::from_value(serde_json::json!({
7542            "asks": [["16.7", "100", "1"]],
7543            "bids": [["16.65", "100", "1"]],
7544            "ts": "1780044924909",
7545            "seqId": 1_779_935_772_619_784_u64,
7546        }))
7547        .unwrap();
7548        let instrument_id = InstrumentId::from("ETH-USD-260925_ETH-USD-261225.OKX");
7549
7550        let deltas = parse_book_msg(
7551            &msg,
7552            instrument_id,
7553            2,
7554            0,
7555            &OKXBookAction::Snapshot,
7556            UnixNanos::default(),
7557        )
7558        .unwrap();
7559
7560        assert_eq!(deltas.instrument_id, instrument_id);
7561        assert_eq!(
7562            deltas.flags,
7563            RecordFlag::F_SNAPSHOT as u8 | RecordFlag::F_LAST as u8
7564        );
7565        let bid = deltas
7566            .deltas
7567            .iter()
7568            .find(|d| d.order.side == OrderSide::Buy.into())
7569            .expect("should have a bid delta");
7570        let ask = deltas
7571            .deltas
7572            .iter()
7573            .find(|d| d.order.side == OrderSide::Sell.into())
7574            .expect("should have an ask delta");
7575        assert_eq!(bid.order.price.as_decimal(), dec!(16.65));
7576        assert_eq!(ask.order.price.as_decimal(), dec!(16.7));
7577    }
7578
7579    #[rstest]
7580    #[case(OKXPositionSide::Long, Some("BTC-USDT-SWAP.OKX-LONG"))]
7581    #[case(OKXPositionSide::Short, Some("BTC-USDT-SWAP.OKX-SHORT"))]
7582    #[case(OKXPositionSide::Net, None)]
7583    #[case(OKXPositionSide::None, None)]
7584    fn test_order_and_fill_position_ids(
7585        #[case] side: OKXPositionSide,
7586        #[case] expected: Option<&str>,
7587    ) {
7588        let payload: Value = serde_json::from_str(&load_test_json("ws_orders.json")).unwrap();
7589        let mut msg: OKXOrderMsg = serde_json::from_value(payload["data"][0].clone()).unwrap();
7590        msg.pos_side = side;
7591        let instrument = InstrumentAny::CryptoPerpetual(create_stub_instrument());
7592        let account_id = AccountId::from("OKX-001");
7593        let order =
7594            parse_order_status_report(&msg, &instrument, account_id, UnixNanos::default()).unwrap();
7595        let fill = parse_fill_report(
7596            &msg,
7597            &instrument,
7598            account_id,
7599            None,
7600            None,
7601            UnixNanos::default(),
7602        )
7603        .unwrap()
7604        .unwrap();
7605        let expected = expected.map(PositionId::from);
7606        assert_eq!(order.venue_position_id, expected);
7607        assert_eq!(fill.venue_position_id, expected);
7608    }
7609
7610    #[rstest]
7611    #[case(OKXPositionSide::Long, Some("BTC-USDT-SWAP.OKX-LONG"))]
7612    #[case(OKXPositionSide::Short, Some("BTC-USDT-SWAP.OKX-SHORT"))]
7613    #[case(OKXPositionSide::Net, None)]
7614    fn test_algo_order_position_id(#[case] side: OKXPositionSide, #[case] expected: Option<&str>) {
7615        let payload: Value = serde_json::from_str(&load_test_json("ws_orders_algo.json")).unwrap();
7616        let mut msg: OKXAlgoOrderMsg = serde_json::from_value(payload["data"][0].clone()).unwrap();
7617        msg.pos_side = side;
7618        let instrument = InstrumentAny::CryptoPerpetual(create_stub_instrument());
7619        let report = parse_algo_order_status_report(
7620            &msg,
7621            &instrument,
7622            AccountId::from("OKX-001"),
7623            UnixNanos::default(),
7624        )
7625        .unwrap();
7626        assert_eq!(report.venue_position_id, expected.map(PositionId::from));
7627    }
7628}