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