Skip to main content

nautilus_okx/common/
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//! Parsing utilities that convert OKX payloads into Nautilus domain models.
17
18use std::str::FromStr;
19
20use anyhow::Context;
21use indexmap::IndexMap;
22use jiff::Timestamp;
23pub use nautilus_core::serialization::{
24    deserialize_empty_string_as_none, deserialize_empty_ustr_as_none,
25    deserialize_optional_string_to_u64, deserialize_string_to_u64,
26};
27use nautilus_core::{Params, UUID4, datetime::NANOSECONDS_IN_MILLISECOND, nanos::UnixNanos};
28use nautilus_model::{
29    data::{
30        Bar, BarSpecification, BarType, Data, FundingRateUpdate, IndexPriceUpdate, MarkPriceUpdate,
31        TradeTick,
32        bar::{
33            BAR_SPEC_1_DAY_LAST, BAR_SPEC_1_HOUR_LAST, BAR_SPEC_1_MINUTE_LAST,
34            BAR_SPEC_1_MONTH_LAST, BAR_SPEC_1_SECOND_LAST, BAR_SPEC_1_WEEK_LAST,
35            BAR_SPEC_2_DAY_LAST, BAR_SPEC_2_HOUR_LAST, BAR_SPEC_3_DAY_LAST, BAR_SPEC_3_MINUTE_LAST,
36            BAR_SPEC_3_MONTH_LAST, BAR_SPEC_4_HOUR_LAST, BAR_SPEC_5_DAY_LAST,
37            BAR_SPEC_5_MINUTE_LAST, BAR_SPEC_6_HOUR_LAST, BAR_SPEC_6_MONTH_LAST,
38            BAR_SPEC_12_HOUR_LAST, BAR_SPEC_12_MONTH_LAST, BAR_SPEC_15_MINUTE_LAST,
39            BAR_SPEC_30_MINUTE_LAST,
40        },
41    },
42    enums::{
43        AccountType, AggregationSource, AggressorSide, AssetClass, ExerciseStyle, LiquiditySide,
44        MarketStatusAction, OptionKind, OrderSide, OrderStatus, OrderType, PositionSide,
45        SettlementType, TimeInForce,
46    },
47    events::AccountState,
48    identifiers::{
49        AccountId, ClientOrderId, InstrumentId, PositionId, Symbol, TradeId, VenueOrderId,
50    },
51    instruments::{
52        BinaryOption, CryptoFuture, CryptoFuturesSpread, CryptoOption, CryptoOptionSpread,
53        CryptoPerpetual, CurrencyPair, InstrumentAny,
54    },
55    reports::{FillReport, OrderStatusReport, PositionStatusReport},
56    types::{AccountBalance, Currency, MarginBalance, Money, Price, Quantity},
57};
58use rust_decimal::Decimal;
59use serde::{Deserialize, Deserializer, de::DeserializeOwned};
60use ustr::Ustr;
61
62use super::enums::OKXContractType;
63use crate::{
64    common::{
65        consts::OKX_VENUE,
66        enums::{
67            OKXExecType, OKXInstrumentCategory, OKXInstrumentStatus, OKXInstrumentType,
68            OKXOrderCategory, OKXOrderStatus, OKXOrderType, OKXPositionSide, OKXSide,
69            OKXSpreadState, OKXSpreadType, OKXTargetCurrency, OKXVipLevel,
70        },
71        models::OKXInstrument,
72    },
73    http::models::{
74        OKXAccount, OKXCandlestick, OKXFundingRateHistory, OKXIndexTicker, OKXMarkPrice,
75        OKXOrderHistory, OKXPosition, OKXSpread, OKXSpreadOrder, OKXSpreadTrade, OKXTrade,
76        OKXTransactionDetail,
77    },
78    websocket::{enums::OKXWsChannel, messages::OKXFundingRateMsg},
79};
80
81pub(crate) fn prefer_rpi_response_fields(value: &mut serde_json::Value) {
82    match value {
83        serde_json::Value::Object(fields) => {
84            for (current, legacy) in [("rpi", "elp"), ("rpiMaker", "elpMaker")] {
85                if fields.contains_key(current) {
86                    fields.remove(legacy);
87                } else if let Some(legacy_value) = fields.remove(legacy) {
88                    fields.insert(current.to_string(), legacy_value);
89                }
90            }
91
92            for (name, nested) in fields.iter_mut() {
93                // Fee groups expose current and legacy rates independently
94                if name != "feeGroup" {
95                    prefer_rpi_response_fields(nested);
96                }
97            }
98        }
99        serde_json::Value::Array(items) => {
100            for item in items {
101                prefer_rpi_response_fields(item);
102            }
103        }
104        _ => {}
105    }
106}
107
108/// Determines if a price string represents a market order.
109///
110/// OKX uses special values to indicate market execution:
111/// - Empty string
112/// - "0"
113/// - "-1" (optimal market price)
114/// - "-2" (optimal market price, alternate)
115pub fn is_market_price(px: &str) -> bool {
116    px.is_empty() || px == "0" || px == "-1" || px == "-2"
117}
118
119/// Determines the [`OrderType`] from OKX order type and price.
120///
121/// For FOK, IOC, and `OptimalLimitIoc` orders, the presence of a price
122/// determines whether it's a market or limit order execution.
123///
124/// # Errors
125///
126/// Returns an error if the OKX order type has no Nautilus equivalent.
127pub fn determine_order_type(okx_ord_type: OKXOrderType, px: &str) -> anyhow::Result<OrderType> {
128    determine_order_type_with_alt(okx_ord_type, px, "", "")
129}
130
131/// Like [`determine_order_type`] but considers alternative pricing fields.
132///
133/// When options are priced via `px_vol` or `px_usd`, the primary `px` field
134/// is empty. Treating that as a market order is wrong: the order was a limit
135/// priced in an alternative unit.
136///
137/// # Errors
138///
139/// Returns an error if the OKX order type has no Nautilus equivalent.
140pub fn determine_order_type_with_alt(
141    okx_ord_type: OKXOrderType,
142    px: &str,
143    px_vol: &str,
144    px_usd: &str,
145) -> anyhow::Result<OrderType> {
146    match okx_ord_type {
147        OKXOrderType::OpFok => Ok(OrderType::Limit),
148        OKXOrderType::Fok | OKXOrderType::Ioc | OKXOrderType::OptimalLimitIoc => {
149            let has_alt_price = !px_vol.is_empty() || !px_usd.is_empty();
150            if has_alt_price || !is_market_price(px) {
151                Ok(OrderType::Limit)
152            } else {
153                Ok(OrderType::Market)
154            }
155        }
156        other => other
157            .try_into()
158            .map_err(|e| anyhow::anyhow!("Unsupported OKX order type: {e}")),
159    }
160}
161
162/// Deserializes a string into `Option<OKXTargetCurrency>`, treating empty strings as `None`.
163///
164/// # Errors
165///
166/// Returns an error if the string cannot be parsed into an `OKXTargetCurrency`.
167pub fn deserialize_target_currency_as_none<'de, D>(
168    deserializer: D,
169) -> Result<Option<OKXTargetCurrency>, D::Error>
170where
171    D: Deserializer<'de>,
172{
173    let s = String::deserialize(deserializer)?;
174    if s.is_empty() {
175        Ok(None)
176    } else {
177        s.parse().map(Some).map_err(serde::de::Error::custom)
178    }
179}
180
181/// Deserializes an OKX VIP level string into [`OKXVipLevel`].
182///
183/// OKX returns VIP levels in multiple formats:
184/// - "VIP0", "VIP1", ..., "VIP9" (VIP tier format)
185/// - "Lv0", "Lv1", ..., "Lv9" (Level format)
186/// - "0", "1", ..., "9" (bare numeric)
187/// - "" (empty string, defaults to VIP0)
188///
189/// This function handles all formats by stripping any prefix and parsing the numeric value.
190///
191/// # Errors
192///
193/// Returns an error if the string cannot be parsed into a valid VIP level.
194pub fn deserialize_vip_level<'de, D>(deserializer: D) -> Result<OKXVipLevel, D::Error>
195where
196    D: Deserializer<'de>,
197{
198    let s = String::deserialize(deserializer)?;
199
200    if s.is_empty() {
201        return Ok(OKXVipLevel::Vip0);
202    }
203
204    let level_str = if s.len() >= 3 && s[..3].eq_ignore_ascii_case("vip") {
205        &s[3..]
206    } else if s.len() >= 2 && s[..2].eq_ignore_ascii_case("lv") {
207        &s[2..]
208    } else {
209        &s
210    };
211
212    let level_num = level_str
213        .parse::<u8>()
214        .map_err(|e| serde::de::Error::custom(format!("Invalid VIP level '{s}': {e}")))?;
215
216    Ok(OKXVipLevel::from(level_num))
217}
218
219/// Returns the [`OKXInstrumentType`] that corresponds to the supplied
220/// [`InstrumentAny`].
221///
222/// # Errors
223///
224/// Returns an error if the instrument variant is not supported by OKX.
225pub fn okx_instrument_type(instrument: &InstrumentAny) -> anyhow::Result<OKXInstrumentType> {
226    match instrument {
227        InstrumentAny::BinaryOption(_) => Ok(OKXInstrumentType::Events),
228        InstrumentAny::CurrencyPair(_) => Ok(OKXInstrumentType::Spot),
229        InstrumentAny::CryptoPerpetual(_) => Ok(OKXInstrumentType::Swap),
230        InstrumentAny::CryptoFuture(_) => Ok(OKXInstrumentType::Futures),
231        InstrumentAny::CryptoOption(_) => Ok(OKXInstrumentType::Option),
232        _ => anyhow::bail!("Invalid instrument type for OKX: {instrument:?}"),
233    }
234}
235
236/// Returns whether the OKX symbol uses the spread ID format.
237#[must_use]
238pub fn is_okx_spread_symbol(symbol: &str) -> bool {
239    let Some((base, _)) = symbol.split_once('-') else {
240        return false;
241    };
242
243    symbol.split('_').skip(1).any(|leg| {
244        leg.split_once('-')
245            .is_some_and(|(leg_base, _)| leg_base == base)
246    })
247}
248
249/// Parses `OKXInstrumentType` from an instrument symbol.
250///
251/// OKX instrument symbol formats:
252/// - SPOT: {BASE}-{QUOTE} (e.g., BTC-USDT)
253/// - MARGIN: {BASE}-{QUOTE} (same as SPOT, determined by trade mode)
254/// - SWAP: {BASE}-{QUOTE}-SWAP (e.g., BTC-USDT-SWAP)
255/// - FUTURES: {BASE}-{QUOTE}-{YYMMDD} (e.g., BTC-USDT-250328)
256/// - OPTION: {BASE}-{QUOTE}-{YYMMDD}-{STRIKE}-{C/P} (e.g., BTC-USD-250328-50000-C)
257/// - EVENTS: venue-defined event contract IDs (e.g., BTC-ABOVE-DAILY-260224-1600-65000)
258pub fn okx_instrument_type_from_symbol(symbol: &str) -> OKXInstrumentType {
259    // Count dashes to determine part count
260    let dash_count = symbol.bytes().filter(|&b| b == b'-').count();
261
262    match dash_count {
263        1 => OKXInstrumentType::Spot, // 2 parts: BASE-QUOTE
264        2 => {
265            // 3 parts: Check suffix after last dash
266            let suffix = symbol.rsplit('-').next().unwrap_or("");
267            if suffix == "SWAP" {
268                OKXInstrumentType::Swap
269            } else if suffix.len() == 6 && suffix.bytes().all(|b| b.is_ascii_digit()) {
270                // Date format YYMMDD
271                OKXInstrumentType::Futures
272            } else {
273                OKXInstrumentType::Spot
274            }
275        }
276        4 => {
277            let suffix = symbol.rsplit('-').next().unwrap_or("");
278            if matches!(suffix, "C" | "P") {
279                OKXInstrumentType::Option
280            } else {
281                OKXInstrumentType::Events
282            }
283        }
284        _ if dash_count > 4 => OKXInstrumentType::Events,
285        _ => OKXInstrumentType::Spot, // Default fallback
286    }
287}
288
289/// Extracts base and quote currencies from an OKX symbol.
290///
291/// All OKX instrument symbols start with {BASE}-{QUOTE}, regardless of type.
292///
293/// # Errors
294///
295/// Returns an error if the symbol doesn't contain at least two parts separated by '-'.
296pub fn parse_base_quote_from_symbol(symbol: &str) -> anyhow::Result<(&str, &str)> {
297    let mut parts = symbol.split('-');
298    let base = parts.next().ok_or_else(|| {
299        anyhow::anyhow!("Invalid symbol format: missing base currency in '{symbol}'")
300    })?;
301    let quote = parts.next().ok_or_else(|| {
302        anyhow::anyhow!("Invalid symbol format: missing quote currency in '{symbol}'")
303    })?;
304    Ok((base, quote))
305}
306
307/// Extracts the instrument family from an OKX symbol string.
308///
309/// All OKX derivative symbols encode the family as the first two segments:
310/// `BTC-USD-250328-92000-C` -> `BTC-USD`, `BTC-USDT-SWAP` -> `BTC-USDT`.
311///
312/// # Errors
313///
314/// Returns an error if the symbol does not contain at least two dash-separated parts.
315pub fn extract_inst_family(symbol: &str) -> anyhow::Result<Ustr> {
316    let (base, quote) = parse_base_quote_from_symbol(symbol)?;
317    Ok(Ustr::from(&format!("{base}-{quote}")))
318}
319
320/// Maps an [`OKXInstrumentStatus`] to a Nautilus [`MarketStatusAction`].
321#[must_use]
322pub fn okx_status_to_market_action(status: OKXInstrumentStatus) -> MarketStatusAction {
323    match status {
324        OKXInstrumentStatus::Live => MarketStatusAction::Trading,
325        OKXInstrumentStatus::Suspend => MarketStatusAction::Suspend,
326        OKXInstrumentStatus::Preopen => MarketStatusAction::PreOpen,
327        OKXInstrumentStatus::Test => MarketStatusAction::NotAvailableForTrading,
328        OKXInstrumentStatus::PostOnly => MarketStatusAction::Quoting,
329        OKXInstrumentStatus::Rebase => MarketStatusAction::NotAvailableForTrading,
330        OKXInstrumentStatus::Settling => MarketStatusAction::NotAvailableForTrading,
331        OKXInstrumentStatus::Unknown => MarketStatusAction::NotAvailableForTrading,
332    }
333}
334
335/// Parses a Nautilus instrument ID from the given OKX `symbol` value.
336#[must_use]
337pub fn parse_instrument_id(symbol: Ustr) -> InstrumentId {
338    InstrumentId::new(Symbol::from_ustr_unchecked(symbol), *OKX_VENUE)
339}
340
341/// Parses a Nautilus client order ID from the given OKX `clOrdId` value.
342#[must_use]
343pub fn parse_client_order_id(value: &str) -> Option<ClientOrderId> {
344    if value.is_empty() {
345        None
346    } else {
347        Some(ClientOrderId::new(value))
348    }
349}
350
351pub(crate) fn parse_parent_client_order_id(
352    algo_client_order_id: Option<&str>,
353    client_order_id: &str,
354) -> Option<ClientOrderId> {
355    // OKX keeps the submitted algo client ID when it creates a triggered child order.
356    algo_client_order_id
357        .and_then(parse_client_order_id)
358        .or_else(|| parse_client_order_id(client_order_id))
359}
360
361pub(crate) fn is_order_status_report_more_advanced(
362    candidate: &OrderStatusReport,
363    current: &OrderStatusReport,
364) -> bool {
365    if candidate.filled_qty != current.filled_qty {
366        return candidate.filled_qty > current.filled_qty;
367    }
368
369    let candidate_priority = order_status_priority(candidate.order_status);
370    let current_priority = order_status_priority(current.order_status);
371    if candidate_priority != current_priority {
372        return candidate_priority > current_priority;
373    }
374
375    candidate.ts_last > current.ts_last
376}
377
378const fn order_status_priority(status: OrderStatus) -> u8 {
379    match status {
380        OrderStatus::Initialized | OrderStatus::Submitted | OrderStatus::Emulated => 0,
381        OrderStatus::Released | OrderStatus::Denied => 1,
382        OrderStatus::Accepted | OrderStatus::PendingUpdate | OrderStatus::PendingCancel => 2,
383        OrderStatus::Triggered => 3,
384        OrderStatus::PartiallyFilled => 4,
385        OrderStatus::Canceled | OrderStatus::Expired | OrderStatus::Rejected => 5,
386        OrderStatus::Filled | OrderStatus::Voided => 6,
387    }
388}
389
390/// Converts a millisecond-based timestamp (as returned by OKX) into
391/// [`UnixNanos`].
392#[must_use]
393pub fn parse_millisecond_timestamp(timestamp_ms: u64) -> UnixNanos {
394    UnixNanos::from(timestamp_ms * NANOSECONDS_IN_MILLISECOND)
395}
396
397/// Parses an RFC 3339 timestamp string into [`UnixNanos`].
398///
399/// # Errors
400///
401/// Returns an error if the string is not a valid RFC 3339 datetime or if the
402/// timestamp cannot be represented in nanoseconds.
403pub fn parse_rfc3339_timestamp(timestamp: &str) -> anyhow::Result<UnixNanos> {
404    let dt = timestamp.parse::<Timestamp>()?;
405    let nanos = dt.as_nanosecond();
406    if nanos < 0 {
407        anyhow::bail!("Negative nanosecond timestamp from: {timestamp}");
408    }
409    let nanos = u64::try_from(nanos)
410        .with_context(|| format!("Timestamp is outside the UnixNanos range: {timestamp}"))?;
411    Ok(UnixNanos::from(nanos))
412}
413
414/// Converts a textual price to a [`Price`] using the given precision.
415///
416/// # Errors
417///
418/// Returns an error if the string fails to parse into `Decimal` or if the number
419/// of decimal places exceeds `precision`.
420pub fn parse_price(value: &str, precision: u8) -> anyhow::Result<Price> {
421    let decimal = Decimal::from_str(value)?;
422    Price::from_decimal_dp(decimal, precision).map_err(Into::into)
423}
424
425/// Converts a textual quantity to a [`Quantity`].
426///
427/// # Errors
428///
429/// Returns an error if parsing fails or precision is invalid, as in [`parse_price`].
430pub fn parse_quantity(value: &str, precision: u8) -> anyhow::Result<Quantity> {
431    let decimal = Decimal::from_str(value)?;
432    Quantity::from_decimal_dp(decimal, precision).map_err(Into::into)
433}
434
435/// Converts a textual fee amount into a [`Money`] value.
436///
437/// OKX represents *charges* as positive numbers but they reduce the account
438/// balance, hence the value is negated.
439///
440/// # Errors
441///
442/// Returns an error if the fee is missing or empty, cannot be parsed into
443/// `Decimal`, or fails internal validation in [`Money::from_decimal`].
444pub fn parse_fee(value: Option<&str>, currency: Currency) -> anyhow::Result<Money> {
445    // OKX uses opposite sign convention: negative = cost, positive = rebate.
446    // Negate to match Nautilus convention: positive = cost, negative = rebate.
447    let decimal = required_fee_amount(value)?;
448    Money::from_decimal(-decimal, currency).map_err(Into::into)
449}
450
451fn required_fee_amount(value: Option<&str>) -> anyhow::Result<Decimal> {
452    let value = value
453        .map(str::trim)
454        .filter(|fee| !fee.is_empty())
455        .ok_or_else(|| anyhow::anyhow!("missing fee"))?;
456    Decimal::from_str(value).map_err(Into::into)
457}
458
459/// Parses OKX fee currency code, handling empty strings.
460///
461/// OKX sometimes returns empty fee currency codes.
462/// When the fee currency is empty, defaults to USDT and logs a warning for non-zero fees.
463pub fn parse_fee_currency(
464    fee_ccy: &str,
465    fee_amount: Decimal,
466    context: impl FnOnce() -> String,
467) -> Currency {
468    let trimmed = fee_ccy.trim();
469    if trimmed.is_empty() {
470        if !fee_amount.is_zero() {
471            let ctx = context();
472            log::warn!(
473                "Empty fee_ccy in {ctx} with non-zero fee={fee_amount}, using USDT as fallback"
474            );
475        }
476        return Currency::USDT();
477    }
478
479    // Non-empty path: skip context() to avoid the format-string allocation that
480    // `get_or_create_crypto_with_context` would only consume in its own
481    // empty-input warning branch (which we have already short-circuited above).
482    Currency::get_or_create_crypto(trimmed)
483}
484
485/// Parses OKX side to Nautilus aggressor side.
486pub fn parse_aggressor_side(side: &Option<OKXSide>) -> AggressorSide {
487    match side {
488        Some(OKXSide::Buy) => AggressorSide::Buy,
489        Some(OKXSide::Sell) => AggressorSide::Sell,
490        None => AggressorSide::NoAggressor,
491    }
492}
493
494/// Parses OKX execution type to Nautilus liquidity side.
495pub fn parse_execution_type(liquidity: &Option<OKXExecType>) -> LiquiditySide {
496    match liquidity {
497        Some(OKXExecType::Maker) => LiquiditySide::Maker,
498        Some(OKXExecType::Taker) => LiquiditySide::Taker,
499        _ => LiquiditySide::NoLiquiditySide,
500    }
501}
502
503/// Parses quantity to Nautilus position side.
504pub fn parse_position_side(current_qty: Option<i64>) -> PositionSide {
505    match current_qty {
506        Some(qty) if qty > 0 => PositionSide::Long,
507        Some(qty) if qty < 0 => PositionSide::Short,
508        _ => PositionSide::Flat,
509    }
510}
511
512/// Parses an OKX mark price record into a Nautilus [`MarkPriceUpdate`].
513///
514/// # Errors
515///
516/// Returns an error if `raw.mark_px` cannot be parsed into a [`Price`] with
517/// the specified precision.
518pub fn parse_mark_price_update(
519    raw: &OKXMarkPrice,
520    instrument_id: InstrumentId,
521    price_precision: u8,
522    ts_init: UnixNanos,
523) -> anyhow::Result<MarkPriceUpdate> {
524    let ts_event = parse_millisecond_timestamp(raw.ts);
525    let price = parse_price(&raw.mark_px, price_precision)?;
526    Ok(MarkPriceUpdate::new(
527        instrument_id,
528        price,
529        ts_event,
530        ts_init,
531    ))
532}
533
534/// Parses an OKX index ticker record into a Nautilus [`IndexPriceUpdate`].
535///
536/// # Errors
537///
538/// Returns an error if `raw.idx_px` cannot be parsed into a [`Price`] with the
539/// specified precision.
540pub fn parse_index_price_update(
541    raw: &OKXIndexTicker,
542    instrument_id: InstrumentId,
543    price_precision: u8,
544    ts_init: UnixNanos,
545) -> anyhow::Result<IndexPriceUpdate> {
546    let ts_event = parse_millisecond_timestamp(raw.ts);
547    let price = parse_price(&raw.idx_px, price_precision)?;
548    Ok(IndexPriceUpdate::new(
549        instrument_id,
550        price,
551        ts_event,
552        ts_init,
553    ))
554}
555
556/// Parses an [`OKXFundingRateMsg`] into a [`FundingRateUpdate`].
557///
558/// # Errors
559///
560/// Returns an error if the `funding_rate` field fails
561/// to parse into a Decimal value or `next_funding_time` fails to parse into a positive, in bounds interval.
562pub fn parse_funding_rate_msg(
563    msg: &OKXFundingRateMsg,
564    instrument_id: InstrumentId,
565    ts_init: UnixNanos,
566) -> anyhow::Result<FundingRateUpdate> {
567    let funding_rate = msg
568        .funding_rate
569        .as_str()
570        .parse::<Decimal>()
571        .map_err(|e| anyhow::anyhow!("Invalid funding_rate value: {e}"))?;
572
573    let funding_time = parse_millisecond_timestamp(msg.funding_time);
574    let next_funding_time = parse_millisecond_timestamp(msg.next_funding_time);
575    let funding_interval_nanos =
576        next_funding_time
577            .duration_since(&funding_time)
578            .ok_or(anyhow::anyhow!(
579                "Invalid funding_interval, cannot be negative"
580            ))?;
581    let funding_interval = u16::try_from(funding_interval_nanos.as_mins())
582        .context("funding_interval out of bounds")?;
583    let ts_event = parse_millisecond_timestamp(msg.ts);
584
585    Ok(FundingRateUpdate::new(
586        instrument_id,
587        funding_rate,
588        Some(funding_interval),
589        Some(funding_time),
590        ts_event,
591        ts_init,
592    ))
593}
594
595/// Parses a [`OKXFundingRateHistory`] into a [`FundingRateUpdate`].
596///
597/// # Errors
598///
599/// Returns an error if the `funding_rate` field fails
600/// to parse into a Decimal value or `interval_millis` fails to parse into a positive, in bounds interval.
601pub fn parse_funding_rate(
602    raw: &OKXFundingRateHistory,
603    instrument_id: InstrumentId,
604    interval_millis: Option<u64>,
605) -> anyhow::Result<FundingRateUpdate> {
606    let funding_rate =
607        Decimal::from_str(&raw.funding_rate).context("invalid funding_rate value")?;
608    let ts_event = UnixNanos::from(raw.funding_time * NANOSECONDS_IN_MILLISECOND);
609    let interval = interval_millis
610        .map(|ms| u16::try_from(ms / 60_000).context("interval milliseconds out of bounds"))
611        .transpose()?;
612
613    Ok(FundingRateUpdate::new(
614        instrument_id,
615        funding_rate,
616        interval,
617        None,
618        ts_event,
619        ts_event,
620    ))
621}
622
623/// Parses an OKX trade record into a Nautilus [`TradeTick`].
624///
625/// # Errors
626///
627/// Returns an error if the price or quantity strings cannot be parsed, or if
628/// [`TradeTick::new_checked`] validation fails.
629pub fn parse_trade_tick(
630    raw: &OKXTrade,
631    instrument_id: InstrumentId,
632    price_precision: u8,
633    size_precision: u8,
634    ts_init: UnixNanos,
635) -> anyhow::Result<TradeTick> {
636    let ts_event = parse_millisecond_timestamp(raw.ts);
637    let price = parse_price(&raw.px, price_precision)?;
638    let size = parse_quantity(&raw.sz, size_precision)?;
639    let aggressor: AggressorSide = raw.side.into();
640    let trade_id = TradeId::new(raw.trade_id);
641
642    TradeTick::new_checked(
643        instrument_id,
644        price,
645        size,
646        aggressor,
647        trade_id,
648        ts_event,
649        ts_init,
650    )
651}
652
653/// Parses an OKX historical candlestick record into a Nautilus [`Bar`].
654///
655/// # Errors
656///
657/// Returns an error if any of the price or volume strings cannot be parsed or
658/// if [`Bar::new`] validation fails.
659pub fn parse_candlestick(
660    raw: &OKXCandlestick,
661    bar_type: BarType,
662    price_precision: u8,
663    size_precision: u8,
664    ts_init: UnixNanos,
665) -> anyhow::Result<Bar> {
666    let ts_event = parse_millisecond_timestamp(raw.0.parse()?);
667    let open = parse_price(&raw.1, price_precision)?;
668    let high = parse_price(&raw.2, price_precision)?;
669    let low = parse_price(&raw.3, price_precision)?;
670    let close = parse_price(&raw.4, price_precision)?;
671    let volume = parse_quantity(&raw.5, size_precision)?;
672
673    Ok(Bar::new(
674        bar_type, open, high, low, close, volume, ts_event, ts_init,
675    ))
676}
677
678/// Parses an OKX order history record into a Nautilus [`OrderStatusReport`].
679///
680/// # Errors
681///
682/// Returns an error if the average price cannot be converted to a valid `Decimal`.
683#[expect(clippy::too_many_lines)]
684pub fn parse_order_status_report(
685    order: &OKXOrderHistory,
686    account_id: AccountId,
687    instrument_id: InstrumentId,
688    price_precision: u8,
689    size_precision: u8,
690    ts_init: UnixNanos,
691) -> anyhow::Result<OrderStatusReport> {
692    match order.category {
693        OKXOrderCategory::FullLiquidation | OKXOrderCategory::PartialLiquidation => {
694            log::warn!(
695                "Liquidation order (HTTP history): ord_id={}, category={:?}, inst_id={}, state={:?}, side={:?}, sz={}, fill_sz={}",
696                order.ord_id,
697                order.category,
698                instrument_id,
699                order.state,
700                order.side,
701                order.sz,
702                order.acc_fill_sz,
703            );
704        }
705        OKXOrderCategory::Adl => {
706            log::warn!(
707                "ADL (Auto-Deleveraging) order (HTTP history): ord_id={}, inst_id={}, state={:?}, side={:?}, sz={}, fill_sz={}",
708                order.ord_id,
709                instrument_id,
710                order.state,
711                order.side,
712                order.sz,
713                order.acc_fill_sz,
714            );
715        }
716        _ => {}
717    }
718
719    let okx_ord_type: OKXOrderType = order.ord_type;
720    let order_type =
721        determine_order_type_with_alt(okx_ord_type, &order.px, &order.px_vol, &order.px_usd)?;
722
723    // Parse quantities based on target currency
724    // OKX always returns acc_fill_sz in base currency, but sz depends on tgt_ccy
725
726    // Determine if this is a quote-quantity order
727    // Method 1: Explicit tgt_ccy field set to QuoteCcy
728    let is_quote_qty_explicit = order.tgt_ccy == Some(OKXTargetCurrency::QuoteCcy);
729
730    // Method 2: Use OKX defaults when tgt_ccy is None (old orders or missing field)
731    // OKX API defaults for SPOT market orders: BUY orders use quote_ccy, SELL orders use base_ccy
732    // Note: tgtCcy only applies to SPOT market orders (not limit orders)
733    // For limit orders, sz is always in base currency regardless of side
734    let is_quote_qty_heuristic = order.tgt_ccy.is_none()
735        && (order.inst_type == OKXInstrumentType::Spot
736            || order.inst_type == OKXInstrumentType::Margin)
737        && order.side == OKXSide::Buy
738        && order_type == OrderType::Market;
739
740    let (quantity, filled_qty) = if is_quote_qty_explicit || is_quote_qty_heuristic {
741        // Quote-quantity order: sz is in quote currency, need to convert to base
742        let sz_quote_dec = Decimal::from_str(&order.sz).ok();
743
744        // Determine the price to use for conversion
745        // Priority: 1) limit price (px) for limit orders, 2) avg_px for market orders
746        let conversion_price_dec = if !order.px.is_empty() && order.px != "0" {
747            // Limit order: use the limit price (order.px)
748            Decimal::from_str(&order.px).ok()
749        } else if !order.avg_px.is_empty() && order.avg_px != "0" {
750            // Market order with fills: use average fill price
751            Decimal::from_str(&order.avg_px).ok()
752        } else {
753            log::warn!(
754                "No price available for conversion: ord_id={}, px='{}', avg_px='{}'",
755                order.ord_id.as_str(),
756                order.px,
757                order.avg_px
758            );
759            None
760        };
761
762        // Convert quote quantity to base: quantity_base = sz_quote / price
763        let quantity_base = if let (Some(sz), Some(price)) = (sz_quote_dec, conversion_price_dec) {
764            if price.is_zero() {
765                log::warn!(
766                    "Cannot convert quote quantity with zero price: ord_id={}, sz={}, using sz as-is",
767                    order.ord_id.as_str(),
768                    order.sz
769                );
770                Quantity::from_str(&order.sz).map_err(|e| {
771                    anyhow::anyhow!(
772                        "Failed to parse fallback quantity for ord_id={}, sz='{}': {e}",
773                        order.ord_id.as_str(),
774                        order.sz
775                    )
776                })?
777            } else {
778                let quantity_dec = sz / price;
779                Quantity::from_decimal_dp(quantity_dec, size_precision).map_err(|e| {
780                    anyhow::anyhow!(
781                        "Failed to convert quote-to-base quantity for ord_id={}, sz={sz}, price={price}, quantity_dec={quantity_dec}: {e}",
782                        order.ord_id.as_str()
783                    )
784                })?
785            }
786        } else {
787            log::warn!(
788                "Cannot convert quote quantity to base without price, using raw sz: \
789                 ord_id={}, sz={}, px='{}', avg_px='{}'",
790                order.ord_id.as_str(),
791                order.sz,
792                order.px,
793                order.avg_px
794            );
795            Quantity::from_str(&order.sz).map_err(|e| {
796                anyhow::anyhow!(
797                    "Failed to parse fallback quantity for ord_id={}, sz='{}': {e}",
798                    order.ord_id.as_str(),
799                    order.sz
800                )
801            })?
802        };
803
804        let filled_qty_dec = parse_quantity(&order.acc_fill_sz, size_precision).map_err(|e| {
805            anyhow::anyhow!(
806                "Failed to parse filled quantity for ord_id={}, acc_fill_sz='{}': {e}",
807                order.ord_id.as_str(),
808                order.acc_fill_sz
809            )
810        })?;
811
812        (quantity_base, filled_qty_dec)
813    } else {
814        // Base-quantity order: both sz and acc_fill_sz are in base currency
815        let quantity_dec = parse_quantity(&order.sz, size_precision).map_err(|e| {
816            anyhow::anyhow!(
817                "Failed to parse base quantity for ord_id={}, sz='{}': {e}",
818                order.ord_id.as_str(),
819                order.sz
820            )
821        })?;
822        let filled_qty_dec = parse_quantity(&order.acc_fill_sz, size_precision).map_err(|e| {
823            anyhow::anyhow!(
824                "Failed to parse filled quantity for ord_id={}, acc_fill_sz='{}': {e}",
825                order.ord_id.as_str(),
826                order.acc_fill_sz
827            )
828        })?;
829
830        (quantity_dec, filled_qty_dec)
831    };
832
833    // Normalize quote conversion and base shortfalls to the venue's terminal filled size
834    let quantity = if order.state == OKXOrderStatus::Filled && filled_qty.is_positive() {
835        filled_qty
836    } else {
837        quantity
838    };
839
840    let order_side = OrderSide::from(order.side);
841    let order_status: OrderStatus = order
842        .state
843        .try_into()
844        .map_err(|e| anyhow::anyhow!("Unsupported OKX order status: {e}"))?;
845    let time_in_force = match okx_ord_type {
846        OKXOrderType::Fok | OKXOrderType::OpFok => TimeInForce::Fok,
847        OKXOrderType::Ioc | OKXOrderType::OptimalLimitIoc => TimeInForce::Ioc,
848        _ => TimeInForce::Gtc,
849    };
850
851    let client_order_id = parse_parent_client_order_id(
852        order.algo_cl_ord_id.as_ref().map(Ustr::as_str),
853        order.cl_ord_id.as_str(),
854    );
855    let mut linked_ids = Vec::new();
856
857    if let Some(attach_algo_cl_ord_id) = order
858        .attach_algo_cl_ord_id
859        .as_ref()
860        .filter(|value| !value.as_str().is_empty())
861    {
862        let attach_client_id = ClientOrderId::new(attach_algo_cl_ord_id.as_str());
863        match &client_order_id {
864            Some(existing) if existing == &attach_client_id => {}
865            _ if linked_ids.contains(&attach_client_id) => {}
866            _ => linked_ids.push(attach_client_id),
867        }
868    }
869
870    for attach_algo in &order.attach_algo_ords {
871        if attach_algo.attach_algo_cl_ord_id.is_empty() {
872            continue;
873        }
874
875        let attach_client_id = ClientOrderId::new(attach_algo.attach_algo_cl_ord_id.as_str());
876        match &client_order_id {
877            Some(existing) if existing == &attach_client_id => {}
878            _ if linked_ids.contains(&attach_client_id) => {}
879            _ => linked_ids.push(attach_client_id),
880        }
881    }
882
883    let venue_order_id = if order.ord_id.is_empty() {
884        if let Some(algo_id) = order.algo_id.as_ref().filter(|value| !value.is_empty()) {
885            VenueOrderId::new(algo_id)
886        } else if !order.cl_ord_id.is_empty() {
887            VenueOrderId::new(order.cl_ord_id)
888        } else {
889            let synthetic_id = format!("{}:{}", account_id, order.c_time);
890            VenueOrderId::new(&synthetic_id)
891        }
892    } else {
893        VenueOrderId::new(order.ord_id)
894    };
895
896    let ts_accepted = parse_millisecond_timestamp(order.c_time);
897    let ts_last = UnixNanos::from(order.u_time * NANOSECONDS_IN_MILLISECOND);
898
899    let mut report = OrderStatusReport::new(
900        account_id,
901        instrument_id,
902        client_order_id,
903        venue_order_id,
904        order_side.into(),
905        order_type,
906        time_in_force,
907        order_status,
908        quantity,
909        filled_qty,
910        ts_accepted,
911        ts_last,
912        ts_init,
913        None,
914    );
915
916    report.venue_position_id = venue_position_id(instrument_id, order.pos_side);
917
918    // Optional fields
919    if !is_market_price(&order.px)
920        && let Ok(decimal) = Decimal::from_str(&order.px)
921        && let Ok(price) = Price::from_decimal_dp(decimal, price_precision)
922    {
923        report = report.with_price(price);
924    }
925
926    if !order.avg_px.is_empty()
927        && let Ok(decimal) = Decimal::from_str(&order.avg_px)
928    {
929        report.avg_px = Some(decimal);
930    }
931
932    if matches!(order.ord_type, OKXOrderType::PostOnly | OKXOrderType::Rpi) {
933        report = report.with_post_only(true);
934    }
935
936    if order.reduce_only == "true" {
937        report = report.with_reduce_only(true);
938    }
939
940    if !linked_ids.is_empty() {
941        report = report.with_linked_order_ids(linked_ids);
942    }
943
944    Ok(report)
945}
946
947/// Parses the net balance of `ccy` into a spot position side and quantity.
948///
949/// Uses signed wallet `cashBal`, including borrowing reflected in that balance. `liab` reports
950/// the loan separately and is not deducted again. Separate margin positions are not included.
951/// Sums balance rows before rounding the absolute balance down to `size_precision`.
952/// Positive balances report `LONG`, negative balances report `SHORT`, and quantities that round
953/// to zero report `FLAT`. A missing balance row has a zero quantity.
954///
955/// # Errors
956///
957/// Returns an error if `cashBal` or `liab` cannot be parsed exactly, balance arithmetic
958/// overflows or loses precision, or the quantity cannot be represented.
959pub fn parse_spot_position_quantity(
960    accounts: &[OKXAccount],
961    ccy: Ustr,
962    size_precision: u8,
963) -> anyhow::Result<(PositionSide, Quantity)> {
964    let mut net_balance = Decimal::ZERO;
965
966    for detail in accounts.iter().flat_map(|account| &account.details) {
967        if detail.ccy != ccy {
968            continue;
969        }
970
971        let liab = detail.liab.trim();
972        if !liab.is_empty() {
973            Decimal::from_str_exact(liab)
974                .with_context(|| format!("invalid liab '{liab}' for {ccy}"))?;
975        }
976
977        let cash_bal = Decimal::from_str_exact(detail.cash_bal.trim())
978            .with_context(|| format!("invalid cashBal '{}' for {ccy}", detail.cash_bal))?;
979        let sum = net_balance
980            .checked_add(cash_bal)
981            .with_context(|| format!("net balance overflowed for {ccy}"))?;
982
983        // Decimal addition can round; subtraction must recover both operands
984        anyhow::ensure!(
985            sum.checked_sub(net_balance) == Some(cash_bal)
986                && sum.checked_sub(cash_bal) == Some(net_balance),
987            "net balance lost precision for {ccy}"
988        );
989        net_balance = sum;
990    }
991
992    let quantity = Quantity::from_decimal_dp(
993        net_balance
994            .abs()
995            .trunc_with_scale(u32::from(size_precision)),
996        size_precision,
997    )?;
998
999    let position_side = if quantity.is_zero() {
1000        PositionSide::Flat
1001    } else if net_balance.is_sign_negative() {
1002        PositionSide::Short
1003    } else {
1004        PositionSide::Long
1005    };
1006
1007    Ok((position_side, quantity))
1008}
1009
1010/// Parses an OKX position into a Nautilus [`PositionStatusReport`].
1011///
1012/// # Position Mode Handling
1013///
1014/// OKX returns position data differently based on the account's position mode:
1015///
1016/// - **Net mode** (`posSide="net"`): The `pos` field uses signed quantities where
1017///   positive = long, negative = short. Position side is derived from the sign.
1018///
1019/// - **Long/Short mode** (`posSide="long"` or `"short"`): The `pos` field is always
1020///   positive regardless of side. Position side is determined from the `posSide` field.
1021///   Position IDs are suffixed with `-LONG` or `-SHORT` for uniqueness.
1022///
1023/// See: <https://www.okx.com/docs-v5/en/#trading-account-rest-api-get-positions>
1024///
1025/// # Errors
1026///
1027/// Returns an error if any numeric fields cannot be parsed into their target types.
1028pub fn parse_position_status_report(
1029    position: &OKXPosition,
1030    account_id: AccountId,
1031    instrument_id: InstrumentId,
1032    size_precision: u8,
1033    ts_init: UnixNanos,
1034) -> anyhow::Result<PositionStatusReport> {
1035    let pos_dec = Decimal::from_str(&position.pos).map_err(|e| {
1036        anyhow::anyhow!(
1037            "Failed to parse position quantity '{}' for instrument {}: {e:?}",
1038            position.pos,
1039            instrument_id
1040        )
1041    })?;
1042
1043    // For SPOT/MARGIN: determine position side and quantity based on pos_ccy
1044    // - If pos_ccy = base currency: LONG position, pos is in base currency
1045    // - If pos_ccy = quote currency: SHORT position, pos is in quote currency (needs conversion)
1046    // - If pos_ccy is empty: FLAT position (no position)
1047    let (position_side, quantity_dec) = if position.inst_type == OKXInstrumentType::Spot
1048        || position.inst_type == OKXInstrumentType::Margin
1049    {
1050        // Extract base and quote currencies from instrument symbol
1051        let (base_ccy, quote_ccy) = parse_base_quote_from_symbol(instrument_id.symbol.as_str())?;
1052
1053        let pos_ccy = position.pos_ccy.as_str();
1054
1055        if pos_ccy.is_empty() || pos_dec.is_zero() {
1056            // Flat position: no position or zero quantity
1057            (PositionSide::Flat, Decimal::ZERO)
1058        } else if pos_ccy == base_ccy {
1059            // Long position: pos_ccy is base currency, pos is already in base
1060            (PositionSide::Long, pos_dec.abs())
1061        } else if pos_ccy == quote_ccy {
1062            // Short position: pos_ccy is quote currency, need to convert to base
1063            // Use Decimal arithmetic to avoid floating-point precision errors
1064            let avg_px_str = if position.avg_px.is_empty() {
1065                // If no avg_px, use mark_px as fallback
1066                &position.mark_px
1067            } else {
1068                &position.avg_px
1069            };
1070            let avg_px_dec = Decimal::from_str(avg_px_str)?;
1071
1072            if avg_px_dec.is_zero() {
1073                anyhow::bail!(
1074                    "Cannot convert SHORT position from quote to base: avg_px is zero for {instrument_id}"
1075                );
1076            }
1077
1078            let quantity_dec = (pos_dec.abs() / avg_px_dec).round_dp(u32::from(size_precision));
1079            (PositionSide::Short, quantity_dec)
1080        } else {
1081            anyhow::bail!(
1082                "Unknown position currency '{pos_ccy}' for instrument {instrument_id} (base={base_ccy}, quote={quote_ccy})"
1083            );
1084        }
1085    } else {
1086        // For SWAP/FUTURES/OPTION: use existing logic
1087        // Determine position side based on OKX position mode:
1088        // - Net mode: posSide="net", uses signed quantities (positive=long, negative=short)
1089        // - Long/Short mode: posSide="long"/"short", quantities are always positive, side from field
1090        let side = match position.pos_side {
1091            OKXPositionSide::Net | OKXPositionSide::None => {
1092                // Net mode: derive side from signed quantity
1093                if pos_dec.is_sign_positive() && !pos_dec.is_zero() {
1094                    PositionSide::Long
1095                } else if pos_dec.is_sign_negative() {
1096                    PositionSide::Short
1097                } else {
1098                    PositionSide::Flat
1099                }
1100            }
1101            OKXPositionSide::Long => {
1102                // Long/Short mode: trust the pos_side field
1103                PositionSide::Long
1104            }
1105            OKXPositionSide::Short => {
1106                // Long/Short mode: trust the pos_side field
1107                PositionSide::Short
1108            }
1109        };
1110        (side, pos_dec.abs())
1111    };
1112
1113    // Convert to absolute quantity (positions are always positive in Nautilus)
1114    let quantity = Quantity::from_decimal_dp(quantity_dec, size_precision)?;
1115
1116    let venue_position_id = venue_position_id(instrument_id, position.pos_side);
1117
1118    let avg_px_open = if position.avg_px.is_empty() {
1119        None
1120    } else {
1121        Some(Decimal::from_str(&position.avg_px)?)
1122    };
1123    let ts_last = parse_millisecond_timestamp(position.u_time);
1124
1125    Ok(PositionStatusReport::new(
1126        account_id,
1127        instrument_id,
1128        position_side,
1129        quantity,
1130        ts_last,
1131        ts_init,
1132        None, // Will generate a UUID4
1133        venue_position_id,
1134        avg_px_open,
1135    ))
1136}
1137
1138/// Parses an OKX transaction detail into a Nautilus `FillReport`.
1139///
1140/// # Errors
1141///
1142/// Returns an error if the OKX transaction detail cannot be parsed.
1143pub fn parse_fill_report(
1144    detail: &OKXTransactionDetail,
1145    account_id: AccountId,
1146    instrument_id: InstrumentId,
1147    price_precision: u8,
1148    size_precision: u8,
1149    ts_init: UnixNanos,
1150) -> anyhow::Result<FillReport> {
1151    let client_order_id = if detail.cl_ord_id.is_empty() {
1152        None
1153    } else {
1154        Some(ClientOrderId::new(detail.cl_ord_id))
1155    };
1156    let venue_order_id = VenueOrderId::new(detail.ord_id);
1157    let trade_id = TradeId::new(detail.trade_id);
1158    let order_side = OrderSide::from(detail.side);
1159    let last_px = parse_price(&detail.fill_px, price_precision)?;
1160    let last_qty = parse_quantity(&detail.fill_sz, size_precision)?;
1161    let fee_dec = required_fee_amount(detail.fee.as_deref()).with_context(|| {
1162        format!("missing or invalid fee for fill report instrument_id={instrument_id}")
1163    })?;
1164    let fee_currency = parse_fee_currency(&detail.fee_ccy, fee_dec, || {
1165        format!("fill report for instrument_id={instrument_id}")
1166    });
1167    let commission = Money::from_decimal(-fee_dec, fee_currency)?;
1168    let liquidity_side: LiquiditySide = detail.exec_type.into();
1169    let ts_event = parse_millisecond_timestamp(detail.ts);
1170
1171    Ok(FillReport::new(
1172        account_id,
1173        instrument_id,
1174        venue_order_id,
1175        trade_id,
1176        order_side,
1177        last_qty,
1178        last_px,
1179        commission,
1180        liquidity_side,
1181        client_order_id,
1182        venue_position_id(
1183            instrument_id,
1184            detail.pos_side.unwrap_or(OKXPositionSide::None),
1185        ),
1186        ts_event,
1187        ts_init,
1188        None, // Will generate a new UUID4
1189    ))
1190}
1191
1192pub(crate) fn venue_position_id(
1193    instrument_id: InstrumentId,
1194    position_side: OKXPositionSide,
1195) -> Option<PositionId> {
1196    let suffix = match position_side {
1197        OKXPositionSide::Long => "LONG",
1198        OKXPositionSide::Short => "SHORT",
1199        OKXPositionSide::Net | OKXPositionSide::None => return None,
1200    };
1201
1202    if !matches!(
1203        okx_instrument_type_from_symbol(instrument_id.symbol.as_str()),
1204        OKXInstrumentType::Swap | OKXInstrumentType::Futures
1205    ) {
1206        return None;
1207    }
1208
1209    Some(PositionId::new(format!("{instrument_id}-{suffix}")))
1210}
1211
1212/// Parses an OKX spread order record into a Nautilus [`OrderStatusReport`].
1213///
1214/// # Errors
1215///
1216/// Returns an error if quantities or prices cannot be parsed.
1217pub fn parse_spread_order_status_report(
1218    order: &OKXSpreadOrder,
1219    account_id: AccountId,
1220    instrument_id: InstrumentId,
1221    price_precision: u8,
1222    size_precision: u8,
1223    ts_init: UnixNanos,
1224) -> anyhow::Result<OrderStatusReport> {
1225    let order_type = determine_order_type(order.ord_type, &order.px)?;
1226    let quantity = parse_quantity(&order.sz, size_precision)?;
1227    let filled_qty = parse_quantity(&order.acc_fill_sz, size_precision)?;
1228    let order_side = OrderSide::from(order.side);
1229    let order_status: OrderStatus = order
1230        .state
1231        .try_into()
1232        .map_err(|e| anyhow::anyhow!("Unsupported OKX order status: {e}"))?;
1233    let time_in_force = match order.ord_type {
1234        OKXOrderType::Ioc | OKXOrderType::OptimalLimitIoc => TimeInForce::Ioc,
1235        OKXOrderType::Fok | OKXOrderType::OpFok => TimeInForce::Fok,
1236        _ => TimeInForce::Gtc,
1237    };
1238    let client_order_id = if order.cl_ord_id.is_empty() {
1239        None
1240    } else {
1241        Some(ClientOrderId::new(order.cl_ord_id))
1242    };
1243    let venue_order_id = if order.ord_id.is_empty() {
1244        VenueOrderId::new(order.cl_ord_id)
1245    } else {
1246        VenueOrderId::new(order.ord_id)
1247    };
1248    let ts_accepted = order.c_time.map_or(ts_init, parse_millisecond_timestamp);
1249    let ts_last = order
1250        .u_time
1251        .or(order.c_time)
1252        .map_or(ts_accepted, parse_millisecond_timestamp);
1253
1254    let mut report = OrderStatusReport::new(
1255        account_id,
1256        instrument_id,
1257        client_order_id,
1258        venue_order_id,
1259        order_side.into(),
1260        order_type,
1261        time_in_force,
1262        order_status,
1263        quantity,
1264        filled_qty,
1265        ts_accepted,
1266        ts_last,
1267        ts_init,
1268        None,
1269    );
1270
1271    if !order.px.is_empty()
1272        && let Ok(decimal) = Decimal::from_str(&order.px)
1273        && let Ok(price) = Price::from_decimal_dp(decimal, price_precision)
1274    {
1275        report = report.with_price(price);
1276    }
1277
1278    if !order.avg_px.is_empty()
1279        && let Ok(decimal) = Decimal::from_str(&order.avg_px)
1280    {
1281        report.avg_px = Some(decimal);
1282    }
1283
1284    if matches!(order.ord_type, OKXOrderType::PostOnly | OKXOrderType::Rpi) {
1285        report = report.with_post_only(true);
1286    }
1287
1288    Ok(report)
1289}
1290
1291/// Parses an OKX spread trade into a Nautilus [`FillReport`].
1292///
1293/// # Errors
1294///
1295/// Returns an error if the trade quantity, price, or fee cannot be parsed.
1296pub fn parse_spread_fill_report(
1297    detail: &OKXSpreadTrade,
1298    account_id: AccountId,
1299    instrument_id: InstrumentId,
1300    price_precision: u8,
1301    size_precision: u8,
1302    ts_init: UnixNanos,
1303) -> anyhow::Result<FillReport> {
1304    let client_order_id = if detail.cl_ord_id.is_empty() {
1305        None
1306    } else {
1307        Some(ClientOrderId::new(detail.cl_ord_id))
1308    };
1309    let venue_order_id = VenueOrderId::new(detail.ord_id);
1310    let trade_id = TradeId::new(detail.trade_id);
1311    let order_side = OrderSide::from(detail.side);
1312    let last_px = parse_price(&detail.fill_px, price_precision)?;
1313    let last_qty = parse_quantity(&detail.fill_sz, size_precision)?;
1314    let fee_dec = required_fee_amount(detail.fee.as_deref()).with_context(|| {
1315        format!("missing or invalid fee for spread fill report instrument_id={instrument_id}")
1316    })?;
1317    let fee_currency = parse_fee_currency(&detail.fee_ccy, fee_dec, || {
1318        format!("spread fill report for instrument_id={instrument_id}")
1319    });
1320    let commission = Money::from_decimal(-fee_dec, fee_currency)?;
1321    let liquidity_side: LiquiditySide = detail.exec_type.into();
1322    let ts_event = parse_millisecond_timestamp(detail.ts);
1323
1324    Ok(FillReport::new(
1325        account_id,
1326        instrument_id,
1327        venue_order_id,
1328        trade_id,
1329        order_side,
1330        last_qty,
1331        last_px,
1332        commission,
1333        liquidity_side,
1334        client_order_id,
1335        None,
1336        ts_event,
1337        ts_init,
1338        None,
1339    ))
1340}
1341
1342/// Parses vector messages from OKX WebSocket data.
1343///
1344/// Reduces code duplication by providing a common pattern for deserializing JSON arrays,
1345/// parsing each message, and wrapping results in Nautilus Data enum variants.
1346///
1347/// # Errors
1348///
1349/// Returns an error if the payload is not an array or if individual messages
1350/// cannot be parsed.
1351pub fn parse_message_vec<T, R, F, W>(
1352    data: serde_json::Value,
1353    parser: F,
1354    wrapper: W,
1355) -> anyhow::Result<Vec<Data>>
1356where
1357    T: DeserializeOwned,
1358    F: Fn(&T) -> anyhow::Result<R>,
1359    W: Fn(R) -> Data,
1360{
1361    let messages: Vec<T> =
1362        serde_json::from_value(data).map_err(|e| anyhow::anyhow!("Expected array payload: {e}"))?;
1363
1364    let mut results = Vec::with_capacity(messages.len());
1365
1366    for message in &messages {
1367        let parsed = parser(message)?;
1368        results.push(wrapper(parsed));
1369    }
1370
1371    Ok(results)
1372}
1373
1374/// Converts a Nautilus bar specification into the matching OKX candle channel.
1375///
1376/// # Errors
1377///
1378/// Returns an error if the provided bar specification does not have a matching
1379/// OKX websocket channel.
1380pub fn bar_spec_as_okx_channel(bar_spec: BarSpecification) -> anyhow::Result<OKXWsChannel> {
1381    let channel = match bar_spec {
1382        BAR_SPEC_1_SECOND_LAST => OKXWsChannel::Candle1Second,
1383        BAR_SPEC_1_MINUTE_LAST => OKXWsChannel::Candle1Minute,
1384        BAR_SPEC_3_MINUTE_LAST => OKXWsChannel::Candle3Minute,
1385        BAR_SPEC_5_MINUTE_LAST => OKXWsChannel::Candle5Minute,
1386        BAR_SPEC_15_MINUTE_LAST => OKXWsChannel::Candle15Minute,
1387        BAR_SPEC_30_MINUTE_LAST => OKXWsChannel::Candle30Minute,
1388        BAR_SPEC_1_HOUR_LAST => OKXWsChannel::Candle1Hour,
1389        BAR_SPEC_2_HOUR_LAST => OKXWsChannel::Candle2Hour,
1390        BAR_SPEC_4_HOUR_LAST => OKXWsChannel::Candle4Hour,
1391        BAR_SPEC_6_HOUR_LAST => OKXWsChannel::Candle6Hour,
1392        BAR_SPEC_12_HOUR_LAST => OKXWsChannel::Candle12Hour,
1393        BAR_SPEC_1_DAY_LAST => OKXWsChannel::Candle1Day,
1394        BAR_SPEC_2_DAY_LAST => OKXWsChannel::Candle2Day,
1395        BAR_SPEC_3_DAY_LAST => OKXWsChannel::Candle3Day,
1396        BAR_SPEC_5_DAY_LAST => OKXWsChannel::Candle5Day,
1397        BAR_SPEC_1_WEEK_LAST => OKXWsChannel::Candle1Week,
1398        BAR_SPEC_1_MONTH_LAST => OKXWsChannel::Candle1Month,
1399        BAR_SPEC_3_MONTH_LAST => OKXWsChannel::Candle3Month,
1400        BAR_SPEC_6_MONTH_LAST => OKXWsChannel::Candle6Month,
1401        BAR_SPEC_12_MONTH_LAST => OKXWsChannel::Candle1Year,
1402        _ => anyhow::bail!("Invalid `BarSpecification` for channel, was {bar_spec}"),
1403    };
1404    Ok(channel)
1405}
1406
1407/// Converts Nautilus bar specification to OKX mark price channel.
1408///
1409/// # Errors
1410///
1411/// Returns an error if the bar specification does not map to a mark price
1412/// channel.
1413pub fn bar_spec_as_okx_mark_price_channel(
1414    bar_spec: BarSpecification,
1415) -> anyhow::Result<OKXWsChannel> {
1416    let channel = match bar_spec {
1417        BAR_SPEC_1_SECOND_LAST => OKXWsChannel::MarkPriceCandle1Second,
1418        BAR_SPEC_1_MINUTE_LAST => OKXWsChannel::MarkPriceCandle1Minute,
1419        BAR_SPEC_3_MINUTE_LAST => OKXWsChannel::MarkPriceCandle3Minute,
1420        BAR_SPEC_5_MINUTE_LAST => OKXWsChannel::MarkPriceCandle5Minute,
1421        BAR_SPEC_15_MINUTE_LAST => OKXWsChannel::MarkPriceCandle15Minute,
1422        BAR_SPEC_30_MINUTE_LAST => OKXWsChannel::MarkPriceCandle30Minute,
1423        BAR_SPEC_1_HOUR_LAST => OKXWsChannel::MarkPriceCandle1Hour,
1424        BAR_SPEC_2_HOUR_LAST => OKXWsChannel::MarkPriceCandle2Hour,
1425        BAR_SPEC_4_HOUR_LAST => OKXWsChannel::MarkPriceCandle4Hour,
1426        BAR_SPEC_6_HOUR_LAST => OKXWsChannel::MarkPriceCandle6Hour,
1427        BAR_SPEC_12_HOUR_LAST => OKXWsChannel::MarkPriceCandle12Hour,
1428        BAR_SPEC_1_DAY_LAST => OKXWsChannel::MarkPriceCandle1Day,
1429        BAR_SPEC_2_DAY_LAST => OKXWsChannel::MarkPriceCandle2Day,
1430        BAR_SPEC_3_DAY_LAST => OKXWsChannel::MarkPriceCandle3Day,
1431        BAR_SPEC_5_DAY_LAST => OKXWsChannel::MarkPriceCandle5Day,
1432        BAR_SPEC_1_WEEK_LAST => OKXWsChannel::MarkPriceCandle1Week,
1433        BAR_SPEC_1_MONTH_LAST => OKXWsChannel::MarkPriceCandle1Month,
1434        BAR_SPEC_3_MONTH_LAST => OKXWsChannel::MarkPriceCandle3Month,
1435        _ => anyhow::bail!("Invalid `BarSpecification` for mark price channel, was {bar_spec}"),
1436    };
1437    Ok(channel)
1438}
1439
1440/// Converts Nautilus bar specification to OKX timeframe string.
1441///
1442/// # Errors
1443///
1444/// Returns an error if the bar specification does not have a corresponding
1445/// OKX timeframe value.
1446pub fn bar_spec_as_okx_timeframe(bar_spec: BarSpecification) -> anyhow::Result<&'static str> {
1447    let timeframe = match bar_spec {
1448        BAR_SPEC_1_SECOND_LAST => "1s",
1449        BAR_SPEC_1_MINUTE_LAST => "1m",
1450        BAR_SPEC_3_MINUTE_LAST => "3m",
1451        BAR_SPEC_5_MINUTE_LAST => "5m",
1452        BAR_SPEC_15_MINUTE_LAST => "15m",
1453        BAR_SPEC_30_MINUTE_LAST => "30m",
1454        BAR_SPEC_1_HOUR_LAST => "1H",
1455        BAR_SPEC_2_HOUR_LAST => "2H",
1456        BAR_SPEC_4_HOUR_LAST => "4H",
1457        BAR_SPEC_6_HOUR_LAST => "6H",
1458        BAR_SPEC_12_HOUR_LAST => "12H",
1459        BAR_SPEC_1_DAY_LAST => "1D",
1460        BAR_SPEC_2_DAY_LAST => "2D",
1461        BAR_SPEC_3_DAY_LAST => "3D",
1462        BAR_SPEC_5_DAY_LAST => "5D",
1463        BAR_SPEC_1_WEEK_LAST => "1W",
1464        BAR_SPEC_1_MONTH_LAST => "1M",
1465        BAR_SPEC_3_MONTH_LAST => "3M",
1466        BAR_SPEC_6_MONTH_LAST => "6M",
1467        BAR_SPEC_12_MONTH_LAST => "1Y",
1468        _ => anyhow::bail!("Invalid `BarSpecification` for timeframe, was {bar_spec}"),
1469    };
1470    Ok(timeframe)
1471}
1472
1473/// Converts OKX timeframe string to Nautilus bar specification.
1474///
1475/// # Errors
1476///
1477/// Returns an error if the timeframe string is not recognized.
1478pub fn okx_timeframe_as_bar_spec(timeframe: &str) -> anyhow::Result<BarSpecification> {
1479    let bar_spec = match timeframe {
1480        "1s" => BAR_SPEC_1_SECOND_LAST,
1481        "1m" => BAR_SPEC_1_MINUTE_LAST,
1482        "3m" => BAR_SPEC_3_MINUTE_LAST,
1483        "5m" => BAR_SPEC_5_MINUTE_LAST,
1484        "15m" => BAR_SPEC_15_MINUTE_LAST,
1485        "30m" => BAR_SPEC_30_MINUTE_LAST,
1486        "1H" => BAR_SPEC_1_HOUR_LAST,
1487        "2H" => BAR_SPEC_2_HOUR_LAST,
1488        "4H" => BAR_SPEC_4_HOUR_LAST,
1489        "6H" => BAR_SPEC_6_HOUR_LAST,
1490        "12H" => BAR_SPEC_12_HOUR_LAST,
1491        "1D" => BAR_SPEC_1_DAY_LAST,
1492        "2D" => BAR_SPEC_2_DAY_LAST,
1493        "3D" => BAR_SPEC_3_DAY_LAST,
1494        "5D" => BAR_SPEC_5_DAY_LAST,
1495        "1W" => BAR_SPEC_1_WEEK_LAST,
1496        "1M" => BAR_SPEC_1_MONTH_LAST,
1497        "3M" => BAR_SPEC_3_MONTH_LAST,
1498        "6M" => BAR_SPEC_6_MONTH_LAST,
1499        "1Y" => BAR_SPEC_12_MONTH_LAST,
1500        _ => anyhow::bail!("Invalid timeframe for `BarSpecification`, was {timeframe}"),
1501    };
1502    Ok(bar_spec)
1503}
1504
1505/// Constructs a properly formatted `BarType` from OKX instrument ID and timeframe string.
1506/// This ensures the `BarType` uses canonical Nautilus format instead of raw OKX strings.
1507///
1508/// # Errors
1509///
1510/// Returns an error if the timeframe cannot be converted into a
1511/// `BarSpecification`.
1512pub fn okx_bar_type_from_timeframe(
1513    instrument_id: InstrumentId,
1514    timeframe: &str,
1515) -> anyhow::Result<BarType> {
1516    let bar_spec = okx_timeframe_as_bar_spec(timeframe)?;
1517    Ok(BarType::new(
1518        instrument_id,
1519        bar_spec,
1520        AggregationSource::External,
1521    ))
1522}
1523
1524/// Converts OKX WebSocket channel to bar specification if it's a candle channel.
1525#[allow(
1526    clippy::enum_glob_use,
1527    reason = "a wildcard import keeps the wide candle-channel match readable"
1528)]
1529pub fn okx_channel_to_bar_spec(channel: &OKXWsChannel) -> Option<BarSpecification> {
1530    use OKXWsChannel::*;
1531
1532    match channel {
1533        Candle1Second | MarkPriceCandle1Second => Some(BAR_SPEC_1_SECOND_LAST),
1534        Candle1Minute | MarkPriceCandle1Minute => Some(BAR_SPEC_1_MINUTE_LAST),
1535        Candle3Minute | MarkPriceCandle3Minute => Some(BAR_SPEC_3_MINUTE_LAST),
1536        Candle5Minute | MarkPriceCandle5Minute => Some(BAR_SPEC_5_MINUTE_LAST),
1537        Candle15Minute | MarkPriceCandle15Minute => Some(BAR_SPEC_15_MINUTE_LAST),
1538        Candle30Minute | MarkPriceCandle30Minute => Some(BAR_SPEC_30_MINUTE_LAST),
1539        Candle1Hour | MarkPriceCandle1Hour => Some(BAR_SPEC_1_HOUR_LAST),
1540        Candle2Hour | MarkPriceCandle2Hour => Some(BAR_SPEC_2_HOUR_LAST),
1541        Candle4Hour | MarkPriceCandle4Hour => Some(BAR_SPEC_4_HOUR_LAST),
1542        Candle6Hour | MarkPriceCandle6Hour => Some(BAR_SPEC_6_HOUR_LAST),
1543        Candle12Hour | MarkPriceCandle12Hour => Some(BAR_SPEC_12_HOUR_LAST),
1544        Candle1Day | MarkPriceCandle1Day => Some(BAR_SPEC_1_DAY_LAST),
1545        Candle2Day | MarkPriceCandle2Day => Some(BAR_SPEC_2_DAY_LAST),
1546        Candle3Day | MarkPriceCandle3Day => Some(BAR_SPEC_3_DAY_LAST),
1547        Candle5Day | MarkPriceCandle5Day => Some(BAR_SPEC_5_DAY_LAST),
1548        Candle1Week | MarkPriceCandle1Week => Some(BAR_SPEC_1_WEEK_LAST),
1549        Candle1Month | MarkPriceCandle1Month => Some(BAR_SPEC_1_MONTH_LAST),
1550        Candle3Month | MarkPriceCandle3Month => Some(BAR_SPEC_3_MONTH_LAST),
1551        Candle6Month => Some(BAR_SPEC_6_MONTH_LAST),
1552        Candle1Year => Some(BAR_SPEC_12_MONTH_LAST),
1553        _ => None,
1554    }
1555}
1556
1557/// Parses an OKX instrument definition into a Nautilus instrument.
1558///
1559/// # Errors
1560///
1561/// Returns an error if the instrument definition cannot be parsed.
1562pub fn parse_instrument_any(
1563    instrument: &OKXInstrument,
1564    margin_init: Option<Decimal>,
1565    margin_maint: Option<Decimal>,
1566    ts_init: UnixNanos,
1567) -> anyhow::Result<Option<InstrumentAny>> {
1568    match instrument.inst_type {
1569        OKXInstrumentType::Spot => {
1570            parse_spot_instrument(instrument, margin_init, margin_maint, ts_init).map(Some)
1571        }
1572        OKXInstrumentType::Margin => {
1573            parse_spot_instrument(instrument, margin_init, margin_maint, ts_init).map(Some)
1574        }
1575        OKXInstrumentType::Swap => {
1576            parse_swap_instrument(instrument, margin_init, margin_maint, ts_init).map(Some)
1577        }
1578        OKXInstrumentType::Futures => {
1579            parse_futures_instrument(instrument, margin_init, margin_maint, ts_init).map(Some)
1580        }
1581        OKXInstrumentType::Option => {
1582            parse_option_instrument(instrument, margin_init, margin_maint, ts_init).map(Some)
1583        }
1584        OKXInstrumentType::Events => {
1585            parse_event_contract_instrument(instrument, margin_init, margin_maint, ts_init)
1586                .map(Some)
1587        }
1588        OKXInstrumentType::Any => Ok(None),
1589    }
1590}
1591
1592/// Parses an OKX spread definition into a Nautilus crypto spread.
1593///
1594/// # Errors
1595///
1596/// Returns an error if the spread definition cannot be parsed.
1597///
1598/// # Panics
1599///
1600/// Panics if the constructed instrument fails validation.
1601pub fn parse_spread_instrument(
1602    definition: &OKXSpread,
1603    margin_init: Option<Decimal>,
1604    margin_maint: Option<Decimal>,
1605    ts_init: UnixNanos,
1606) -> anyhow::Result<InstrumentAny> {
1607    if definition.tick_sz.is_empty() {
1608        anyhow::bail!("`tick_sz` is empty for {}", definition.sprd_id);
1609    }
1610
1611    if definition.lot_sz.is_empty() {
1612        anyhow::bail!("`lot_sz` is empty for {}", definition.sprd_id);
1613    }
1614
1615    let context = format!("SPREAD instrument {}", definition.sprd_id);
1616    let instrument_id = parse_instrument_id(definition.sprd_id);
1617    let raw_symbol = Symbol::from_ustr_unchecked(definition.sprd_id);
1618    let underlying =
1619        Currency::get_or_create_crypto_with_context(definition.base_ccy, Some(&context));
1620    let quote_currency =
1621        Currency::get_or_create_crypto_with_context(definition.quote_ccy, Some(&context));
1622    let settlement_currency = spread_settlement_currency(definition, underlying, quote_currency);
1623    let is_inverse = matches!(definition.sprd_type, OKXSpreadType::Inverse);
1624    let activation_ns = definition
1625        .list_time
1626        .map(parse_millisecond_timestamp)
1627        .ok_or_else(|| anyhow::anyhow!("`list_time` is required for {}", definition.sprd_id))?;
1628    let expiration_ns = definition
1629        .exp_time
1630        .map_or_default(parse_millisecond_timestamp);
1631    let ts_event = definition
1632        .u_time
1633        .map_or(ts_init, parse_millisecond_timestamp);
1634
1635    let price_increment = Price::from_str(&definition.tick_sz).map_err(|e| {
1636        anyhow::anyhow!(
1637            "Failed to parse `tick_sz` '{}' for {}: {e}",
1638            definition.tick_sz,
1639            definition.sprd_id
1640        )
1641    })?;
1642    let size_increment = Quantity::from_str(&definition.lot_sz).map_err(|e| {
1643        anyhow::anyhow!(
1644            "Failed to parse `lot_sz` '{}' for {}: {e}",
1645            definition.lot_sz,
1646            definition.sprd_id
1647        )
1648    })?;
1649    let min_quantity = if definition.min_sz.is_empty() {
1650        None
1651    } else {
1652        Some(Quantity::from_str(&definition.min_sz).map_err(|e| {
1653            anyhow::anyhow!(
1654                "Failed to parse `min_sz` '{}' for {}: {e}",
1655                definition.min_sz,
1656                definition.sprd_id
1657            )
1658        })?)
1659    };
1660
1661    let info = Some(build_spread_info(definition));
1662
1663    if spread_has_option_leg(definition) {
1664        let instrument = CryptoOptionSpread::builder()
1665            .instrument_id(instrument_id)
1666            .raw_symbol(raw_symbol)
1667            .underlying(underlying)
1668            .quote_currency(quote_currency)
1669            .settlement_currency(settlement_currency)
1670            .is_inverse(is_inverse)
1671            .strategy_type(Ustr::from(spread_type_literal(definition.sprd_type)))
1672            .activation_ns(activation_ns)
1673            .expiration_ns(expiration_ns)
1674            .price_precision(price_increment.precision)
1675            .size_precision(size_increment.precision)
1676            .price_increment(price_increment)
1677            .size_increment(size_increment)
1678            .lot_size(size_increment)
1679            .maybe_min_quantity(min_quantity)
1680            .maybe_margin_init(margin_init)
1681            .maybe_margin_maint(margin_maint)
1682            .maybe_info(info)
1683            .ts_event(ts_event)
1684            .ts_init(ts_init)
1685            .build()
1686            .unwrap();
1687
1688        return Ok(InstrumentAny::CryptoOptionSpread(instrument));
1689    }
1690
1691    let instrument = CryptoFuturesSpread::builder()
1692        .instrument_id(instrument_id)
1693        .raw_symbol(raw_symbol)
1694        .underlying(underlying)
1695        .quote_currency(quote_currency)
1696        .settlement_currency(settlement_currency)
1697        .is_inverse(is_inverse)
1698        .strategy_type(Ustr::from(spread_type_literal(definition.sprd_type)))
1699        .activation_ns(activation_ns)
1700        .expiration_ns(expiration_ns)
1701        .price_precision(price_increment.precision)
1702        .size_precision(size_increment.precision)
1703        .price_increment(price_increment)
1704        .size_increment(size_increment)
1705        .lot_size(size_increment)
1706        .maybe_min_quantity(min_quantity)
1707        .maybe_margin_init(margin_init)
1708        .maybe_margin_maint(margin_maint)
1709        .maybe_info(info)
1710        .ts_event(ts_event)
1711        .ts_init(ts_init)
1712        .build()
1713        .unwrap();
1714
1715    Ok(InstrumentAny::CryptoFuturesSpread(instrument))
1716}
1717
1718fn spread_has_option_leg(definition: &OKXSpread) -> bool {
1719    definition.legs.iter().any(|leg| {
1720        okx_instrument_type_from_symbol(leg.inst_id.as_str()) == OKXInstrumentType::Option
1721    })
1722}
1723
1724fn spread_settlement_currency(
1725    definition: &OKXSpread,
1726    underlying: Currency,
1727    quote_currency: Currency,
1728) -> Currency {
1729    match definition.sprd_type {
1730        OKXSpreadType::Inverse => underlying,
1731        OKXSpreadType::Linear | OKXSpreadType::Hybrid | OKXSpreadType::Unknown => quote_currency,
1732    }
1733}
1734
1735fn build_spread_info(definition: &OKXSpread) -> Params {
1736    let mut info = IndexMap::from([
1737        (
1738            "okx_sprd_id".to_string(),
1739            serde_json::json!(definition.sprd_id),
1740        ),
1741        (
1742            "okx_sprd_type".to_string(),
1743            serde_json::json!(spread_type_literal(definition.sprd_type)),
1744        ),
1745        (
1746            "okx_spread_state".to_string(),
1747            serde_json::json!(spread_state_literal(definition.state)),
1748        ),
1749        (
1750            "okx_base_ccy".to_string(),
1751            serde_json::json!(definition.base_ccy),
1752        ),
1753        (
1754            "okx_sz_ccy".to_string(),
1755            serde_json::json!(definition.sz_ccy),
1756        ),
1757        (
1758            "okx_quote_ccy".to_string(),
1759            serde_json::json!(definition.quote_ccy),
1760        ),
1761        (
1762            "okx_list_time".to_string(),
1763            serde_json::json!(definition.list_time),
1764        ),
1765        (
1766            "okx_exp_time".to_string(),
1767            serde_json::json!(definition.exp_time),
1768        ),
1769        (
1770            "okx_u_time".to_string(),
1771            serde_json::json!(definition.u_time),
1772        ),
1773    ]);
1774
1775    let legs = definition
1776        .legs
1777        .iter()
1778        .map(|leg| {
1779            let leg_id = parse_instrument_id(leg.inst_id);
1780            serde_json::json!({
1781                "inst_id": leg.inst_id,
1782                "instrument_id": leg_id.to_string(),
1783                "side": side_literal(leg.side),
1784                "ratio": leg_ratio(leg.side),
1785            })
1786        })
1787        .collect::<Vec<_>>();
1788    info.insert("okx_spread_legs".to_string(), serde_json::json!(legs));
1789
1790    Params::new(info)
1791}
1792
1793fn spread_type_literal(spread_type: OKXSpreadType) -> &'static str {
1794    match spread_type {
1795        OKXSpreadType::Linear => "linear",
1796        OKXSpreadType::Inverse => "inverse",
1797        OKXSpreadType::Hybrid => "hybrid",
1798        OKXSpreadType::Unknown => "unknown",
1799    }
1800}
1801
1802fn spread_state_literal(state: OKXSpreadState) -> &'static str {
1803    match state {
1804        OKXSpreadState::Live => "live",
1805        OKXSpreadState::Suspend => "suspend",
1806        OKXSpreadState::Expired => "expired",
1807        OKXSpreadState::Unknown => "unknown",
1808    }
1809}
1810
1811fn side_literal(side: OKXSide) -> &'static str {
1812    match side {
1813        OKXSide::Buy => "buy",
1814        OKXSide::Sell => "sell",
1815    }
1816}
1817
1818fn leg_ratio(side: OKXSide) -> i8 {
1819    match side {
1820        OKXSide::Buy => 1,
1821        OKXSide::Sell => -1,
1822    }
1823}
1824
1825/// Common parsed instrument data extracted from OKX definitions.
1826#[derive(Debug)]
1827struct CommonInstrumentData {
1828    instrument_id: InstrumentId,
1829    raw_symbol: Symbol,
1830    price_increment: Price,
1831    size_increment: Quantity,
1832    lot_size: Option<Quantity>,
1833    max_quantity: Option<Quantity>,
1834    min_quantity: Option<Quantity>,
1835    max_notional: Option<Money>,
1836    min_notional: Option<Money>,
1837    max_price: Option<Price>,
1838    min_price: Option<Price>,
1839}
1840
1841/// Margin rates for an instrument.
1842struct MarginRates {
1843    margin_init: Option<Decimal>,
1844    margin_maint: Option<Decimal>,
1845}
1846
1847/// Parses the multiplier as the product of `ct_mult` and `ct_val`.
1848///
1849/// For SPOT instruments where both fields are empty, returns None.
1850/// For derivatives, multiplies the two fields to get the final multiplier.
1851fn parse_multiplier_product(definition: &OKXInstrument) -> anyhow::Result<Option<Quantity>> {
1852    if definition.ct_mult.is_empty() && definition.ct_val.is_empty() {
1853        return Ok(None);
1854    }
1855
1856    let mult_value = if definition.ct_mult.is_empty() {
1857        Decimal::ONE
1858    } else {
1859        Decimal::from_str(&definition.ct_mult).map_err(|e| {
1860            anyhow::anyhow!(
1861                "Failed to parse `ct_mult` '{}' for {}: {e}",
1862                definition.ct_mult,
1863                definition.inst_id
1864            )
1865        })?
1866    };
1867
1868    let val_value = if definition.ct_val.is_empty() {
1869        Decimal::ONE
1870    } else {
1871        Decimal::from_str(&definition.ct_val).map_err(|e| {
1872            anyhow::anyhow!(
1873                "Failed to parse `ct_val` '{}' for {}: {e}",
1874                definition.ct_val,
1875                definition.inst_id
1876            )
1877        })?
1878    };
1879
1880    let product = mult_value * val_value;
1881    Ok(Some(Quantity::from(product.to_string())))
1882}
1883
1884/// Trait for instrument-specific parsing logic.
1885trait InstrumentParser {
1886    /// Parses instrument-specific fields and creates the final instrument.
1887    fn parse_specific_fields(
1888        &self,
1889        definition: &OKXInstrument,
1890        common: CommonInstrumentData,
1891        margin: MarginRates,
1892        ts_init: UnixNanos,
1893    ) -> anyhow::Result<InstrumentAny>;
1894}
1895
1896/// Extracts common fields shared across all instrument types.
1897fn parse_common_instrument_data(
1898    definition: &OKXInstrument,
1899) -> anyhow::Result<CommonInstrumentData> {
1900    let instrument_id = parse_instrument_id(definition.inst_id);
1901    let raw_symbol = Symbol::from_ustr_unchecked(definition.inst_id);
1902
1903    if definition.tick_sz.is_empty() {
1904        anyhow::bail!("`tick_sz` is empty for {}", definition.inst_id);
1905    }
1906
1907    let price_increment = Price::from_str(&definition.tick_sz).map_err(|e| {
1908        anyhow::anyhow!(
1909            "Failed to parse `tick_sz` '{}' into Price for {}: {e}",
1910            definition.tick_sz,
1911            definition.inst_id,
1912        )
1913    })?;
1914
1915    if definition.lot_sz.is_empty() {
1916        anyhow::bail!("`lot_sz` is empty for {}", definition.inst_id);
1917    }
1918
1919    let size_increment = Quantity::from_str(&definition.lot_sz).map_err(|e| {
1920        anyhow::anyhow!(
1921            "Failed to parse `lot_sz` '{}' for {}: {e}",
1922            definition.lot_sz,
1923            definition.inst_id,
1924        )
1925    })?;
1926    let lot_size = Some(size_increment);
1927    let max_quantity = if definition.max_mkt_sz.is_empty() {
1928        None
1929    } else {
1930        Some(Quantity::from_str(&definition.max_mkt_sz).map_err(|e| {
1931            anyhow::anyhow!(
1932                "Failed to parse `max_mkt_sz` '{}' for {}: {e}",
1933                definition.max_mkt_sz,
1934                definition.inst_id,
1935            )
1936        })?)
1937    };
1938    let min_quantity = if definition.min_sz.is_empty() {
1939        None
1940    } else {
1941        Some(Quantity::from_str(&definition.min_sz).map_err(|e| {
1942            anyhow::anyhow!(
1943                "Failed to parse `min_sz` '{}' for {}: {e}",
1944                definition.min_sz,
1945                definition.inst_id,
1946            )
1947        })?)
1948    };
1949    let max_notional: Option<Money> = None;
1950    let min_notional: Option<Money> = None;
1951    let max_price = None; // TBD
1952    let min_price = None; // TBD
1953
1954    Ok(CommonInstrumentData {
1955        instrument_id,
1956        raw_symbol,
1957        price_increment,
1958        size_increment,
1959        lot_size,
1960        max_quantity,
1961        min_quantity,
1962        max_notional,
1963        min_notional,
1964        max_price,
1965        min_price,
1966    })
1967}
1968
1969/// Generic instrument parsing function that delegates to type-specific parsers.
1970fn parse_instrument_with_parser<P: InstrumentParser>(
1971    definition: &OKXInstrument,
1972    parser: &P,
1973    margin_init: Option<Decimal>,
1974    margin_maint: Option<Decimal>,
1975    ts_init: UnixNanos,
1976) -> anyhow::Result<InstrumentAny> {
1977    let common = parse_common_instrument_data(definition)?;
1978    parser.parse_specific_fields(
1979        definition,
1980        common,
1981        MarginRates {
1982            margin_init,
1983            margin_maint,
1984        },
1985        ts_init,
1986    )
1987}
1988
1989/// Parser for spot trading pairs (`CurrencyPair`).
1990struct SpotInstrumentParser;
1991
1992impl InstrumentParser for SpotInstrumentParser {
1993    fn parse_specific_fields(
1994        &self,
1995        definition: &OKXInstrument,
1996        common: CommonInstrumentData,
1997        margin: MarginRates,
1998        ts_init: UnixNanos,
1999    ) -> anyhow::Result<InstrumentAny> {
2000        let context = format!("{} instrument {}", definition.inst_type, definition.inst_id);
2001        let base_currency =
2002            Currency::get_or_create_crypto_with_context(definition.base_ccy, Some(&context));
2003        let quote_currency =
2004            Currency::get_or_create_crypto_with_context(definition.quote_ccy, Some(&context));
2005
2006        // Parse multiplier as product of ct_mult and ct_val
2007        let multiplier = parse_multiplier_product(definition)?;
2008        let info = build_price_limit_info(definition).map(Params::new);
2009
2010        let instrument = CurrencyPair::builder()
2011            .instrument_id(common.instrument_id)
2012            .raw_symbol(common.raw_symbol)
2013            .base_currency(base_currency)
2014            .quote_currency(quote_currency)
2015            .price_precision(common.price_increment.precision)
2016            .size_precision(common.size_increment.precision)
2017            .price_increment(common.price_increment)
2018            .size_increment(common.size_increment)
2019            .maybe_multiplier(multiplier)
2020            .maybe_lot_size(common.lot_size)
2021            .maybe_max_quantity(common.max_quantity)
2022            .maybe_min_quantity(common.min_quantity)
2023            .maybe_max_notional(common.max_notional)
2024            .maybe_min_notional(common.min_notional)
2025            .maybe_max_price(common.max_price)
2026            .maybe_min_price(common.min_price)
2027            .maybe_margin_init(margin.margin_init)
2028            .maybe_margin_maint(margin.margin_maint)
2029            .maybe_info(info)
2030            .ts_event(ts_init)
2031            .ts_init(ts_init)
2032            .build()
2033            .unwrap();
2034
2035        Ok(InstrumentAny::CurrencyPair(instrument))
2036    }
2037}
2038
2039/// Parses an OKX spot instrument definition into a Nautilus currency pair.
2040///
2041/// # Errors
2042///
2043/// Returns an error if the instrument definition cannot be parsed.
2044pub fn parse_spot_instrument(
2045    definition: &OKXInstrument,
2046    margin_init: Option<Decimal>,
2047    margin_maint: Option<Decimal>,
2048    ts_init: UnixNanos,
2049) -> anyhow::Result<InstrumentAny> {
2050    parse_instrument_with_parser(
2051        definition,
2052        &SpotInstrumentParser,
2053        margin_init,
2054        margin_maint,
2055        ts_init,
2056    )
2057}
2058
2059/// Validates that the underlying field is not empty for derivative instruments.
2060///
2061/// # Errors
2062///
2063/// Returns an error if the underlying field is empty, which typically indicates
2064/// a pre-open or misconfigured instrument.
2065fn validate_underlying(inst_id: Ustr, uly: Ustr) -> anyhow::Result<()> {
2066    if uly.is_empty() {
2067        anyhow::bail!(
2068            "Empty underlying for {inst_id}: instrument may be pre-open or misconfigured"
2069        );
2070    }
2071    Ok(())
2072}
2073
2074/// Parses an OKX swap instrument definition into a Nautilus crypto perpetual.
2075///
2076/// # Errors
2077///
2078/// Returns an error if the instrument definition cannot be parsed.
2079///
2080/// # Panics
2081///
2082/// Panics if the constructed instrument fails validation.
2083pub fn parse_swap_instrument(
2084    definition: &OKXInstrument,
2085    margin_init: Option<Decimal>,
2086    margin_maint: Option<Decimal>,
2087    ts_init: UnixNanos,
2088) -> anyhow::Result<InstrumentAny> {
2089    validate_underlying(definition.inst_id, definition.uly)?;
2090
2091    let context = format!("SWAP instrument {}", definition.inst_id);
2092    let (base_currency, quote_currency) = definition.uly.split_once('-').ok_or_else(|| {
2093        anyhow::anyhow!(
2094            "Invalid underlying '{}' for {}: expected format 'BASE-QUOTE'",
2095            definition.uly,
2096            definition.inst_id
2097        )
2098    })?;
2099
2100    let instrument_id = parse_instrument_id(definition.inst_id);
2101    let raw_symbol = Symbol::from_ustr_unchecked(definition.inst_id);
2102    let base_currency = Currency::get_or_create_crypto_with_context(base_currency, Some(&context));
2103    let quote_currency =
2104        Currency::get_or_create_crypto_with_context(quote_currency, Some(&context));
2105    let settlement_currency =
2106        Currency::get_or_create_crypto_with_context(definition.settle_ccy, Some(&context));
2107    let is_inverse = match definition.ct_type {
2108        OKXContractType::Linear => false,
2109        OKXContractType::Inverse => true,
2110        OKXContractType::None => {
2111            anyhow::bail!(
2112                "Invalid contract type '{}' for {}: expected 'linear' or 'inverse'",
2113                definition.ct_type,
2114                definition.inst_id
2115            )
2116        }
2117    };
2118
2119    if definition.tick_sz.is_empty() {
2120        anyhow::bail!("`tick_sz` is empty for {}", definition.inst_id);
2121    }
2122
2123    let price_increment = Price::from_str(&definition.tick_sz).map_err(|e| {
2124        anyhow::anyhow!(
2125            "Failed to parse `tick_sz` '{}' into Price for {}: {e}",
2126            definition.tick_sz,
2127            definition.inst_id
2128        )
2129    })?;
2130
2131    if definition.lot_sz.is_empty() {
2132        anyhow::bail!("`lot_sz` is empty for {}", definition.inst_id);
2133    }
2134    let size_increment = Quantity::from_str(&definition.lot_sz).map_err(|e| {
2135        anyhow::anyhow!(
2136            "Failed to parse `lot_sz` '{}' for {}: {e}",
2137            definition.lot_sz,
2138            definition.inst_id
2139        )
2140    })?;
2141    let multiplier = parse_multiplier_product(definition)?;
2142    let lot_size = Some(size_increment);
2143    let max_quantity = if definition.max_mkt_sz.is_empty() {
2144        None
2145    } else {
2146        Some(Quantity::from_str(&definition.max_mkt_sz).map_err(|e| {
2147            anyhow::anyhow!(
2148                "Failed to parse `max_mkt_sz` '{}' for {}: {e}",
2149                definition.max_mkt_sz,
2150                definition.inst_id
2151            )
2152        })?)
2153    };
2154    let min_quantity = if definition.min_sz.is_empty() {
2155        None
2156    } else {
2157        Some(Quantity::from_str(&definition.min_sz).map_err(|e| {
2158            anyhow::anyhow!(
2159                "Failed to parse `min_sz` '{}' for {}: {e}",
2160                definition.min_sz,
2161                definition.inst_id
2162            )
2163        })?)
2164    };
2165    let max_notional: Option<Money> = None;
2166    let min_notional: Option<Money> = None;
2167    let max_price = None; // TBD
2168    let min_price = None; // TBD
2169    let info = build_price_limit_info(definition).map(Params::new);
2170
2171    let instrument = CryptoPerpetual::builder()
2172        .instrument_id(instrument_id)
2173        .raw_symbol(raw_symbol)
2174        .base_currency(base_currency)
2175        .quote_currency(quote_currency)
2176        .settlement_currency(settlement_currency)
2177        .is_inverse(is_inverse)
2178        .price_precision(price_increment.precision)
2179        .size_precision(size_increment.precision)
2180        .price_increment(price_increment)
2181        .size_increment(size_increment)
2182        .maybe_multiplier(multiplier)
2183        .maybe_lot_size(lot_size)
2184        .maybe_max_quantity(max_quantity)
2185        .maybe_min_quantity(min_quantity)
2186        .maybe_max_notional(max_notional)
2187        .maybe_min_notional(min_notional)
2188        .maybe_max_price(max_price)
2189        .maybe_min_price(min_price)
2190        .maybe_margin_init(margin_init)
2191        .maybe_margin_maint(margin_maint)
2192        .maybe_info(info)
2193        // No ts_event for response
2194        .ts_event(ts_init)
2195        .ts_init(ts_init)
2196        .build()
2197        .unwrap();
2198
2199    Ok(InstrumentAny::CryptoPerpetual(instrument))
2200}
2201
2202/// Parses an OKX futures instrument definition into a Nautilus crypto future.
2203///
2204/// # Errors
2205///
2206/// Returns an error if the instrument definition cannot be parsed.
2207///
2208/// # Panics
2209///
2210/// Panics if the constructed instrument fails validation.
2211pub fn parse_futures_instrument(
2212    definition: &OKXInstrument,
2213    margin_init: Option<Decimal>,
2214    margin_maint: Option<Decimal>,
2215    ts_init: UnixNanos,
2216) -> anyhow::Result<InstrumentAny> {
2217    validate_underlying(definition.inst_id, definition.uly)?;
2218
2219    let context = format!("FUTURES instrument {}", definition.inst_id);
2220    let (_, quote_currency) = definition.uly.split_once('-').ok_or_else(|| {
2221        anyhow::anyhow!(
2222            "Invalid underlying '{}' for {}: expected format 'BASE-QUOTE'",
2223            definition.uly,
2224            definition.inst_id
2225        )
2226    })?;
2227
2228    let instrument_id = parse_instrument_id(definition.inst_id);
2229    let raw_symbol = Symbol::from_ustr_unchecked(definition.inst_id);
2230    let underlying = Currency::get_or_create_crypto_with_context(definition.uly, Some(&context));
2231    let quote_currency =
2232        Currency::get_or_create_crypto_with_context(quote_currency, Some(&context));
2233    let settlement_currency =
2234        Currency::get_or_create_crypto_with_context(definition.settle_ccy, Some(&context));
2235    let is_inverse = match definition.ct_type {
2236        OKXContractType::Linear => false,
2237        OKXContractType::Inverse => true,
2238        OKXContractType::None => {
2239            anyhow::bail!(
2240                "Invalid contract type '{}' for {}: expected 'linear' or 'inverse'",
2241                definition.ct_type,
2242                definition.inst_id
2243            )
2244        }
2245    };
2246    let listing_time = definition
2247        .list_time
2248        .ok_or_else(|| anyhow::anyhow!("`list_time` is required for {}", definition.inst_id))?;
2249    let expiry_time = definition
2250        .exp_time
2251        .ok_or_else(|| anyhow::anyhow!("`exp_time` is required for {}", definition.inst_id))?;
2252    let activation_ns = parse_millisecond_timestamp(listing_time);
2253    let expiration_ns = parse_millisecond_timestamp(expiry_time);
2254
2255    if definition.tick_sz.is_empty() {
2256        anyhow::bail!("`tick_sz` is empty for {}", definition.inst_id);
2257    }
2258
2259    let price_increment = Price::from_str(&definition.tick_sz).map_err(|e| {
2260        anyhow::anyhow!(
2261            "Failed to parse `tick_sz` '{}' for {}: {e}",
2262            definition.tick_sz,
2263            definition.inst_id
2264        )
2265    })?;
2266
2267    if definition.lot_sz.is_empty() {
2268        anyhow::bail!("`lot_sz` is empty for {}", definition.inst_id);
2269    }
2270    let size_increment = Quantity::from_str(&definition.lot_sz).map_err(|e| {
2271        anyhow::anyhow!(
2272            "Failed to parse `lot_sz` '{}' for {}: {e}",
2273            definition.lot_sz,
2274            definition.inst_id
2275        )
2276    })?;
2277    let multiplier = parse_multiplier_product(definition)?;
2278    let lot_size = Some(size_increment);
2279    let max_quantity = if definition.max_mkt_sz.is_empty() {
2280        None
2281    } else {
2282        Some(Quantity::from_str(&definition.max_mkt_sz).map_err(|e| {
2283            anyhow::anyhow!(
2284                "Failed to parse `max_mkt_sz` '{}' for {}: {e}",
2285                definition.max_mkt_sz,
2286                definition.inst_id
2287            )
2288        })?)
2289    };
2290    let min_quantity = if definition.min_sz.is_empty() {
2291        None
2292    } else {
2293        Some(Quantity::from_str(&definition.min_sz).map_err(|e| {
2294            anyhow::anyhow!(
2295                "Failed to parse `min_sz` '{}' for {}: {e}",
2296                definition.min_sz,
2297                definition.inst_id
2298            )
2299        })?)
2300    };
2301    let max_notional: Option<Money> = None;
2302    let min_notional: Option<Money> = None;
2303    let max_price = None; // TBD
2304    let min_price = None; // TBD
2305
2306    let info = build_futures_info(definition);
2307
2308    let instrument = CryptoFuture::builder()
2309        .instrument_id(instrument_id)
2310        .raw_symbol(raw_symbol)
2311        .underlying(underlying)
2312        .quote_currency(quote_currency)
2313        .settlement_currency(settlement_currency)
2314        .is_inverse(is_inverse)
2315        .activation_ns(activation_ns)
2316        .expiration_ns(expiration_ns)
2317        .price_precision(price_increment.precision)
2318        .size_precision(size_increment.precision)
2319        .price_increment(price_increment)
2320        .size_increment(size_increment)
2321        .maybe_multiplier(multiplier)
2322        .maybe_lot_size(lot_size)
2323        .maybe_max_quantity(max_quantity)
2324        .maybe_min_quantity(min_quantity)
2325        .maybe_max_notional(max_notional)
2326        .maybe_min_notional(min_notional)
2327        .maybe_max_price(max_price)
2328        .maybe_min_price(min_price)
2329        .maybe_margin_init(margin_init)
2330        .maybe_margin_maint(margin_maint)
2331        .maybe_info(info)
2332        // No ts_event for response
2333        .ts_event(ts_init)
2334        .ts_init(ts_init)
2335        .build()
2336        .unwrap();
2337
2338    Ok(InstrumentAny::CryptoFuture(instrument))
2339}
2340
2341/// Returns `true` if the futures `rule_type` identifies an OKX X-Perp
2342/// (expiring perpetual). X-Perps trade like perpetual swaps but expire on
2343/// a fixed date, so they should be carried as `CryptoFuture` instruments
2344/// while still supporting funding-rate flows.
2345#[must_use]
2346pub fn is_xperp_rule_type(rule_type: &str) -> bool {
2347    rule_type.eq_ignore_ascii_case("xperp")
2348}
2349
2350fn build_futures_info(definition: &OKXInstrument) -> Option<Params> {
2351    let mut info = build_price_limit_info(definition).unwrap_or_default();
2352
2353    if !definition.rule_type.is_empty() {
2354        info.insert(
2355            "rule_type".to_string(),
2356            serde_json::Value::String(definition.rule_type.clone()),
2357        );
2358    }
2359
2360    (!info.is_empty()).then(|| Params::new(info))
2361}
2362
2363fn build_price_limit_info(
2364    definition: &OKXInstrument,
2365) -> Option<IndexMap<String, serde_json::Value>> {
2366    let mut info = IndexMap::new();
2367
2368    insert_non_empty_info(
2369        &mut info,
2370        "okx_init_px_lmt_pct",
2371        &definition.init_px_lmt_pct,
2372    );
2373    insert_non_empty_info(
2374        &mut info,
2375        "okx_float_px_lmt_pct",
2376        &definition.float_px_lmt_pct,
2377    );
2378    insert_non_empty_info(&mut info, "okx_max_px_lmt_pct", &definition.max_px_lmt_pct);
2379    if let Some(rpi_min_level) = definition.rpi_min_level {
2380        info.insert(
2381            "okx_rpi_min_level".to_string(),
2382            serde_json::Value::from(rpi_min_level),
2383        );
2384    }
2385
2386    if let Some(rpi_min_px_band) = definition.rpi_min_px_band {
2387        info.insert(
2388            "okx_rpi_min_px_band".to_string(),
2389            serde_json::Value::String(rpi_min_px_band.to_string()),
2390        );
2391    }
2392
2393    if !definition.trade_quote_ccy_list.is_empty() {
2394        info.insert(
2395            "okx_trade_quote_ccy_list".to_string(),
2396            serde_json::json!(
2397                definition
2398                    .trade_quote_ccy_list
2399                    .iter()
2400                    .map(Ustr::as_str)
2401                    .collect::<Vec<_>>()
2402            ),
2403        );
2404    }
2405
2406    (!info.is_empty()).then_some(info)
2407}
2408
2409fn insert_non_empty_info(info: &mut IndexMap<String, serde_json::Value>, key: &str, value: &str) {
2410    if !value.is_empty() {
2411        info.insert(
2412            key.to_string(),
2413            serde_json::Value::String(value.to_string()),
2414        );
2415    }
2416}
2417
2418/// Parses an OKX option instrument definition into a Nautilus option contract.
2419///
2420/// # Errors
2421///
2422/// Returns an error if the instrument definition cannot be parsed.
2423///
2424/// # Panics
2425///
2426/// Panics if the constructed instrument fails validation.
2427pub fn parse_option_instrument(
2428    definition: &OKXInstrument,
2429    margin_init: Option<Decimal>,
2430    margin_maint: Option<Decimal>,
2431    ts_init: UnixNanos,
2432) -> anyhow::Result<InstrumentAny> {
2433    validate_underlying(definition.inst_id, definition.uly)?;
2434
2435    let context = format!("OPTION instrument {}", definition.inst_id);
2436    let (underlying_str, quote_ccy_str) = definition.uly.split_once('-').ok_or_else(|| {
2437        anyhow::anyhow!(
2438            "Invalid underlying '{}' for {}: expected format 'BASE-QUOTE'",
2439            definition.uly,
2440            definition.inst_id
2441        )
2442    })?;
2443
2444    let instrument_id = parse_instrument_id(definition.inst_id);
2445    let raw_symbol = Symbol::from_ustr_unchecked(definition.inst_id);
2446    let underlying = Currency::get_or_create_crypto_with_context(underlying_str, Some(&context));
2447    let option_kind: OptionKind = OptionKind::try_from(definition.opt_type).map_err(|kind| {
2448        anyhow::anyhow!(
2449            "Unsupported `optType` '{kind:?}' for {}: cannot map to Nautilus OptionKind",
2450            definition.inst_id
2451        )
2452    })?;
2453    let strike_price = Price::from_str(&definition.stk).map_err(|e| {
2454        anyhow::anyhow!(
2455            "Failed to parse `stk` '{}' for {}: {e}",
2456            definition.stk,
2457            definition.inst_id
2458        )
2459    })?;
2460    let quote_currency = Currency::get_or_create_crypto_with_context(quote_ccy_str, Some(&context));
2461    let settlement_currency =
2462        Currency::get_or_create_crypto_with_context(definition.settle_ccy, Some(&context));
2463
2464    let is_inverse = if definition.ct_type == OKXContractType::None {
2465        settlement_currency == underlying
2466    } else {
2467        matches!(definition.ct_type, OKXContractType::Inverse)
2468    };
2469
2470    let listing_time = definition
2471        .list_time
2472        .ok_or_else(|| anyhow::anyhow!("`list_time` is required for {}", definition.inst_id))?;
2473    let expiry_time = definition
2474        .exp_time
2475        .ok_or_else(|| anyhow::anyhow!("`exp_time` is required for {}", definition.inst_id))?;
2476    let activation_ns = parse_millisecond_timestamp(listing_time);
2477    let expiration_ns = parse_millisecond_timestamp(expiry_time);
2478
2479    if definition.tick_sz.is_empty() {
2480        anyhow::bail!("`tick_sz` is empty for {}", definition.inst_id);
2481    }
2482
2483    let price_increment = Price::from_str(&definition.tick_sz).map_err(|e| {
2484        anyhow::anyhow!(
2485            "Failed to parse `tick_sz` '{}' for {}: {e}",
2486            definition.tick_sz,
2487            definition.inst_id
2488        )
2489    })?;
2490
2491    if definition.lot_sz.is_empty() {
2492        anyhow::bail!("`lot_sz` is empty for {}", definition.inst_id);
2493    }
2494    let size_increment = Quantity::from_str(&definition.lot_sz).map_err(|e| {
2495        anyhow::anyhow!(
2496            "Failed to parse `lot_sz` '{}' for {}: {e}",
2497            definition.lot_sz,
2498            definition.inst_id
2499        )
2500    })?;
2501    let multiplier = parse_multiplier_product(definition)?;
2502    let lot_size = size_increment;
2503    let max_quantity = if definition.max_mkt_sz.is_empty() {
2504        None
2505    } else {
2506        Some(Quantity::from_str(&definition.max_mkt_sz).map_err(|e| {
2507            anyhow::anyhow!(
2508                "Failed to parse `max_mkt_sz` '{}' for {}: {e}",
2509                definition.max_mkt_sz,
2510                definition.inst_id
2511            )
2512        })?)
2513    };
2514    let min_quantity = if definition.min_sz.is_empty() {
2515        None
2516    } else {
2517        Some(Quantity::from_str(&definition.min_sz).map_err(|e| {
2518            anyhow::anyhow!(
2519                "Failed to parse `min_sz` '{}' for {}: {e}",
2520                definition.min_sz,
2521                definition.inst_id
2522            )
2523        })?)
2524    };
2525    let max_notional = None;
2526    let min_notional = None;
2527    let max_price = None;
2528    let min_price = None;
2529
2530    let instrument = CryptoOption::builder()
2531        .instrument_id(instrument_id)
2532        .raw_symbol(raw_symbol)
2533        .underlying(underlying)
2534        .quote_currency(quote_currency)
2535        .settlement_currency(settlement_currency)
2536        .is_inverse(is_inverse)
2537        .option_kind(option_kind)
2538        .strike_price(strike_price)
2539        .activation_ns(activation_ns)
2540        .expiration_ns(expiration_ns)
2541        .price_precision(price_increment.precision)
2542        .size_precision(size_increment.precision)
2543        .price_increment(price_increment)
2544        .size_increment(size_increment)
2545        .maybe_multiplier(multiplier)
2546        .lot_size(lot_size)
2547        .maybe_max_quantity(max_quantity)
2548        .maybe_min_quantity(min_quantity)
2549        .maybe_max_notional(max_notional)
2550        .maybe_min_notional(min_notional)
2551        .maybe_max_price(max_price)
2552        .maybe_min_price(min_price)
2553        .maybe_margin_init(margin_init)
2554        .maybe_margin_maint(margin_maint)
2555        .exercise_style(ExerciseStyle::European)
2556        .settlement_type(SettlementType::Cash)
2557        .ts_event(ts_init)
2558        .ts_init(ts_init)
2559        .build()
2560        .unwrap();
2561
2562    Ok(InstrumentAny::CryptoOption(instrument))
2563}
2564
2565fn okx_inst_category_to_asset_class(category: Option<OKXInstrumentCategory>) -> AssetClass {
2566    match category {
2567        Some(OKXInstrumentCategory::Crypto) => AssetClass::Cryptocurrency,
2568        Some(OKXInstrumentCategory::Equity) => AssetClass::Equity,
2569        Some(OKXInstrumentCategory::Commodity) => AssetClass::Commodity,
2570        Some(OKXInstrumentCategory::Fx) => AssetClass::FX,
2571        Some(OKXInstrumentCategory::Debt) => AssetClass::Debt,
2572        Some(OKXInstrumentCategory::Unknown) | None => AssetClass::Alternative,
2573    }
2574}
2575
2576fn parse_event_contract_currency(definition: &OKXInstrument) -> anyhow::Result<Currency> {
2577    let context = format!("EVENTS instrument {}", definition.inst_id);
2578    let currency = if !definition.settle_ccy.is_empty() {
2579        definition.settle_ccy
2580    } else if !definition.quote_ccy.is_empty() {
2581        definition.quote_ccy
2582    } else {
2583        anyhow::bail!(
2584            "`settle_ccy` or `quote_ccy` is required for EVENTS instrument {}",
2585            definition.inst_id
2586        );
2587    };
2588
2589    Ok(Currency::get_or_create_crypto_with_context(
2590        currency,
2591        Some(&context),
2592    ))
2593}
2594
2595fn build_event_contract_info(definition: &OKXInstrument) -> anyhow::Result<Params> {
2596    let mut map = serde_json::Map::new();
2597
2598    if let Some(series_id) = definition.series_id {
2599        map.insert(
2600            "series_id".to_string(),
2601            serde_json::Value::String(series_id.to_string()),
2602        );
2603    }
2604
2605    if let Some(inst_category) = definition.inst_category {
2606        let code = inst_category.as_ref();
2607        if !code.is_empty() {
2608            map.insert(
2609                "inst_category".to_string(),
2610                serde_json::Value::String(code.to_string()),
2611            );
2612        }
2613    }
2614
2615    if let Some(inst_id_code) = definition.inst_id_code {
2616        map.insert(
2617            "inst_id_code".to_string(),
2618            serde_json::Value::Number(inst_id_code.into()),
2619        );
2620    }
2621
2622    map.insert(
2623        "state".to_string(),
2624        serde_json::Value::String(definition.state.to_string()),
2625    );
2626    map.insert(
2627        "rule_type".to_string(),
2628        serde_json::Value::String(definition.rule_type.clone()),
2629    );
2630
2631    Ok(serde_json::from_value(serde_json::Value::Object(map))?)
2632}
2633
2634/// Parses an OKX event contract instrument definition into a Nautilus binary option.
2635///
2636/// # Errors
2637///
2638/// Returns an error if the instrument definition cannot be parsed.
2639pub fn parse_event_contract_instrument(
2640    definition: &OKXInstrument,
2641    margin_init: Option<Decimal>,
2642    margin_maint: Option<Decimal>,
2643    ts_init: UnixNanos,
2644) -> anyhow::Result<InstrumentAny> {
2645    let common = parse_common_instrument_data(definition)?;
2646    let currency = parse_event_contract_currency(definition)?;
2647
2648    let activation_ns = definition
2649        .list_time
2650        .map_or_default(parse_millisecond_timestamp);
2651    let expiration_ns = definition
2652        .exp_time
2653        .map_or_default(parse_millisecond_timestamp);
2654    let asset_class = okx_inst_category_to_asset_class(definition.inst_category);
2655    let info = build_event_contract_info(definition)?;
2656
2657    let instrument = BinaryOption::builder()
2658        .instrument_id(common.instrument_id)
2659        .raw_symbol(common.raw_symbol)
2660        .asset_class(asset_class)
2661        .currency(currency)
2662        .activation_ns(activation_ns)
2663        .expiration_ns(expiration_ns)
2664        .price_precision(common.price_increment.precision)
2665        .size_precision(common.size_increment.precision)
2666        .price_increment(common.price_increment)
2667        .size_increment(common.size_increment)
2668        .maybe_description(definition.series_id)
2669        .maybe_max_quantity(common.max_quantity)
2670        .maybe_min_quantity(common.min_quantity)
2671        .maybe_max_notional(common.max_notional)
2672        .maybe_min_notional(common.min_notional)
2673        .max_price(Price::from("1"))
2674        .min_price(Price::from("0"))
2675        .maybe_margin_init(margin_init)
2676        .maybe_margin_maint(margin_maint)
2677        .info(info)
2678        .ts_event(ts_init)
2679        .ts_init(ts_init)
2680        .build()?;
2681
2682    Ok(InstrumentAny::BinaryOption(instrument))
2683}
2684
2685/// Parses an OKX account into a Nautilus account state.
2686fn parse_balance_field(value_str: &str, field_name: &str, ccy_str: &str) -> Option<Decimal> {
2687    match Decimal::from_str(value_str) {
2688        Ok(decimal) => Some(decimal),
2689        Err(e) => {
2690            log::warn!(
2691                "Skipping balance detail for {ccy_str} with invalid {field_name} '{value_str}': {e}"
2692            );
2693            None
2694        }
2695    }
2696}
2697
2698/// Parses an OKX balance snapshot into a Nautilus [`AccountState`].
2699///
2700/// Pass the execution client's configured account type: the OKX balance payload carries no
2701/// account-mode field, and the emitted type decides which account the engine materializes for
2702/// this venue.
2703///
2704/// # Errors
2705///
2706/// Returns an error if the data cannot be parsed.
2707pub fn parse_account_state(
2708    okx_account: &OKXAccount,
2709    account_id: AccountId,
2710    account_type: AccountType,
2711    ts_init: UnixNanos,
2712) -> anyhow::Result<AccountState> {
2713    Ok(parse_account_state_with_completeness(okx_account, account_id, account_type, ts_init).0)
2714}
2715
2716pub(crate) fn parse_account_state_with_completeness(
2717    okx_account: &OKXAccount,
2718    account_id: AccountId,
2719    account_type: AccountType,
2720    ts_init: UnixNanos,
2721) -> (AccountState, bool) {
2722    let mut balances = Vec::new();
2723
2724    for b in &okx_account.details {
2725        // Skip balances with empty or whitespace-only currency codes
2726        let ccy_str = b.ccy.trim();
2727        if ccy_str.is_empty() {
2728            log::debug!("Skipping balance detail with empty currency code | raw_data={b:?}");
2729            continue;
2730        }
2731
2732        // Get or create currency (consistent with instrument parsing)
2733        let currency = Currency::get_or_create_crypto_with_context(ccy_str, Some("balance detail"));
2734
2735        // Parse balance values, skip if invalid
2736        let Some(total) = parse_balance_field(&b.cash_bal, "cash_bal", ccy_str) else {
2737            continue;
2738        };
2739
2740        let Some(free) = parse_balance_field(&b.avail_bal, "avail_bal", ccy_str) else {
2741            continue;
2742        };
2743
2744        match AccountBalance::from_total_and_free(total, free, currency) {
2745            Ok(balance) => balances.push(balance),
2746            Err(e) => {
2747                log::warn!("Skipping balance detail for {ccy_str} with invalid total/free: {e}");
2748            }
2749        }
2750    }
2751
2752    let balances_complete = balances.len() == okx_account.details.len();
2753
2754    // Ensure at least one balance exists (Nautilus requires non-empty balances)
2755    // OKX may return empty details for certain account configurations
2756    if balances.is_empty() {
2757        let zero_currency = Currency::USD();
2758        let zero_money = Money::new(0.0, zero_currency);
2759        let zero_balance = AccountBalance::new(zero_money, zero_money, zero_money);
2760        balances.push(zero_balance);
2761    }
2762
2763    let mut margins = Vec::new();
2764
2765    // OKX reports aggregate cross-margin requirements (`imr` / `mmr`) in USD terms;
2766    // emit as an account-wide margin entry keyed by USD.
2767    if !okx_account.imr.is_empty() && !okx_account.mmr.is_empty() {
2768        match (
2769            Decimal::from_str(&okx_account.imr),
2770            Decimal::from_str(&okx_account.mmr),
2771        ) {
2772            (Ok(imr_dec), Ok(mmr_dec)) => {
2773                if !imr_dec.is_zero() || !mmr_dec.is_zero() {
2774                    let margin_currency = Currency::USD();
2775
2776                    let initial_margin = Money::from_decimal(imr_dec, margin_currency)
2777                        .unwrap_or_else(|e| {
2778                            log::error!("Failed to create initial margin: {e}");
2779                            Money::zero(margin_currency)
2780                        });
2781                    let maintenance_margin = Money::from_decimal(mmr_dec, margin_currency)
2782                        .unwrap_or_else(|e| {
2783                            log::error!("Failed to create maintenance margin: {e}");
2784                            Money::zero(margin_currency)
2785                        });
2786
2787                    margins.push(MarginBalance::new(initial_margin, maintenance_margin, None));
2788                }
2789            }
2790            (Err(e1), _) => {
2791                log::warn!(
2792                    "Failed to parse initial margin requirement '{}': {}",
2793                    okx_account.imr,
2794                    e1
2795                );
2796            }
2797            (_, Err(e2)) => {
2798                log::warn!(
2799                    "Failed to parse maintenance margin requirement '{}': {}",
2800                    okx_account.mmr,
2801                    e2
2802                );
2803            }
2804        }
2805    }
2806
2807    let is_reported = true;
2808    let event_id = UUID4::new();
2809    let ts_event = parse_millisecond_timestamp(okx_account.u_time);
2810
2811    (
2812        AccountState::new(
2813            account_id,
2814            account_type,
2815            balances,
2816            margins,
2817            is_reported,
2818            event_id,
2819            ts_event,
2820            ts_init,
2821            None,
2822        ),
2823        balances_complete,
2824    )
2825}
2826
2827/// Converts an optional `UnixNanos` to an optional `Timestamp`.
2828pub fn nanos_to_datetime(value: Option<UnixNanos>) -> Option<jiff::Timestamp> {
2829    value.map(|nanos| nanos.to_datetime_utc())
2830}
2831
2832/// Returns `true` when two instruments carry the same tradable definition,
2833/// ignoring event timestamps.
2834///
2835/// Comparison runs on the serialized form so every venue field, including
2836/// the free-form `info` metadata, participates without listing each field.
2837pub(crate) fn instrument_definitions_match(a: &InstrumentAny, b: &InstrumentAny) -> bool {
2838    fn normalized(instrument: &InstrumentAny) -> Option<serde_json::Value> {
2839        let mut value = serde_json::to_value(instrument).ok()?;
2840
2841        if let Some(definition) = value
2842            .as_object_mut()
2843            .and_then(|obj| obj.values_mut().next())
2844            .and_then(serde_json::Value::as_object_mut)
2845        {
2846            definition.remove("ts_event");
2847            definition.remove("ts_init");
2848        }
2849
2850        Some(value)
2851    }
2852
2853    // A serialization failure compares as changed so updates are never suppressed
2854    match (normalized(a), normalized(b)) {
2855        (Some(a), Some(b)) => a == b,
2856        _ => false,
2857    }
2858}
2859
2860#[cfg(test)]
2861mod tests {
2862    use nautilus_model::{enums::OrderSide, identifiers::PositionId, instruments::Instrument};
2863    use rstest::rstest;
2864    use rust_decimal_macros::dec;
2865
2866    use super::*;
2867    use crate::{
2868        OKXPositionSide,
2869        common::{enums::OKXMarginMode, testing::load_test_json},
2870        http::{
2871            client::OKXResponse,
2872            models::{
2873                OKXAccount, OKXBalanceDetail, OKXCandlestick, OKXIndexTicker, OKXMarkPrice,
2874                OKXOrderHistory, OKXPlaceOrderResponse, OKXPosition, OKXPositionHistory,
2875                OKXPositionTier, OKXSpread, OKXTrade, OKXTransactionDetail,
2876            },
2877        },
2878    };
2879
2880    #[rstest]
2881    #[case::zero_fee_empty("", Decimal::ZERO, Currency::USDT())]
2882    #[case::zero_fee_valid("BTC", Decimal::ZERO, Currency::BTC())]
2883    #[case::valid("BTC", dec!(0.001), Currency::BTC())]
2884    #[case::nonzero_fee_empty("", dec!(0.5), Currency::USDT())]
2885    #[case::whitespace("  ETH  ", dec!(0.002), Currency::ETH())]
2886    fn test_parse_fee_currency(
2887        #[case] fee_ccy: &str,
2888        #[case] amount: Decimal,
2889        #[case] expected: Currency,
2890    ) {
2891        let result = parse_fee_currency(fee_ccy, amount, || "test context".to_string());
2892        assert_eq!(result, expected);
2893    }
2894
2895    #[rstest]
2896    fn test_parse_fee_currency_with_unknown_code() {
2897        let result = parse_fee_currency("NEWTOKEN", dec!(0.5), || "test context".to_string());
2898        assert_eq!(result.code, "NEWTOKEN");
2899        assert_eq!(result.precision, 8);
2900    }
2901
2902    #[rstest]
2903    #[case::valid("100.5", Some(dec!(100.5)))]
2904    #[case::invalid_numeric("not_a_number", None)]
2905    #[case::empty("", None)]
2906    fn test_parse_balance_field(#[case] value: &str, #[case] expected: Option<Decimal>) {
2907        let result = parse_balance_field(value, "test_field", "BTC");
2908        assert_eq!(result, expected);
2909    }
2910
2911    // Note: Tests for parse_account_state with edge cases (empty currency codes, invalid values)
2912    // are covered by the existing tests using test data files (e.g., http_get_account_balance.json)
2913
2914    #[rstest]
2915    fn test_parse_trades() {
2916        let json_data = load_test_json("http_get_trades.json");
2917        let parsed: OKXResponse<OKXTrade> = serde_json::from_str(&json_data).unwrap();
2918
2919        // Basic response envelope
2920        assert_eq!(parsed.code, "0");
2921        assert_eq!(parsed.msg, "");
2922        assert_eq!(parsed.data.len(), 2);
2923
2924        // Inspect first record
2925        let trade0 = &parsed.data[0];
2926        assert_eq!(trade0.inst_id, "BTC-USDT");
2927        assert_eq!(trade0.px, "102537.9");
2928        assert_eq!(trade0.sz, "0.00013669");
2929        assert_eq!(trade0.side, OKXSide::Sell);
2930        assert_eq!(trade0.trade_id, "734864333");
2931        assert_eq!(trade0.ts, 1_747_087_163_557);
2932        assert_eq!(trade0.source.as_deref(), Some("1"));
2933
2934        // Inspect second record
2935        let trade1 = &parsed.data[1];
2936        assert_eq!(trade1.inst_id, "BTC-USDT");
2937        assert_eq!(trade1.px, "102537.9");
2938        assert_eq!(trade1.sz, "0.0000125");
2939        assert_eq!(trade1.side, OKXSide::Buy);
2940        assert_eq!(trade1.trade_id, "734864332");
2941        assert_eq!(trade1.ts, 1_747_087_161_666);
2942        assert_eq!(trade1.source.as_deref(), Some("0"));
2943    }
2944
2945    #[rstest]
2946    fn test_parse_candlesticks() {
2947        let json_data = load_test_json("http_get_candlesticks.json");
2948        let parsed: OKXResponse<OKXCandlestick> = serde_json::from_str(&json_data).unwrap();
2949
2950        // Basic response envelope
2951        assert_eq!(parsed.code, "0");
2952        assert_eq!(parsed.msg, "");
2953        assert_eq!(parsed.data.len(), 2);
2954
2955        let bar0 = &parsed.data[0];
2956        assert_eq!(bar0.0, "1625097600000");
2957        assert_eq!(bar0.1, "33528.6");
2958        assert_eq!(bar0.2, "33870.0");
2959        assert_eq!(bar0.3, "33528.6");
2960        assert_eq!(bar0.4, "33783.9");
2961        assert_eq!(bar0.5, "778.838");
2962
2963        let bar1 = &parsed.data[1];
2964        assert_eq!(bar1.0, "1625097660000");
2965        assert_eq!(bar1.1, "33783.9");
2966        assert_eq!(bar1.2, "33783.9");
2967        assert_eq!(bar1.3, "33782.1");
2968        assert_eq!(bar1.4, "33782.1");
2969        assert_eq!(bar1.5, "0.123");
2970    }
2971
2972    #[rstest]
2973    fn test_parse_candlesticks_full() {
2974        let json_data = load_test_json("http_get_candlesticks_full.json");
2975        let parsed: OKXResponse<OKXCandlestick> = serde_json::from_str(&json_data).unwrap();
2976
2977        // Basic response envelope
2978        assert_eq!(parsed.code, "0");
2979        assert_eq!(parsed.msg, "");
2980        assert_eq!(parsed.data.len(), 2);
2981
2982        // Inspect first record
2983        let bar0 = &parsed.data[0];
2984        assert_eq!(bar0.0, "1747094040000");
2985        assert_eq!(bar0.1, "102806.1");
2986        assert_eq!(bar0.2, "102820.4");
2987        assert_eq!(bar0.3, "102806.1");
2988        assert_eq!(bar0.4, "102820.4");
2989        assert_eq!(bar0.5, "1040.37");
2990        assert_eq!(bar0.6, "10.4037");
2991        assert_eq!(bar0.7, "1069603.34883");
2992        assert_eq!(bar0.8, "1");
2993
2994        // Inspect second record
2995        let bar1 = &parsed.data[1];
2996        assert_eq!(bar1.0, "1747093980000");
2997        assert_eq!(bar1.5, "7164.04");
2998        assert_eq!(bar1.6, "71.6404");
2999        assert_eq!(bar1.7, "7364701.57952");
3000        assert_eq!(bar1.8, "1");
3001    }
3002
3003    #[rstest]
3004    fn test_parse_mark_price() {
3005        let json_data = load_test_json("http_get_mark_price.json");
3006        let parsed: OKXResponse<OKXMarkPrice> = serde_json::from_str(&json_data).unwrap();
3007
3008        // Basic response envelope
3009        assert_eq!(parsed.code, "0");
3010        assert_eq!(parsed.msg, "");
3011        assert_eq!(parsed.data.len(), 1);
3012
3013        // Inspect first record
3014        let mark_price = &parsed.data[0];
3015
3016        assert_eq!(mark_price.inst_id, "BTC-USDT-SWAP");
3017        assert_eq!(mark_price.mark_px, "84660.1");
3018        assert_eq!(mark_price.ts, 1_744_590_349_506);
3019    }
3020
3021    #[rstest]
3022    fn test_parse_index_price() {
3023        let json_data = load_test_json("http_get_index_price.json");
3024        let parsed: OKXResponse<OKXIndexTicker> = serde_json::from_str(&json_data).unwrap();
3025
3026        // Basic response envelope
3027        assert_eq!(parsed.code, "0");
3028        assert_eq!(parsed.msg, "");
3029        assert_eq!(parsed.data.len(), 1);
3030
3031        // Inspect first record
3032        let index_price = &parsed.data[0];
3033
3034        assert_eq!(index_price.inst_id, "BTC-USDT");
3035        assert_eq!(index_price.idx_px, "103895");
3036        assert_eq!(index_price.ts, 1_746_942_707_815);
3037    }
3038
3039    #[rstest]
3040    fn test_parse_account() {
3041        let json_data = load_test_json("http_get_account_balance.json");
3042        let parsed: OKXResponse<OKXAccount> = serde_json::from_str(&json_data).unwrap();
3043
3044        // Basic response envelope
3045        assert_eq!(parsed.code, "0");
3046        assert_eq!(parsed.msg, "");
3047        assert_eq!(parsed.data.len(), 1);
3048
3049        // Inspect first record
3050        let account = &parsed.data[0];
3051        assert_eq!(account.adj_eq, "");
3052        assert_eq!(account.borrow_froz, "");
3053        assert_eq!(account.imr, "");
3054        assert_eq!(account.iso_eq, "5.4682385526666675");
3055        assert_eq!(account.mgn_ratio, "");
3056        assert_eq!(account.mmr, "");
3057        assert_eq!(account.notional_usd, "");
3058        assert_eq!(account.notional_usd_for_borrow, "");
3059        assert_eq!(account.notional_usd_for_futures, "");
3060        assert_eq!(account.notional_usd_for_option, "");
3061        assert_eq!(account.notional_usd_for_swap, "");
3062        assert_eq!(account.ord_froz, "");
3063        assert_eq!(account.total_eq, "99.88870288820581");
3064        assert_eq!(account.upl, "");
3065        assert_eq!(account.u_time, 1_744_499_648_556);
3066        assert_eq!(account.details.len(), 1);
3067
3068        let detail = &account.details[0];
3069        assert_eq!(detail.ccy, "USDT");
3070        assert_eq!(detail.avail_bal, "94.42612990333333");
3071        assert_eq!(detail.avail_eq, "94.42612990333333");
3072        assert_eq!(detail.cash_bal, "94.42612990333333");
3073        assert_eq!(detail.dis_eq, "5.4682385526666675");
3074        assert_eq!(detail.eq, "99.89469657000001");
3075        assert_eq!(detail.eq_usd, "99.88870288820581");
3076        assert_eq!(detail.fixed_bal, "0");
3077        assert_eq!(detail.frozen_bal, "5.468566666666667");
3078        assert_eq!(detail.imr, "0");
3079        assert_eq!(detail.iso_eq, "5.468566666666667");
3080        assert_eq!(detail.iso_upl, "-0.0273000000000002");
3081        assert_eq!(detail.mmr, "0");
3082        assert_eq!(detail.notional_lever, "0");
3083        assert_eq!(detail.ord_frozen, "0");
3084        assert_eq!(detail.reward_bal, "0");
3085        assert_eq!(detail.smt_sync_eq, "0");
3086        assert_eq!(detail.spot_copy_trading_eq, "0");
3087        assert_eq!(detail.spot_iso_bal, "0");
3088        assert_eq!(detail.stgy_eq, "0");
3089        assert_eq!(detail.twap, "0");
3090        assert_eq!(detail.upl, "-0.0273000000000002");
3091        assert_eq!(detail.u_time, 1_744_498_994_783);
3092    }
3093
3094    #[rstest]
3095    fn test_parse_order_history() {
3096        let json_data = load_test_json("http_get_orders_history.json");
3097        let parsed: OKXResponse<OKXOrderHistory> = serde_json::from_str(&json_data).unwrap();
3098
3099        // Basic response envelope
3100        assert_eq!(parsed.code, "0");
3101        assert_eq!(parsed.msg, "");
3102        assert_eq!(parsed.data.len(), 1);
3103
3104        // Inspect first record
3105        let order = &parsed.data[0];
3106        assert_eq!(order.ord_id, "2497956918703120384");
3107        assert_eq!(order.fill_sz, "0.03");
3108        assert_eq!(order.acc_fill_sz, "0.03");
3109        assert_eq!(order.state, OKXOrderStatus::Filled);
3110        assert!(order.fill_fee.is_none());
3111    }
3112
3113    #[rstest]
3114    fn test_parse_position() {
3115        let json_data = load_test_json("http_get_positions.json");
3116        let parsed: OKXResponse<OKXPosition> = serde_json::from_str(&json_data).unwrap();
3117
3118        // Basic response envelope
3119        assert_eq!(parsed.code, "0");
3120        assert_eq!(parsed.msg, "");
3121        assert_eq!(parsed.data.len(), 1);
3122
3123        // Inspect first record
3124        let pos = &parsed.data[0];
3125        assert_eq!(pos.inst_id, "BTC-USDT-SWAP");
3126        assert_eq!(pos.pos_side, OKXPositionSide::Long);
3127        assert_eq!(pos.pos, "0.5");
3128        assert_eq!(pos.base_bal, "0.5");
3129        assert_eq!(pos.quote_bal, "5000");
3130        assert_eq!(pos.u_time, 1_622_559_930_237);
3131    }
3132
3133    #[rstest]
3134    fn test_parse_position_history() {
3135        let json_data = load_test_json("http_get_account_positions-history.json");
3136        let parsed: OKXResponse<OKXPositionHistory> = serde_json::from_str(&json_data).unwrap();
3137
3138        // Basic response envelope
3139        assert_eq!(parsed.code, "0");
3140        assert_eq!(parsed.msg, "");
3141        assert_eq!(parsed.data.len(), 1);
3142
3143        // Inspect first record
3144        let hist = &parsed.data[0];
3145        assert_eq!(hist.inst_id, "ETH-USDT-SWAP");
3146        assert_eq!(hist.inst_type, OKXInstrumentType::Swap);
3147        assert_eq!(hist.mgn_mode, OKXMarginMode::Isolated);
3148        assert_eq!(hist.pos_side, OKXPositionSide::Long);
3149        assert_eq!(hist.lever, "3.0");
3150        assert_eq!(hist.open_avg_px, "3226.93");
3151        assert_eq!(hist.close_avg_px.as_deref(), Some("3224.8"));
3152        assert_eq!(hist.pnl.as_deref(), Some("-0.0213"));
3153        assert!(!hist.c_time.is_empty());
3154        assert!(hist.u_time > 0);
3155    }
3156
3157    #[rstest]
3158    fn test_parse_position_tiers() {
3159        let json_data = load_test_json("http_get_position_tiers.json");
3160        let parsed: OKXResponse<OKXPositionTier> = serde_json::from_str(&json_data).unwrap();
3161
3162        // Basic response envelope
3163        assert_eq!(parsed.code, "0");
3164        assert_eq!(parsed.msg, "");
3165        assert_eq!(parsed.data.len(), 1);
3166
3167        // Inspect first tier record
3168        let tier = &parsed.data[0];
3169        assert_eq!(tier.inst_id, "BTC-USDT");
3170        assert_eq!(tier.tier, "1");
3171        assert_eq!(tier.min_sz, "0");
3172        assert_eq!(tier.max_sz, "50");
3173        assert_eq!(tier.imr, "0.1");
3174        assert_eq!(tier.mmr, "0.03");
3175    }
3176
3177    #[rstest]
3178    fn test_parse_account_field_name_compatibility() {
3179        // Test with new field names (with Amt suffix)
3180        let json_new = load_test_json("http_balance_detail_new_fields.json");
3181        let detail_new: OKXBalanceDetail = serde_json::from_str(&json_new).unwrap();
3182        assert_eq!(detail_new.max_spot_in_use_amt, "50.0");
3183        assert_eq!(detail_new.spot_in_use_amt, "30.0");
3184        assert_eq!(detail_new.cl_spot_in_use_amt, "25.0");
3185
3186        // Test with old field names (without Amt suffix) - for backward compatibility
3187        let json_old = load_test_json("http_balance_detail_old_fields.json");
3188        let detail_old: OKXBalanceDetail = serde_json::from_str(&json_old).unwrap();
3189        assert_eq!(detail_old.max_spot_in_use_amt, "75.0");
3190        assert_eq!(detail_old.spot_in_use_amt, "40.0");
3191        assert_eq!(detail_old.cl_spot_in_use_amt, "35.0");
3192    }
3193
3194    #[rstest]
3195    fn test_parse_place_order_response() {
3196        let json_data = load_test_json("http_place_order_response.json");
3197        let parsed: OKXPlaceOrderResponse = serde_json::from_str(&json_data).unwrap();
3198        assert_eq!(parsed.ord_id, Some(Ustr::from("12345678901234567890")));
3199        assert_eq!(parsed.cl_ord_id, Some(Ustr::from("client_order_123")));
3200        assert_eq!(parsed.tag, Some(String::new()));
3201    }
3202
3203    #[rstest]
3204    fn test_parse_transaction_details() {
3205        let json_data = load_test_json("http_transaction_detail.json");
3206        let parsed: OKXTransactionDetail = serde_json::from_str(&json_data).unwrap();
3207        assert_eq!(parsed.inst_type, OKXInstrumentType::Spot);
3208        assert_eq!(parsed.inst_id, Ustr::from("BTC-USDT"));
3209        assert_eq!(parsed.trade_id, Ustr::from("123456789"));
3210        assert_eq!(parsed.ord_id, Ustr::from("987654321"));
3211        assert_eq!(parsed.cl_ord_id, Ustr::from("client_123"));
3212        assert_eq!(parsed.bill_id, Ustr::from("bill_456"));
3213        assert_eq!(parsed.fill_px, "42000.5");
3214        assert_eq!(parsed.fill_sz, "0.001");
3215        assert_eq!(parsed.side, OKXSide::Buy);
3216        assert_eq!(parsed.exec_type, OKXExecType::Taker);
3217        assert_eq!(parsed.fee_ccy, "USDT");
3218        assert_eq!(parsed.fee, Some("0.042".to_string()));
3219        assert_eq!(parsed.ts, 1_625_097_600_000);
3220    }
3221
3222    #[rstest]
3223    fn test_parse_empty_fee_field() {
3224        let json_data = load_test_json("http_transaction_detail_empty_fee.json");
3225        let parsed: OKXTransactionDetail = serde_json::from_str(&json_data).unwrap();
3226        assert_eq!(parsed.fee, None);
3227    }
3228
3229    #[rstest]
3230    fn test_parse_optional_string_to_u64() {
3231        use serde::Deserialize;
3232
3233        #[derive(Deserialize)]
3234        struct TestStruct {
3235            #[serde(deserialize_with = "crate::common::parse::deserialize_optional_string_to_u64")]
3236            value: Option<u64>,
3237        }
3238
3239        let json_cases = load_test_json("common_optional_string_to_u64.json");
3240        let cases: Vec<TestStruct> = serde_json::from_str(&json_cases).unwrap();
3241
3242        assert_eq!(cases[0].value, Some(12345));
3243        assert_eq!(cases[1].value, None);
3244        assert_eq!(cases[2].value, None);
3245    }
3246
3247    #[rstest]
3248    fn test_parse_spot_instrument() {
3249        let json_data = load_test_json("http_get_instruments_spot.json");
3250        let response: OKXResponse<OKXInstrument> = serde_json::from_str(&json_data).unwrap();
3251        let okx_inst: &OKXInstrument = response
3252            .data
3253            .first()
3254            .expect("Test data must have an instrument");
3255
3256        let instrument = parse_spot_instrument(okx_inst, None, None, UnixNanos::default()).unwrap();
3257
3258        assert_eq!(instrument.id(), InstrumentId::from("BTC-USD.OKX"));
3259        assert_eq!(instrument.raw_symbol(), Symbol::from("BTC-USD"));
3260        assert_eq!(instrument.underlying(), None);
3261        assert_eq!(instrument.base_currency(), Some(Currency::BTC()));
3262        assert_eq!(instrument.quote_currency(), Currency::USD());
3263        assert_eq!(instrument.settlement_currency(), Currency::USD());
3264        assert_eq!(instrument.price_precision(), 1);
3265        assert_eq!(instrument.size_precision(), 8);
3266        assert_eq!(instrument.price_increment(), Price::from("0.1"));
3267        assert_eq!(instrument.size_increment(), Quantity::from("0.00000001"));
3268        assert_eq!(instrument.multiplier(), Quantity::from(1));
3269        assert_eq!(instrument.lot_size(), Some(Quantity::from("0.00000001")));
3270        assert_eq!(instrument.max_quantity(), Some(Quantity::from(1_000_000)));
3271        assert_eq!(instrument.min_quantity(), Some(Quantity::from("0.00001")));
3272        assert_eq!(instrument.max_notional(), None);
3273        assert_eq!(instrument.min_notional(), None);
3274        assert_eq!(instrument.max_price(), None);
3275        assert_eq!(instrument.min_price(), None);
3276        assert!(okx_inst.trade_quote_ccy_list.is_empty());
3277    }
3278
3279    #[rstest]
3280    fn test_parse_spot_instrument_retains_trade_quote_ccy_list() {
3281        let json_data = load_test_json("http_get_instruments_spot_usdc.json");
3282        let response: OKXResponse<OKXInstrument> = serde_json::from_str(&json_data).unwrap();
3283        let okx_inst: &OKXInstrument = response
3284            .data
3285            .first()
3286            .expect("Test data must have an instrument");
3287
3288        assert_eq!(okx_inst.inst_id, "BTC-USDC");
3289        assert_eq!(okx_inst.quote_ccy, "USDC");
3290        assert_eq!(okx_inst.inst_id_code, Some(20459));
3291        assert_eq!(
3292            okx_inst.trade_quote_ccy_list,
3293            vec![Ustr::from("USD"), Ustr::from("USDC")]
3294        );
3295
3296        let instrument = parse_spot_instrument(okx_inst, None, None, UnixNanos::default()).unwrap();
3297
3298        assert_eq!(instrument.id(), InstrumentId::from("BTC-USDC.OKX"));
3299        assert_eq!(instrument.quote_currency(), Currency::USDC());
3300
3301        let InstrumentAny::CurrencyPair(pair) = instrument else {
3302            panic!("expected CurrencyPair");
3303        };
3304
3305        let info = pair.info.expect("trade quote info must be set");
3306        assert_eq!(
3307            info.get("okx_trade_quote_ccy_list"),
3308            Some(&serde_json::json!(["USD", "USDC"]))
3309        );
3310    }
3311
3312    #[rstest]
3313    fn test_parse_spot_instrument_exposes_price_limit_percentages_as_info() {
3314        let json_data = load_test_json("http_get_instruments_price_limit.json");
3315        let response: OKXResponse<OKXInstrument> = serde_json::from_str(&json_data).unwrap();
3316        let okx_inst = response
3317            .data
3318            .first()
3319            .expect("Test data must have an instrument");
3320
3321        assert_eq!(okx_inst.init_px_lmt_pct, "0.05");
3322        assert_eq!(okx_inst.float_px_lmt_pct, "0.03");
3323        assert_eq!(okx_inst.max_px_lmt_pct, "0.15");
3324
3325        let instrument = parse_spot_instrument(okx_inst, None, None, UnixNanos::default()).unwrap();
3326
3327        let InstrumentAny::CurrencyPair(pair) = instrument else {
3328            panic!("expected CurrencyPair");
3329        };
3330        let info = pair.info.expect("price-limit info must be set");
3331
3332        assert_eq!(info.get_str("okx_init_px_lmt_pct"), Some("0.05"));
3333        assert_eq!(info.get_str("okx_float_px_lmt_pct"), Some("0.03"));
3334        assert_eq!(info.get_str("okx_max_px_lmt_pct"), Some("0.15"));
3335        assert_eq!(pair.max_price, None);
3336        assert_eq!(pair.min_price, None);
3337    }
3338
3339    #[rstest]
3340    fn test_parse_margin_instrument() {
3341        let json_data = load_test_json("http_get_instruments_margin.json");
3342        let response: OKXResponse<OKXInstrument> = serde_json::from_str(&json_data).unwrap();
3343        let okx_inst: &OKXInstrument = response
3344            .data
3345            .first()
3346            .expect("Test data must have an instrument");
3347
3348        let instrument = parse_spot_instrument(okx_inst, None, None, UnixNanos::default()).unwrap();
3349
3350        assert_eq!(instrument.id(), InstrumentId::from("BTC-USDT.OKX"));
3351        assert_eq!(instrument.raw_symbol(), Symbol::from("BTC-USDT"));
3352        assert_eq!(instrument.underlying(), None);
3353        assert_eq!(instrument.base_currency(), Some(Currency::BTC()));
3354        assert_eq!(instrument.quote_currency(), Currency::USDT());
3355        assert_eq!(instrument.settlement_currency(), Currency::USDT());
3356        assert_eq!(instrument.price_precision(), 1);
3357        assert_eq!(instrument.size_precision(), 8);
3358        assert_eq!(instrument.price_increment(), Price::from("0.1"));
3359        assert_eq!(instrument.size_increment(), Quantity::from("0.00000001"));
3360        assert_eq!(instrument.multiplier(), Quantity::from(1));
3361        assert_eq!(instrument.lot_size(), Some(Quantity::from("0.00000001")));
3362        assert_eq!(instrument.max_quantity(), Some(Quantity::from(1_000_000)));
3363        assert_eq!(instrument.min_quantity(), Some(Quantity::from("0.00001")));
3364        assert_eq!(instrument.max_notional(), None);
3365        assert_eq!(instrument.min_notional(), None);
3366        assert_eq!(instrument.max_price(), None);
3367        assert_eq!(instrument.min_price(), None);
3368    }
3369
3370    #[rstest]
3371    fn test_parse_spot_instrument_with_valid_ct_mult() {
3372        let json_data = load_test_json("http_get_instruments_spot.json");
3373        let mut response: OKXResponse<OKXInstrument> = serde_json::from_str(&json_data).unwrap();
3374
3375        // Modify ctMult to have a valid multiplier value (ctVal is empty, defaults to 1)
3376        if let Some(inst) = response.data.first_mut() {
3377            inst.ct_mult = "0.01".to_string();
3378        }
3379
3380        let okx_inst = response.data.first().unwrap();
3381        let instrument = parse_spot_instrument(okx_inst, None, None, UnixNanos::default()).unwrap();
3382
3383        // Should parse the multiplier as product of ctMult * ctVal (0.01 * 1 = 0.01)
3384        if let InstrumentAny::CurrencyPair(pair) = instrument {
3385            assert_eq!(pair.multiplier, Quantity::from("0.01"));
3386        } else {
3387            panic!("Expected CurrencyPair instrument");
3388        }
3389    }
3390
3391    #[rstest]
3392    fn test_parse_spot_instrument_with_invalid_ct_mult() {
3393        let json_data = load_test_json("http_get_instruments_spot.json");
3394        let mut response: OKXResponse<OKXInstrument> = serde_json::from_str(&json_data).unwrap();
3395
3396        // Modify ctMult to be invalid
3397        if let Some(inst) = response.data.first_mut() {
3398            inst.ct_mult = "invalid_number".to_string();
3399        }
3400
3401        let okx_inst = response.data.first().unwrap();
3402        let result = parse_spot_instrument(okx_inst, None, None, UnixNanos::default());
3403
3404        // Should error instead of silently defaulting to 1.0
3405        assert!(result.is_err());
3406        assert!(
3407            result
3408                .unwrap_err()
3409                .to_string()
3410                .contains("Failed to parse `ct_mult`")
3411        );
3412    }
3413
3414    #[rstest]
3415    fn test_parse_swap_instrument() {
3416        let json_data = load_test_json("http_get_instruments_swap.json");
3417        let response: OKXResponse<OKXInstrument> = serde_json::from_str(&json_data).unwrap();
3418        let okx_inst: &OKXInstrument = response
3419            .data
3420            .first()
3421            .expect("Test data must have an instrument");
3422
3423        let instrument = parse_swap_instrument(okx_inst, None, None, UnixNanos::default()).unwrap();
3424
3425        assert_eq!(instrument.id(), InstrumentId::from("BTC-USD-SWAP.OKX"));
3426        assert_eq!(instrument.raw_symbol(), Symbol::from("BTC-USD-SWAP"));
3427        assert_eq!(instrument.underlying(), None);
3428        assert_eq!(instrument.base_currency(), Some(Currency::BTC()));
3429        assert_eq!(instrument.quote_currency(), Currency::USD());
3430        assert_eq!(instrument.settlement_currency(), Currency::BTC());
3431        assert!(instrument.is_inverse());
3432        assert_eq!(instrument.price_precision(), 1);
3433        assert_eq!(instrument.size_precision(), 0);
3434        assert_eq!(instrument.price_increment(), Price::from("0.1"));
3435        assert_eq!(instrument.size_increment(), Quantity::from(1));
3436        assert_eq!(instrument.multiplier(), Quantity::from(100));
3437        assert_eq!(instrument.lot_size(), Some(Quantity::from(1)));
3438        assert_eq!(instrument.max_quantity(), Some(Quantity::from(30000)));
3439        assert_eq!(instrument.min_quantity(), Some(Quantity::from(1)));
3440        assert_eq!(instrument.max_notional(), None);
3441        assert_eq!(instrument.min_notional(), None);
3442        assert_eq!(instrument.max_price(), None);
3443        assert_eq!(instrument.min_price(), None);
3444    }
3445
3446    #[rstest]
3447    fn test_parse_swap_instrument_exposes_price_limit_percentages_as_info() {
3448        let json_data = load_test_json("http_get_instruments_swap.json");
3449        let mut response: OKXResponse<OKXInstrument> = serde_json::from_str(&json_data).unwrap();
3450        let okx_inst = response
3451            .data
3452            .first_mut()
3453            .expect("Test data must have an instrument");
3454        okx_inst.init_px_lmt_pct = "0.05".to_string();
3455        okx_inst.float_px_lmt_pct = "0.03".to_string();
3456        okx_inst.max_px_lmt_pct = "0.15".to_string();
3457
3458        let instrument = parse_swap_instrument(okx_inst, None, None, UnixNanos::default()).unwrap();
3459
3460        let InstrumentAny::CryptoPerpetual(perpetual) = instrument else {
3461            panic!("expected CryptoPerpetual");
3462        };
3463        let info = perpetual.info.expect("price-limit info must be set");
3464
3465        assert_eq!(info.get_str("okx_init_px_lmt_pct"), Some("0.05"));
3466        assert_eq!(info.get_str("okx_float_px_lmt_pct"), Some("0.03"));
3467        assert_eq!(info.get_str("okx_max_px_lmt_pct"), Some("0.15"));
3468        assert_eq!(perpetual.max_price, None);
3469        assert_eq!(perpetual.min_price, None);
3470    }
3471
3472    #[rstest]
3473    fn test_deserialize_swap_instrument_with_rebase_state() {
3474        let json_data = load_test_json("http_get_instruments_swap.json");
3475        let mut value: serde_json::Value = serde_json::from_str(&json_data).unwrap();
3476        value["data"][0]["state"] = serde_json::Value::String("rebase".to_string());
3477
3478        let response: OKXResponse<OKXInstrument> = serde_json::from_value(value).unwrap();
3479
3480        assert_eq!(response.data[0].inst_id, "BTC-USD-SWAP");
3481    }
3482
3483    #[rstest]
3484    fn test_parse_inverse_spread_instrument() {
3485        let json_data = load_test_json("http_get_spreads.json");
3486        let response: OKXResponse<OKXSpread> = serde_json::from_str(&json_data).unwrap();
3487        let okx_spread = response.data.first().expect("Test data must have a spread");
3488
3489        let instrument =
3490            parse_spread_instrument(okx_spread, None, None, UnixNanos::default()).unwrap();
3491
3492        let InstrumentAny::CryptoFuturesSpread(spread) = instrument else {
3493            panic!("Expected CryptoFuturesSpread");
3494        };
3495        let info = spread.info.as_ref().expect("spread info must be set");
3496        let legs = info
3497            .get("okx_spread_legs")
3498            .and_then(serde_json::Value::as_array)
3499            .expect("spread legs must be present");
3500
3501        assert_eq!(
3502            spread.id,
3503            InstrumentId::from("ETH-USD-SWAP_ETH-USD-231229.OKX")
3504        );
3505        assert_eq!(
3506            spread.raw_symbol,
3507            Symbol::from("ETH-USD-SWAP_ETH-USD-231229")
3508        );
3509        assert_eq!(spread.underlying, Currency::ETH());
3510        assert_eq!(spread.quote_currency, Currency::USD());
3511        assert_eq!(spread.settlement_currency, Currency::ETH());
3512        assert!(spread.is_inverse);
3513        assert_eq!(spread.strategy_type, Ustr::from("inverse"));
3514        assert_eq!(spread.price_precision, 2);
3515        assert_eq!(spread.size_precision, 0);
3516        assert_eq!(spread.price_increment, Price::from("0.01"));
3517        assert_eq!(spread.size_increment, Quantity::from("10"));
3518        assert_eq!(spread.lot_size, Quantity::from("10"));
3519        assert_eq!(spread.min_quantity, Some(Quantity::from("10")));
3520        assert_eq!(spread.max_quantity, None);
3521        assert_eq!(info.get_str("okx_sz_ccy"), Some("USD"));
3522        assert_eq!(legs.len(), 2);
3523        assert_eq!(legs[0]["inst_id"].as_str(), Some("ETH-USD-SWAP"));
3524        assert_eq!(legs[0]["side"].as_str(), Some("sell"));
3525        assert_eq!(legs[0]["ratio"].as_i64(), Some(-1));
3526        assert_eq!(legs[1]["inst_id"].as_str(), Some("ETH-USD-231229"));
3527        assert_eq!(legs[1]["side"].as_str(), Some("buy"));
3528        assert_eq!(legs[1]["ratio"].as_i64(), Some(1));
3529    }
3530
3531    #[rstest]
3532    fn test_parse_linear_spread_instrument_without_expiry() {
3533        let json_data = load_test_json("http_get_spreads.json");
3534        let response: OKXResponse<OKXSpread> = serde_json::from_str(&json_data).unwrap();
3535        let okx_spread = response
3536            .data
3537            .get(1)
3538            .expect("Test data must have a linear spread");
3539
3540        let instrument =
3541            parse_spread_instrument(okx_spread, None, None, UnixNanos::default()).unwrap();
3542
3543        let InstrumentAny::CryptoFuturesSpread(spread) = instrument else {
3544            panic!("Expected CryptoFuturesSpread");
3545        };
3546
3547        assert_eq!(spread.id, InstrumentId::from("BTC-USDT_BTC-USDT-SWAP.OKX"));
3548        assert_eq!(spread.underlying, Currency::BTC());
3549        assert_eq!(spread.quote_currency, Currency::USDT());
3550        assert_eq!(spread.settlement_currency, Currency::USDT());
3551        assert!(!spread.is_inverse);
3552        assert_eq!(spread.price_precision, 4);
3553        assert_eq!(spread.size_precision, 3);
3554        assert_eq!(spread.price_increment, Price::from("0.0001"));
3555        assert_eq!(spread.size_increment, Quantity::from("0.001"));
3556        assert_eq!(spread.expiration_ns, UnixNanos::default());
3557    }
3558
3559    #[rstest]
3560    fn test_parse_option_spread_instrument() {
3561        let json_data = load_test_json("http_get_spreads.json");
3562        let mut payload: serde_json::Value = serde_json::from_str(&json_data).unwrap();
3563        let spread = payload["data"][0]
3564            .as_object_mut()
3565            .expect("spread payload must be an object");
3566        spread.insert(
3567            "sprdId".to_string(),
3568            serde_json::Value::String(
3569                "BTC-USD-260626-100000-C_BTC-USD-260626-110000-C".to_string(),
3570            ),
3571        );
3572        spread.insert(
3573            "baseCcy".to_string(),
3574            serde_json::Value::String("BTC".to_string()),
3575        );
3576        spread.insert(
3577            "quoteCcy".to_string(),
3578            serde_json::Value::String("USD".to_string()),
3579        );
3580        spread["legs"][0]["instId"] =
3581            serde_json::Value::String("BTC-USD-260626-100000-C".to_string());
3582        spread["legs"][1]["instId"] =
3583            serde_json::Value::String("BTC-USD-260626-110000-C".to_string());
3584
3585        let response: OKXResponse<OKXSpread> = serde_json::from_value(payload).unwrap();
3586        let instrument = parse_spread_instrument(
3587            response.data.first().expect("Test data must have a spread"),
3588            None,
3589            None,
3590            UnixNanos::default(),
3591        )
3592        .unwrap();
3593
3594        let InstrumentAny::CryptoOptionSpread(spread) = instrument else {
3595            panic!("Expected CryptoOptionSpread");
3596        };
3597        let info = spread.info.as_ref().expect("spread info must be set");
3598        let legs = info
3599            .get("okx_spread_legs")
3600            .and_then(serde_json::Value::as_array)
3601            .expect("spread legs must be present");
3602
3603        assert_eq!(
3604            spread.id,
3605            InstrumentId::from("BTC-USD-260626-100000-C_BTC-USD-260626-110000-C.OKX")
3606        );
3607        assert_eq!(spread.underlying, Currency::BTC());
3608        assert_eq!(spread.quote_currency, Currency::USD());
3609        assert_eq!(legs[0]["inst_id"].as_str(), Some("BTC-USD-260626-100000-C"));
3610        assert_eq!(legs[1]["inst_id"].as_str(), Some("BTC-USD-260626-110000-C"));
3611    }
3612
3613    #[rstest]
3614    #[case::empty_tick_size("tickSz", Some(""), "`tick_sz` is empty")]
3615    #[case::empty_lot_size("lotSz", Some(""), "`lot_sz` is empty")]
3616    #[case::invalid_min_size("minSz", Some("not-a-quantity"), "Failed to parse `min_sz`")]
3617    #[case::missing_list_time("listTime", None, "`list_time` is required")]
3618    fn test_parse_spread_instrument_rejects_invalid_fields(
3619        #[case] field: &str,
3620        #[case] value: Option<&str>,
3621        #[case] expected: &str,
3622    ) {
3623        let json_data = load_test_json("http_get_spreads.json");
3624        let mut payload: serde_json::Value = serde_json::from_str(&json_data).unwrap();
3625        let spread = payload["data"][0]
3626            .as_object_mut()
3627            .expect("spread payload must be an object");
3628
3629        if let Some(value) = value {
3630            spread.insert(
3631                field.to_string(),
3632                serde_json::Value::String(value.to_string()),
3633            );
3634        } else {
3635            spread.remove(field);
3636        }
3637
3638        let response: OKXResponse<OKXSpread> = serde_json::from_value(payload).unwrap();
3639        let result = parse_spread_instrument(
3640            response.data.first().expect("Test data must have a spread"),
3641            None,
3642            None,
3643            UnixNanos::default(),
3644        );
3645
3646        let err = result.expect_err("invalid spread field must fail");
3647        assert!(
3648            err.to_string().contains(expected),
3649            "expected error to contain {expected:?}, was {err}"
3650        );
3651    }
3652
3653    #[rstest]
3654    fn test_parse_event_contract_instrument() {
3655        let instrument = OKXInstrument {
3656            inst_type: OKXInstrumentType::Events,
3657            inst_id: Ustr::from("BTC-ABOVE-DAILY-260224-1600-65000"),
3658            inst_id_code: Some(1_000_000_001),
3659            uly: Ustr::from(""),
3660            inst_family: Ustr::from(""),
3661            series_id: Some(Ustr::from("BTC-ABOVE-DAILY")),
3662            inst_category: Some(OKXInstrumentCategory::Crypto),
3663            group_id: None,
3664            init_px_lmt_pct: String::new(),
3665            float_px_lmt_pct: String::new(),
3666            max_px_lmt_pct: String::new(),
3667            base_ccy: Ustr::from(""),
3668            quote_ccy: Ustr::from("USDT"),
3669            settle_ccy: Ustr::from("USDT"),
3670            ct_val: String::new(),
3671            ct_mult: String::new(),
3672            ct_val_ccy: String::new(),
3673            opt_type: crate::common::enums::OKXOptionType::None,
3674            stk: String::new(),
3675            list_time: Some(1_769_697_132_335),
3676            exp_time: Some(1_769_700_732_335),
3677            lever: String::new(),
3678            tick_sz: "0.001".to_string(),
3679            lot_sz: "1".to_string(),
3680            min_sz: "1".to_string(),
3681            ct_type: OKXContractType::None,
3682            state: OKXInstrumentStatus::Settling,
3683            rule_type: "normal".to_string(),
3684            max_lmt_sz: "1000000".to_string(),
3685            max_mkt_sz: "1000000".to_string(),
3686            max_lmt_amt: String::new(),
3687            max_mkt_amt: String::new(),
3688            max_twap_sz: String::new(),
3689            max_iceberg_sz: String::new(),
3690            max_trigger_sz: String::new(),
3691            max_stop_sz: String::new(),
3692            rpi: None,
3693            rpi_min_level: None,
3694            rpi_min_px_band: None,
3695            trade_quote_ccy_list: Vec::new(),
3696        };
3697
3698        let parsed =
3699            parse_event_contract_instrument(&instrument, None, None, UnixNanos::default()).unwrap();
3700
3701        let InstrumentAny::BinaryOption(binary) = parsed else {
3702            panic!("Expected BinaryOption");
3703        };
3704
3705        assert_eq!(
3706            binary.id,
3707            InstrumentId::from("BTC-ABOVE-DAILY-260224-1600-65000.OKX")
3708        );
3709        assert_eq!(binary.asset_class, AssetClass::Cryptocurrency);
3710        assert_eq!(binary.currency, Currency::USDT());
3711        assert_eq!(binary.price_increment, Price::from("0.001"));
3712        assert_eq!(binary.size_increment, Quantity::from(1));
3713        assert_eq!(binary.description, Some(Ustr::from("BTC-ABOVE-DAILY")));
3714    }
3715
3716    #[rstest]
3717    fn test_parse_linear_swap_instrument() {
3718        let json_data = load_test_json("http_get_instruments_swap.json");
3719        let response: OKXResponse<OKXInstrument> = serde_json::from_str(&json_data).unwrap();
3720
3721        let okx_inst = response
3722            .data
3723            .iter()
3724            .find(|i| i.inst_id == "ETH-USDT-SWAP")
3725            .expect("ETH-USDT-SWAP must be in test data");
3726
3727        let instrument = parse_swap_instrument(okx_inst, None, None, UnixNanos::default()).unwrap();
3728
3729        assert_eq!(instrument.id(), InstrumentId::from("ETH-USDT-SWAP.OKX"));
3730        assert_eq!(instrument.raw_symbol(), Symbol::from("ETH-USDT-SWAP"));
3731        assert_eq!(instrument.base_currency(), Some(Currency::ETH()));
3732        assert_eq!(instrument.quote_currency(), Currency::USDT());
3733        assert_eq!(instrument.settlement_currency(), Currency::USDT());
3734        assert!(!instrument.is_inverse());
3735        assert_eq!(instrument.multiplier(), Quantity::from("0.1"));
3736        assert_eq!(instrument.price_precision(), 2);
3737        assert_eq!(instrument.size_precision(), 2);
3738        assert_eq!(instrument.price_increment(), Price::from("0.01"));
3739        assert_eq!(instrument.size_increment(), Quantity::from("0.01"));
3740        assert_eq!(instrument.lot_size(), Some(Quantity::from("0.01")));
3741        assert_eq!(instrument.min_quantity(), Some(Quantity::from("0.01")));
3742        assert_eq!(instrument.max_quantity(), Some(Quantity::from(20000)));
3743    }
3744
3745    #[rstest]
3746    fn test_parse_inst_id_code_from_swap_instrument() {
3747        let json_data = load_test_json("http_get_instruments_swap.json");
3748        let response: OKXResponse<OKXInstrument> = serde_json::from_str(&json_data).unwrap();
3749
3750        // Verify instIdCode is parsed correctly for BTC-USD-SWAP (inverse)
3751        let btc_usd_swap = response
3752            .data
3753            .iter()
3754            .find(|i| i.inst_id == "BTC-USD-SWAP")
3755            .expect("BTC-USD-SWAP must be in test data");
3756        assert_eq!(btc_usd_swap.inst_id_code, Some(10458));
3757
3758        // Verify instIdCode is parsed correctly for ETH-USDT-SWAP (linear)
3759        let eth_usdt_swap = response
3760            .data
3761            .iter()
3762            .find(|i| i.inst_id == "ETH-USDT-SWAP")
3763            .expect("ETH-USDT-SWAP must be in test data");
3764        assert_eq!(eth_usdt_swap.inst_id_code, Some(10461));
3765
3766        // Verify instIdCode is parsed correctly for BTC-USDT-SWAP
3767        let btc_usdt_swap = response
3768            .data
3769            .iter()
3770            .find(|i| i.inst_id == "BTC-USDT-SWAP")
3771            .expect("BTC-USDT-SWAP must be in test data");
3772        assert_eq!(btc_usdt_swap.inst_id_code, Some(10459));
3773    }
3774
3775    #[rstest]
3776    fn test_fee_field_selection_for_contract_types() {
3777        // Mock OKXFeeRate with different values for crypto vs USDT-margined
3778        let maker_crypto = "0.0002"; // Crypto-margined maker fee
3779        let taker_crypto = "0.0005"; // Crypto-margined taker fee
3780        let maker_usdt = "0.0008"; // USDT-margined maker fee
3781        let taker_usdt = "0.0010"; // USDT-margined taker fee
3782
3783        // Test Linear (USDT-margined) - should use maker_u/taker_u
3784        let is_usdt_margined = true;
3785        let (maker_str, taker_str) = if is_usdt_margined {
3786            (maker_usdt, taker_usdt)
3787        } else {
3788            (maker_crypto, taker_crypto)
3789        };
3790
3791        assert_eq!(maker_str, "0.0008");
3792        assert_eq!(taker_str, "0.0010");
3793
3794        let maker_fee = Decimal::from_str(maker_str).unwrap();
3795        let taker_fee = Decimal::from_str(taker_str).unwrap();
3796
3797        assert_eq!(maker_fee, dec!(0.0008));
3798        assert_eq!(taker_fee, dec!(0.0010));
3799
3800        // Test Inverse (crypto-margined) - should use maker/taker
3801        let is_usdt_margined = false;
3802        let (maker_str, taker_str) = if is_usdt_margined {
3803            (maker_usdt, taker_usdt)
3804        } else {
3805            (maker_crypto, taker_crypto)
3806        };
3807
3808        assert_eq!(maker_str, "0.0002");
3809        assert_eq!(taker_str, "0.0005");
3810
3811        let maker_fee = Decimal::from_str(maker_str).unwrap();
3812        let taker_fee = Decimal::from_str(taker_str).unwrap();
3813
3814        assert_eq!(maker_fee, dec!(0.0002));
3815        assert_eq!(taker_fee, dec!(0.0005));
3816    }
3817
3818    #[rstest]
3819    fn test_parse_futures_instrument() {
3820        let json_data = load_test_json("http_get_instruments_futures.json");
3821        let response: OKXResponse<OKXInstrument> = serde_json::from_str(&json_data).unwrap();
3822        let okx_inst: &OKXInstrument = response
3823            .data
3824            .first()
3825            .expect("Test data must have an instrument");
3826
3827        let instrument =
3828            parse_futures_instrument(okx_inst, None, None, UnixNanos::default()).unwrap();
3829
3830        assert_eq!(instrument.id(), InstrumentId::from("BTC-USD-241220.OKX"));
3831        assert_eq!(instrument.raw_symbol(), Symbol::from("BTC-USD-241220"));
3832        assert_eq!(instrument.underlying(), Some(Ustr::from("BTC-USD")));
3833        assert_eq!(instrument.quote_currency(), Currency::USD());
3834        assert_eq!(instrument.settlement_currency(), Currency::BTC());
3835        assert!(instrument.is_inverse());
3836        assert_eq!(instrument.price_precision(), 1);
3837        assert_eq!(instrument.size_precision(), 0);
3838        assert_eq!(instrument.price_increment(), Price::from("0.1"));
3839        assert_eq!(instrument.size_increment(), Quantity::from(1));
3840        assert_eq!(instrument.multiplier(), Quantity::from(100));
3841        assert_eq!(instrument.lot_size(), Some(Quantity::from(1)));
3842        assert_eq!(instrument.min_quantity(), Some(Quantity::from(1)));
3843        assert_eq!(instrument.max_quantity(), Some(Quantity::from(10000)));
3844
3845        let InstrumentAny::CryptoFuture(crypto_future) = instrument else {
3846            panic!("expected CryptoFuture, was {instrument:?}");
3847        };
3848        let info = crypto_future.info.expect("info populated for FUTURES");
3849        assert_eq!(info.get_str("rule_type"), Some("normal"));
3850    }
3851
3852    #[rstest]
3853    fn test_parse_futures_instrument_merges_price_limit_percentages_with_rule_type() {
3854        let json_data = load_test_json("http_get_instruments_futures.json");
3855        let mut response: OKXResponse<OKXInstrument> = serde_json::from_str(&json_data).unwrap();
3856        let okx_inst = response
3857            .data
3858            .first_mut()
3859            .expect("Test data must have an instrument");
3860        okx_inst.init_px_lmt_pct = "0.04".to_string();
3861        okx_inst.float_px_lmt_pct = "0.02".to_string();
3862        okx_inst.max_px_lmt_pct = "0.12".to_string();
3863
3864        let instrument =
3865            parse_futures_instrument(okx_inst, None, None, UnixNanos::default()).unwrap();
3866
3867        let InstrumentAny::CryptoFuture(crypto_future) = instrument else {
3868            panic!("expected CryptoFuture");
3869        };
3870        let info = crypto_future.info.expect("price-limit info must be set");
3871
3872        assert_eq!(info.get_str("rule_type"), Some("normal"));
3873        assert_eq!(info.get_str("okx_init_px_lmt_pct"), Some("0.04"));
3874        assert_eq!(info.get_str("okx_float_px_lmt_pct"), Some("0.02"));
3875        assert_eq!(info.get_str("okx_max_px_lmt_pct"), Some("0.12"));
3876        assert_eq!(crypto_future.max_price, None);
3877        assert_eq!(crypto_future.min_price, None);
3878    }
3879
3880    #[rstest]
3881    fn test_parse_futures_instrument_xperp_carries_rule_type() {
3882        // X-Perp instruments ship with the standard 3-part futures symbol
3883        // shape; the `ruleType=xperp` field is what distinguishes them from
3884        // regular dated futures.
3885        let instrument = OKXInstrument {
3886            inst_type: OKXInstrumentType::Futures,
3887            inst_id: Ustr::from("BTC-USDT-250328"),
3888            uly: Ustr::from("BTC-USDT"),
3889            inst_family: Ustr::from("BTC-USDT"),
3890            series_id: None,
3891            inst_category: None,
3892            group_id: None,
3893            init_px_lmt_pct: String::new(),
3894            float_px_lmt_pct: String::new(),
3895            max_px_lmt_pct: String::new(),
3896            base_ccy: Ustr::from(""),
3897            quote_ccy: Ustr::from("USDT"),
3898            settle_ccy: Ustr::from("USDT"),
3899            ct_val: "1".to_string(),
3900            ct_mult: "1".to_string(),
3901            ct_val_ccy: "USDT".to_string(),
3902            opt_type: crate::common::enums::OKXOptionType::None,
3903            stk: String::new(),
3904            list_time: Some(1_700_000_000_000),
3905            exp_time: Some(1_743_004_800_000),
3906            lever: "10".to_string(),
3907            tick_sz: "0.1".to_string(),
3908            lot_sz: "1".to_string(),
3909            min_sz: "1".to_string(),
3910            ct_type: OKXContractType::Linear,
3911            state: crate::common::enums::OKXInstrumentStatus::Live,
3912            rule_type: "xperp".to_string(),
3913            max_lmt_sz: String::new(),
3914            max_mkt_sz: String::new(),
3915            max_lmt_amt: String::new(),
3916            max_mkt_amt: String::new(),
3917            max_twap_sz: String::new(),
3918            max_iceberg_sz: String::new(),
3919            max_trigger_sz: String::new(),
3920            max_stop_sz: String::new(),
3921            inst_id_code: None,
3922            rpi: None,
3923            rpi_min_level: None,
3924            rpi_min_px_band: None,
3925            trade_quote_ccy_list: Vec::new(),
3926        };
3927
3928        let parsed = parse_futures_instrument(&instrument, None, None, UnixNanos::default())
3929            .expect("parses synthetic X-Perp instrument");
3930
3931        let InstrumentAny::CryptoFuture(crypto_future) = parsed else {
3932            panic!("expected CryptoFuture for X-Perp");
3933        };
3934        let info = crypto_future.info.expect("info populated for X-Perp");
3935        assert_eq!(info.get_str("rule_type"), Some("xperp"));
3936        assert!(is_xperp_rule_type("xperp"));
3937        assert!(is_xperp_rule_type("XPERP"));
3938        assert!(!is_xperp_rule_type("normal"));
3939    }
3940
3941    #[rstest]
3942    fn test_parse_option_instrument() {
3943        let json_data = load_test_json("http_get_instruments_option.json");
3944        let response: OKXResponse<OKXInstrument> = serde_json::from_str(&json_data).unwrap();
3945        let okx_inst: &OKXInstrument = response
3946            .data
3947            .first()
3948            .expect("Test data must have an instrument");
3949
3950        let instrument =
3951            parse_option_instrument(okx_inst, None, None, UnixNanos::default()).unwrap();
3952
3953        let InstrumentAny::CryptoOption(option) = &instrument else {
3954            panic!("Expected CryptoOption, was {instrument:?}");
3955        };
3956
3957        assert_eq!(
3958            instrument.id(),
3959            InstrumentId::from("BTC-USD-241217-92000-C.OKX")
3960        );
3961        assert_eq!(
3962            instrument.raw_symbol(),
3963            Symbol::from("BTC-USD-241217-92000-C")
3964        );
3965        assert_eq!(instrument.base_currency(), Some(Currency::BTC()));
3966        assert_eq!(instrument.quote_currency(), Currency::USD());
3967        assert_eq!(instrument.settlement_currency(), Currency::BTC());
3968        assert!(instrument.is_inverse());
3969        assert_eq!(instrument.price_precision(), 4);
3970        assert_eq!(instrument.size_precision(), 0);
3971        assert_eq!(instrument.price_increment(), Price::from("0.0001"));
3972        assert_eq!(instrument.size_increment(), Quantity::from(1));
3973        assert_eq!(instrument.multiplier(), Quantity::from("0.01"));
3974        assert_eq!(instrument.lot_size(), Some(Quantity::from(1)));
3975        assert_eq!(instrument.min_quantity(), Some(Quantity::from(1)));
3976        assert_eq!(instrument.max_quantity(), Some(Quantity::from(5000)));
3977        assert_eq!(instrument.max_notional(), None);
3978        assert_eq!(instrument.min_notional(), None);
3979        assert_eq!(instrument.max_price(), None);
3980        assert_eq!(instrument.min_price(), None);
3981        assert_eq!(option.option_kind, OptionKind::Call);
3982        assert_eq!(option.exercise_style, Some(ExerciseStyle::European));
3983        assert_eq!(option.settlement_type, Some(SettlementType::Cash));
3984    }
3985
3986    #[rstest]
3987    #[case::margin(AccountType::Margin)]
3988    #[case::cash(AccountType::Cash)]
3989    fn test_parse_account_state(#[case] account_type: AccountType) {
3990        let json_data = load_test_json("http_get_account_balance.json");
3991        let response: OKXResponse<OKXAccount> = serde_json::from_str(&json_data).unwrap();
3992        let okx_account = response
3993            .data
3994            .first()
3995            .expect("Test data must have an account");
3996
3997        let account_id = AccountId::new("OKX-001");
3998        let account_state =
3999            parse_account_state(okx_account, account_id, account_type, UnixNanos::default())
4000                .unwrap();
4001
4002        assert_eq!(account_state.account_id, account_id);
4003        assert_eq!(account_state.account_type, account_type);
4004        assert_eq!(account_state.balances.len(), 1);
4005        assert_eq!(account_state.margins.len(), 0); // No margins in this test data (spot account)
4006        assert!(account_state.is_reported);
4007        assert!(account_state.info.is_none());
4008
4009        // Check the USDT balance details
4010        let usdt_balance = &account_state.balances[0];
4011        assert_eq!(
4012            usdt_balance.total,
4013            Money::new(94.426_129_903_333_33, Currency::USDT())
4014        );
4015        assert_eq!(
4016            usdt_balance.free,
4017            Money::new(94.426_129_903_333_33, Currency::USDT())
4018        );
4019        assert_eq!(usdt_balance.locked, Money::new(0.0, Currency::USDT()));
4020    }
4021
4022    #[rstest]
4023    fn test_parse_account_state_completeness() {
4024        let response: OKXResponse<OKXAccount> =
4025            serde_json::from_str(&load_test_json("http_get_account_balance.json")).unwrap();
4026        let valid = response.data[0].clone();
4027        let mut invalid = valid.clone();
4028        invalid.details[0].cash_bal = "not-a-number".to_string();
4029        let empty_json: serde_json::Value =
4030            serde_json::from_str(&load_test_json("ws_account_empty.json")).unwrap();
4031        let empty: OKXAccount = serde_json::from_value(empty_json["data"][0].clone()).unwrap();
4032        let account_id = AccountId::new("OKX-001");
4033
4034        let (_, valid_complete) = parse_account_state_with_completeness(
4035            &valid,
4036            account_id,
4037            AccountType::Cash,
4038            UnixNanos::default(),
4039        );
4040        let (_, invalid_complete) = parse_account_state_with_completeness(
4041            &invalid,
4042            account_id,
4043            AccountType::Cash,
4044            UnixNanos::default(),
4045        );
4046        let (_, empty_complete) = parse_account_state_with_completeness(
4047            &empty,
4048            account_id,
4049            AccountType::Cash,
4050            UnixNanos::default(),
4051        );
4052
4053        assert!(valid_complete);
4054        assert!(!invalid_complete);
4055        assert!(empty_complete);
4056    }
4057
4058    #[rstest]
4059    fn test_parse_account_state_with_margins() {
4060        // Create test data with margin requirements
4061        let account_json = load_test_json("http_get_account_balance_with_margins.json");
4062
4063        let okx_account: OKXAccount = serde_json::from_str(&account_json).unwrap();
4064        let account_id = AccountId::new("OKX-001");
4065        let account_state = parse_account_state(
4066            &okx_account,
4067            account_id,
4068            AccountType::Margin,
4069            UnixNanos::default(),
4070        )
4071        .unwrap();
4072
4073        // Verify account details
4074        assert_eq!(account_state.account_id, account_id);
4075        assert_eq!(account_state.account_type, AccountType::Margin);
4076        assert_eq!(account_state.balances.len(), 1);
4077
4078        // Verify margin information was parsed
4079        assert_eq!(account_state.margins.len(), 1);
4080        let margin = &account_state.margins[0];
4081
4082        // Check margin values
4083        assert_eq!(margin.initial, Money::new(500.25, Currency::USD()));
4084        assert_eq!(margin.maintenance, Money::new(250.75, Currency::USD()));
4085        assert_eq!(margin.currency, Currency::USD());
4086        assert!(margin.instrument_id.is_none());
4087
4088        // Check the USDT balance details
4089        let usdt_balance = &account_state.balances[0];
4090        assert_eq!(usdt_balance.total, Money::new(10000.0, Currency::USDT()));
4091        assert_eq!(usdt_balance.free, Money::new(8000.0, Currency::USDT()));
4092        assert_eq!(usdt_balance.locked, Money::new(2000.0, Currency::USDT()));
4093    }
4094
4095    #[rstest]
4096    fn test_parse_account_state_empty_margins() {
4097        // Create test data with empty margin strings (common for spot accounts)
4098        let account_json = load_test_json("http_get_account_balance_empty_margins.json");
4099
4100        let okx_account: OKXAccount = serde_json::from_str(&account_json).unwrap();
4101        let account_id = AccountId::new("OKX-SPOT");
4102        let account_state = parse_account_state(
4103            &okx_account,
4104            account_id,
4105            AccountType::Margin,
4106            UnixNanos::default(),
4107        )
4108        .unwrap();
4109
4110        // Verify no margins are created when fields are empty
4111        assert_eq!(account_state.margins.len(), 0);
4112        assert_eq!(account_state.balances.len(), 1);
4113
4114        // Check the BTC balance
4115        let btc_balance = &account_state.balances[0];
4116        assert_eq!(btc_balance.total, Money::new(1000.0, Currency::BTC()));
4117    }
4118
4119    #[rstest]
4120    fn test_parse_order_status_report() {
4121        let json_data = load_test_json("http_get_orders_history.json");
4122        let response: OKXResponse<OKXOrderHistory> = serde_json::from_str(&json_data).unwrap();
4123        let okx_order = response
4124            .data
4125            .first()
4126            .expect("Test data must have an order")
4127            .clone();
4128
4129        let account_id = AccountId::new("OKX-001");
4130        let instrument_id = InstrumentId::from("BTC-USDT-SWAP.OKX");
4131        let order_report = parse_order_status_report(
4132            &okx_order,
4133            account_id,
4134            instrument_id,
4135            2,
4136            8,
4137            UnixNanos::default(),
4138        )
4139        .unwrap();
4140
4141        assert_eq!(order_report.account_id, account_id);
4142        assert_eq!(order_report.instrument_id, instrument_id);
4143        assert_eq!(order_report.quantity, Quantity::from("0.03000000"));
4144        assert_eq!(order_report.filled_qty, Quantity::from("0.03000000"));
4145        assert_eq!(order_report.order_side, OrderSide::Buy.into());
4146        assert_eq!(order_report.order_type, OrderType::Market);
4147        assert_eq!(order_report.order_status, OrderStatus::Filled);
4148    }
4149
4150    #[rstest]
4151    #[case::base_filled(
4152        OKXOrderStatus::Filled,
4153        OKXTargetCurrency::BaseCcy,
4154        "0.00296487",
4155        "0.00296475",
4156        "0.00296475"
4157    )]
4158    #[case::base_partial(
4159        OKXOrderStatus::PartiallyFilled,
4160        OKXTargetCurrency::BaseCcy,
4161        "0.00296487",
4162        "0.00296475",
4163        "0.00296487"
4164    )]
4165    #[case::base_canceled(
4166        OKXOrderStatus::Canceled,
4167        OKXTargetCurrency::BaseCcy,
4168        "0.00296487",
4169        "0.00296475",
4170        "0.00296487"
4171    )]
4172    #[case::base_zero_fill(
4173        OKXOrderStatus::Filled,
4174        OKXTargetCurrency::BaseCcy,
4175        "0.00296487",
4176        "0",
4177        "0.00296487"
4178    )]
4179    #[case::quote_filled(
4180        OKXOrderStatus::Filled,
4181        OKXTargetCurrency::QuoteCcy,
4182        "296.487",
4183        "0.00296475",
4184        "0.00296475"
4185    )]
4186    fn test_parse_order_status_report_terminal_quantity(
4187        #[values("", "0")] price: &str,
4188        #[case] state: OKXOrderStatus,
4189        #[case] target: OKXTargetCurrency,
4190        #[case] size: &str,
4191        #[case] filled: &str,
4192        #[case] expected_quantity: &str,
4193    ) {
4194        let response: OKXResponse<OKXOrderHistory> =
4195            serde_json::from_str(&load_test_json("http_get_orders_history.json")).unwrap();
4196        let mut order = response.data[0].clone();
4197        order.inst_type = OKXInstrumentType::Spot;
4198        order.ord_type = OKXOrderType::Market;
4199        order.side = OKXSide::Buy;
4200        order.tgt_ccy = Some(target);
4201        order.state = state;
4202        order.sz = size.to_string();
4203        order.acc_fill_sz = filled.to_string();
4204        order.px = price.to_string();
4205        order.avg_px = "100000".to_string();
4206
4207        let report = parse_order_status_report(
4208            &order,
4209            AccountId::from("OKX-001"),
4210            InstrumentId::from("BTC-USDC.OKX"),
4211            2,
4212            8,
4213            UnixNanos::default(),
4214        )
4215        .unwrap();
4216
4217        assert_eq!(report.price, None);
4218        assert_eq!(report.order_status, OrderStatus::try_from(state).unwrap());
4219        assert_eq!(report.quantity, Quantity::from(expected_quantity));
4220        assert_eq!(report.filled_qty, Quantity::from(filled));
4221    }
4222
4223    #[rstest]
4224    fn test_parse_triggered_order_history_preserves_parent_identity() {
4225        let json_data = load_test_json("http_get_orders_history.json");
4226        let response: OKXResponse<OKXOrderHistory> = serde_json::from_str(&json_data).unwrap();
4227        let mut okx_order = response
4228            .data
4229            .first()
4230            .expect("Test data must have an order")
4231            .clone();
4232        okx_order.cl_ord_id = Ustr::from("706620792746729474_0");
4233        okx_order.algo_cl_ord_id = Some(Ustr::from("STOP003BTCUSDT20250120"));
4234        okx_order.ord_id = Ustr::from("706620792746729999");
4235
4236        let order_report = parse_order_status_report(
4237            &okx_order,
4238            AccountId::new("OKX-001"),
4239            InstrumentId::from("BTC-USDT-SWAP.OKX"),
4240            2,
4241            8,
4242            UnixNanos::default(),
4243        )
4244        .unwrap();
4245
4246        assert_eq!(
4247            order_report.client_order_id,
4248            Some(ClientOrderId::from("STOP003BTCUSDT20250120"))
4249        );
4250        assert_eq!(
4251            order_report.venue_order_id,
4252            VenueOrderId::from("706620792746729999")
4253        );
4254    }
4255
4256    #[rstest]
4257    fn test_parse_position_status_report() {
4258        let json_data = load_test_json("http_get_positions.json");
4259        let response: OKXResponse<OKXPosition> = serde_json::from_str(&json_data).unwrap();
4260        let okx_position = response
4261            .data
4262            .first()
4263            .expect("Test data must have a position")
4264            .clone();
4265
4266        let account_id = AccountId::new("OKX-001");
4267        let instrument_id = InstrumentId::from("BTC-USDT.OKX");
4268        let position_report = parse_position_status_report(
4269            &okx_position,
4270            account_id,
4271            instrument_id,
4272            8,
4273            UnixNanos::default(),
4274        )
4275        .unwrap();
4276
4277        assert_eq!(position_report.account_id, account_id);
4278        assert_eq!(position_report.instrument_id, instrument_id);
4279    }
4280
4281    #[rstest]
4282    fn test_parse_trade_tick() {
4283        let json_data = load_test_json("http_get_trades.json");
4284        let response: OKXResponse<OKXTrade> = serde_json::from_str(&json_data).unwrap();
4285        let okx_trade = response.data.first().expect("Test data must have a trade");
4286
4287        let instrument_id = InstrumentId::from("BTC-USDT.OKX");
4288        let trade_tick =
4289            parse_trade_tick(okx_trade, instrument_id, 2, 8, UnixNanos::default()).unwrap();
4290
4291        assert_eq!(trade_tick.instrument_id, instrument_id);
4292        assert_eq!(trade_tick.price, Price::from("102537.90"));
4293        assert_eq!(trade_tick.size, Quantity::from("0.00013669"));
4294        assert_eq!(trade_tick.aggressor_side, AggressorSide::Sell);
4295        assert_eq!(trade_tick.trade_id, TradeId::new("734864333"));
4296    }
4297
4298    #[rstest]
4299    fn test_parse_mark_price_update() {
4300        let json_data = load_test_json("http_get_mark_price.json");
4301        let response: OKXResponse<crate::http::models::OKXMarkPrice> =
4302            serde_json::from_str(&json_data).unwrap();
4303        let okx_mark_price = response
4304            .data
4305            .first()
4306            .expect("Test data must have a mark price");
4307
4308        let instrument_id = InstrumentId::from("BTC-USDT-SWAP.OKX");
4309        let mark_price_update =
4310            parse_mark_price_update(okx_mark_price, instrument_id, 2, UnixNanos::default())
4311                .unwrap();
4312
4313        assert_eq!(mark_price_update.instrument_id, instrument_id);
4314        assert_eq!(mark_price_update.value, Price::from("84660.10"));
4315        assert_eq!(
4316            mark_price_update.ts_event,
4317            UnixNanos::from(1_744_590_349_506_000_000)
4318        );
4319    }
4320
4321    #[rstest]
4322    fn test_parse_index_price_update() {
4323        let json_data = load_test_json("http_get_index_price.json");
4324        let response: OKXResponse<crate::http::models::OKXIndexTicker> =
4325            serde_json::from_str(&json_data).unwrap();
4326        let okx_index_ticker = response
4327            .data
4328            .first()
4329            .expect("Test data must have an index ticker");
4330
4331        let instrument_id = InstrumentId::from("BTC-USDT.OKX");
4332        let index_price_update =
4333            parse_index_price_update(okx_index_ticker, instrument_id, 2, UnixNanos::default())
4334                .unwrap();
4335
4336        assert_eq!(index_price_update.instrument_id, instrument_id);
4337        assert_eq!(index_price_update.value, Price::from("103895.00"));
4338        assert_eq!(
4339            index_price_update.ts_event,
4340            UnixNanos::from(1_746_942_707_815_000_000)
4341        );
4342    }
4343
4344    #[rstest]
4345    fn test_parse_candlestick() {
4346        let json_data = load_test_json("http_get_candlesticks.json");
4347        let response: OKXResponse<crate::http::models::OKXCandlestick> =
4348            serde_json::from_str(&json_data).unwrap();
4349        let okx_candlestick = response
4350            .data
4351            .first()
4352            .expect("Test data must have a candlestick");
4353
4354        let instrument_id = InstrumentId::from("BTC-USDT.OKX");
4355        let bar_type = BarType::new(
4356            instrument_id,
4357            BAR_SPEC_1_DAY_LAST,
4358            AggregationSource::External,
4359        );
4360        let bar = parse_candlestick(okx_candlestick, bar_type, 2, 8, UnixNanos::default()).unwrap();
4361
4362        assert_eq!(bar.bar_type, bar_type);
4363        assert_eq!(bar.open, Price::from("33528.60"));
4364        assert_eq!(bar.high, Price::from("33870.00"));
4365        assert_eq!(bar.low, Price::from("33528.60"));
4366        assert_eq!(bar.close, Price::from("33783.90"));
4367        assert_eq!(bar.volume, Quantity::from("778.83800000"));
4368        assert_eq!(bar.ts_event, UnixNanos::from(1_625_097_600_000_000_000));
4369    }
4370
4371    #[rstest]
4372    fn test_parse_millisecond_timestamp() {
4373        let timestamp_ms = 1_625_097_600_000_u64;
4374        let result = parse_millisecond_timestamp(timestamp_ms);
4375        assert_eq!(result, UnixNanos::from(1_625_097_600_000_000_000));
4376    }
4377
4378    #[rstest]
4379    fn test_parse_rfc3339_timestamp() {
4380        let timestamp_str = "2021-07-01T00:00:00.000Z";
4381        let result = parse_rfc3339_timestamp(timestamp_str).unwrap();
4382        assert_eq!(result, UnixNanos::from(1_625_097_600_000_000_000));
4383
4384        // Test with timezone
4385        let timestamp_str_tz = "2021-07-01T08:00:00.000+08:00";
4386        let result_tz = parse_rfc3339_timestamp(timestamp_str_tz).unwrap();
4387        assert_eq!(result_tz, UnixNanos::from(1_625_097_600_000_000_000));
4388
4389        // Test error case
4390        let invalid_timestamp = "invalid-timestamp";
4391        parse_rfc3339_timestamp(invalid_timestamp).unwrap_err();
4392    }
4393
4394    #[rstest]
4395    fn test_parse_price() {
4396        let price_str = "42219.5";
4397        let precision = 2;
4398        let result = parse_price(price_str, precision).unwrap();
4399        assert_eq!(result, Price::from("42219.50"));
4400
4401        // Test error case
4402        let invalid_price = "invalid-price";
4403        parse_price(invalid_price, precision).unwrap_err();
4404    }
4405
4406    #[rstest]
4407    fn test_parse_quantity() {
4408        let quantity_str = "0.12345678";
4409        let precision = 8;
4410        let result = parse_quantity(quantity_str, precision).unwrap();
4411        assert_eq!(result, Quantity::from("0.12345678"));
4412
4413        // Test error case
4414        let invalid_quantity = "invalid-quantity";
4415        parse_quantity(invalid_quantity, precision).unwrap_err();
4416    }
4417
4418    #[rstest]
4419    fn test_parse_aggressor_side() {
4420        assert_eq!(
4421            parse_aggressor_side(&Some(OKXSide::Buy)),
4422            AggressorSide::Buy
4423        );
4424        assert_eq!(
4425            parse_aggressor_side(&Some(OKXSide::Sell)),
4426            AggressorSide::Sell
4427        );
4428        assert_eq!(parse_aggressor_side(&None), AggressorSide::NoAggressor);
4429    }
4430
4431    #[rstest]
4432    fn test_parse_execution_type() {
4433        assert_eq!(
4434            parse_execution_type(&Some(OKXExecType::Maker)),
4435            LiquiditySide::Maker
4436        );
4437        assert_eq!(
4438            parse_execution_type(&Some(OKXExecType::Taker)),
4439            LiquiditySide::Taker
4440        );
4441        assert_eq!(parse_execution_type(&None), LiquiditySide::NoLiquiditySide);
4442    }
4443
4444    #[rstest]
4445    fn test_parse_position_side() {
4446        assert_eq!(parse_position_side(Some(100)), PositionSide::Long);
4447        assert_eq!(parse_position_side(Some(-100)), PositionSide::Short);
4448        assert_eq!(parse_position_side(Some(0)), PositionSide::Flat);
4449        assert_eq!(parse_position_side(None), PositionSide::Flat);
4450    }
4451
4452    #[rstest]
4453    fn test_parse_client_order_id() {
4454        let valid_id = "client_order_123";
4455        let result = parse_client_order_id(valid_id);
4456        assert_eq!(result, Some(ClientOrderId::new(valid_id)));
4457
4458        let empty_id = "";
4459        let result_empty = parse_client_order_id(empty_id);
4460        assert_eq!(result_empty, None);
4461    }
4462
4463    #[rstest]
4464    fn test_deserialize_string_to_u64() {
4465        use serde::Deserialize;
4466
4467        #[derive(Deserialize)]
4468        struct TestStruct {
4469            #[serde(deserialize_with = "deserialize_string_to_u64")]
4470            value: u64,
4471        }
4472
4473        let json_value = r#"{"value": "12345"}"#;
4474        let result: TestStruct = serde_json::from_str(json_value).unwrap();
4475        assert_eq!(result.value, 12345);
4476
4477        let json_empty = r#"{"value": ""}"#;
4478        let result_empty: TestStruct = serde_json::from_str(json_empty).unwrap();
4479        assert_eq!(result_empty.value, 0);
4480    }
4481
4482    #[rstest]
4483    #[case(None, None)]
4484    #[case(Some(OKXPositionSide::Net), None)]
4485    #[case(Some(OKXPositionSide::Long), Some("BTC-USDT-SWAP.OKX-LONG"))]
4486    #[case(Some(OKXPositionSide::Short), Some("BTC-USDT-SWAP.OKX-SHORT"))]
4487    fn test_fill_report_parsing(
4488        #[case] pos_side: Option<OKXPositionSide>,
4489        #[case] expected: Option<&str>,
4490    ) {
4491        // Create a mock transaction detail for testing
4492        let transaction_detail = crate::http::models::OKXTransactionDetail {
4493            inst_type: OKXInstrumentType::Swap,
4494            inst_id: Ustr::from("BTC-USDT-SWAP"),
4495            trade_id: Ustr::from("12345"),
4496            ord_id: Ustr::from("67890"),
4497            cl_ord_id: Ustr::from("client_123"),
4498            bill_id: Ustr::from("bill_456"),
4499            pos_side,
4500            fill_px: "42219.5".to_string(),
4501            fill_sz: "0.001".to_string(),
4502            side: OKXSide::Buy,
4503            exec_type: OKXExecType::Taker,
4504            fee_ccy: "USDT".to_string(),
4505            fee: Some("0.042".to_string()),
4506            ts: 1_625_097_600_000,
4507        };
4508
4509        let account_id = AccountId::new("OKX-001");
4510        let instrument_id = InstrumentId::from("BTC-USDT-SWAP.OKX");
4511        let fill_report = parse_fill_report(
4512            &transaction_detail,
4513            account_id,
4514            instrument_id,
4515            2,
4516            8,
4517            UnixNanos::default(),
4518        )
4519        .unwrap();
4520
4521        assert_eq!(
4522            fill_report.venue_position_id,
4523            expected.map(PositionId::from)
4524        );
4525        assert_eq!(fill_report.account_id, account_id);
4526        assert_eq!(fill_report.instrument_id, instrument_id);
4527        assert_eq!(fill_report.trade_id, TradeId::new("12345"));
4528        assert_eq!(fill_report.venue_order_id, VenueOrderId::new("67890"));
4529        assert_eq!(fill_report.order_side, OrderSide::Buy);
4530        assert_eq!(fill_report.last_px, Price::from("42219.50"));
4531        assert_eq!(fill_report.last_qty, Quantity::from("0.00100000"));
4532        assert_eq!(fill_report.liquidity_side, LiquiditySide::Taker);
4533        assert_eq!(
4534            fill_report.commission,
4535            Money::from_decimal(dec!(-0.042), Currency::USDT()).unwrap()
4536        );
4537    }
4538
4539    #[rstest]
4540    fn test_parse_fee_rejects_missing_or_empty() {
4541        let currency = Currency::USDT();
4542
4543        let missing = parse_fee(None, currency).unwrap_err();
4544        assert!(missing.to_string().contains("missing fee"));
4545
4546        let empty = parse_fee(Some(""), currency).unwrap_err();
4547        assert!(empty.to_string().contains("missing fee"));
4548
4549        let blank = parse_fee(Some("   "), currency).unwrap_err();
4550        assert!(blank.to_string().contains("missing fee"));
4551    }
4552
4553    #[rstest]
4554    fn test_parse_fill_report_rejects_missing_fee() {
4555        let json_data = load_test_json("http_transaction_detail_empty_fee.json");
4556        let detail: OKXTransactionDetail = serde_json::from_str(&json_data).unwrap();
4557        let error = parse_fill_report(
4558            &detail,
4559            AccountId::new("OKX-001"),
4560            InstrumentId::from("BTC-USDT.OKX"),
4561            2,
4562            8,
4563            UnixNanos::default(),
4564        )
4565        .unwrap_err();
4566
4567        let message = format!("{error:#}");
4568        assert!(message.contains("missing fee"), "was {message}");
4569    }
4570
4571    #[rstest]
4572    fn test_parse_spread_fill_report_rejects_missing_fee() {
4573        let detail = OKXSpreadTrade {
4574            sprd_id: Ustr::from("ETH-USD-SWAP_ETH-USD-231229"),
4575            trade_id: Ustr::from("9001"),
4576            ord_id: Ustr::from("12345"),
4577            cl_ord_id: Ustr::from("O-spread-entry"),
4578            fill_px: "1.20".to_string(),
4579            fill_sz: "5".to_string(),
4580            side: OKXSide::Buy,
4581            exec_type: OKXExecType::Taker,
4582            fee_ccy: "USDT".to_string(),
4583            fee: None,
4584            ts: 1_700_000_001_000,
4585        };
4586        let error = parse_spread_fill_report(
4587            &detail,
4588            AccountId::new("OKX-001"),
4589            InstrumentId::from("ETH-USD-SWAP_ETH-USD-231229.OKX"),
4590            2,
4591            0,
4592            UnixNanos::default(),
4593        )
4594        .unwrap_err();
4595
4596        let message = format!("{error:#}");
4597        assert!(message.contains("missing fee"), "was {message}");
4598    }
4599
4600    #[rstest]
4601    fn test_bar_type_identity_preserved_through_parse() {
4602        use std::str::FromStr;
4603
4604        use crate::http::models::OKXCandlestick;
4605
4606        // Create a BarType
4607        let bar_type = BarType::from_str("ETH-USDT-SWAP.OKX-1-MINUTE-LAST-EXTERNAL").unwrap();
4608
4609        // Create sample candlestick data
4610        let raw_candlestick = OKXCandlestick(
4611            "1721807460000".to_string(), // timestamp
4612            "3177.9".to_string(),        // open
4613            "3177.9".to_string(),        // high
4614            "3177.7".to_string(),        // low
4615            "3177.8".to_string(),        // close
4616            "18.603".to_string(),        // volume
4617            "59054.8231".to_string(),    // turnover
4618            "18.603".to_string(),        // base_volume
4619            "1".to_string(),             // count
4620        );
4621
4622        // Parse the candlestick
4623        let bar =
4624            parse_candlestick(&raw_candlestick, bar_type, 1, 3, UnixNanos::default()).unwrap();
4625
4626        // Verify that the BarType is preserved exactly
4627        assert_eq!(
4628            bar.bar_type, bar_type,
4629            "BarType must be preserved exactly through parsing"
4630        );
4631    }
4632
4633    #[rstest]
4634    fn test_okx_bar_channel_mappings() {
4635        let regular_cases = [
4636            (OKXWsChannel::Candle1Second, BAR_SPEC_1_SECOND_LAST),
4637            (OKXWsChannel::Candle1Minute, BAR_SPEC_1_MINUTE_LAST),
4638            (OKXWsChannel::Candle3Minute, BAR_SPEC_3_MINUTE_LAST),
4639            (OKXWsChannel::Candle5Minute, BAR_SPEC_5_MINUTE_LAST),
4640            (OKXWsChannel::Candle15Minute, BAR_SPEC_15_MINUTE_LAST),
4641            (OKXWsChannel::Candle30Minute, BAR_SPEC_30_MINUTE_LAST),
4642            (OKXWsChannel::Candle1Hour, BAR_SPEC_1_HOUR_LAST),
4643            (OKXWsChannel::Candle2Hour, BAR_SPEC_2_HOUR_LAST),
4644            (OKXWsChannel::Candle4Hour, BAR_SPEC_4_HOUR_LAST),
4645            (OKXWsChannel::Candle6Hour, BAR_SPEC_6_HOUR_LAST),
4646            (OKXWsChannel::Candle12Hour, BAR_SPEC_12_HOUR_LAST),
4647            (OKXWsChannel::Candle1Day, BAR_SPEC_1_DAY_LAST),
4648            (OKXWsChannel::Candle2Day, BAR_SPEC_2_DAY_LAST),
4649            (OKXWsChannel::Candle3Day, BAR_SPEC_3_DAY_LAST),
4650            (OKXWsChannel::Candle5Day, BAR_SPEC_5_DAY_LAST),
4651            (OKXWsChannel::Candle1Week, BAR_SPEC_1_WEEK_LAST),
4652            (OKXWsChannel::Candle1Month, BAR_SPEC_1_MONTH_LAST),
4653            (OKXWsChannel::Candle3Month, BAR_SPEC_3_MONTH_LAST),
4654            (OKXWsChannel::Candle6Month, BAR_SPEC_6_MONTH_LAST),
4655            (OKXWsChannel::Candle1Year, BAR_SPEC_12_MONTH_LAST),
4656        ];
4657
4658        for (channel, bar_spec) in regular_cases {
4659            assert_eq!(okx_channel_to_bar_spec(&channel), Some(bar_spec));
4660            assert_eq!(bar_spec_as_okx_channel(bar_spec).unwrap(), channel);
4661        }
4662
4663        let mark_price_cases = [
4664            (OKXWsChannel::MarkPriceCandle1Second, BAR_SPEC_1_SECOND_LAST),
4665            (OKXWsChannel::MarkPriceCandle1Minute, BAR_SPEC_1_MINUTE_LAST),
4666            (OKXWsChannel::MarkPriceCandle3Minute, BAR_SPEC_3_MINUTE_LAST),
4667            (OKXWsChannel::MarkPriceCandle5Minute, BAR_SPEC_5_MINUTE_LAST),
4668            (
4669                OKXWsChannel::MarkPriceCandle15Minute,
4670                BAR_SPEC_15_MINUTE_LAST,
4671            ),
4672            (
4673                OKXWsChannel::MarkPriceCandle30Minute,
4674                BAR_SPEC_30_MINUTE_LAST,
4675            ),
4676            (OKXWsChannel::MarkPriceCandle1Hour, BAR_SPEC_1_HOUR_LAST),
4677            (OKXWsChannel::MarkPriceCandle2Hour, BAR_SPEC_2_HOUR_LAST),
4678            (OKXWsChannel::MarkPriceCandle4Hour, BAR_SPEC_4_HOUR_LAST),
4679            (OKXWsChannel::MarkPriceCandle6Hour, BAR_SPEC_6_HOUR_LAST),
4680            (OKXWsChannel::MarkPriceCandle12Hour, BAR_SPEC_12_HOUR_LAST),
4681            (OKXWsChannel::MarkPriceCandle1Day, BAR_SPEC_1_DAY_LAST),
4682            (OKXWsChannel::MarkPriceCandle2Day, BAR_SPEC_2_DAY_LAST),
4683            (OKXWsChannel::MarkPriceCandle3Day, BAR_SPEC_3_DAY_LAST),
4684            (OKXWsChannel::MarkPriceCandle5Day, BAR_SPEC_5_DAY_LAST),
4685            (OKXWsChannel::MarkPriceCandle1Week, BAR_SPEC_1_WEEK_LAST),
4686            (OKXWsChannel::MarkPriceCandle1Month, BAR_SPEC_1_MONTH_LAST),
4687            (OKXWsChannel::MarkPriceCandle3Month, BAR_SPEC_3_MONTH_LAST),
4688        ];
4689
4690        for (channel, bar_spec) in mark_price_cases {
4691            assert_eq!(okx_channel_to_bar_spec(&channel), Some(bar_spec));
4692            assert_eq!(
4693                bar_spec_as_okx_mark_price_channel(bar_spec).unwrap(),
4694                channel
4695            );
4696        }
4697
4698        assert_eq!(okx_channel_to_bar_spec(&OKXWsChannel::Trades), None);
4699    }
4700
4701    #[rstest]
4702    #[case::vip_prefix_4("VIP4", OKXVipLevel::Vip4)]
4703    #[case::vip_prefix_5("VIP5", OKXVipLevel::Vip5)]
4704    #[case::lv_prefix_1("Lv1", OKXVipLevel::Vip1)]
4705    #[case::lv_prefix_0("Lv0", OKXVipLevel::Vip0)]
4706    #[case::lv_prefix_9("Lv9", OKXVipLevel::Vip9)]
4707    #[case::empty_defaults_to_vip0("", OKXVipLevel::Vip0)]
4708    #[case::without_prefix("5", OKXVipLevel::Vip5)]
4709    fn test_deserialize_vip_level(#[case] raw: &str, #[case] expected: OKXVipLevel) {
4710        #[derive(serde::Deserialize)]
4711        struct TestFeeRate {
4712            #[serde(deserialize_with = "crate::common::parse::deserialize_vip_level")]
4713            level: OKXVipLevel,
4714        }
4715
4716        let json = format!(r#"{{"level":"{raw}"}}"#);
4717        let result: TestFeeRate = serde_json::from_str(&json).unwrap();
4718        assert_eq!(result.level, expected);
4719    }
4720
4721    #[rstest]
4722    fn test_parse_position_status_report_net_mode_long() {
4723        // Test Net mode: positive quantity = Long position
4724        let position = OKXPosition {
4725            inst_id: Ustr::from("BTC-USDT-SWAP"),
4726            inst_type: OKXInstrumentType::Swap,
4727            mgn_mode: OKXMarginMode::Cross,
4728            pos_id: Some(Ustr::from("12345")),
4729            pos_side: OKXPositionSide::Net, // Net mode
4730            pos: "1.5".to_string(),         // Positive = Long
4731            base_bal: "1.5".to_string(),
4732            ccy: "BTC".to_string(),
4733            fee: "0.01".to_string(),
4734            lever: "10.0".to_string(),
4735            last: "50000".to_string(),
4736            mark_px: "50000".to_string(),
4737            liq_px: "45000".to_string(),
4738            mmr: "0.1".to_string(),
4739            interest: "0".to_string(),
4740            trade_id: Ustr::from("111"),
4741            notional_usd: "75000".to_string(),
4742            avg_px: "50000".to_string(),
4743            upl: "0".to_string(),
4744            upl_ratio: "0".to_string(),
4745            u_time: 1_622_559_930_237,
4746            margin: "0.5".to_string(),
4747            mgn_ratio: "0.01".to_string(),
4748            adl: "0".to_string(),
4749            c_time: "1622559930237".to_string(),
4750            realized_pnl: "0".to_string(),
4751            upl_last_px: "0".to_string(),
4752            upl_ratio_last_px: "0".to_string(),
4753            avail_pos: "1.5".to_string(),
4754            be_px: "0".to_string(),
4755            funding_fee: "0".to_string(),
4756            idx_px: "0".to_string(),
4757            liq_penalty: "0".to_string(),
4758            opt_val: "0".to_string(),
4759            pending_close_ord_liab_val: "0".to_string(),
4760            pnl: "0".to_string(),
4761            pos_ccy: "BTC".to_string(),
4762            quote_bal: "75000".to_string(),
4763            quote_borrowed: "0".to_string(),
4764            quote_interest: "0".to_string(),
4765            spot_in_use_amt: "0".to_string(),
4766            spot_in_use_ccy: "BTC".to_string(),
4767            usd_px: "50000".to_string(),
4768            delta_bs: String::new(),
4769            gamma_bs: String::new(),
4770            theta_bs: String::new(),
4771            vega_bs: String::new(),
4772            close_order_algo: Vec::new(),
4773        };
4774
4775        let account_id = AccountId::new("OKX-001");
4776        let instrument_id = InstrumentId::from("BTC-USDT-SWAP.OKX");
4777        let report = parse_position_status_report(
4778            &position,
4779            account_id,
4780            instrument_id,
4781            8,
4782            UnixNanos::default(),
4783        )
4784        .unwrap();
4785
4786        assert_eq!(report.account_id, account_id);
4787        assert_eq!(report.instrument_id, instrument_id);
4788        assert_eq!(report.position_side, PositionSide::Long);
4789        assert_eq!(report.quantity, Quantity::from("1.5"));
4790        // Net mode: venue_position_id is None (signals NETTING OMS)
4791        assert_eq!(report.venue_position_id, None);
4792    }
4793
4794    #[rstest]
4795    fn test_parse_position_status_report_net_mode_short() {
4796        // Test Net mode: negative quantity = Short position
4797        let position = OKXPosition {
4798            inst_id: Ustr::from("BTC-USDT-SWAP"),
4799            inst_type: OKXInstrumentType::Swap,
4800            mgn_mode: OKXMarginMode::Isolated,
4801            pos_id: Some(Ustr::from("67890")),
4802            pos_side: OKXPositionSide::Net, // Net mode
4803            pos: "-2.3".to_string(),        // Negative = Short
4804            base_bal: "2.3".to_string(),
4805            ccy: "BTC".to_string(),
4806            fee: "0.02".to_string(),
4807            lever: "5.0".to_string(),
4808            last: "50000".to_string(),
4809            mark_px: "50000".to_string(),
4810            liq_px: "55000".to_string(),
4811            mmr: "0.2".to_string(),
4812            interest: "0".to_string(),
4813            trade_id: Ustr::from("222"),
4814            notional_usd: "115000".to_string(),
4815            avg_px: "50000".to_string(),
4816            upl: "0".to_string(),
4817            upl_ratio: "0".to_string(),
4818            u_time: 1_622_559_930_237,
4819            margin: "1.0".to_string(),
4820            mgn_ratio: "0.02".to_string(),
4821            adl: "0".to_string(),
4822            c_time: "1622559930237".to_string(),
4823            realized_pnl: "0".to_string(),
4824            upl_last_px: "0".to_string(),
4825            upl_ratio_last_px: "0".to_string(),
4826            avail_pos: "2.3".to_string(),
4827            be_px: "0".to_string(),
4828            funding_fee: "0".to_string(),
4829            idx_px: "0".to_string(),
4830            liq_penalty: "0".to_string(),
4831            opt_val: "0".to_string(),
4832            pending_close_ord_liab_val: "0".to_string(),
4833            pnl: "0".to_string(),
4834            pos_ccy: "BTC".to_string(),
4835            quote_bal: "115000".to_string(),
4836            quote_borrowed: "0".to_string(),
4837            quote_interest: "0".to_string(),
4838            spot_in_use_amt: "0".to_string(),
4839            spot_in_use_ccy: "BTC".to_string(),
4840            usd_px: "50000".to_string(),
4841            delta_bs: String::new(),
4842            gamma_bs: String::new(),
4843            theta_bs: String::new(),
4844            vega_bs: String::new(),
4845            close_order_algo: Vec::new(),
4846        };
4847
4848        let account_id = AccountId::new("OKX-001");
4849        let instrument_id = InstrumentId::from("BTC-USDT-SWAP.OKX");
4850        let report = parse_position_status_report(
4851            &position,
4852            account_id,
4853            instrument_id,
4854            8,
4855            UnixNanos::default(),
4856        )
4857        .unwrap();
4858
4859        assert_eq!(report.account_id, account_id);
4860        assert_eq!(report.instrument_id, instrument_id);
4861        assert_eq!(report.position_side, PositionSide::Short);
4862        assert_eq!(report.quantity, Quantity::from("2.3")); // Absolute value
4863        // Net mode: venue_position_id is None (signals NETTING OMS)
4864        assert_eq!(report.venue_position_id, None);
4865    }
4866
4867    #[rstest]
4868    fn test_parse_position_status_report_net_mode_flat() {
4869        // Test Net mode: zero quantity = Flat position
4870        let position = OKXPosition {
4871            inst_id: Ustr::from("ETH-USDT-SWAP"),
4872            inst_type: OKXInstrumentType::Swap,
4873            mgn_mode: OKXMarginMode::Cross,
4874            pos_id: Some(Ustr::from("99999")),
4875            pos_side: OKXPositionSide::Net, // Net mode
4876            pos: "0".to_string(),           // Zero = Flat
4877            base_bal: "0".to_string(),
4878            ccy: "ETH".to_string(),
4879            fee: "0".to_string(),
4880            lever: "10.0".to_string(),
4881            last: "3000".to_string(),
4882            mark_px: "3000".to_string(),
4883            liq_px: "0".to_string(),
4884            mmr: "0".to_string(),
4885            interest: "0".to_string(),
4886            trade_id: Ustr::from("333"),
4887            notional_usd: "0".to_string(),
4888            avg_px: String::new(),
4889            upl: "0".to_string(),
4890            upl_ratio: "0".to_string(),
4891            u_time: 1_622_559_930_237,
4892            margin: "0".to_string(),
4893            mgn_ratio: "0".to_string(),
4894            adl: "0".to_string(),
4895            c_time: "1622559930237".to_string(),
4896            realized_pnl: "0".to_string(),
4897            upl_last_px: "0".to_string(),
4898            upl_ratio_last_px: "0".to_string(),
4899            avail_pos: "0".to_string(),
4900            be_px: "0".to_string(),
4901            funding_fee: "0".to_string(),
4902            idx_px: "0".to_string(),
4903            liq_penalty: "0".to_string(),
4904            opt_val: "0".to_string(),
4905            pending_close_ord_liab_val: "0".to_string(),
4906            pnl: "0".to_string(),
4907            pos_ccy: "ETH".to_string(),
4908            quote_bal: "0".to_string(),
4909            quote_borrowed: "0".to_string(),
4910            quote_interest: "0".to_string(),
4911            spot_in_use_amt: "0".to_string(),
4912            spot_in_use_ccy: "ETH".to_string(),
4913            usd_px: "3000".to_string(),
4914            delta_bs: String::new(),
4915            gamma_bs: String::new(),
4916            theta_bs: String::new(),
4917            vega_bs: String::new(),
4918            close_order_algo: Vec::new(),
4919        };
4920
4921        let account_id = AccountId::new("OKX-001");
4922        let instrument_id = InstrumentId::from("ETH-USDT-SWAP.OKX");
4923        let report = parse_position_status_report(
4924            &position,
4925            account_id,
4926            instrument_id,
4927            8,
4928            UnixNanos::default(),
4929        )
4930        .unwrap();
4931
4932        assert_eq!(report.account_id, account_id);
4933        assert_eq!(report.instrument_id, instrument_id);
4934        assert_eq!(report.position_side, PositionSide::Flat);
4935        assert_eq!(report.quantity, Quantity::from("0"));
4936        // Net mode: venue_position_id is None (signals NETTING OMS)
4937        assert_eq!(report.venue_position_id, None);
4938    }
4939
4940    #[rstest]
4941    fn test_parse_position_status_report_long_short_mode_long() {
4942        // Test Long/Short mode: posSide="long" with positive quantity
4943        let position = OKXPosition {
4944            inst_id: Ustr::from("BTC-USDT-SWAP"),
4945            inst_type: OKXInstrumentType::Swap,
4946            mgn_mode: OKXMarginMode::Cross,
4947            pos_id: Some(Ustr::from("11111")),
4948            pos_side: OKXPositionSide::Long, // Long/Short mode - Long leg
4949            pos: "3.2".to_string(),          // Positive quantity (always positive in this mode)
4950            base_bal: "3.2".to_string(),
4951            ccy: "BTC".to_string(),
4952            fee: "0.01".to_string(),
4953            lever: "10.0".to_string(),
4954            last: "50000".to_string(),
4955            mark_px: "50000".to_string(),
4956            liq_px: "45000".to_string(),
4957            mmr: "0.1".to_string(),
4958            interest: "0".to_string(),
4959            trade_id: Ustr::from("444"),
4960            notional_usd: "160000".to_string(),
4961            avg_px: "50000".to_string(),
4962            upl: "0".to_string(),
4963            upl_ratio: "0".to_string(),
4964            u_time: 1_622_559_930_237,
4965            margin: "1.6".to_string(),
4966            mgn_ratio: "0.01".to_string(),
4967            adl: "0".to_string(),
4968            c_time: "1622559930237".to_string(),
4969            realized_pnl: "0".to_string(),
4970            upl_last_px: "0".to_string(),
4971            upl_ratio_last_px: "0".to_string(),
4972            avail_pos: "3.2".to_string(),
4973            be_px: "0".to_string(),
4974            funding_fee: "0".to_string(),
4975            idx_px: "0".to_string(),
4976            liq_penalty: "0".to_string(),
4977            opt_val: "0".to_string(),
4978            pending_close_ord_liab_val: "0".to_string(),
4979            pnl: "0".to_string(),
4980            pos_ccy: "BTC".to_string(),
4981            quote_bal: "160000".to_string(),
4982            quote_borrowed: "0".to_string(),
4983            quote_interest: "0".to_string(),
4984            spot_in_use_amt: "0".to_string(),
4985            spot_in_use_ccy: "BTC".to_string(),
4986            usd_px: "50000".to_string(),
4987            delta_bs: String::new(),
4988            gamma_bs: String::new(),
4989            theta_bs: String::new(),
4990            vega_bs: String::new(),
4991            close_order_algo: Vec::new(),
4992        };
4993
4994        let account_id = AccountId::new("OKX-001");
4995        let instrument_id = InstrumentId::from("BTC-USDT-SWAP.OKX");
4996        let report = parse_position_status_report(
4997            &position,
4998            account_id,
4999            instrument_id,
5000            8,
5001            UnixNanos::default(),
5002        )
5003        .unwrap();
5004
5005        assert_eq!(report.account_id, account_id);
5006        assert_eq!(report.instrument_id, instrument_id);
5007        assert_eq!(report.position_side, PositionSide::Long);
5008        assert_eq!(report.quantity, Quantity::from("3.2"));
5009        // Long/Short mode - Long leg: "-LONG" suffix
5010        assert_eq!(
5011            report.venue_position_id,
5012            Some(PositionId::new(format!("{instrument_id}-LONG")))
5013        );
5014    }
5015
5016    #[rstest]
5017    fn test_parse_position_status_report_long_short_mode_short() {
5018        // Test Long/Short mode: posSide="short" with positive quantity
5019        // This is the critical test - positive quantity but SHORT side!
5020        let position = OKXPosition {
5021            inst_id: Ustr::from("BTC-USDT-SWAP"),
5022            inst_type: OKXInstrumentType::Swap,
5023            mgn_mode: OKXMarginMode::Cross,
5024            pos_id: Some(Ustr::from("22222")),
5025            pos_side: OKXPositionSide::Short, // Long/Short mode - Short leg
5026            pos: "1.8".to_string(),           // Positive quantity (always positive in this mode)
5027            base_bal: "1.8".to_string(),
5028            ccy: "BTC".to_string(),
5029            fee: "0.02".to_string(),
5030            lever: "10.0".to_string(),
5031            last: "50000".to_string(),
5032            mark_px: "50000".to_string(),
5033            liq_px: "55000".to_string(),
5034            mmr: "0.2".to_string(),
5035            interest: "0".to_string(),
5036            trade_id: Ustr::from("555"),
5037            notional_usd: "90000".to_string(),
5038            avg_px: "50000".to_string(),
5039            upl: "0".to_string(),
5040            upl_ratio: "0".to_string(),
5041            u_time: 1_622_559_930_237,
5042            margin: "0.9".to_string(),
5043            mgn_ratio: "0.02".to_string(),
5044            adl: "0".to_string(),
5045            c_time: "1622559930237".to_string(),
5046            realized_pnl: "0".to_string(),
5047            upl_last_px: "0".to_string(),
5048            upl_ratio_last_px: "0".to_string(),
5049            avail_pos: "1.8".to_string(),
5050            be_px: "0".to_string(),
5051            funding_fee: "0".to_string(),
5052            idx_px: "0".to_string(),
5053            liq_penalty: "0".to_string(),
5054            opt_val: "0".to_string(),
5055            pending_close_ord_liab_val: "0".to_string(),
5056            pnl: "0".to_string(),
5057            pos_ccy: "BTC".to_string(),
5058            quote_bal: "90000".to_string(),
5059            quote_borrowed: "0".to_string(),
5060            quote_interest: "0".to_string(),
5061            spot_in_use_amt: "0".to_string(),
5062            spot_in_use_ccy: "BTC".to_string(),
5063            usd_px: "50000".to_string(),
5064            delta_bs: String::new(),
5065            gamma_bs: String::new(),
5066            theta_bs: String::new(),
5067            vega_bs: String::new(),
5068            close_order_algo: Vec::new(),
5069        };
5070
5071        let account_id = AccountId::new("OKX-001");
5072        let instrument_id = InstrumentId::from("BTC-USDT-SWAP.OKX");
5073        let report = parse_position_status_report(
5074            &position,
5075            account_id,
5076            instrument_id,
5077            8,
5078            UnixNanos::default(),
5079        )
5080        .unwrap();
5081
5082        assert_eq!(report.account_id, account_id);
5083        assert_eq!(report.instrument_id, instrument_id);
5084        // This is the critical assertion: positive quantity but SHORT side
5085        assert_eq!(report.position_side, PositionSide::Short);
5086        assert_eq!(report.quantity, Quantity::from("1.8"));
5087        // Long/Short mode - Short leg: "-SHORT" suffix
5088        assert_eq!(
5089            report.venue_position_id,
5090            Some(PositionId::new(format!("{instrument_id}-SHORT")))
5091        );
5092    }
5093
5094    #[rstest]
5095    fn test_parse_position_status_report_margin_long() {
5096        // Test MARGIN long position: pos_ccy = base currency (ETH)
5097        let position = OKXPosition {
5098            inst_id: Ustr::from("ETH-USDT"),
5099            inst_type: OKXInstrumentType::Margin,
5100            mgn_mode: OKXMarginMode::Cross,
5101            pos_id: Some(Ustr::from("margin-long-1")),
5102            pos_side: OKXPositionSide::Net,
5103            pos: "1.5".to_string(), // Total position (may include pending)
5104            base_bal: "1.5".to_string(),
5105            ccy: "ETH".to_string(),
5106            fee: "0".to_string(),
5107            lever: "3".to_string(),
5108            last: "4000".to_string(),
5109            mark_px: "4000".to_string(),
5110            liq_px: "3500".to_string(),
5111            mmr: "0.1".to_string(),
5112            interest: "0".to_string(),
5113            trade_id: Ustr::from("trade1"),
5114            notional_usd: "6000".to_string(),
5115            avg_px: "3800".to_string(), // Bought at 3800
5116            upl: "300".to_string(),
5117            upl_ratio: "0.05".to_string(),
5118            u_time: 1_622_559_930_237,
5119            margin: "2000".to_string(),
5120            mgn_ratio: "0.33".to_string(),
5121            adl: "0".to_string(),
5122            c_time: "1622559930237".to_string(),
5123            realized_pnl: "0".to_string(),
5124            upl_last_px: "300".to_string(),
5125            upl_ratio_last_px: "0.05".to_string(),
5126            avail_pos: "1.5".to_string(),
5127            be_px: "3800".to_string(),
5128            funding_fee: "0".to_string(),
5129            idx_px: "4000".to_string(),
5130            liq_penalty: "0".to_string(),
5131            opt_val: "0".to_string(),
5132            pending_close_ord_liab_val: "0".to_string(),
5133            pnl: "300".to_string(),
5134            pos_ccy: "ETH".to_string(), // pos_ccy = base = LONG
5135            quote_bal: "0".to_string(),
5136            quote_borrowed: "0".to_string(),
5137            quote_interest: "0".to_string(),
5138            spot_in_use_amt: "0".to_string(),
5139            spot_in_use_ccy: String::new(),
5140            usd_px: "4000".to_string(),
5141            delta_bs: String::new(),
5142            gamma_bs: String::new(),
5143            theta_bs: String::new(),
5144            vega_bs: String::new(),
5145            close_order_algo: Vec::new(),
5146        };
5147
5148        let account_id = AccountId::new("OKX-001");
5149        let instrument_id = InstrumentId::from("ETH-USDT.OKX");
5150        let report = parse_position_status_report(
5151            &position,
5152            account_id,
5153            instrument_id,
5154            4,
5155            UnixNanos::default(),
5156        )
5157        .unwrap();
5158
5159        assert_eq!(report.account_id, account_id);
5160        assert_eq!(report.instrument_id, instrument_id);
5161        assert_eq!(report.position_side, PositionSide::Long);
5162        assert_eq!(report.quantity, Quantity::from("1.5")); // 1.5 ETH in base
5163        assert_eq!(report.venue_position_id, None); // Net mode
5164    }
5165
5166    #[rstest]
5167    fn test_parse_position_status_report_margin_short() {
5168        // Test MARGIN short position: pos_ccy = quote currency (USDT)
5169        // pos is in quote currency and needs conversion to base
5170        let position = OKXPosition {
5171            inst_id: Ustr::from("ETH-USDT"),
5172            inst_type: OKXInstrumentType::Margin,
5173            mgn_mode: OKXMarginMode::Cross,
5174            pos_id: Some(Ustr::from("margin-short-1")),
5175            pos_side: OKXPositionSide::Net,
5176            pos: "244.56".to_string(), // Position in quote currency (USDT)
5177            base_bal: "0".to_string(),
5178            ccy: "USDT".to_string(),
5179            fee: "0".to_string(),
5180            lever: "3".to_string(),
5181            last: "4092".to_string(),
5182            mark_px: "4092".to_string(),
5183            liq_px: "4500".to_string(),
5184            mmr: "0.1".to_string(),
5185            interest: "0".to_string(),
5186            trade_id: Ustr::from("trade2"),
5187            notional_usd: "244.56".to_string(),
5188            avg_px: "4092".to_string(), // Shorted at 4092
5189            upl: "-10".to_string(),
5190            upl_ratio: "-0.04".to_string(),
5191            u_time: 1_622_559_930_237,
5192            margin: "100".to_string(),
5193            mgn_ratio: "0.4".to_string(),
5194            adl: "0".to_string(),
5195            c_time: "1622559930237".to_string(),
5196            realized_pnl: "0".to_string(),
5197            upl_last_px: "-10".to_string(),
5198            upl_ratio_last_px: "-0.04".to_string(),
5199            avail_pos: "244.56".to_string(),
5200            be_px: "4092".to_string(),
5201            funding_fee: "0".to_string(),
5202            idx_px: "4092".to_string(),
5203            liq_penalty: "0".to_string(),
5204            opt_val: "0".to_string(),
5205            pending_close_ord_liab_val: "0".to_string(),
5206            pnl: "-10".to_string(),
5207            pos_ccy: "USDT".to_string(), // pos_ccy = quote indicates SHORT, pos in USDT
5208            quote_bal: "244.56".to_string(),
5209            quote_borrowed: "0".to_string(),
5210            quote_interest: "0".to_string(),
5211            spot_in_use_amt: "0".to_string(),
5212            spot_in_use_ccy: String::new(),
5213            usd_px: "4092".to_string(),
5214            delta_bs: String::new(),
5215            gamma_bs: String::new(),
5216            theta_bs: String::new(),
5217            vega_bs: String::new(),
5218            close_order_algo: Vec::new(),
5219        };
5220
5221        let account_id = AccountId::new("OKX-001");
5222        let instrument_id = InstrumentId::from("ETH-USDT.OKX");
5223        let report = parse_position_status_report(
5224            &position,
5225            account_id,
5226            instrument_id,
5227            4,
5228            UnixNanos::default(),
5229        )
5230        .unwrap();
5231
5232        assert_eq!(report.account_id, account_id);
5233        assert_eq!(report.instrument_id, instrument_id);
5234        assert_eq!(report.position_side, PositionSide::Short);
5235        // Position is 244.56 USDT / 4092 USDT/ETH = 0.0597... ETH
5236        assert_eq!(report.quantity.to_string(), "0.0598");
5237        assert_eq!(report.venue_position_id, None); // Net mode
5238    }
5239
5240    #[rstest]
5241    fn test_parse_position_status_report_margin_short_rounds_to_size_precision() {
5242        // 100.00 USDT / 3333.33 USDT/ETH = 0.030000030000... ETH
5243        // Without round_dp this exceeds size_precision=4 and fails
5244        let position = OKXPosition {
5245            inst_id: Ustr::from("ETH-USDT"),
5246            inst_type: OKXInstrumentType::Margin,
5247            mgn_mode: OKXMarginMode::Cross,
5248            pos_id: Some(Ustr::from("margin-short-2")),
5249            pos_side: OKXPositionSide::Net,
5250            pos: "100.00".to_string(),
5251            base_bal: "0".to_string(),
5252            ccy: "USDT".to_string(),
5253            fee: "0".to_string(),
5254            lever: "3".to_string(),
5255            last: "3333.33".to_string(),
5256            mark_px: "3333.33".to_string(),
5257            liq_px: "3500".to_string(),
5258            mmr: "0.1".to_string(),
5259            interest: "0".to_string(),
5260            trade_id: Ustr::from("trade-round"),
5261            notional_usd: "100.00".to_string(),
5262            avg_px: "3333.33".to_string(),
5263            upl: "0".to_string(),
5264            upl_ratio: "0".to_string(),
5265            u_time: 1_622_559_930_237,
5266            margin: "50".to_string(),
5267            mgn_ratio: "0.5".to_string(),
5268            adl: "0".to_string(),
5269            c_time: "1622559930237".to_string(),
5270            realized_pnl: "0".to_string(),
5271            upl_last_px: "0".to_string(),
5272            upl_ratio_last_px: "0".to_string(),
5273            avail_pos: "100.00".to_string(),
5274            be_px: "3333.33".to_string(),
5275            funding_fee: "0".to_string(),
5276            idx_px: "3333.33".to_string(),
5277            liq_penalty: "0".to_string(),
5278            opt_val: "0".to_string(),
5279            pending_close_ord_liab_val: "0".to_string(),
5280            pnl: "0".to_string(),
5281            pos_ccy: "USDT".to_string(),
5282            quote_bal: "100.00".to_string(),
5283            quote_borrowed: "0".to_string(),
5284            quote_interest: "0".to_string(),
5285            spot_in_use_amt: "0".to_string(),
5286            spot_in_use_ccy: String::new(),
5287            usd_px: "3333.33".to_string(),
5288            delta_bs: String::new(),
5289            gamma_bs: String::new(),
5290            theta_bs: String::new(),
5291            vega_bs: String::new(),
5292            close_order_algo: Vec::new(),
5293        };
5294
5295        let report = parse_position_status_report(
5296            &position,
5297            AccountId::new("OKX-001"),
5298            InstrumentId::from("ETH-USDT.OKX"),
5299            4, // size_precision=4
5300            UnixNanos::default(),
5301        )
5302        .unwrap();
5303
5304        assert_eq!(report.position_side, PositionSide::Short);
5305        assert_eq!(report.quantity.to_string(), "0.0300");
5306    }
5307
5308    #[rstest]
5309    fn test_parse_rfc3339_timestamp_rejects_pre_epoch() {
5310        let result = parse_rfc3339_timestamp("1960-01-01T00:00:00Z");
5311        assert!(result.is_err());
5312        assert!(
5313            result
5314                .unwrap_err()
5315                .to_string()
5316                .contains("Negative nanosecond timestamp")
5317        );
5318    }
5319
5320    #[rstest]
5321    fn test_parse_position_status_report_margin_flat() {
5322        // Test MARGIN flat position: pos_ccy is empty string
5323        let position = OKXPosition {
5324            inst_id: Ustr::from("ETH-USDT"),
5325            inst_type: OKXInstrumentType::Margin,
5326            mgn_mode: OKXMarginMode::Cross,
5327            pos_id: Some(Ustr::from("margin-flat-1")),
5328            pos_side: OKXPositionSide::Net,
5329            pos: "0".to_string(),
5330            base_bal: "0".to_string(),
5331            ccy: "ETH".to_string(),
5332            fee: "0".to_string(),
5333            lever: "0".to_string(),
5334            last: "4000".to_string(),
5335            mark_px: "4000".to_string(),
5336            liq_px: "0".to_string(),
5337            mmr: "0".to_string(),
5338            interest: "0".to_string(),
5339            trade_id: Ustr::from(""),
5340            notional_usd: "0".to_string(),
5341            avg_px: String::new(),
5342            upl: "0".to_string(),
5343            upl_ratio: "0".to_string(),
5344            u_time: 1_622_559_930_237,
5345            margin: "0".to_string(),
5346            mgn_ratio: "0".to_string(),
5347            adl: "0".to_string(),
5348            c_time: "1622559930237".to_string(),
5349            realized_pnl: "0".to_string(),
5350            upl_last_px: "0".to_string(),
5351            upl_ratio_last_px: "0".to_string(),
5352            avail_pos: "0".to_string(),
5353            be_px: "0".to_string(),
5354            funding_fee: "0".to_string(),
5355            idx_px: "0".to_string(),
5356            liq_penalty: "0".to_string(),
5357            opt_val: "0".to_string(),
5358            pending_close_ord_liab_val: "0".to_string(),
5359            pnl: "0".to_string(),
5360            pos_ccy: String::new(), // Empty pos_ccy = FLAT
5361            quote_bal: "0".to_string(),
5362            quote_borrowed: "0".to_string(),
5363            quote_interest: "0".to_string(),
5364            spot_in_use_amt: "0".to_string(),
5365            spot_in_use_ccy: String::new(),
5366            usd_px: "0".to_string(),
5367            delta_bs: String::new(),
5368            gamma_bs: String::new(),
5369            theta_bs: String::new(),
5370            vega_bs: String::new(),
5371            close_order_algo: Vec::new(),
5372        };
5373
5374        let account_id = AccountId::new("OKX-001");
5375        let instrument_id = InstrumentId::from("ETH-USDT.OKX");
5376        let report = parse_position_status_report(
5377            &position,
5378            account_id,
5379            instrument_id,
5380            4,
5381            UnixNanos::default(),
5382        )
5383        .unwrap();
5384
5385        assert_eq!(report.account_id, account_id);
5386        assert_eq!(report.instrument_id, instrument_id);
5387        assert_eq!(report.position_side, PositionSide::Flat);
5388        assert_eq!(report.quantity, Quantity::from("0"));
5389        assert_eq!(report.venue_position_id, None); // Net mode
5390    }
5391
5392    #[rstest]
5393    fn test_parse_swap_instrument_empty_underlying_returns_error() {
5394        let instrument = OKXInstrument {
5395            inst_type: OKXInstrumentType::Swap,
5396            inst_id: Ustr::from("ETH-USD_UM-SWAP"),
5397            uly: Ustr::from(""), // Empty underlying
5398            inst_family: Ustr::from(""),
5399            series_id: None,
5400            inst_category: None,
5401            group_id: None,
5402            init_px_lmt_pct: String::new(),
5403            float_px_lmt_pct: String::new(),
5404            max_px_lmt_pct: String::new(),
5405            base_ccy: Ustr::from(""),
5406            quote_ccy: Ustr::from(""),
5407            settle_ccy: Ustr::from("USD"),
5408            ct_val: "1".to_string(),
5409            ct_mult: "1".to_string(),
5410            ct_val_ccy: "USD".to_string(),
5411            opt_type: crate::common::enums::OKXOptionType::None,
5412            stk: String::new(),
5413            list_time: None,
5414            exp_time: None,
5415            lever: String::new(),
5416            tick_sz: "0.1".to_string(),
5417            lot_sz: "1".to_string(),
5418            min_sz: "1".to_string(),
5419            ct_type: OKXContractType::Linear,
5420            state: crate::common::enums::OKXInstrumentStatus::Preopen,
5421            rule_type: String::new(),
5422            max_lmt_sz: String::new(),
5423            max_mkt_sz: String::new(),
5424            max_lmt_amt: String::new(),
5425            max_mkt_amt: String::new(),
5426            max_twap_sz: String::new(),
5427            max_iceberg_sz: String::new(),
5428            max_trigger_sz: String::new(),
5429            max_stop_sz: String::new(),
5430            inst_id_code: None,
5431            rpi: None,
5432            rpi_min_level: None,
5433            rpi_min_px_band: None,
5434            trade_quote_ccy_list: Vec::new(),
5435        };
5436
5437        let result = parse_swap_instrument(&instrument, None, None, UnixNanos::default());
5438        assert!(result.is_err());
5439        assert!(result.unwrap_err().to_string().contains("Empty underlying"));
5440    }
5441
5442    #[rstest]
5443    fn test_parse_futures_instrument_empty_underlying_returns_error() {
5444        let instrument = OKXInstrument {
5445            inst_type: OKXInstrumentType::Futures,
5446            inst_id: Ustr::from("ETH-USD_UM-250328"),
5447            uly: Ustr::from(""), // Empty underlying
5448            inst_family: Ustr::from(""),
5449            series_id: None,
5450            inst_category: None,
5451            group_id: None,
5452            init_px_lmt_pct: String::new(),
5453            float_px_lmt_pct: String::new(),
5454            max_px_lmt_pct: String::new(),
5455            base_ccy: Ustr::from(""),
5456            quote_ccy: Ustr::from(""),
5457            settle_ccy: Ustr::from("USD"),
5458            ct_val: "1".to_string(),
5459            ct_mult: "1".to_string(),
5460            ct_val_ccy: "USD".to_string(),
5461            opt_type: crate::common::enums::OKXOptionType::None,
5462            stk: String::new(),
5463            list_time: None,
5464            exp_time: Some(1_743_004_800_000),
5465            lever: String::new(),
5466            tick_sz: "0.1".to_string(),
5467            lot_sz: "1".to_string(),
5468            min_sz: "1".to_string(),
5469            ct_type: OKXContractType::Linear,
5470            state: crate::common::enums::OKXInstrumentStatus::Preopen,
5471            rule_type: String::new(),
5472            max_lmt_sz: String::new(),
5473            max_mkt_sz: String::new(),
5474            max_lmt_amt: String::new(),
5475            max_mkt_amt: String::new(),
5476            max_twap_sz: String::new(),
5477            max_iceberg_sz: String::new(),
5478            max_trigger_sz: String::new(),
5479            max_stop_sz: String::new(),
5480            inst_id_code: None,
5481            rpi: None,
5482            rpi_min_level: None,
5483            rpi_min_px_band: None,
5484            trade_quote_ccy_list: Vec::new(),
5485        };
5486
5487        let result = parse_futures_instrument(&instrument, None, None, UnixNanos::default());
5488        assert!(result.is_err());
5489        assert!(result.unwrap_err().to_string().contains("Empty underlying"));
5490    }
5491
5492    #[rstest]
5493    fn test_parse_option_instrument_empty_opt_type_returns_error() {
5494        let instrument = OKXInstrument {
5495            inst_type: OKXInstrumentType::Option,
5496            inst_id: Ustr::from("BTC-USD-250328-50000-C"),
5497            uly: Ustr::from("BTC-USD"),
5498            inst_family: Ustr::from("BTC-USD"),
5499            series_id: None,
5500            inst_category: None,
5501            group_id: None,
5502            init_px_lmt_pct: String::new(),
5503            float_px_lmt_pct: String::new(),
5504            max_px_lmt_pct: String::new(),
5505            base_ccy: Ustr::from(""),
5506            quote_ccy: Ustr::from(""),
5507            settle_ccy: Ustr::from("USD"),
5508            ct_val: "0.01".to_string(),
5509            ct_mult: "1".to_string(),
5510            ct_val_ccy: "BTC".to_string(),
5511            // OKX sends `optType=""` for non-option instruments and the
5512            // occasional malformed payload, which deserializes to `None`.
5513            opt_type: crate::common::enums::OKXOptionType::None,
5514            stk: "50000".to_string(),
5515            list_time: None,
5516            exp_time: Some(1_743_004_800_000),
5517            lever: String::new(),
5518            tick_sz: "0.0005".to_string(),
5519            lot_sz: "0.1".to_string(),
5520            min_sz: "0.1".to_string(),
5521            ct_type: OKXContractType::Linear,
5522            state: crate::common::enums::OKXInstrumentStatus::Preopen,
5523            rule_type: String::new(),
5524            max_lmt_sz: String::new(),
5525            max_mkt_sz: String::new(),
5526            max_lmt_amt: String::new(),
5527            max_mkt_amt: String::new(),
5528            max_twap_sz: String::new(),
5529            max_iceberg_sz: String::new(),
5530            max_trigger_sz: String::new(),
5531            max_stop_sz: String::new(),
5532            inst_id_code: None,
5533            rpi: None,
5534            rpi_min_level: None,
5535            rpi_min_px_band: None,
5536            trade_quote_ccy_list: Vec::new(),
5537        };
5538
5539        let result = parse_option_instrument(&instrument, None, None, UnixNanos::default());
5540        assert!(result.is_err());
5541        let err_msg = result.unwrap_err().to_string();
5542        assert!(
5543            err_msg.contains("Unsupported") && err_msg.contains("optType"),
5544            "expected Unsupported optType error, was: {err_msg}"
5545        );
5546    }
5547
5548    #[rstest]
5549    fn test_parse_option_instrument_empty_underlying_returns_error() {
5550        let instrument = OKXInstrument {
5551            inst_type: OKXInstrumentType::Option,
5552            inst_id: Ustr::from("BTC-USD-250328-50000-C"),
5553            uly: Ustr::from(""), // Empty underlying
5554            inst_family: Ustr::from(""),
5555            series_id: None,
5556            inst_category: None,
5557            group_id: None,
5558            init_px_lmt_pct: String::new(),
5559            float_px_lmt_pct: String::new(),
5560            max_px_lmt_pct: String::new(),
5561            base_ccy: Ustr::from(""),
5562            quote_ccy: Ustr::from(""),
5563            settle_ccy: Ustr::from("USD"),
5564            ct_val: "0.01".to_string(),
5565            ct_mult: "1".to_string(),
5566            ct_val_ccy: "BTC".to_string(),
5567            opt_type: crate::common::enums::OKXOptionType::Call,
5568            stk: "50000".to_string(),
5569            list_time: None,
5570            exp_time: Some(1_743_004_800_000),
5571            lever: String::new(),
5572            tick_sz: "0.0005".to_string(),
5573            lot_sz: "0.1".to_string(),
5574            min_sz: "0.1".to_string(),
5575            ct_type: OKXContractType::Linear,
5576            state: crate::common::enums::OKXInstrumentStatus::Preopen,
5577            rule_type: String::new(),
5578            max_lmt_sz: String::new(),
5579            max_mkt_sz: String::new(),
5580            max_lmt_amt: String::new(),
5581            max_mkt_amt: String::new(),
5582            max_twap_sz: String::new(),
5583            max_iceberg_sz: String::new(),
5584            max_trigger_sz: String::new(),
5585            max_stop_sz: String::new(),
5586            inst_id_code: None,
5587            rpi: None,
5588            rpi_min_level: None,
5589            rpi_min_px_band: None,
5590            trade_quote_ccy_list: Vec::new(),
5591        };
5592
5593        let result = parse_option_instrument(&instrument, None, None, UnixNanos::default());
5594        assert!(result.is_err());
5595        assert!(result.unwrap_err().to_string().contains("Empty underlying"));
5596    }
5597
5598    #[rstest]
5599    #[case::fok(OKXOrderType::Fok, TimeInForce::Fok)]
5600    #[case::ioc(OKXOrderType::Ioc, TimeInForce::Ioc)]
5601    #[case::optimal_limit_ioc(OKXOrderType::OptimalLimitIoc, TimeInForce::Ioc)]
5602    #[case::market(OKXOrderType::Market, TimeInForce::Gtc)]
5603    #[case::limit(OKXOrderType::Limit, TimeInForce::Gtc)]
5604    #[case::post_only(OKXOrderType::PostOnly, TimeInForce::Gtc)]
5605    #[case::trigger(OKXOrderType::Trigger, TimeInForce::Gtc)]
5606    fn test_parse_order_status_report_time_in_force(
5607        #[case] okx_ord_type: OKXOrderType,
5608        #[case] expected: TimeInForce,
5609    ) {
5610        let response: OKXResponse<OKXOrderHistory> =
5611            serde_json::from_str(&load_test_json("http_get_orders_history.json")).unwrap();
5612        let mut order = response.data[0].clone();
5613        order.ord_type = okx_ord_type;
5614        order.px = "50000.0".to_string();
5615
5616        let report = parse_order_status_report(
5617            &order,
5618            AccountId::from("OKX-001"),
5619            InstrumentId::from("BTC-USDT-SWAP.OKX"),
5620            2,
5621            8,
5622            UnixNanos::default(),
5623        )
5624        .unwrap();
5625
5626        assert_eq!(report.time_in_force, expected);
5627    }
5628
5629    #[rstest]
5630    #[case::fok(OKXOrderType::Fok, "\"fok\"")]
5631    #[case::ioc(OKXOrderType::Ioc, "\"ioc\"")]
5632    #[case::optimal_limit_ioc(OKXOrderType::OptimalLimitIoc, "\"optimal_limit_ioc\"")]
5633    fn test_okx_order_type_serde_round_trip(
5634        #[case] ord_type: OKXOrderType,
5635        #[case] expected_json: &str,
5636    ) {
5637        let serialized = serde_json::to_string(&ord_type).unwrap();
5638        let deserialized: OKXOrderType = serde_json::from_str(&serialized).unwrap();
5639
5640        assert_eq!(serialized, expected_json);
5641        assert_eq!(deserialized, ord_type);
5642    }
5643
5644    #[rstest]
5645    #[case::empty_string("", true)]
5646    #[case::zero("0", true)]
5647    #[case::minus_one("-1", true)]
5648    #[case::minus_two("-2", true)]
5649    #[case::normal_price("100.5", false)]
5650    #[case::another_price("0.001", false)]
5651    fn test_is_market_price(#[case] price: &str, #[case] expected: bool) {
5652        assert_eq!(is_market_price(price), expected);
5653    }
5654
5655    #[rstest]
5656    #[case::fok_market(OKXOrderType::Fok, "", OrderType::Market)]
5657    #[case::fok_limit(OKXOrderType::Fok, "100.5", OrderType::Limit)]
5658    #[case::ioc_market(OKXOrderType::Ioc, "", OrderType::Market)]
5659    #[case::ioc_limit(OKXOrderType::Ioc, "100.5", OrderType::Limit)]
5660    #[case::optimal_limit_ioc_market(OKXOrderType::OptimalLimitIoc, "", OrderType::Market)]
5661    #[case::optimal_limit_ioc_market_zero(OKXOrderType::OptimalLimitIoc, "0", OrderType::Market)]
5662    #[case::optimal_limit_ioc_market_minus_one(
5663        OKXOrderType::OptimalLimitIoc,
5664        "-1",
5665        OrderType::Market
5666    )]
5667    #[case::optimal_limit_ioc_limit(OKXOrderType::OptimalLimitIoc, "100.5", OrderType::Limit)]
5668    #[case::market_passthrough(OKXOrderType::Market, "", OrderType::Market)]
5669    #[case::limit_passthrough(OKXOrderType::Limit, "100.5", OrderType::Limit)]
5670    fn test_determine_order_type(
5671        #[case] okx_ord_type: OKXOrderType,
5672        #[case] price: &str,
5673        #[case] expected: OrderType,
5674    ) {
5675        assert_eq!(determine_order_type(okx_ord_type, price).unwrap(), expected);
5676    }
5677
5678    #[rstest]
5679    fn test_determine_order_type_rejects_unknown_order_type() {
5680        assert!(determine_order_type(OKXOrderType::Other, "100.5").is_err());
5681    }
5682
5683    #[rstest]
5684    #[case::option("BTC-USD-250328-92000-C", "BTC-USD")]
5685    #[case::swap("BTC-USDT-SWAP", "BTC-USDT")]
5686    #[case::futures("ETH-USD-250328", "ETH-USD")]
5687    #[case::spot("BTC-USDT", "BTC-USDT")]
5688    fn test_extract_inst_family(#[case] symbol: &str, #[case] expected: &str) {
5689        let family = extract_inst_family(symbol).unwrap();
5690        assert_eq!(family, expected);
5691    }
5692
5693    #[rstest]
5694    fn test_extract_inst_family_single_segment_fails() {
5695        extract_inst_family("BTC").unwrap_err();
5696    }
5697
5698    #[rstest]
5699    #[case("BTC-USDT", false)]
5700    #[case("BTC-USDT-SWAP", false)]
5701    #[case("BTC-USD_UM-SWAP", false)]
5702    #[case("BTC-USD_UM-261030", false)]
5703    #[case("BTC-USD_UM_XPERP-310404", false)]
5704    #[case("BTC-USD-250328-50000-C", false)]
5705    #[case("BTC-USDT_BTC-USDT-SWAP", true)]
5706    #[case("ETH-USD-SWAP_ETH-USD-231229", true)]
5707    #[case("BTC-USD_UM-261030_BTC-USD_UM-261225", true)]
5708    #[case("BTC-USD_UM_XPERP-310404_BTC-USD_UM-261030", true)]
5709    #[case("BTC-USD-250328-50000-C_BTC-USD-250328-60000-C", true)]
5710    fn test_is_okx_spread_symbol(#[case] symbol: &str, #[case] expected: bool) {
5711        assert_eq!(is_okx_spread_symbol(symbol), expected);
5712    }
5713
5714    #[rstest]
5715    #[case("BTC-USDT", OKXInstrumentType::Spot)]
5716    #[case("BTC-USDT-SWAP", OKXInstrumentType::Swap)]
5717    #[case("BTC-USDT-250328", OKXInstrumentType::Futures)]
5718    #[case("BTC-USD_UM-SWAP", OKXInstrumentType::Swap)]
5719    #[case("BTC-USD_UM-261030", OKXInstrumentType::Futures)]
5720    #[case("BTC-USD_UM_XPERP-310404", OKXInstrumentType::Futures)]
5721    #[case("BTC-USD-250328-50000-C", OKXInstrumentType::Option)]
5722    #[case("BTC-ABOVE-DAILY-260224-1600-65000", OKXInstrumentType::Events)]
5723    fn test_okx_instrument_type_from_symbol(
5724        #[case] symbol: &str,
5725        #[case] expected: OKXInstrumentType,
5726    ) {
5727        assert_eq!(okx_instrument_type_from_symbol(symbol), expected);
5728    }
5729
5730    #[rstest]
5731    #[case(OKXInstrumentStatus::Live, MarketStatusAction::Trading)]
5732    #[case(OKXInstrumentStatus::Suspend, MarketStatusAction::Suspend)]
5733    #[case(OKXInstrumentStatus::Preopen, MarketStatusAction::PreOpen)]
5734    #[case(OKXInstrumentStatus::Test, MarketStatusAction::NotAvailableForTrading)]
5735    #[case(OKXInstrumentStatus::PostOnly, MarketStatusAction::Quoting)]
5736    #[case(
5737        OKXInstrumentStatus::Rebase,
5738        MarketStatusAction::NotAvailableForTrading
5739    )]
5740    #[case(
5741        OKXInstrumentStatus::Settling,
5742        MarketStatusAction::NotAvailableForTrading
5743    )]
5744    #[case(
5745        OKXInstrumentStatus::Unknown,
5746        MarketStatusAction::NotAvailableForTrading
5747    )]
5748    fn test_okx_status_to_market_action(
5749        #[case] status: OKXInstrumentStatus,
5750        #[case] expected: MarketStatusAction,
5751    ) {
5752        assert_eq!(okx_status_to_market_action(status), expected);
5753    }
5754
5755    #[rstest]
5756    #[case::future_state("\"future_state_xyz\"")]
5757    #[case::frozen("\"frozen\"")]
5758    #[case::delisting("\"delisting\"")]
5759    fn test_okx_unknown_status_falls_back(#[case] json: &str) {
5760        let parsed: OKXInstrumentStatus = serde_json::from_str(json).unwrap();
5761        assert_eq!(parsed, OKXInstrumentStatus::Unknown);
5762        assert_eq!(
5763            okx_status_to_market_action(parsed),
5764            MarketStatusAction::NotAvailableForTrading
5765        );
5766    }
5767
5768    #[rstest]
5769    #[case::crypto("\"1\"", OKXInstrumentCategory::Crypto, AssetClass::Cryptocurrency)]
5770    #[case::equity("\"3\"", OKXInstrumentCategory::Equity, AssetClass::Equity)]
5771    #[case::commodity("\"4\"", OKXInstrumentCategory::Commodity, AssetClass::Commodity)]
5772    #[case::fx("\"5\"", OKXInstrumentCategory::Fx, AssetClass::FX)]
5773    #[case::debt("\"6\"", OKXInstrumentCategory::Debt, AssetClass::Debt)]
5774    #[case::unknown_code("\"2\"", OKXInstrumentCategory::Unknown, AssetClass::Alternative)]
5775    fn test_okx_inst_category_parsing_and_asset_class(
5776        #[case] json: &str,
5777        #[case] expected: OKXInstrumentCategory,
5778        #[case] asset_class: AssetClass,
5779    ) {
5780        let parsed: OKXInstrumentCategory = serde_json::from_str(json).unwrap();
5781        assert_eq!(parsed, expected);
5782        assert_eq!(okx_inst_category_to_asset_class(Some(parsed)), asset_class);
5783    }
5784
5785    #[rstest]
5786    fn test_okx_instrument_documented_fee_group_id() {
5787        let response: OKXResponse<OKXInstrument> = serde_json::from_str(include_str!(
5788            "../../test_data/http_get_instruments_spot_group_id.json"
5789        ))
5790        .unwrap();
5791
5792        assert_eq!(response.code, "0");
5793        assert!(response.msg.is_empty());
5794        assert_eq!(response.data.len(), 1);
5795        let instrument = &response.data[0];
5796        assert_eq!(instrument.inst_id, Ustr::from("BTC-USDT"));
5797        assert_eq!(instrument.inst_type, OKXInstrumentType::Spot);
5798        assert_eq!(instrument.group_id, Some(Ustr::from("1")));
5799        assert_eq!(
5800            instrument.inst_category,
5801            Some(OKXInstrumentCategory::Crypto)
5802        );
5803    }
5804
5805    #[rstest]
5806    #[case::missing(None, None)]
5807    #[case::empty(Some(""), None)]
5808    #[case::zero(Some("0"), Some("0"))]
5809    #[case::group(Some("101"), Some("101"))]
5810    fn test_okx_instrument_preserves_raw_fee_group_id(
5811        #[case] group_id: Option<&str>,
5812        #[case] expected: Option<&str>,
5813    ) {
5814        let mut payload: serde_json::Value = serde_json::from_str(include_str!(
5815            "../../test_data/http_get_instruments_spot_group_id.json"
5816        ))
5817        .unwrap();
5818        let item = &mut payload["data"][0];
5819        item.as_object_mut().unwrap().remove("groupId");
5820        if let Some(value) = group_id {
5821            item["groupId"] = serde_json::json!(value);
5822        }
5823        item["instCategory"] = serde_json::json!("3");
5824
5825        let instrument: OKXInstrument = serde_json::from_value(item.clone()).unwrap();
5826
5827        assert_eq!(instrument.group_id, expected.map(Ustr::from));
5828        assert_eq!(
5829            instrument.inst_category,
5830            Some(OKXInstrumentCategory::Equity)
5831        );
5832        assert_eq!(instrument.inst_type, OKXInstrumentType::Spot);
5833    }
5834
5835    #[rstest]
5836    fn test_okx_instrument_reads_inst_category_and_ignores_legacy_category() {
5837        // OKX sends both `category` (deprecated) and `instCategory`; the model
5838        // must read `instCategory` and ignore `category`.
5839        let json = crate::common::testing::load_test_json("http_get_instruments_spot.json");
5840        let mut value: serde_json::Value = serde_json::from_str(&json).unwrap();
5841        let item = &mut value["data"][0];
5842        assert_eq!(item["category"], serde_json::json!("1"));
5843        item["instCategory"] = serde_json::json!("3"); // must differ from category to prove it wins
5844
5845        let instrument: OKXInstrument = serde_json::from_value(item.clone()).unwrap();
5846        assert_eq!(
5847            instrument.inst_category,
5848            Some(OKXInstrumentCategory::Equity)
5849        );
5850        assert_eq!(
5851            okx_inst_category_to_asset_class(instrument.inst_category),
5852            AssetClass::Equity
5853        );
5854    }
5855
5856    #[rstest]
5857    fn test_rpi_instrument_permission_parses_current_and_legacy_fields() {
5858        let json = load_test_json("http_get_instruments_spot.json");
5859        let mut value: serde_json::Value = serde_json::from_str(&json).unwrap();
5860        let mut current = value["data"][0].clone();
5861        current["rpi"] = serde_json::json!("2");
5862        let current: OKXInstrument = serde_json::from_value(current).unwrap();
5863
5864        let legacy = &mut value["data"][1];
5865        legacy["elp"] = serde_json::json!("1");
5866        let legacy: OKXInstrument = serde_json::from_value(legacy.clone()).unwrap();
5867
5868        assert_eq!(
5869            current.rpi,
5870            Some(crate::common::enums::OKXRpiPermission::Permitted)
5871        );
5872        assert_eq!(
5873            legacy.rpi,
5874            Some(crate::common::enums::OKXRpiPermission::Enabled)
5875        );
5876    }
5877
5878    #[rstest]
5879    fn test_rpi_instrument_spacing_fields_are_typed_and_reachable() {
5880        let json = load_test_json("http_get_instruments_spot.json");
5881        let response: OKXResponse<OKXInstrument> = serde_json::from_str(&json).unwrap();
5882        let okx_inst = response
5883            .data
5884            .first()
5885            .expect("Test data must have an instrument");
5886
5887        assert_eq!(okx_inst.rpi_min_level, Some(5));
5888        assert_eq!(okx_inst.rpi_min_px_band, Some(Decimal::from(20)));
5889
5890        let instrument = parse_spot_instrument(okx_inst, None, None, UnixNanos::default()).unwrap();
5891        let InstrumentAny::CurrencyPair(pair) = instrument else {
5892            panic!("expected CurrencyPair");
5893        };
5894        let info = pair.info.expect("RPI spacing info must be set");
5895
5896        assert_eq!(info.get_u64("okx_rpi_min_level"), Some(5));
5897        assert_eq!(info.get_str("okx_rpi_min_px_band"), Some("20"));
5898    }
5899
5900    #[rstest]
5901    #[case(
5902        "ETH-USDT-SWAP.OKX",
5903        OKXPositionSide::Long,
5904        Some("ETH-USDT-SWAP.OKX-LONG")
5905    )]
5906    #[case(
5907        "ETH-USDT-271231.OKX",
5908        OKXPositionSide::Short,
5909        Some("ETH-USDT-271231.OKX-SHORT")
5910    )]
5911    #[case("ETH-USDT-SWAP.OKX", OKXPositionSide::Net, None)]
5912    #[case("ETH-USDT-SWAP.OKX", OKXPositionSide::None, None)]
5913    #[case("ETH-USDT.OKX", OKXPositionSide::Long, None)]
5914    #[case("ETH-USD-271231-2000-C.OKX", OKXPositionSide::Short, None)]
5915    fn test_venue_position_id(
5916        #[case] instrument_id: &str,
5917        #[case] side: OKXPositionSide,
5918        #[case] expected: Option<&str>,
5919    ) {
5920        assert_eq!(
5921            venue_position_id(InstrumentId::from(instrument_id), side),
5922            expected.map(PositionId::from)
5923        );
5924    }
5925
5926    #[rstest]
5927    #[case(Some("long"), Some("BTC-USDT-SWAP.OKX-LONG"))]
5928    #[case(Some("short"), Some("BTC-USDT-SWAP.OKX-SHORT"))]
5929    #[case(Some("net"), None)]
5930    #[case(None, None)]
5931    fn test_fill_position_id_from_wire(#[case] side: Option<&str>, #[case] expected: Option<&str>) {
5932        let mut payload: serde_json::Value =
5933            serde_json::from_str(include_str!("../../test_data/http_transaction_detail.json"))
5934                .unwrap();
5935
5936        if let Some(side) = side {
5937            payload["posSide"] = serde_json::Value::String(side.to_string());
5938        } else {
5939            payload.as_object_mut().unwrap().remove("posSide");
5940        }
5941
5942        let detail: OKXTransactionDetail = serde_json::from_value(payload).unwrap();
5943        let report = parse_fill_report(
5944            &detail,
5945            AccountId::from("OKX-001"),
5946            InstrumentId::from("BTC-USDT-SWAP.OKX"),
5947            2,
5948            8,
5949            UnixNanos::default(),
5950        )
5951        .unwrap();
5952        assert_eq!(report.venue_position_id, expected.map(PositionId::from));
5953    }
5954}