Skip to main content

nautilus_okx/websocket/
messages.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//! Data structures modeling OKX WebSocket request and response payloads.
17
18use derive_builder::Builder;
19use nautilus_core::string::secret::SecretString;
20use nautilus_model::{
21    data::{Data, FundingRateUpdate, InstrumentStatus, OrderBookDeltas},
22    events::{
23        AccountState, OrderAccepted, OrderCancelRejected, OrderCanceled, OrderExpired,
24        OrderModifyRejected, OrderRejected, OrderTriggered, OrderUpdated,
25    },
26    identifiers::ClientOrderId,
27    instruments::InstrumentAny,
28    reports::{FillReport, OrderStatusReport, PositionStatusReport},
29};
30use serde::{
31    Deserialize, Serialize,
32    de::{DeserializeOwned, Error, IgnoredAny, MapAccess, Visitor},
33};
34use serde_json::value::RawValue;
35use ustr::Ustr;
36use zeroize::Zeroize;
37
38use super::enums::{OKXWsChannel, OKXWsOperation};
39use crate::{
40    common::{
41        enums::{
42            OKXAlgoOrderStatus, OKXAlgoOrderType, OKXBookAction, OKXCandleConfirm, OKXExecType,
43            OKXInstrumentType, OKXMarginMode, OKXOrderCategory, OKXOrderStatus, OKXOrderType,
44            OKXPositionSide, OKXPriceType, OKXQuickMarginType, OKXSelfTradePreventionMode,
45            OKXSettlementState, OKXSide, OKXTargetCurrency, OKXTradeMode, OKXTriggerType,
46        },
47        models::{OKXInstrument, OKXRpiBookLevel},
48        parse::{
49            deserialize_empty_string_as_none, deserialize_empty_ustr_as_none,
50            deserialize_string_to_u64, deserialize_target_currency_as_none,
51        },
52    },
53    http::models::OKXSpreadOrder,
54    websocket::enums::OKXSubscriptionEvent,
55};
56
57#[derive(Debug, Clone)]
58pub enum NautilusWsMessage {
59    Data(Vec<Data>),
60    Deltas(OrderBookDeltas),
61    FundingRates(Vec<FundingRateUpdate>),
62    Instrument(Box<InstrumentAny>, Option<InstrumentStatus>),
63    InstrumentStatus(InstrumentStatus),
64    AccountUpdate(AccountState),
65    PositionUpdate(PositionStatusReport),
66    OrderAccepted(OrderAccepted),
67    OrderCanceled(OrderCanceled),
68    OrderExpired(OrderExpired),
69    OrderRejected(OrderRejected),
70    OrderCancelRejected(OrderCancelRejected),
71    OrderModifyRejected(OrderModifyRejected),
72    OrderTriggered(OrderTriggered),
73    OrderUpdated(OrderUpdated),
74    ExecutionReports(Vec<ExecutionReport>),
75    Error(OKXWebSocketError),
76    Raw(serde_json::Value), // Unhandled channels
77    Reconnected,
78    Authenticated,
79}
80
81/// Represents an OKX WebSocket error.
82#[derive(Debug, Clone, Serialize, Deserialize)]
83pub struct OKXWebSocketError {
84    /// Error code from OKX (e.g., "50101").
85    pub code: String,
86    /// Error message from OKX.
87    pub message: String,
88    /// Connection ID if available.
89    pub conn_id: Option<String>,
90    /// Timestamp when the error occurred.
91    pub timestamp: u64,
92}
93
94#[derive(Debug, Clone)]
95#[allow(
96    clippy::large_enum_variant,
97    reason = "the variant size gap only crosses the threshold when high-precision widens the raw types"
98)]
99pub enum ExecutionReport {
100    Order(OrderStatusReport),
101    Fill(FillReport),
102}
103
104/// Output from the OKX WebSocket handler.
105///
106/// Contains venue-specific types only. Data parsing occurs in `PyOKXWebSocketClient`
107/// (using an instruments cache), and execution parsing occurs in `execution.rs`
108/// (using the system Cache for order lookups).
109#[derive(Debug)]
110pub enum OKXWsMessage {
111    /// Order book snapshot or update.
112    BookData {
113        arg: OKXWebSocketArg,
114        action: OKXBookAction,
115        data: Vec<OKXBookMsg>,
116    },
117    /// Retail Price Improvement order book snapshot or update.
118    RpiBookData {
119        arg: OKXWebSocketArg,
120        action: OKXBookAction,
121        data: Vec<OKXRpiBookMsg>,
122    },
123    /// Data from a non-book channel (trades, tickers, mark price, funding, candles, etc.).
124    ChannelData {
125        channel: OKXWsChannel,
126        inst_id: Option<Ustr>,
127        data: serde_json::Value,
128    },
129    /// Response to a WebSocket order command (place, cancel, amend, mass-cancel).
130    OrderResponse {
131        id: Option<String>,
132        op: OKXWsOperation,
133        code: String,
134        msg: String,
135        data: Vec<serde_json::Value>,
136        /// Client order IDs correlated with the sent request, if still retained.
137        client_order_ids: Vec<ClientOrderId>,
138    },
139    /// Order push channel updates.
140    Orders(Vec<OKXOrderMsg>),
141    /// Nitro spread order push channel updates.
142    SpreadOrders(Vec<OKXSpreadOrder>),
143    /// Algo order push channel updates.
144    AlgoOrders(Vec<OKXAlgoOrderMsg>),
145    /// Account channel update (raw JSON).
146    Account(serde_json::Value),
147    /// Positions channel update (raw JSON).
148    Positions(serde_json::Value),
149    /// Liquidation risk warnings for account positions.
150    LiquidationWarnings(Vec<OKXLiquidationWarningMsg>),
151    /// Instrument definition updates.
152    Instruments(Vec<OKXInstrument>),
153    /// A WebSocket send failed without a structured venue response.
154    SendFailed {
155        request_id: String,
156        client_order_ids: Vec<ClientOrderId>,
157        op: Option<OKXWsOperation>,
158        error: super::error::OKXWsError,
159    },
160    /// The venue rejected a subscribe request, so no data will flow for it.
161    SubscriptionFailed {
162        channel: OKXWsChannel,
163        inst_id: Option<Ustr>,
164        code: String,
165        msg: String,
166    },
167    /// Error received from OKX.
168    Error(OKXWebSocketError),
169    /// WebSocket reconnected.
170    Reconnected,
171    /// WebSocket authenticated.
172    Authenticated,
173}
174
175/// Generic WebSocket request for OKX trading commands.
176#[derive(Debug, Serialize)]
177#[serde(rename_all = "camelCase")]
178pub struct OKXWsRequest<T> {
179    /// Client request ID (required for order operations).
180    #[serde(skip_serializing_if = "Option::is_none")]
181    pub id: Option<String>,
182    /// Operation type (order, cancel-order, amend-order).
183    pub op: OKXWsOperation,
184    /// Request effective deadline. Unix timestamp format in milliseconds.
185    /// This is when the request itself expires, not related to order expiration.
186    #[serde(skip_serializing_if = "Option::is_none")]
187    pub exp_time: Option<String>,
188    /// Arguments payload for the operation.
189    pub args: Vec<T>,
190}
191
192/// OKX WebSocket authentication message.
193#[derive(Debug, Serialize, Zeroize)]
194pub struct OKXAuthentication {
195    #[zeroize(skip)]
196    pub op: &'static str,
197    pub args: Vec<OKXAuthenticationArg>,
198}
199
200/// OKX WebSocket authentication arguments.
201#[derive(Debug, Serialize, Zeroize)]
202#[serde(rename_all = "camelCase")]
203pub struct OKXAuthenticationArg {
204    pub api_key: SecretString,
205    pub passphrase: SecretString,
206    pub timestamp: String,
207    pub sign: SecretString,
208}
209
210#[derive(Debug, Serialize)]
211pub struct OKXSubscription {
212    pub op: OKXWsOperation,
213    pub args: Vec<OKXSubscriptionArg>,
214}
215
216#[derive(Clone, Debug)]
217pub struct OKXSubscriptionArg {
218    pub channel: OKXWsChannel,
219    pub inst_type: Option<OKXInstrumentType>,
220    pub inst_family: Option<Ustr>,
221    pub inst_id: Option<Ustr>,
222}
223
224impl Serialize for OKXSubscriptionArg {
225    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
226        use serde::ser::SerializeMap;
227
228        let mut map = serializer.serialize_map(None)?;
229        map.serialize_entry("channel", &self.channel)?;
230
231        if let Some(inst_type) = &self.inst_type {
232            map.serialize_entry("instType", inst_type)?;
233        }
234
235        if let Some(inst_family) = &self.inst_family {
236            map.serialize_entry("instFamily", inst_family)?;
237        }
238
239        if let Some(inst_id) = &self.inst_id {
240            let key = if self.channel.is_spread() {
241                "sprdId"
242            } else {
243                "instId"
244            };
245            map.serialize_entry(key, inst_id)?;
246        }
247
248        map.end()
249    }
250}
251
252/// OKX WebSocket message variants.
253///
254/// Uses custom deserialization that checks discriminant fields (event, op, action)
255/// to determine the correct variant.
256#[derive(Debug)]
257pub enum OKXWsFrame {
258    Login {
259        event: String,
260        code: String,
261        msg: String,
262        conn_id: String,
263    },
264    Subscription {
265        event: OKXSubscriptionEvent,
266        arg: OKXWebSocketArg,
267        conn_id: String,
268        code: Option<String>,
269        msg: Option<String>,
270    },
271    ChannelConnCount {
272        event: String,
273        channel: OKXWsChannel,
274        conn_count: String,
275        conn_id: String,
276    },
277    OrderResponse {
278        id: Option<String>,
279        op: OKXWsOperation,
280        code: String,
281        msg: String,
282        data: Vec<serde_json::Value>,
283    },
284    BookData {
285        arg: OKXWebSocketArg,
286        action: OKXBookAction,
287        data: Vec<OKXBookMsg>,
288    },
289    RpiBookData {
290        arg: OKXWebSocketArg,
291        action: OKXBookAction,
292        data: Vec<OKXRpiBookMsg>,
293    },
294    Data {
295        arg: OKXWebSocketArg,
296        data: serde_json::Value,
297    },
298    Error {
299        arg: Option<OKXWebSocketArg>,
300        code: String,
301        msg: String,
302    },
303    Ping,
304    Reconnected,
305}
306
307impl<'de> Deserialize<'de> for OKXWsFrame {
308    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
309    where
310        D: serde::Deserializer<'de>,
311    {
312        deserializer.deserialize_map(OKXWsFrameVisitor)
313    }
314}
315
316#[derive(Deserialize)]
317#[serde(field_identifier, rename_all = "camelCase")]
318enum OKXWsFrameKey {
319    Event,
320    Op,
321    Action,
322    Arg,
323    Data,
324    Code,
325    Msg,
326    ConnId,
327    Id,
328    Channel,
329    ConnCount,
330    #[serde(other)]
331    Other,
332}
333
334// Decodes a frame in one pass. Small fields are held as raw JSON text so the
335// variant is still chosen from field presence once every key is seen, while
336// `data` decodes straight into typed book levels when the keys before it fix
337// the type (OKX sends `arg` and `action` ahead of `data`). Buffering the whole
338// frame as a `serde_json::Value` tree dominated the inbound decode cost for L2
339// books, and holding `data` as raw text meant scanning it twice.
340#[derive(Default)]
341struct OKXWsFrameFields {
342    event: Option<Box<RawValue>>,
343    op: Option<Box<RawValue>>,
344    action: Option<Box<RawValue>>,
345    arg: Option<Box<RawValue>>,
346    arg_decoded: Option<OKXWebSocketArg>,
347    data: Option<OKXWsFrameData>,
348    code: Option<Box<RawValue>>,
349    msg: Option<Box<RawValue>>,
350    conn_id: Option<Box<RawValue>>,
351    id: Option<Box<RawValue>>,
352    channel: Option<Box<RawValue>>,
353    conn_count: Option<Box<RawValue>>,
354}
355
356enum OKXWsFrameData {
357    Value(serde_json::Value),
358    Book(Vec<OKXBookMsg>),
359    RpiBook(Vec<OKXRpiBookMsg>),
360}
361
362impl OKXWsFrameData {
363    fn into_value<E: serde::de::Error>(self) -> Result<serde_json::Value, E> {
364        match self {
365            Self::Value(value) => Ok(value),
366            Self::Book(_) | Self::RpiBook(_) => {
367                Err(E::custom("invalid data: book levels in a non-book frame"))
368            }
369        }
370    }
371}
372
373struct OKXWsFrameVisitor;
374
375impl<'de> Visitor<'de> for OKXWsFrameVisitor {
376    type Value = OKXWsFrame;
377
378    fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
379        formatter.write_str("JSON object for OKXWsFrame")
380    }
381
382    fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
383    where
384        A: MapAccess<'de>,
385    {
386        let mut fields = OKXWsFrameFields::default();
387
388        while let Some(key) = map.next_key::<OKXWsFrameKey>()? {
389            let slot = match key {
390                OKXWsFrameKey::Event => &mut fields.event,
391                OKXWsFrameKey::Op => &mut fields.op,
392                OKXWsFrameKey::Action => &mut fields.action,
393                OKXWsFrameKey::Arg => {
394                    fields.arg_decoded = None;
395                    &mut fields.arg
396                }
397                OKXWsFrameKey::Data => {
398                    fields.data = Some(fields.next_data(&mut map)?);
399                    continue;
400                }
401                OKXWsFrameKey::Code => &mut fields.code,
402                OKXWsFrameKey::Msg => &mut fields.msg,
403                OKXWsFrameKey::ConnId => &mut fields.conn_id,
404                OKXWsFrameKey::Id => &mut fields.id,
405                OKXWsFrameKey::Channel => &mut fields.channel,
406                OKXWsFrameKey::ConnCount => &mut fields.conn_count,
407                OKXWsFrameKey::Other => {
408                    map.next_value::<IgnoredAny>()?;
409                    continue;
410                }
411            };
412
413            *slot = Some(map.next_value()?);
414        }
415
416        fields.into_frame()
417    }
418}
419
420impl OKXWsFrameFields {
421    fn next_data<'de, A: MapAccess<'de>>(
422        &mut self,
423        map: &mut A,
424    ) -> Result<OKXWsFrameData, A::Error> {
425        let invalid_data = |e: A::Error| A::Error::custom(format!("invalid data: {e}"));
426
427        if self.event.is_none()
428            && self.op.is_none()
429            && self.action.is_some()
430            && let Some(raw) = self.arg.as_deref()
431        {
432            let arg: OKXWebSocketArg = parse_raw(raw, "arg")?;
433
434            let data = if arg.channel == OKXWsChannel::BooksRpi {
435                OKXWsFrameData::RpiBook(map.next_value().map_err(invalid_data)?)
436            } else {
437                OKXWsFrameData::Book(map.next_value().map_err(invalid_data)?)
438            };
439
440            self.arg_decoded = Some(arg);
441            return Ok(data);
442        }
443
444        Ok(OKXWsFrameData::Value(map.next_value()?))
445    }
446
447    fn take_arg<E: serde::de::Error>(&mut self) -> Result<OKXWebSocketArg, E> {
448        match self.arg_decoded.take() {
449            Some(arg) => Ok(arg),
450            None => take_typed(self.arg.take(), "arg"),
451        }
452    }
453
454    fn into_frame<E: serde::de::Error>(self) -> Result<OKXWsFrame, E> {
455        // Check discriminant fields in priority order
456
457        // 1. "event" field - Login, Subscription, ChannelConnCount, or Error
458        if let Some(event) = self.event.as_deref().and_then(raw_as_string) {
459            match event.as_str() {
460                "login" => return parse_login(self),
461                "subscribe" | "unsubscribe" => return parse_subscription(self),
462                "error" => return parse_error(self),
463                _ if self.channel.is_some() && self.conn_count.is_some() => {
464                    return parse_channel_conn_count(self);
465                }
466                _ => {}
467            }
468        }
469
470        // 2. "op" field - OrderResponse
471        if self.op.is_some() {
472            return parse_order_response(self);
473        }
474
475        // 3. "action" + "arg" - BookData
476        if self.action.is_some() && self.arg.is_some() {
477            return parse_book_data(self);
478        }
479
480        // 4. "arg" + "data" without "action" - Data
481        if self.arg.is_some() && self.data.is_some() {
482            return parse_data(self);
483        }
484
485        // 5. Fallback to Error if it has "code" and "msg"
486        if self.code.is_some() && self.msg.is_some() {
487            return parse_error(self);
488        }
489
490        Err(E::custom("cannot determine OKXWsFrame variant"))
491    }
492}
493
494fn raw_as_string(raw: &RawValue) -> Option<String> {
495    serde_json::from_str(raw.get()).ok()
496}
497
498fn parse_raw<T: DeserializeOwned, E: serde::de::Error>(
499    raw: &RawValue,
500    key: &'static str,
501) -> Result<T, E> {
502    serde_json::from_str(raw.get()).map_err(|e| E::custom(format!("invalid {key}: {e}")))
503}
504
505fn take_typed<T: DeserializeOwned, E: serde::de::Error>(
506    raw: Option<Box<RawValue>>,
507    key: &'static str,
508) -> Result<T, E> {
509    let raw = raw.ok_or_else(|| E::missing_field(key))?;
510    parse_raw(&raw, key)
511}
512
513fn take_data_typed<T: DeserializeOwned, E: serde::de::Error>(data: OKXWsFrameData) -> Result<T, E> {
514    serde_json::from_value(data.into_value()?).map_err(|e| E::custom(format!("invalid data: {e}")))
515}
516
517fn take_str<E: serde::de::Error>(
518    raw: Option<Box<RawValue>>,
519    key: &'static str,
520) -> Result<String, E> {
521    let raw = raw.ok_or_else(|| E::missing_field(key))?;
522    raw_as_string(&raw).ok_or_else(|| E::custom(format!("field `{key}` is not a string")))
523}
524
525fn take_optional_str(raw: Option<Box<RawValue>>) -> Option<String> {
526    raw.and_then(|raw| raw_as_string(&raw))
527}
528
529fn parse_login<E: serde::de::Error>(fields: OKXWsFrameFields) -> Result<OKXWsFrame, E> {
530    Ok(OKXWsFrame::Login {
531        event: take_str(fields.event, "event")?,
532        code: take_str(fields.code, "code")?,
533        msg: take_str(fields.msg, "msg")?,
534        conn_id: take_str(fields.conn_id, "connId")?,
535    })
536}
537
538fn parse_subscription<E: serde::de::Error>(mut fields: OKXWsFrameFields) -> Result<OKXWsFrame, E> {
539    let event: OKXSubscriptionEvent = take_typed(fields.event.take(), "event")?;
540    let arg = fields.take_arg()?;
541
542    Ok(OKXWsFrame::Subscription {
543        event,
544        arg,
545        conn_id: take_str(fields.conn_id, "connId")?,
546        code: take_optional_str(fields.code),
547        msg: take_optional_str(fields.msg),
548    })
549}
550
551fn parse_channel_conn_count<E: serde::de::Error>(
552    fields: OKXWsFrameFields,
553) -> Result<OKXWsFrame, E> {
554    let channel: OKXWsChannel = take_typed(fields.channel, "channel")?;
555
556    Ok(OKXWsFrame::ChannelConnCount {
557        event: take_str(fields.event, "event")?,
558        channel,
559        conn_count: take_str(fields.conn_count, "connCount")?,
560        conn_id: take_str(fields.conn_id, "connId")?,
561    })
562}
563
564fn parse_order_response<E: serde::de::Error>(fields: OKXWsFrameFields) -> Result<OKXWsFrame, E> {
565    let op: OKXWsOperation = take_typed(fields.op, "op")?;
566
567    let data: Vec<serde_json::Value> = match fields.data {
568        Some(OKXWsFrameData::Value(serde_json::Value::Array(values))) => values,
569        Some(data) => take_data_typed(data)?,
570        None => Vec::new(),
571    };
572
573    Ok(OKXWsFrame::OrderResponse {
574        id: take_optional_str(fields.id),
575        op,
576        code: take_str(fields.code, "code")?,
577        msg: take_str(fields.msg, "msg")?,
578        data,
579    })
580}
581
582fn parse_book_data<E: serde::de::Error>(mut fields: OKXWsFrameFields) -> Result<OKXWsFrame, E> {
583    let arg = fields.take_arg()?;
584    let action: OKXBookAction = take_typed(fields.action, "action")?;
585    let data = fields.data.ok_or_else(|| E::missing_field("data"))?;
586
587    if arg.channel == OKXWsChannel::BooksRpi {
588        let data: Vec<OKXRpiBookMsg> = match data {
589            OKXWsFrameData::RpiBook(data) => data,
590            data => take_data_typed(data)?,
591        };
592
593        return Ok(OKXWsFrame::RpiBookData { arg, action, data });
594    }
595
596    let data: Vec<OKXBookMsg> = match data {
597        OKXWsFrameData::Book(data) => data,
598        data => take_data_typed(data)?,
599    };
600
601    Ok(OKXWsFrame::BookData { arg, action, data })
602}
603
604fn parse_data<E: serde::de::Error>(mut fields: OKXWsFrameFields) -> Result<OKXWsFrame, E> {
605    let arg = fields.take_arg()?;
606    let data = fields
607        .data
608        .ok_or_else(|| E::missing_field("data"))?
609        .into_value()?;
610
611    Ok(OKXWsFrame::Data { arg, data })
612}
613
614fn parse_error<E: serde::de::Error>(mut fields: OKXWsFrameFields) -> Result<OKXWsFrame, E> {
615    let arg = if fields.arg.is_some() {
616        Some(fields.take_arg()?)
617    } else {
618        None
619    };
620
621    Ok(OKXWsFrame::Error {
622        arg,
623        code: take_str(fields.code, "code")?,
624        msg: take_str(fields.msg, "msg")?,
625    })
626}
627
628#[derive(Debug, Serialize, Deserialize)]
629#[serde(rename_all = "camelCase")]
630pub struct OKXWebSocketArg {
631    /// Channel name that pushed the data.
632    pub channel: OKXWsChannel,
633    // Spread channels identify the instrument by `sprdId`; a spread's symbol equals
634    // its `sprdId`, and a message carries `instId` xor `sprdId`, so the alias resolves
635    // both to one field without collision.
636    #[serde(default, alias = "sprdId")]
637    pub inst_id: Option<Ustr>,
638    #[serde(default)]
639    pub inst_type: Option<OKXInstrumentType>,
640    #[serde(default)]
641    pub inst_family: Option<Ustr>,
642    #[serde(default)]
643    pub bar: Option<Ustr>,
644}
645
646/// Ticker data for an instrument.
647#[derive(Debug, Serialize, Deserialize)]
648#[serde(rename_all = "camelCase")]
649pub struct OKXTickerMsg {
650    /// Instrument type, e.g. "SPOT", "SWAP".
651    pub inst_type: OKXInstrumentType,
652    /// Instrument ID, e.g. "BTC-USDT".
653    pub inst_id: Ustr,
654    /// Last traded price.
655    #[serde(rename = "last")]
656    pub last_px: String,
657    /// Last traded size.
658    pub last_sz: String,
659    /// Best ask price.
660    pub ask_px: String,
661    /// Best ask size.
662    pub ask_sz: String,
663    /// Best bid price.
664    pub bid_px: String,
665    /// Best bid size.
666    pub bid_sz: String,
667    /// 24-hour opening price.
668    pub open24h: String,
669    /// 24-hour highest price.
670    pub high24h: String,
671    /// 24-hour lowest price.
672    pub low24h: String,
673    /// 24-hour trading volume in quote currency.
674    pub vol_ccy_24h: String,
675    /// 24-hour trading volume.
676    pub vol24h: String,
677    /// The opening price of the day (UTC 0).
678    pub sod_utc0: String,
679    /// The opening price of the day (UTC 8).
680    pub sod_utc8: String,
681    /// Timestamp of the data generation, Unix timestamp format in milliseconds.
682    #[serde(deserialize_with = "deserialize_string_to_u64")]
683    pub ts: u64,
684    /// Order source for RPI liquidity identification.
685    #[serde(default)]
686    pub source: Option<String>,
687}
688
689/// Represents a single order in the order book.
690#[derive(Debug, Serialize, Deserialize)]
691pub struct OrderBookEntry {
692    /// Price of the order.
693    pub price: String,
694    /// Size of the order.
695    pub size: String,
696    // Spread book levels (`sprd-books5`) are 3-element `[price, size, count]`,
697    // omitting the liquidated-orders field standard books carry; default the
698    // trailing counts so both array shapes deserialize, spread order counts
699    // occupy `liquidated_orders_count`.
700    /// Number of liquidated orders.
701    #[serde(default)]
702    pub liquidated_orders_count: String,
703    /// Total number of orders at this price.
704    #[serde(default)]
705    pub orders_count: String,
706}
707
708/// Order book data for an instrument.
709#[derive(Debug, Serialize, Deserialize)]
710#[serde(rename_all = "camelCase")]
711pub struct OKXBookMsg {
712    /// Order book asks [price, size, liquidated orders count, orders count].
713    pub asks: Vec<OrderBookEntry>,
714    /// Order book bids [price, size, liquidated orders count, orders count].
715    pub bids: Vec<OrderBookEntry>,
716    /// Checksum value.
717    pub checksum: Option<i64>,
718    /// Sequence ID of the last sent message. Only applicable to books, books-l2-tbt, books50-l2-tbt.
719    pub prev_seq_id: Option<i64>,
720    /// Sequence ID of the current message, implementation details below.
721    pub seq_id: u64,
722    /// Order book generation time, Unix timestamp format in milliseconds, e.g. 1597026383085.
723    #[serde(deserialize_with = "deserialize_string_to_u64")]
724    pub ts: u64,
725}
726
727/// Retail Price Improvement order book data for an instrument.
728#[derive(Debug, Serialize, Deserialize)]
729#[serde(rename_all = "camelCase", deny_unknown_fields)]
730pub struct OKXRpiBookMsg {
731    /// Ask levels [price, total quantity, non-RPI quantity, order count].
732    pub asks: Vec<OKXRpiBookLevel>,
733    /// Bid levels [price, total quantity, non-RPI quantity, order count].
734    pub bids: Vec<OKXRpiBookLevel>,
735    /// Sequence ID of the previous message.
736    pub prev_seq_id: i64,
737    /// Sequence ID of the current message.
738    pub seq_id: u64,
739    /// Order book generation time, Unix timestamp in milliseconds.
740    #[serde(deserialize_with = "deserialize_string_to_u64")]
741    pub ts: u64,
742}
743
744/// Trade data for an instrument.
745#[derive(Debug, Serialize, Deserialize)]
746#[serde(rename_all = "camelCase")]
747pub struct OKXTradeMsg {
748    // Spread public trades (`sprd-public-trades`) key the instrument as `sprdId`
749    // and omit `count`; the actual instrument is resolved from the channel arg, so
750    // both fields are tolerated here and unused by parsing.
751    /// Instrument ID (`instId`, or `sprdId` for spread public trades).
752    #[serde(default, alias = "sprdId")]
753    pub inst_id: Ustr,
754    /// Trade ID.
755    pub trade_id: String,
756    /// Trade price.
757    pub px: String,
758    /// Trade size.
759    pub sz: String,
760    /// Trade direction (buy or sell).
761    pub side: OKXSide,
762    /// Count (absent on spread public trades).
763    #[serde(default)]
764    pub count: String,
765    /// Trade timestamp, Unix timestamp format in milliseconds.
766    #[serde(deserialize_with = "deserialize_string_to_u64")]
767    pub ts: u64,
768    /// Order source (0: normal, 1: RPI).
769    #[serde(default)]
770    pub source: Option<String>,
771    /// Sequence ID for trade events.
772    #[serde(default)]
773    pub seq_id: Option<u64>,
774}
775
776/// Funding rate data for perpetual swaps.
777#[derive(Debug, Serialize, Deserialize)]
778#[serde(rename_all = "camelCase")]
779pub struct OKXFundingRateMsg {
780    /// Instrument type.
781    #[serde(default)]
782    pub inst_type: Option<OKXInstrumentType>,
783    /// Instrument ID.
784    pub inst_id: Ustr,
785    /// Current funding rate.
786    pub funding_rate: Ustr,
787    /// Predicted next funding rate.
788    pub next_funding_rate: Ustr,
789    /// Minimum funding rate.
790    #[serde(default)]
791    pub min_funding_rate: Option<String>,
792    /// Maximum funding rate.
793    #[serde(default)]
794    pub max_funding_rate: Option<String>,
795    /// Settlement state.
796    #[serde(default)]
797    pub sett_state: OKXSettlementState,
798    /// Settlement funding rate.
799    #[serde(default)]
800    pub sett_funding_rate: Option<String>,
801    /// Current premium.
802    #[serde(default)]
803    pub premium: Option<String>,
804    /// Funding rate calculation method.
805    #[serde(default)]
806    pub method: Option<String>,
807    /// Funding time, Unix timestamp format in milliseconds.
808    #[serde(deserialize_with = "deserialize_string_to_u64")]
809    pub funding_time: u64,
810    /// Next funding time, Unix timestamp format in milliseconds (used to determine funding interval).
811    #[serde(deserialize_with = "deserialize_string_to_u64")]
812    pub next_funding_time: u64,
813    /// Message timestamp, Unix timestamp format in milliseconds.
814    #[serde(deserialize_with = "deserialize_string_to_u64")]
815    pub ts: u64,
816}
817
818/// Mark price data for perpetual swaps.
819#[derive(Debug, Serialize, Deserialize)]
820#[serde(rename_all = "camelCase")]
821pub struct OKXMarkPriceMsg {
822    /// Instrument ID.
823    pub inst_id: Ustr,
824    /// Current mark price.
825    pub mark_px: String,
826    /// Timestamp of the data generation, Unix timestamp format in milliseconds.
827    #[serde(deserialize_with = "deserialize_string_to_u64")]
828    pub ts: u64,
829}
830
831/// Index price data.
832#[derive(Debug, Serialize, Deserialize)]
833#[serde(rename_all = "camelCase")]
834pub struct OKXIndexPriceMsg {
835    /// Index name, e.g. "BTC-USD".
836    pub inst_id: Ustr,
837    /// Latest index price.
838    pub idx_px: String,
839    /// 24-hour highest price.
840    pub high24h: String,
841    /// 24-hour lowest price.
842    pub low24h: String,
843    /// 24-hour opening price.
844    pub open24h: String,
845    /// The opening price of the day (UTC 0).
846    pub sod_utc0: String,
847    /// The opening price of the day (UTC 8).
848    pub sod_utc8: String,
849    /// Timestamp of the data generation, Unix timestamp format in milliseconds.
850    #[serde(deserialize_with = "deserialize_string_to_u64")]
851    pub ts: u64,
852}
853
854/// Price limit data (upper and lower limits).
855#[derive(Debug, Serialize, Deserialize)]
856#[serde(rename_all = "camelCase")]
857pub struct OKXPriceLimitMsg {
858    /// Instrument ID.
859    pub inst_id: Ustr,
860    /// Buy limit price.
861    pub buy_lmt: String,
862    /// Sell limit price.
863    pub sell_lmt: String,
864    /// Timestamp of the data generation, Unix timestamp format in milliseconds.
865    #[serde(deserialize_with = "deserialize_string_to_u64")]
866    pub ts: u64,
867}
868
869/// Candlestick data for an instrument.
870#[derive(Debug, Serialize, Deserialize)]
871#[serde(rename_all = "camelCase")]
872pub struct OKXCandleMsg {
873    /// Candlestick timestamp, Unix timestamp format in milliseconds.
874    #[serde(deserialize_with = "deserialize_string_to_u64")]
875    pub ts: u64,
876    /// Opening price.
877    pub o: String,
878    /// Highest price.
879    pub h: String,
880    /// Lowest price.
881    pub l: String,
882    /// Closing price.
883    pub c: String,
884    /// Trading volume in contracts.
885    pub vol: String,
886    /// Trading volume in quote currency.
887    pub vol_ccy: String,
888    pub vol_ccy_quote: String,
889    /// Whether this is a completed candle.
890    pub confirm: OKXCandleConfirm,
891}
892
893/// Open interest data.
894#[derive(Debug, Serialize, Deserialize)]
895#[serde(rename_all = "camelCase")]
896pub struct OKXOpenInterestMsg {
897    /// Instrument ID.
898    pub inst_id: Ustr,
899    /// Open interest in contracts.
900    pub oi: String,
901    /// Open interest in quote currency.
902    pub oi_ccy: String,
903    /// Timestamp of the data generation, Unix timestamp format in milliseconds.
904    #[serde(deserialize_with = "deserialize_string_to_u64")]
905    pub ts: u64,
906}
907
908/// Option market data summary.
909#[derive(Debug, Serialize, Deserialize)]
910#[serde(rename_all = "camelCase")]
911pub struct OKXOptionSummaryMsg {
912    /// Instrument type.
913    #[serde(default)]
914    pub inst_type: Option<OKXInstrumentType>,
915    /// Instrument ID.
916    pub inst_id: Ustr,
917    /// Underlying.
918    pub uly: String,
919    /// Delta.
920    pub delta: String,
921    /// Gamma.
922    pub gamma: String,
923    /// Theta.
924    pub theta: String,
925    /// Vega.
926    pub vega: String,
927    /// Black-Scholes delta.
928    #[serde(alias = "deltaBS")]
929    pub delta_bs: String,
930    /// Black-Scholes gamma.
931    #[serde(alias = "gammaBS")]
932    pub gamma_bs: String,
933    /// Black-Scholes theta.
934    #[serde(alias = "thetaBS")]
935    pub theta_bs: String,
936    /// Black-Scholes vega.
937    #[serde(alias = "vegaBS")]
938    pub vega_bs: String,
939    /// Realized volatility.
940    pub real_vol: String,
941    /// Bid volatility.
942    pub bid_vol: String,
943    /// Ask volatility.
944    pub ask_vol: String,
945    /// Mark volatility.
946    pub mark_vol: String,
947    /// Leverage.
948    pub lever: String,
949    /// Forward price.
950    #[serde(default)]
951    pub fwd_px: Option<String>,
952    /// Mark price.
953    #[serde(default)]
954    pub mark_px: Option<String>,
955    /// Volatility level.
956    #[serde(default)]
957    pub vol_lv: Option<String>,
958    /// Timestamp of the data generation, Unix timestamp format in milliseconds.
959    #[serde(deserialize_with = "deserialize_string_to_u64")]
960    pub ts: u64,
961}
962
963/// Estimated delivery/exercise price data.
964#[derive(Debug, Serialize, Deserialize)]
965#[serde(rename_all = "camelCase")]
966pub struct OKXEstimatedPriceMsg {
967    /// Instrument ID.
968    pub inst_id: Ustr,
969    /// Estimated settlement price.
970    pub settle_px: String,
971    /// Timestamp of the data generation, Unix timestamp format in milliseconds.
972    #[serde(deserialize_with = "deserialize_string_to_u64")]
973    pub ts: u64,
974}
975
976/// Platform status updates.
977#[derive(Debug, Serialize, Deserialize)]
978#[serde(rename_all = "camelCase")]
979pub struct OKXStatusMsg {
980    /// System maintenance status.
981    pub title: Ustr,
982    /// Status type: planned or scheduled.
983    #[serde(rename = "type")]
984    pub status_type: Ustr,
985    /// System maintenance state: canceled, completed, pending, ongoing.
986    pub state: Ustr,
987    /// Expected completion timestamp.
988    pub end_time: Option<String>,
989    /// Planned start timestamp.
990    pub begin_time: Option<String>,
991    /// Service involved.
992    pub service_type: Option<Ustr>,
993    /// Reason for status change.
994    pub reason: Option<String>,
995    /// Timestamp of the data generation, Unix timestamp format in milliseconds.
996    #[serde(deserialize_with = "deserialize_string_to_u64")]
997    pub ts: u64,
998}
999
1000pub use crate::common::models::OKXAttachedAlgoOrd;
1001
1002/// Liquidation risk warning pushed by the `liquidation-warning` channel.
1003///
1004/// OKX sends this when an isolated position, or all positions under cross
1005/// margin, approach liquidation. It is a risk warning only: the position may
1006/// already be liquidated by the time the message arrives.
1007#[derive(Clone, Debug, Serialize, Deserialize)]
1008#[serde(rename_all = "camelCase")]
1009pub struct OKXLiquidationWarningMsg {
1010    /// Instrument type.
1011    pub inst_type: OKXInstrumentType,
1012    /// Instrument family.
1013    #[serde(default)]
1014    pub inst_family: Option<Ustr>,
1015    /// Instrument ID.
1016    pub inst_id: Ustr,
1017    /// Margin mode.
1018    pub mgn_mode: OKXMarginMode,
1019    /// Position ID.
1020    #[serde(default)]
1021    pub pos_id: Option<Ustr>,
1022    /// Position side.
1023    pub pos_side: OKXPositionSide,
1024    /// Position quantity.
1025    pub pos: String,
1026    /// Position currency (margin positions only).
1027    #[serde(default)]
1028    pub pos_ccy: Option<Ustr>,
1029    /// Leverage.
1030    pub lever: String,
1031    /// Mark price.
1032    pub mark_px: String,
1033    /// Maintenance margin ratio.
1034    pub mgn_ratio: String,
1035    /// Margin currency.
1036    pub ccy: Ustr,
1037    /// Creation time, Unix timestamp in milliseconds.
1038    #[serde(deserialize_with = "deserialize_string_to_u64")]
1039    pub c_time: u64,
1040    /// Last update time, Unix timestamp in milliseconds.
1041    #[serde(deserialize_with = "deserialize_string_to_u64")]
1042    pub u_time: u64,
1043    /// Push time, Unix timestamp in milliseconds.
1044    #[serde(default)]
1045    pub p_time: Option<String>,
1046}
1047
1048/// Linked algo order metadata from order push updates.
1049#[derive(Clone, Debug, Default, Serialize, Deserialize)]
1050#[serde(rename_all = "camelCase")]
1051pub struct OKXLinkedAlgoOrd {
1052    /// Parent algo order ID.
1053    #[serde(default)]
1054    pub algo_id: String,
1055}
1056
1057/// Order update message from WebSocket orders channel.
1058#[derive(Clone, Debug, Serialize, Deserialize)]
1059#[serde(rename_all = "camelCase")]
1060pub struct OKXOrderMsg {
1061    /// Accumulated filled size.
1062    #[serde(default, deserialize_with = "deserialize_empty_string_as_none")]
1063    pub acc_fill_sz: Option<String>,
1064    /// Algo order ID.
1065    #[serde(default, deserialize_with = "deserialize_empty_string_as_none")]
1066    pub algo_id: Option<String>,
1067    /// Average price.
1068    pub avg_px: String,
1069    /// Creation time, Unix timestamp in milliseconds.
1070    #[serde(deserialize_with = "deserialize_string_to_u64")]
1071    pub c_time: u64,
1072    /// Cancel source.
1073    #[serde(default)]
1074    pub cancel_source: Option<String>,
1075    /// Cancel source reason.
1076    #[serde(default)]
1077    pub cancel_source_reason: Option<String>,
1078    /// Order category (normal, liquidation, ADL, etc.).
1079    pub category: OKXOrderCategory,
1080    /// Currency.
1081    pub ccy: Ustr,
1082    /// Client order ID.
1083    pub cl_ord_id: String,
1084    /// Parent algo client order ID if present.
1085    #[serde(default, deserialize_with = "deserialize_empty_string_as_none")]
1086    pub algo_cl_ord_id: Option<String>,
1087    /// Attached child client order ID if surfaced at the top level.
1088    #[serde(default, deserialize_with = "deserialize_empty_string_as_none")]
1089    pub attach_algo_cl_ord_id: Option<String>,
1090    /// Attached TP/SL child order metadata.
1091    #[serde(default)]
1092    pub attach_algo_ords: Vec<OKXAttachedAlgoOrd>,
1093    /// Event contract market outcome, if applicable.
1094    #[serde(default, deserialize_with = "deserialize_empty_string_as_none")]
1095    pub outcome: Option<String>,
1096    /// Fee (cumulative).
1097    #[serde(default, deserialize_with = "deserialize_empty_string_as_none")]
1098    pub fee: Option<String>,
1099    /// Fee currency.
1100    pub fee_ccy: Ustr,
1101    /// Fee for this fill.
1102    #[serde(default, deserialize_with = "deserialize_empty_string_as_none")]
1103    pub fill_fee: Option<String>,
1104    /// Fill fee currency.
1105    #[serde(default, deserialize_with = "deserialize_empty_ustr_as_none")]
1106    pub fill_fee_ccy: Option<Ustr>,
1107    /// Mark price at fill time.
1108    #[serde(default, deserialize_with = "deserialize_empty_string_as_none")]
1109    pub fill_mark_px: Option<String>,
1110    /// Mark volatility at fill time (options).
1111    #[serde(default, deserialize_with = "deserialize_empty_string_as_none")]
1112    pub fill_mark_vol: Option<String>,
1113    /// Implied volatility at fill time (options).
1114    #[serde(default, deserialize_with = "deserialize_empty_string_as_none")]
1115    pub fill_px_vol: Option<String>,
1116    /// Fill price in USD (options).
1117    #[serde(default, deserialize_with = "deserialize_empty_string_as_none")]
1118    pub fill_px_usd: Option<String>,
1119    /// Forward price at fill time (options).
1120    #[serde(default, deserialize_with = "deserialize_empty_string_as_none")]
1121    pub fill_fwd_px: Option<String>,
1122    /// Fill notional in USD.
1123    #[serde(default, deserialize_with = "deserialize_empty_string_as_none")]
1124    pub fill_notional_usd: Option<String>,
1125    /// PnL for this fill.
1126    #[serde(default, deserialize_with = "deserialize_empty_string_as_none")]
1127    pub fill_pnl: Option<String>,
1128    /// Fill price.
1129    pub fill_px: String,
1130    /// Fill size.
1131    pub fill_sz: String,
1132    /// Fill time, Unix timestamp in milliseconds.
1133    #[serde(deserialize_with = "deserialize_string_to_u64")]
1134    pub fill_time: u64,
1135    /// Instrument ID.
1136    pub inst_id: Ustr,
1137    /// Instrument type.
1138    pub inst_type: OKXInstrumentType,
1139    /// Whether the TP order is a limit order.
1140    #[serde(default)]
1141    pub is_tp_limit: Option<String>,
1142    /// Leverage.
1143    pub lever: String,
1144    /// Linked algo order metadata.
1145    #[serde(default)]
1146    pub linked_algo_ord: Option<OKXLinkedAlgoOrd>,
1147    /// Notional value in USD.
1148    #[serde(default, deserialize_with = "deserialize_empty_string_as_none")]
1149    pub notional_usd: Option<String>,
1150    /// Order ID.
1151    pub ord_id: Ustr,
1152    /// Order type.
1153    pub ord_type: OKXOrderType,
1154    /// Profit and loss.
1155    pub pnl: String,
1156    /// Position side.
1157    pub pos_side: OKXPositionSide,
1158    /// Price (algo orders use ordPx instead).
1159    #[serde(default)]
1160    pub px: String,
1161    /// Price type (options).
1162    #[serde(default)]
1163    pub px_type: OKXPriceType,
1164    /// Price in USD (options).
1165    #[serde(default)]
1166    pub px_usd: Option<String>,
1167    /// Price in volatility (options).
1168    #[serde(default)]
1169    pub px_vol: Option<String>,
1170    /// Quick margin type.
1171    #[serde(default)]
1172    pub quick_mgn_type: OKXQuickMarginType,
1173    /// Rebate amount.
1174    #[serde(default, deserialize_with = "deserialize_empty_string_as_none")]
1175    pub rebate: Option<String>,
1176    /// Rebate currency.
1177    #[serde(default, deserialize_with = "deserialize_empty_ustr_as_none")]
1178    pub rebate_ccy: Option<Ustr>,
1179    /// Reduce only flag.
1180    pub reduce_only: String,
1181    /// Side.
1182    pub side: OKXSide,
1183    /// Stop-loss order price.
1184    #[serde(default)]
1185    pub sl_ord_px: Option<String>,
1186    /// Stop-loss trigger price.
1187    #[serde(default)]
1188    pub sl_trigger_px: Option<String>,
1189    /// Stop-loss trigger price type (last, mark, index).
1190    #[serde(default)]
1191    pub sl_trigger_px_type: Option<OKXTriggerType>,
1192    /// Order source.
1193    #[serde(default)]
1194    pub source: Option<String>,
1195    /// Order state.
1196    pub state: OKXOrderStatus,
1197    /// Self-trade prevention ID.
1198    #[serde(default)]
1199    pub stp_id: Option<String>,
1200    /// Self-trade prevention mode.
1201    #[serde(default)]
1202    pub stp_mode: OKXSelfTradePreventionMode,
1203    /// Execution type.
1204    pub exec_type: OKXExecType,
1205    /// Size.
1206    pub sz: String,
1207    /// Order tag.
1208    #[serde(default)]
1209    pub tag: Option<String>,
1210    /// Trade mode.
1211    pub td_mode: OKXTradeMode,
1212    /// Quantity unit for spot market orders (`base_ccy` or `quote_ccy`).
1213    #[serde(default, deserialize_with = "deserialize_target_currency_as_none")]
1214    pub tgt_ccy: Option<OKXTargetCurrency>,
1215    /// Take-profit order price.
1216    #[serde(default)]
1217    pub tp_ord_px: Option<String>,
1218    /// Take-profit trigger price.
1219    #[serde(default)]
1220    pub tp_trigger_px: Option<String>,
1221    /// Take-profit trigger price type (last, mark, index).
1222    #[serde(default)]
1223    pub tp_trigger_px_type: Option<OKXTriggerType>,
1224    /// Trade ID.
1225    pub trade_id: String,
1226    /// Last update time, Unix timestamp in milliseconds.
1227    #[serde(deserialize_with = "deserialize_string_to_u64")]
1228    pub u_time: u64,
1229    /// Amend result code.
1230    #[serde(default)]
1231    pub amend_result: Option<String>,
1232    /// Request ID (for amend responses).
1233    #[serde(default)]
1234    pub req_id: Option<String>,
1235    /// Error code.
1236    #[serde(default)]
1237    pub code: Option<String>,
1238    /// Error message.
1239    #[serde(default)]
1240    pub msg: Option<String>,
1241}
1242
1243/// Represents an algo order message from WebSocket updates.
1244#[derive(Clone, Debug, Deserialize, Serialize)]
1245#[serde(rename_all = "camelCase")]
1246pub struct OKXAlgoOrderMsg {
1247    /// Algorithm ID.
1248    pub algo_id: String,
1249    /// Algorithm client order ID.
1250    #[serde(default)]
1251    pub algo_cl_ord_id: String,
1252    /// Client order ID (empty for algo orders until triggered).
1253    pub cl_ord_id: String,
1254    /// Order ID (empty until algo order is triggered).
1255    pub ord_id: String,
1256    /// Triggered child order IDs.
1257    #[serde(default)]
1258    pub ord_id_list: Vec<String>,
1259    /// Instrument ID.
1260    pub inst_id: Ustr,
1261    /// Instrument type.
1262    pub inst_type: OKXInstrumentType,
1263    /// Algo order type (trigger, `move_order_stop`, oco, iceberg, twap).
1264    pub ord_type: OKXAlgoOrderType,
1265    /// Order state.
1266    pub state: OKXAlgoOrderStatus,
1267    /// Side.
1268    pub side: OKXSide,
1269    /// Position side.
1270    pub pos_side: OKXPositionSide,
1271    /// Size.
1272    #[serde(default)]
1273    pub sz: String,
1274    /// Trigger price.
1275    #[serde(default)]
1276    pub trigger_px: String,
1277    /// Trigger price type (last, mark, index).
1278    #[serde(default)]
1279    pub trigger_px_type: OKXTriggerType,
1280    /// Stop-loss trigger price for conditional close orders.
1281    #[serde(default)]
1282    pub sl_trigger_px: String,
1283    /// Stop-loss order price for conditional close orders.
1284    #[serde(default)]
1285    pub sl_ord_px: String,
1286    /// Stop-loss trigger price type (last, mark, index).
1287    #[serde(default)]
1288    pub sl_trigger_px_type: OKXTriggerType,
1289    /// Take-profit trigger price for conditional close orders.
1290    #[serde(default)]
1291    pub tp_trigger_px: String,
1292    /// Take-profit order price for conditional close orders.
1293    #[serde(default)]
1294    pub tp_ord_px: String,
1295    /// Take-profit trigger price type (last, mark, index).
1296    #[serde(default)]
1297    pub tp_trigger_px_type: OKXTriggerType,
1298    /// Order price (-1 for market orders).
1299    #[serde(default)]
1300    pub ord_px: String,
1301    /// Trade mode.
1302    pub td_mode: OKXTradeMode,
1303    /// Leverage.
1304    pub lever: String,
1305    /// Reduce only flag.
1306    #[serde(default)]
1307    pub reduce_only: String,
1308    /// Fraction of the position to close for close-order algos.
1309    #[serde(default)]
1310    pub close_fraction: String,
1311    /// Actual filled price.
1312    #[serde(default)]
1313    pub actual_px: String,
1314    /// Actual filled size.
1315    #[serde(default)]
1316    pub actual_sz: String,
1317    /// Notional USD value.
1318    #[serde(default)]
1319    pub notional_usd: String,
1320    /// Creation time, Unix timestamp in milliseconds.
1321    #[serde(deserialize_with = "deserialize_string_to_u64")]
1322    pub c_time: u64,
1323    /// Update time, Unix timestamp in milliseconds.
1324    #[serde(deserialize_with = "deserialize_string_to_u64")]
1325    pub u_time: u64,
1326    /// Trigger time (empty until triggered).
1327    #[serde(default)]
1328    pub trigger_time: String,
1329    /// Failure code for rejected algo orders.
1330    #[serde(default)]
1331    pub fail_code: String,
1332    /// Tag.
1333    #[serde(default)]
1334    pub tag: String,
1335    /// Callback price ratio for trailing stop (e.g. "0.01" for 1%).
1336    #[serde(default)]
1337    pub callback_ratio: String,
1338    /// Callback price spread for trailing stop (absolute distance).
1339    #[serde(default)]
1340    pub callback_spread: String,
1341    /// Activation price for trailing stop.
1342    #[serde(default)]
1343    pub active_px: String,
1344    /// Currency.
1345    #[serde(default, deserialize_with = "deserialize_empty_ustr_as_none")]
1346    pub ccy: Option<Ustr>,
1347    /// Target currency (`base_ccy` or `quote_ccy`).
1348    #[serde(default, deserialize_with = "deserialize_target_currency_as_none")]
1349    pub tgt_ccy: Option<OKXTargetCurrency>,
1350    /// Fee amount.
1351    #[serde(default)]
1352    pub fee: Option<String>,
1353    /// Fee currency.
1354    #[serde(default, deserialize_with = "deserialize_empty_ustr_as_none")]
1355    pub fee_ccy: Option<Ustr>,
1356    /// Trigger order type (fok, ioc).
1357    #[serde(default, deserialize_with = "deserialize_empty_string_as_none")]
1358    pub advance_ord_type: Option<String>,
1359}
1360
1361/// Parameters for WebSocket place order operation.
1362#[derive(Clone, Debug, Default, Deserialize, Serialize, Builder)]
1363#[builder(default)]
1364#[builder(setter(into, strip_option))]
1365#[serde(rename_all = "camelCase")]
1366pub struct WsAttachAlgoOrdParams {
1367    /// Attached algo client order ID.
1368    #[serde(skip_serializing_if = "Option::is_none")]
1369    pub attach_algo_cl_ord_id: Option<String>,
1370    /// Stop-loss trigger price.
1371    #[serde(skip_serializing_if = "Option::is_none")]
1372    pub sl_trigger_px: Option<String>,
1373    /// Stop-loss order price (`-1` for market).
1374    #[serde(skip_serializing_if = "Option::is_none")]
1375    pub sl_ord_px: Option<String>,
1376    /// Stop-loss trigger price type (last, mark, index).
1377    #[serde(skip_serializing_if = "Option::is_none")]
1378    pub sl_trigger_px_type: Option<OKXTriggerType>,
1379    /// Take-profit trigger price.
1380    #[serde(skip_serializing_if = "Option::is_none")]
1381    pub tp_trigger_px: Option<String>,
1382    /// Take-profit order price (`-1` for market).
1383    #[serde(skip_serializing_if = "Option::is_none")]
1384    pub tp_ord_px: Option<String>,
1385    /// Take-profit trigger price type (last, mark, index).
1386    #[serde(skip_serializing_if = "Option::is_none")]
1387    pub tp_trigger_px_type: Option<OKXTriggerType>,
1388    /// Callback ratio for attached trailing stop orders.
1389    #[serde(skip_serializing_if = "Option::is_none")]
1390    pub callback_ratio: Option<String>,
1391    /// Callback spread for attached trailing stop orders.
1392    #[serde(skip_serializing_if = "Option::is_none")]
1393    pub callback_spread: Option<String>,
1394    /// Activation price for attached trailing stop orders.
1395    #[serde(skip_serializing_if = "Option::is_none")]
1396    pub active_px: Option<String>,
1397    /// New callback ratio for amended attached trailing stop orders.
1398    #[serde(skip_serializing_if = "Option::is_none")]
1399    pub new_callback_ratio: Option<String>,
1400    /// New callback spread for amended attached trailing stop orders.
1401    #[serde(skip_serializing_if = "Option::is_none")]
1402    pub new_callback_spread: Option<String>,
1403    /// New activation price for amended attached trailing stop orders.
1404    #[serde(skip_serializing_if = "Option::is_none")]
1405    pub new_active_px: Option<String>,
1406}
1407
1408/// Parameters for WebSocket place order operation.
1409#[derive(Clone, Debug, Deserialize, Serialize, Builder)]
1410#[builder(setter(into, strip_option))]
1411#[serde(rename_all = "camelCase")]
1412pub struct WsPostOrderParams {
1413    /// Instrument type: SPOT, MARGIN, SWAP, FUTURES, OPTION (optional for WebSocket).
1414    #[builder(default)]
1415    #[serde(skip_serializing_if = "Option::is_none")]
1416    pub inst_type: Option<OKXInstrumentType>,
1417    /// Instrument ID code (numeric). Replaced `instId` for WebSocket order operations.
1418    pub inst_id_code: u64,
1419    /// Trading mode: cash, isolated, cross.
1420    pub td_mode: OKXTradeMode,
1421    /// Margin currency (only for isolated margin).
1422    #[builder(default)]
1423    #[serde(skip_serializing_if = "Option::is_none")]
1424    pub ccy: Option<Ustr>,
1425    /// Unique client order ID.
1426    #[builder(default)]
1427    #[serde(skip_serializing_if = "Option::is_none")]
1428    pub cl_ord_id: Option<String>,
1429    /// Order side: buy or sell.
1430    pub side: OKXSide,
1431    /// Position side: long, short, net (optional).
1432    #[builder(default)]
1433    #[serde(skip_serializing_if = "Option::is_none")]
1434    pub pos_side: Option<OKXPositionSide>,
1435    /// Order type: limit, market, `post_only`, fok, ioc, etc.
1436    pub ord_type: OKXOrderType,
1437    /// Order size.
1438    pub sz: String,
1439    /// Order price (required for limit orders).
1440    #[builder(default)]
1441    #[serde(skip_serializing_if = "Option::is_none")]
1442    pub px: Option<String>,
1443    /// Price in USD, only applicable to options. Mutually exclusive with `px` and `px_vol`.
1444    #[builder(default)]
1445    #[serde(rename = "pxUsd", skip_serializing_if = "Option::is_none")]
1446    pub px_usd: Option<String>,
1447    /// Price in implied volatility (1 = 100%), only applicable to options.
1448    /// Mutually exclusive with `px` and `px_usd`.
1449    #[builder(default)]
1450    #[serde(rename = "pxVol", skip_serializing_if = "Option::is_none")]
1451    pub px_vol: Option<String>,
1452    /// Reduce-only flag.
1453    #[builder(default)]
1454    #[serde(skip_serializing_if = "Option::is_none")]
1455    pub reduce_only: Option<bool>,
1456    /// Whether to close the entire position.
1457    #[builder(default)]
1458    #[serde(rename = "closePosition", skip_serializing_if = "Option::is_none")]
1459    pub close_position: Option<bool>,
1460    /// Target currency for net orders.
1461    #[builder(default)]
1462    #[serde(skip_serializing_if = "Option::is_none")]
1463    pub tgt_ccy: Option<OKXTargetCurrency>,
1464    /// Quote currency used for trading. Only applicable to SPOT.
1465    #[builder(default)]
1466    #[serde(skip_serializing_if = "Option::is_none")]
1467    pub trade_quote_ccy: Option<Ustr>,
1468    /// Order tag for categorization.
1469    #[builder(default)]
1470    #[serde(skip_serializing_if = "Option::is_none")]
1471    pub tag: Option<String>,
1472    /// Attached TP/SL orders submitted with the parent order.
1473    #[builder(default)]
1474    #[serde(skip_serializing_if = "Option::is_none")]
1475    pub attach_algo_ords: Option<Vec<WsAttachAlgoOrdParams>>,
1476    /// Event contract market outcome: yes or no.
1477    #[builder(default)]
1478    #[serde(skip_serializing_if = "Option::is_none")]
1479    pub outcome: Option<String>,
1480    /// Slippage tolerance for market orders, expressed as a decimal fraction
1481    /// (e.g., "0.005" for 0.5%). Supported instrument/order-type scope is
1482    /// venue-controlled; rejected with `54084`/`54085` if exceeded or out of
1483    /// the venue's accepted range. See the OKX v5 docs for the current matrix.
1484    #[builder(default)]
1485    #[serde(skip_serializing_if = "Option::is_none")]
1486    pub slippage_pct: Option<String>,
1487    /// Whether the order may take RPI liquidity.
1488    #[builder(default)]
1489    #[serde(skip_serializing_if = "Option::is_none")]
1490    pub rpi_taker_access: Option<bool>,
1491    /// Whether OKX may round the order price to an eligible RPI price.
1492    #[builder(default)]
1493    #[serde(skip_serializing_if = "Option::is_none")]
1494    pub rpi_px_round: Option<bool>,
1495}
1496
1497/// Parameters for WebSocket cancel order operation (instType not included).
1498#[derive(Clone, Debug, Default, Deserialize, Serialize, Builder)]
1499#[builder(default)]
1500#[builder(setter(into, strip_option))]
1501#[serde(rename_all = "camelCase")]
1502pub struct WsCancelOrderParams {
1503    /// Instrument ID code (numeric). Replaced `instId` for WebSocket order operations.
1504    pub inst_id_code: u64,
1505    /// Exchange-assigned order ID.
1506    #[serde(skip_serializing_if = "Option::is_none")]
1507    pub ord_id: Option<String>,
1508    /// User-assigned client order ID.
1509    #[serde(skip_serializing_if = "Option::is_none")]
1510    pub cl_ord_id: Option<String>,
1511}
1512
1513/// Parameters for WebSocket mass cancel operation.
1514#[derive(Clone, Debug, Default, Deserialize, Serialize, Builder)]
1515#[builder(default)]
1516#[builder(setter(into, strip_option))]
1517#[serde(rename_all = "camelCase")]
1518pub struct WsMassCancelParams {
1519    /// Instrument type.
1520    pub inst_type: OKXInstrumentType,
1521    /// Instrument family, e.g. "BTC-USD", "BTC-USDT".
1522    pub inst_family: Ustr,
1523}
1524
1525/// Parameters for WebSocket amend order operation (instType not included).
1526#[derive(Clone, Debug, Default, Deserialize, Serialize, Builder)]
1527#[builder(default)]
1528#[builder(setter(into, strip_option))]
1529#[serde(rename_all = "camelCase")]
1530pub struct WsAmendOrderParams {
1531    /// Instrument ID code (numeric). Replaced `instId` for WebSocket order operations.
1532    pub inst_id_code: u64,
1533    /// Exchange-assigned order ID (optional if using clOrdId).
1534    #[serde(skip_serializing_if = "Option::is_none")]
1535    pub ord_id: Option<String>,
1536    /// User-assigned client order ID (optional if using ordId).
1537    #[serde(skip_serializing_if = "Option::is_none")]
1538    pub cl_ord_id: Option<String>,
1539    /// Client request ID for correlating the amendment response.
1540    #[serde(skip_serializing_if = "Option::is_none")]
1541    pub req_id: Option<String>,
1542    /// New order price (optional).
1543    #[serde(skip_serializing_if = "Option::is_none")]
1544    pub new_px: Option<String>,
1545    /// New price in USD, only applicable to options. Must match the pricing mode used at placement.
1546    #[serde(rename = "newPxUsd", skip_serializing_if = "Option::is_none")]
1547    pub new_px_usd: Option<String>,
1548    /// New price in implied volatility, only applicable to options.
1549    /// Must match the pricing mode used at placement.
1550    #[serde(rename = "newPxVol", skip_serializing_if = "Option::is_none")]
1551    pub new_px_vol: Option<String>,
1552    /// New order size (optional).
1553    #[serde(skip_serializing_if = "Option::is_none")]
1554    pub new_sz: Option<String>,
1555    /// Whether the order may take RPI liquidity after amendment.
1556    #[serde(skip_serializing_if = "Option::is_none")]
1557    pub rpi_taker_access: Option<bool>,
1558    /// Whether OKX may round the amended price to an eligible RPI price.
1559    #[serde(skip_serializing_if = "Option::is_none")]
1560    pub rpi_px_round: Option<bool>,
1561}
1562
1563/// Parameters for WebSocket algo order placement.
1564#[derive(Clone, Debug, Deserialize, Serialize, Builder)]
1565#[builder(setter(into, strip_option))]
1566#[serde(rename_all = "camelCase")]
1567pub struct WsPostAlgoOrderParams {
1568    /// Instrument ID code (numeric). Replaced `instId` for WebSocket order operations.
1569    pub inst_id_code: u64,
1570    /// Trading mode: cash, isolated, cross.
1571    pub td_mode: OKXTradeMode,
1572    /// Order side: buy or sell.
1573    pub side: OKXSide,
1574    /// Order type: trigger (for stop orders).
1575    pub ord_type: OKXAlgoOrderType,
1576    /// Order size.
1577    pub sz: String,
1578    /// Client order ID (optional).
1579    #[builder(default)]
1580    #[serde(skip_serializing_if = "Option::is_none")]
1581    pub cl_ord_id: Option<String>,
1582    /// Position side: long, short, net (optional).
1583    #[builder(default)]
1584    #[serde(skip_serializing_if = "Option::is_none")]
1585    pub pos_side: Option<OKXPositionSide>,
1586    /// Trigger price for stop/conditional orders.
1587    #[serde(skip_serializing_if = "Option::is_none")]
1588    pub trigger_px: Option<String>,
1589    /// Trigger price type: last, index, mark.
1590    #[builder(default)]
1591    #[serde(skip_serializing_if = "Option::is_none")]
1592    pub trigger_px_type: Option<OKXTriggerType>,
1593    /// Order price (for limit orders after trigger).
1594    #[builder(default)]
1595    #[serde(skip_serializing_if = "Option::is_none")]
1596    pub order_px: Option<String>,
1597    /// Reduce-only flag.
1598    #[builder(default)]
1599    #[serde(skip_serializing_if = "Option::is_none")]
1600    pub reduce_only: Option<bool>,
1601    /// Order tag for categorization.
1602    #[builder(default)]
1603    #[serde(skip_serializing_if = "Option::is_none")]
1604    pub tag: Option<String>,
1605    /// Callback rate for trailing stop (e.g., "0.01" for 1%).
1606    #[builder(default)]
1607    #[serde(skip_serializing_if = "Option::is_none")]
1608    pub callback_ratio: Option<String>,
1609    /// Callback spread for trailing stop (fixed price distance).
1610    #[builder(default)]
1611    #[serde(skip_serializing_if = "Option::is_none")]
1612    pub callback_spread: Option<String>,
1613    /// Activation price for trailing stop.
1614    #[builder(default)]
1615    #[serde(skip_serializing_if = "Option::is_none")]
1616    pub active_px: Option<String>,
1617}
1618
1619/// Parameters for WebSocket cancel algo order operation.
1620#[derive(Clone, Debug, Deserialize, Serialize, Builder)]
1621#[builder(setter(into, strip_option))]
1622#[serde(rename_all = "camelCase")]
1623pub struct WsCancelAlgoOrderParams {
1624    /// Instrument ID code (numeric). Replaced `instId` for WebSocket order operations.
1625    pub inst_id_code: u64,
1626    /// Algo order ID.
1627    #[builder(default)]
1628    #[serde(skip_serializing_if = "Option::is_none")]
1629    pub algo_id: Option<String>,
1630    /// Client algo order ID.
1631    #[builder(default)]
1632    #[serde(skip_serializing_if = "Option::is_none")]
1633    pub algo_cl_ord_id: Option<String>,
1634}
1635
1636#[cfg(test)]
1637mod tests {
1638    use nautilus_core::string::secret::REDACTED;
1639    use rstest::rstest;
1640    use rust_decimal::Decimal;
1641
1642    use super::*;
1643
1644    #[rstest]
1645    fn authentication_preserves_wire_values_and_redacts_debug() {
1646        let authentication = OKXAuthentication {
1647            op: "login",
1648            args: vec![OKXAuthenticationArg {
1649                api_key: SecretString::from("api-key-value"),
1650                passphrase: SecretString::from("passphrase-value"),
1651                timestamp: "1700000000".to_string(),
1652                sign: SecretString::from("signature-value"),
1653            }],
1654        };
1655
1656        let json = serde_json::to_value(&authentication).unwrap();
1657        let formatted = format!("{authentication:?}");
1658
1659        assert_eq!(json["op"], "login");
1660        assert_eq!(json["args"][0]["apiKey"], "api-key-value");
1661        assert_eq!(json["args"][0]["passphrase"], "passphrase-value");
1662        assert_eq!(json["args"][0]["sign"], "signature-value");
1663        assert!(formatted.contains(REDACTED));
1664        assert!(!formatted.contains("api-key-value"));
1665        assert!(!formatted.contains("passphrase-value"));
1666        assert!(!formatted.contains("signature-value"));
1667    }
1668    use crate::common::testing::load_test_json;
1669
1670    #[rstest]
1671    fn test_deserialize_websocket_arg() {
1672        let json_str = r#"{"channel":"instruments","instType":"SPOT"}"#;
1673
1674        let result: Result<OKXWebSocketArg, _> = serde_json::from_str(json_str);
1675        match result {
1676            Ok(arg) => {
1677                assert_eq!(arg.channel, OKXWsChannel::Instruments);
1678                assert_eq!(arg.inst_type, Some(OKXInstrumentType::Spot));
1679                assert_eq!(arg.inst_id, None);
1680            }
1681            Err(e) => {
1682                panic!("Failed to deserialize WebSocket arg: {e}");
1683            }
1684        }
1685    }
1686
1687    #[rstest]
1688    fn test_deserialize_subscribe_confirmation() {
1689        let json_str = r#"{"event":"subscribe","arg":{"channel":"instruments","instType":"SPOT"},"connId":"380cfa6a"}"#;
1690
1691        let result: Result<OKXWsFrame, _> = serde_json::from_str(json_str);
1692        match result {
1693            Ok(msg) => {
1694                if let OKXWsFrame::Subscription {
1695                    event,
1696                    arg,
1697                    conn_id,
1698                    ..
1699                } = msg
1700                {
1701                    assert_eq!(event, OKXSubscriptionEvent::Subscribe);
1702                    assert_eq!(arg.channel, OKXWsChannel::Instruments);
1703                    assert_eq!(conn_id, "380cfa6a");
1704                } else {
1705                    panic!("Expected Subscribe variant, was: {msg:?}");
1706                }
1707            }
1708            Err(e) => {
1709                panic!("Failed to deserialize subscription confirmation: {e}");
1710            }
1711        }
1712    }
1713
1714    #[rstest]
1715    fn test_deserialize_subscribe_with_inst_id() {
1716        let json_str = r#"{"event":"subscribe","arg":{"channel":"candle1m","instId":"ETH-USDT"},"connId":"358602f5"}"#;
1717
1718        let result: Result<OKXWsFrame, _> = serde_json::from_str(json_str);
1719        match result {
1720            Ok(msg) => {
1721                if let OKXWsFrame::Subscription {
1722                    event,
1723                    arg,
1724                    conn_id,
1725                    ..
1726                } = msg
1727                {
1728                    assert_eq!(event, OKXSubscriptionEvent::Subscribe);
1729                    assert_eq!(arg.channel, OKXWsChannel::Candle1Minute);
1730                    assert_eq!(conn_id, "358602f5");
1731                } else {
1732                    panic!("Expected Subscribe variant, was: {msg:?}");
1733                }
1734            }
1735            Err(e) => {
1736                panic!("Failed to deserialize subscription confirmation: {e}");
1737            }
1738        }
1739    }
1740
1741    #[rstest]
1742    fn test_channel_serialization_for_logging() {
1743        let channel = OKXWsChannel::Candle1Minute;
1744        let serialized = serde_json::to_string(&channel).unwrap();
1745        let cleaned = serialized.trim_matches('"').to_string();
1746        assert_eq!(cleaned, "candle1m");
1747
1748        let channel = OKXWsChannel::BboTbt;
1749        let serialized = serde_json::to_string(&channel).unwrap();
1750        let cleaned = serialized.trim_matches('"').to_string();
1751        assert_eq!(cleaned, "bbo-tbt");
1752
1753        let channel = OKXWsChannel::Trades;
1754        let serialized = serde_json::to_string(&channel).unwrap();
1755        let cleaned = serialized.trim_matches('"').to_string();
1756        assert_eq!(cleaned, "trades");
1757    }
1758
1759    #[rstest]
1760    fn test_order_response_with_enum_operation() {
1761        let json_str = r#"{"id":"req-123","op":"order","code":"0","msg":"","data":[]}"#;
1762        let result: Result<OKXWsFrame, _> = serde_json::from_str(json_str);
1763        match result {
1764            Ok(OKXWsFrame::OrderResponse {
1765                id,
1766                op,
1767                code,
1768                msg,
1769                data,
1770            }) => {
1771                assert_eq!(id, Some("req-123".to_string()));
1772                assert_eq!(op, OKXWsOperation::Order);
1773                assert_eq!(code, "0");
1774                assert_eq!(msg, "");
1775                assert!(data.is_empty());
1776            }
1777            Ok(other) => panic!("Expected OrderResponse, was: {other:?}"),
1778            Err(e) => panic!("Failed to deserialize: {e}"),
1779        }
1780
1781        let json_str = r#"{"id":"cancel-456","op":"cancel-order","code":"50001","msg":"Order not found","data":[]}"#;
1782        let result: Result<OKXWsFrame, _> = serde_json::from_str(json_str);
1783        match result {
1784            Ok(OKXWsFrame::OrderResponse {
1785                id,
1786                op,
1787                code,
1788                msg,
1789                data,
1790            }) => {
1791                assert_eq!(id, Some("cancel-456".to_string()));
1792                assert_eq!(op, OKXWsOperation::CancelOrder);
1793                assert_eq!(code, "50001");
1794                assert_eq!(msg, "Order not found");
1795                assert!(data.is_empty());
1796            }
1797            Ok(other) => panic!("Expected OrderResponse, was: {other:?}"),
1798            Err(e) => panic!("Failed to deserialize: {e}"),
1799        }
1800
1801        let json_str = r#"{"id":"amend-789","op":"amend-order","code":"50002","msg":"Invalid price","data":[]}"#;
1802        let result: Result<OKXWsFrame, _> = serde_json::from_str(json_str);
1803        match result {
1804            Ok(OKXWsFrame::OrderResponse {
1805                id,
1806                op,
1807                code,
1808                msg,
1809                data,
1810            }) => {
1811                assert_eq!(id, Some("amend-789".to_string()));
1812                assert_eq!(op, OKXWsOperation::AmendOrder);
1813                assert_eq!(code, "50002");
1814                assert_eq!(msg, "Invalid price");
1815                assert!(data.is_empty());
1816            }
1817            Ok(other) => panic!("Expected OrderResponse, was: {other:?}"),
1818            Err(e) => panic!("Failed to deserialize: {e}"),
1819        }
1820    }
1821
1822    #[rstest]
1823    fn test_operation_enum_serialization() {
1824        let op = OKXWsOperation::Order;
1825        let serialized = serde_json::to_string(&op).unwrap();
1826        assert_eq!(serialized, "\"order\"");
1827
1828        let op = OKXWsOperation::CancelOrder;
1829        let serialized = serde_json::to_string(&op).unwrap();
1830        assert_eq!(serialized, "\"cancel-order\"");
1831
1832        let op = OKXWsOperation::AmendOrder;
1833        let serialized = serde_json::to_string(&op).unwrap();
1834        assert_eq!(serialized, "\"amend-order\"");
1835
1836        let op = OKXWsOperation::Subscribe;
1837        let serialized = serde_json::to_string(&op).unwrap();
1838        assert_eq!(serialized, "\"subscribe\"");
1839    }
1840
1841    #[rstest]
1842    fn test_order_response_parsing() {
1843        let success_response = r#"{
1844            "id": "req-123",
1845            "op": "order",
1846            "code": "0",
1847            "msg": "",
1848            "data": [{"sMsg": "Order placed successfully"}]
1849        }"#;
1850
1851        let parsed: OKXWsFrame = serde_json::from_str(success_response).unwrap();
1852
1853        match parsed {
1854            OKXWsFrame::OrderResponse {
1855                id,
1856                op,
1857                code,
1858                msg,
1859                data,
1860            } => {
1861                assert_eq!(id, Some("req-123".to_string()));
1862                assert_eq!(op, OKXWsOperation::Order);
1863                assert_eq!(code, "0");
1864                assert_eq!(msg, "");
1865                assert_eq!(data.len(), 1);
1866            }
1867            _ => panic!("Expected OrderResponse variant"),
1868        }
1869
1870        let failure_response = r#"{
1871            "id": "req-456",
1872            "op": "cancel-order",
1873            "code": "50001",
1874            "msg": "Order not found",
1875            "data": [{"sMsg": "Order with client order ID not found"}]
1876        }"#;
1877
1878        let parsed: OKXWsFrame = serde_json::from_str(failure_response).unwrap();
1879
1880        match parsed {
1881            OKXWsFrame::OrderResponse {
1882                id,
1883                op,
1884                code,
1885                msg,
1886                data,
1887            } => {
1888                assert_eq!(id, Some("req-456".to_string()));
1889                assert_eq!(op, OKXWsOperation::CancelOrder);
1890                assert_eq!(code, "50001");
1891                assert_eq!(msg, "Order not found");
1892                assert_eq!(data.len(), 1);
1893            }
1894            _ => panic!("Expected OrderResponse variant"),
1895        }
1896    }
1897
1898    #[rstest]
1899    fn test_subscription_event_parsing() {
1900        let subscription_json = r#"{
1901            "event": "subscribe",
1902            "arg": {
1903                "channel": "tickers",
1904                "instId": "BTC-USDT"
1905            },
1906            "connId": "a4d3ae55"
1907        }"#;
1908
1909        let parsed: OKXWsFrame = serde_json::from_str(subscription_json).unwrap();
1910
1911        match parsed {
1912            OKXWsFrame::Subscription {
1913                event,
1914                arg,
1915                conn_id,
1916                ..
1917            } => {
1918                assert_eq!(
1919                    event,
1920                    crate::websocket::enums::OKXSubscriptionEvent::Subscribe
1921                );
1922                assert_eq!(arg.channel, OKXWsChannel::Tickers);
1923                assert_eq!(arg.inst_id, Some(Ustr::from("BTC-USDT")));
1924                assert_eq!(conn_id, "a4d3ae55");
1925            }
1926            _ => panic!("Expected Subscription variant"),
1927        }
1928    }
1929
1930    #[rstest]
1931    fn test_login_event_parsing() {
1932        let login_success = r#"{
1933            "event": "login",
1934            "code": "0",
1935            "msg": "Login successful",
1936            "connId": "a4d3ae55"
1937        }"#;
1938
1939        let parsed: OKXWsFrame = serde_json::from_str(login_success).unwrap();
1940
1941        match parsed {
1942            OKXWsFrame::Login {
1943                event,
1944                code,
1945                msg,
1946                conn_id,
1947            } => {
1948                assert_eq!(event, "login");
1949                assert_eq!(code, "0");
1950                assert_eq!(msg, "Login successful");
1951                assert_eq!(conn_id, "a4d3ae55");
1952            }
1953            _ => panic!("Expected Login variant, was: {parsed:?}"),
1954        }
1955    }
1956
1957    #[rstest]
1958    fn test_error_event_parsing() {
1959        let error_json = r#"{
1960            "code": "60012",
1961            "msg": "Invalid request"
1962        }"#;
1963
1964        let parsed: OKXWsFrame = serde_json::from_str(error_json).unwrap();
1965
1966        match parsed {
1967            OKXWsFrame::Error { arg, code, msg } => {
1968                assert!(arg.is_none());
1969                assert_eq!(code, "60012");
1970                assert_eq!(msg, "Invalid request");
1971            }
1972            _ => panic!("Expected Error variant"),
1973        }
1974    }
1975
1976    #[rstest]
1977    fn test_error_event_with_event_field_parsing() {
1978        // OKX sends error events with "event":"error" field (e.g., login failures)
1979        let error_json = r#"{
1980            "event": "error",
1981            "code": "60018",
1982            "msg": "Invalid sign"
1983        }"#;
1984
1985        let parsed: OKXWsFrame = serde_json::from_str(error_json).unwrap();
1986
1987        match parsed {
1988            OKXWsFrame::Error { arg, code, msg } => {
1989                assert!(arg.is_none());
1990                assert_eq!(code, "60018");
1991                assert_eq!(msg, "Invalid sign");
1992            }
1993            _ => panic!("Expected Error variant, was: {parsed:?}"),
1994        }
1995    }
1996
1997    #[rstest]
1998    fn test_subscription_error_with_arg_field_parsing() {
1999        // OKX sends subscription errors with arg field (channel subscription failures)
2000        let error_json = r#"{
2001            "event": "error",
2002            "arg": {"channel": "tickers", "instId": "INVALID-INST"},
2003            "code": "60012",
2004            "msg": "Invalid request: channel not found",
2005            "connId": "a4d3ae55"
2006        }"#;
2007
2008        let parsed: OKXWsFrame = serde_json::from_str(error_json).unwrap();
2009
2010        match parsed {
2011            OKXWsFrame::Error { arg, code, msg } => {
2012                let arg = arg.expect("subscription error arg");
2013                assert_eq!(arg.channel, OKXWsChannel::Tickers);
2014                assert_eq!(arg.inst_id, Some(Ustr::from("INVALID-INST")));
2015                assert_eq!(code, "60012");
2016                assert_eq!(msg, "Invalid request: channel not found");
2017            }
2018            _ => panic!("Expected Error variant, was: {parsed:?}"),
2019        }
2020    }
2021
2022    #[rstest]
2023    fn test_websocket_request_serialization() {
2024        let request = OKXWsRequest {
2025            id: Some("req-123".to_string()),
2026            op: OKXWsOperation::Order,
2027            args: vec![serde_json::json!({
2028                "instId": "BTC-USDT",
2029                "tdMode": "cash",
2030                "side": "buy",
2031                "ordType": "market",
2032                "sz": "0.1"
2033            })],
2034            exp_time: None,
2035        };
2036
2037        let serialized = serde_json::to_string(&request).unwrap();
2038        let parsed: serde_json::Value = serde_json::from_str(&serialized).unwrap();
2039
2040        assert_eq!(parsed["id"], "req-123");
2041        assert_eq!(parsed["op"], "order");
2042        assert!(parsed["args"].is_array());
2043        assert_eq!(parsed["args"].as_array().unwrap().len(), 1);
2044    }
2045
2046    #[rstest]
2047    fn test_subscription_request_serialization() {
2048        let subscription = OKXSubscription {
2049            op: OKXWsOperation::Subscribe,
2050            args: vec![OKXSubscriptionArg {
2051                channel: OKXWsChannel::Tickers,
2052                inst_type: Some(OKXInstrumentType::Spot),
2053                inst_family: None,
2054                inst_id: Some(Ustr::from("BTC-USDT")),
2055            }],
2056        };
2057
2058        let serialized = serde_json::to_string(&subscription).unwrap();
2059        let parsed: serde_json::Value = serde_json::from_str(&serialized).unwrap();
2060
2061        assert_eq!(parsed["op"], "subscribe");
2062        assert!(parsed["args"].is_array());
2063        assert_eq!(parsed["args"][0]["channel"], "tickers");
2064        assert_eq!(parsed["args"][0]["instType"], "SPOT");
2065        assert_eq!(parsed["args"][0]["instId"], "BTC-USDT");
2066    }
2067
2068    #[rstest]
2069    fn test_book_data_parsing() {
2070        let parsed: OKXWsFrame =
2071            serde_json::from_str(&load_test_json("ws_books_snapshot.json")).unwrap();
2072
2073        match parsed {
2074            OKXWsFrame::BookData { arg, action, data } => {
2075                assert_eq!(arg.channel, OKXWsChannel::Books);
2076                assert_eq!(arg.inst_id, Some(Ustr::from("BTC-USDT")));
2077                assert_eq!(
2078                    action,
2079                    super::super::super::common::enums::OKXBookAction::Snapshot
2080                );
2081                assert_eq!(data.len(), 1);
2082            }
2083            _ => panic!("Expected BookData variant"),
2084        }
2085    }
2086
2087    #[rstest]
2088    #[case::arg_first(
2089        r#"{"arg":{"channel":"books","instId":"ETH-USDT"},"action":"update","data":[{"asks":[["3000.5","2","0","3"]],"bids":[["2999.5","4","1","5"]],"ts":"1640995200001","checksum":-42,"prevSeqId":1001,"seqId":1002}]}"#
2090    )]
2091    #[case::data_first(
2092        r#"{"data":[{"asks":[["3000.5","2","0","3"]],"bids":[["2999.5","4","1","5"]],"ts":"1640995200001","checksum":-42,"prevSeqId":1001,"seqId":1002}],"action":"update","arg":{"channel":"books","instId":"ETH-USDT"}}"#
2093    )]
2094    fn test_book_data_parsing_is_independent_of_key_order(#[case] json: &str) {
2095        let parsed: OKXWsFrame = serde_json::from_str(json).unwrap();
2096
2097        let OKXWsFrame::BookData { arg, action, data } = parsed else {
2098            panic!("Expected BookData variant");
2099        };
2100
2101        assert_eq!(arg.channel, OKXWsChannel::Books);
2102        assert_eq!(arg.inst_id, Some(Ustr::from("ETH-USDT")));
2103        assert_eq!(action, OKXBookAction::Update);
2104        assert_eq!(data.len(), 1);
2105        let msg = &data[0];
2106        assert_eq!(msg.asks.len(), 1);
2107        assert_eq!(msg.asks[0].price, "3000.5");
2108        assert_eq!(msg.asks[0].size, "2");
2109        assert_eq!(msg.asks[0].liquidated_orders_count, "0");
2110        assert_eq!(msg.asks[0].orders_count, "3");
2111        assert_eq!(msg.bids.len(), 1);
2112        assert_eq!(msg.bids[0].price, "2999.5");
2113        assert_eq!(msg.bids[0].size, "4");
2114        assert_eq!(msg.bids[0].liquidated_orders_count, "1");
2115        assert_eq!(msg.bids[0].orders_count, "5");
2116        assert_eq!(msg.checksum, Some(-42));
2117        assert_eq!(msg.prev_seq_id, Some(1001));
2118        assert_eq!(msg.seq_id, 1002);
2119        assert_eq!(msg.ts, 1_640_995_200_001);
2120    }
2121
2122    #[rstest]
2123    #[case::op_first(
2124        r#"{"id":"req-7","op":"cancel-order","data":[{"sCode":"51400","sMsg":"Cancellation failed"}],"code":"1","msg":"Operation failed"}"#
2125    )]
2126    #[case::data_first(
2127        r#"{"data":[{"sCode":"51400","sMsg":"Cancellation failed"}],"code":"1","msg":"Operation failed","op":"cancel-order","id":"req-7"}"#
2128    )]
2129    fn test_order_response_parsing_is_independent_of_key_order(#[case] json: &str) {
2130        let parsed: OKXWsFrame = serde_json::from_str(json).unwrap();
2131
2132        let OKXWsFrame::OrderResponse {
2133            id,
2134            op,
2135            code,
2136            msg,
2137            data,
2138        } = parsed
2139        else {
2140            panic!("Expected OrderResponse variant");
2141        };
2142
2143        assert_eq!(id, Some("req-7".to_string()));
2144        assert_eq!(op, OKXWsOperation::CancelOrder);
2145        assert_eq!(code, "1");
2146        assert_eq!(msg, "Operation failed");
2147        assert_eq!(
2148            data,
2149            vec![serde_json::json!({"sCode": "51400", "sMsg": "Cancellation failed"})]
2150        );
2151    }
2152
2153    #[rstest]
2154    #[case::op_first(r#"{"op":"order","data":null,"event":"error","code":"60012","msg":"Bad"}"#)]
2155    #[case::event_first(r#"{"event":"error","code":"60012","msg":"Bad","op":"order","data":null}"#)]
2156    fn test_error_event_takes_priority_over_op_in_any_key_order(#[case] json: &str) {
2157        let parsed: OKXWsFrame = serde_json::from_str(json).unwrap();
2158
2159        let OKXWsFrame::Error { arg, code, msg } = parsed else {
2160            panic!("Expected Error variant");
2161        };
2162
2163        assert!(arg.is_none());
2164        assert_eq!(code, "60012");
2165        assert_eq!(msg, "Bad");
2166    }
2167
2168    #[rstest]
2169    fn test_rpi_book_fixtures_preserve_depth_types_and_sequence() {
2170        let snapshot: OKXWsFrame =
2171            serde_json::from_str(&load_test_json("ws_books_rpi_snapshot.json")).unwrap();
2172        let update: OKXWsFrame =
2173            serde_json::from_str(&load_test_json("ws_books_rpi_update.json")).unwrap();
2174
2175        let OKXWsFrame::RpiBookData { arg, action, data } = snapshot else {
2176            panic!("Expected RPI book snapshot");
2177        };
2178        let snapshot = &data[0];
2179        assert_eq!(arg.channel, OKXWsChannel::BooksRpi);
2180        assert_eq!(arg.inst_id, Some(Ustr::from("OMI-USD")));
2181        assert_eq!(action, OKXBookAction::Snapshot);
2182        assert_eq!(data.len(), 1);
2183        assert_eq!(snapshot.asks.len(), 4);
2184        assert_eq!(snapshot.bids.len(), 10);
2185        assert_eq!(
2186            snapshot.asks[0],
2187            OKXRpiBookLevel(
2188                Decimal::from_str_exact("0.0001617").unwrap(),
2189                Decimal::from_str_exact("12325166.992").unwrap(),
2190                Decimal::from(1000),
2191                2,
2192            )
2193        );
2194        assert_eq!(
2195            serde_json::to_value(&snapshot.asks[0]).unwrap(),
2196            serde_json::json!(["0.0001617", "12325166.992", "1000", "2"])
2197        );
2198        assert_eq!(snapshot.prev_seq_id, -1);
2199        assert_eq!(snapshot.seq_id, 1_082_831_226);
2200        assert_eq!(snapshot.ts, 1_785_406_442_403);
2201
2202        let OKXWsFrame::RpiBookData { arg, action, data } = update else {
2203            panic!("Expected RPI book update");
2204        };
2205        let update = &data[0];
2206        assert_eq!(arg.channel, OKXWsChannel::BooksRpi);
2207        assert_eq!(arg.inst_id, Some(Ustr::from("OMI-USD")));
2208        assert_eq!(action, OKXBookAction::Update);
2209        assert_eq!(data.len(), 1);
2210        assert_eq!(update.asks.len(), 2);
2211        assert!(update.bids.is_empty());
2212        assert_eq!(
2213            update.asks[1],
2214            OKXRpiBookLevel(
2215                Decimal::from_str_exact("0.0001625").unwrap(),
2216                Decimal::from_str_exact("12324367.786").unwrap(),
2217                Decimal::from(1000),
2218                2,
2219            )
2220        );
2221        assert_eq!(update.prev_seq_id, snapshot.seq_id as i64);
2222        assert_eq!(update.seq_id, 1_082_831_230);
2223        assert_eq!(update.ts, 1_785_406_443_903);
2224    }
2225
2226    #[rstest]
2227    fn test_rpi_book_rejects_checksum_field() {
2228        let mut payload: serde_json::Value =
2229            serde_json::from_str(&load_test_json("ws_books_rpi_update.json")).unwrap();
2230        payload["data"][0]["checksum"] = serde_json::json!(0);
2231
2232        let error = serde_json::from_value::<OKXWsFrame>(payload).unwrap_err();
2233
2234        assert!(error.to_string().contains("checksum"));
2235    }
2236
2237    #[rstest]
2238    fn test_data_event_parsing() {
2239        let parsed: OKXWsFrame = serde_json::from_str(&load_test_json("ws_trades.json")).unwrap();
2240
2241        match parsed {
2242            OKXWsFrame::Data { arg, data } => {
2243                assert_eq!(arg.channel, OKXWsChannel::Trades);
2244                assert_eq!(arg.inst_id, Some(Ustr::from("BTC-USD")));
2245                assert!(data.is_array());
2246            }
2247            _ => panic!("Expected Data variant"),
2248        }
2249    }
2250
2251    #[rstest]
2252    fn test_ws_post_order_params_serializes_inst_id_code() {
2253        use super::WsPostOrderParamsBuilder;
2254        use crate::common::enums::{OKXOrderType, OKXSide, OKXTradeMode};
2255
2256        let params = WsPostOrderParamsBuilder::default()
2257            .inst_id_code(10459u64)
2258            .td_mode(OKXTradeMode::Cross)
2259            .side(OKXSide::Buy)
2260            .ord_type(OKXOrderType::Limit)
2261            .sz("0.01".to_string())
2262            .px("50000".to_string())
2263            .build()
2264            .unwrap();
2265
2266        let json = serde_json::to_string(&params).unwrap();
2267
2268        assert!(json.contains("\"instIdCode\":10459"));
2269        assert!(!json.contains("\"instId\""));
2270    }
2271
2272    #[rstest]
2273    fn test_ws_post_order_params_serializes_slippage_pct() {
2274        use super::WsPostOrderParamsBuilder;
2275        use crate::common::enums::{OKXOrderType, OKXSide, OKXTradeMode};
2276
2277        let params = WsPostOrderParamsBuilder::default()
2278            .inst_id_code(10459u64)
2279            .td_mode(OKXTradeMode::Cross)
2280            .side(OKXSide::Buy)
2281            .ord_type(OKXOrderType::Market)
2282            .sz("0.01".to_string())
2283            .slippage_pct("0.005".to_string())
2284            .build()
2285            .unwrap();
2286
2287        let json: serde_json::Value = serde_json::to_value(&params).unwrap();
2288        assert_eq!(json["slippagePct"], "0.005");
2289    }
2290
2291    #[rstest]
2292    fn test_ws_post_order_params_omits_slippage_pct_when_unset() {
2293        use super::WsPostOrderParamsBuilder;
2294        use crate::common::enums::{OKXOrderType, OKXSide, OKXTradeMode};
2295
2296        let params = WsPostOrderParamsBuilder::default()
2297            .inst_id_code(10459u64)
2298            .td_mode(OKXTradeMode::Cross)
2299            .side(OKXSide::Buy)
2300            .ord_type(OKXOrderType::Market)
2301            .sz("0.01".to_string())
2302            .build()
2303            .unwrap();
2304
2305        let json = serde_json::to_string(&params).unwrap();
2306        assert!(!json.contains("slippagePct"));
2307        assert!(!json.contains("tradeQuoteCcy"));
2308    }
2309
2310    #[rstest]
2311    fn test_ws_post_order_params_serializes_trade_quote_ccy_usd() {
2312        use super::WsPostOrderParamsBuilder;
2313        use crate::common::enums::{OKXOrderType, OKXSide, OKXTradeMode};
2314
2315        let params = WsPostOrderParamsBuilder::default()
2316            .inst_id_code(20459u64)
2317            .td_mode(OKXTradeMode::Cash)
2318            .side(OKXSide::Buy)
2319            .ord_type(OKXOrderType::Limit)
2320            .sz("0.01".to_string())
2321            .px("100000".to_string())
2322            .trade_quote_ccy("USD")
2323            .build()
2324            .unwrap();
2325
2326        let json: serde_json::Value = serde_json::to_value(&params).unwrap();
2327        assert_eq!(json["instIdCode"], 20459);
2328        assert_eq!(json["tradeQuoteCcy"], "USD");
2329        assert!(json.get("instId").is_none());
2330    }
2331
2332    #[rstest]
2333    fn test_ws_post_order_params_serializes_trade_quote_ccy_usdc() {
2334        use super::WsPostOrderParamsBuilder;
2335        use crate::common::enums::{OKXOrderType, OKXSide, OKXTradeMode};
2336
2337        let params = WsPostOrderParamsBuilder::default()
2338            .inst_id_code(20459u64)
2339            .td_mode(OKXTradeMode::Cash)
2340            .side(OKXSide::Buy)
2341            .ord_type(OKXOrderType::Limit)
2342            .sz("0.01".to_string())
2343            .px("100000".to_string())
2344            .trade_quote_ccy("USDC")
2345            .build()
2346            .unwrap();
2347
2348        let json: serde_json::Value = serde_json::to_value(&params).unwrap();
2349        assert_eq!(json["tradeQuoteCcy"], "USDC");
2350    }
2351
2352    #[rstest]
2353    fn test_ws_post_order_params_serializes_attached_tp_sl() {
2354        use super::{WsAttachAlgoOrdParamsBuilder, WsPostOrderParamsBuilder};
2355        use crate::common::enums::{OKXOrderType, OKXSide, OKXTradeMode, OKXTriggerType};
2356
2357        let params = WsPostOrderParamsBuilder::default()
2358            .inst_id_code(10459u64)
2359            .td_mode(OKXTradeMode::Cross)
2360            .side(OKXSide::Buy)
2361            .ord_type(OKXOrderType::Limit)
2362            .sz("0.01".to_string())
2363            .px("50000".to_string())
2364            .attach_algo_ords(vec![
2365                WsAttachAlgoOrdParamsBuilder::default()
2366                    .attach_algo_cl_ord_id("O-bracket-sl")
2367                    .sl_trigger_px("39000")
2368                    .sl_ord_px("-1")
2369                    .sl_trigger_px_type(OKXTriggerType::Last)
2370                    .build()
2371                    .unwrap(),
2372                WsAttachAlgoOrdParamsBuilder::default()
2373                    .attach_algo_cl_ord_id("O-bracket-tp")
2374                    .tp_trigger_px("41000")
2375                    .tp_ord_px("-1")
2376                    .tp_trigger_px_type(OKXTriggerType::Last)
2377                    .build()
2378                    .unwrap(),
2379            ])
2380            .build()
2381            .unwrap();
2382
2383        let json = serde_json::to_string(&params).unwrap();
2384
2385        assert!(json.contains("\"attachAlgoOrds\""));
2386        assert!(json.contains("\"attachAlgoClOrdId\":\"O-bracket-sl\""));
2387        assert!(json.contains("\"slTriggerPx\":\"39000\""));
2388        assert!(json.contains("\"slOrdPx\":\"-1\""));
2389        assert!(json.contains("\"attachAlgoClOrdId\":\"O-bracket-tp\""));
2390        assert!(json.contains("\"tpTriggerPx\":\"41000\""));
2391        assert!(json.contains("\"tpOrdPx\":\"-1\""));
2392    }
2393
2394    #[rstest]
2395    fn test_ws_cancel_order_params_serializes_inst_id_code() {
2396        use super::WsCancelOrderParamsBuilder;
2397
2398        let params = WsCancelOrderParamsBuilder::default()
2399            .inst_id_code(10461u64)
2400            .ord_id("12345678".to_string())
2401            .build()
2402            .unwrap();
2403
2404        let json = serde_json::to_string(&params).unwrap();
2405
2406        assert!(json.contains("\"instIdCode\":10461"));
2407        assert!(!json.contains("\"instId\""));
2408        assert!(json.contains("\"ordId\":\"12345678\""));
2409    }
2410
2411    #[rstest]
2412    fn test_ws_amend_order_params_serializes_inst_id_code() {
2413        use super::WsAmendOrderParamsBuilder;
2414
2415        let params = WsAmendOrderParamsBuilder::default()
2416            .inst_id_code(10459u64)
2417            .cl_ord_id("client123".to_string())
2418            .new_px("51000".to_string())
2419            .build()
2420            .unwrap();
2421
2422        let json = serde_json::to_string(&params).unwrap();
2423
2424        assert!(json.contains("\"instIdCode\":10459"));
2425        assert!(!json.contains("\"instId\""));
2426        assert!(json.contains("\"newPx\":\"51000\""));
2427    }
2428
2429    #[rstest]
2430    fn test_ws_post_algo_order_params_serializes_inst_id_code() {
2431        use super::WsPostAlgoOrderParamsBuilder;
2432        use crate::common::enums::{OKXAlgoOrderType, OKXSide, OKXTradeMode, OKXTriggerType};
2433
2434        let params = WsPostAlgoOrderParamsBuilder::default()
2435            .inst_id_code(10459u64)
2436            .td_mode(OKXTradeMode::Cross)
2437            .side(OKXSide::Buy)
2438            .ord_type(OKXAlgoOrderType::Trigger)
2439            .sz("0.01".to_string())
2440            .trigger_px("48000".to_string())
2441            .trigger_px_type(OKXTriggerType::Last)
2442            .build()
2443            .unwrap();
2444
2445        let json = serde_json::to_string(&params).unwrap();
2446
2447        assert!(json.contains("\"instIdCode\":10459"));
2448        assert!(!json.contains("\"instId\""));
2449        assert!(json.contains("\"triggerPx\":\"48000\""));
2450    }
2451
2452    #[rstest]
2453    fn test_ws_cancel_algo_order_params_serializes_inst_id_code() {
2454        let params = WsCancelAlgoOrderParams {
2455            inst_id_code: 10459,
2456            algo_id: Some("987654321".to_string()),
2457            algo_cl_ord_id: None,
2458        };
2459
2460        let json = serde_json::to_string(&params).unwrap();
2461
2462        assert!(json.contains("\"instIdCode\":10459"));
2463        assert!(!json.contains("\"instId\""));
2464        assert!(json.contains("\"algoId\":\"987654321\""));
2465    }
2466
2467    #[rstest]
2468    fn test_ws_cancel_algo_order_params_builder_allows_either_identifier() {
2469        use super::WsCancelAlgoOrderParamsBuilder;
2470
2471        let by_cl_ord_id = WsCancelAlgoOrderParamsBuilder::default()
2472            .inst_id_code(10459u64)
2473            .algo_cl_ord_id("Odstalgocancel0000001".to_string())
2474            .build()
2475            .unwrap();
2476        let json = serde_json::to_value(&by_cl_ord_id).unwrap();
2477        assert_eq!(json["algoClOrdId"], "Odstalgocancel0000001");
2478        assert!(json.get("algoId").is_none());
2479
2480        let by_algo_id = WsCancelAlgoOrderParamsBuilder::default()
2481            .inst_id_code(10459u64)
2482            .algo_id("987654321".to_string())
2483            .build()
2484            .unwrap();
2485        let json = serde_json::to_value(&by_algo_id).unwrap();
2486        assert_eq!(json["algoId"], "987654321");
2487        assert!(json.get("algoClOrdId").is_none());
2488    }
2489
2490    #[rstest]
2491    fn test_ws_post_order_params_serializes_px_usd() {
2492        use super::WsPostOrderParamsBuilder;
2493        use crate::common::enums::{OKXOrderType, OKXSide, OKXTradeMode};
2494
2495        let params = WsPostOrderParamsBuilder::default()
2496            .inst_id_code(10459u64)
2497            .td_mode(OKXTradeMode::Cross)
2498            .side(OKXSide::Buy)
2499            .ord_type(OKXOrderType::Limit)
2500            .sz("1".to_string())
2501            .px_usd("100.5".to_string())
2502            .build()
2503            .unwrap();
2504
2505        let json = serde_json::to_string(&params).unwrap();
2506        assert!(json.contains("\"pxUsd\":\"100.5\""));
2507        assert!(!json.contains("\"pxVol\""));
2508        assert!(!json.contains("\"px\":"));
2509    }
2510
2511    #[rstest]
2512    fn test_ws_post_order_params_serializes_px_vol() {
2513        use super::WsPostOrderParamsBuilder;
2514        use crate::common::enums::{OKXOrderType, OKXSide, OKXTradeMode};
2515
2516        let params = WsPostOrderParamsBuilder::default()
2517            .inst_id_code(10459u64)
2518            .td_mode(OKXTradeMode::Cross)
2519            .side(OKXSide::Buy)
2520            .ord_type(OKXOrderType::Limit)
2521            .sz("1".to_string())
2522            .px_vol("0.55".to_string())
2523            .build()
2524            .unwrap();
2525
2526        let json = serde_json::to_string(&params).unwrap();
2527        assert!(json.contains("\"pxVol\":\"0.55\""));
2528        assert!(!json.contains("\"pxUsd\""));
2529        assert!(!json.contains("\"px\":"));
2530    }
2531
2532    #[rstest]
2533    fn test_ws_amend_order_params_serializes_new_px_usd() {
2534        use super::WsAmendOrderParamsBuilder;
2535
2536        let params = WsAmendOrderParamsBuilder::default()
2537            .inst_id_code(10459u64)
2538            .cl_ord_id("client123".to_string())
2539            .new_px_usd("105.0".to_string())
2540            .build()
2541            .unwrap();
2542
2543        let json = serde_json::to_string(&params).unwrap();
2544        assert!(json.contains("\"newPxUsd\":\"105.0\""));
2545        assert!(!json.contains("\"newPx\":"));
2546        assert!(!json.contains("\"newPxVol\""));
2547    }
2548
2549    #[rstest]
2550    fn test_ws_amend_order_params_serializes_new_px_vol() {
2551        use super::WsAmendOrderParamsBuilder;
2552
2553        let params = WsAmendOrderParamsBuilder::default()
2554            .inst_id_code(10459u64)
2555            .cl_ord_id("client123".to_string())
2556            .new_px_vol("0.60".to_string())
2557            .build()
2558            .unwrap();
2559
2560        let json = serde_json::to_string(&params).unwrap();
2561        assert!(json.contains("\"newPxVol\":\"0.60\""));
2562        assert!(!json.contains("\"newPx\":"));
2563        assert!(!json.contains("\"newPxUsd\""));
2564    }
2565
2566    #[rstest]
2567    fn test_ws_event_contract_markets_channel_serialization() {
2568        let json = serde_json::to_string(&OKXWsChannel::EventContractMarkets).unwrap();
2569        let channel: OKXWsChannel = serde_json::from_str(&json).unwrap();
2570
2571        assert_eq!(json, "\"event-contract-markets\"");
2572        assert_eq!(channel, OKXWsChannel::EventContractMarkets);
2573    }
2574
2575    #[rstest]
2576    fn test_ws_post_order_params_serializes_event_contract_fields() {
2577        use super::WsPostOrderParamsBuilder;
2578        use crate::common::enums::{OKXOrderType, OKXSide, OKXTradeMode};
2579
2580        let params = WsPostOrderParamsBuilder::default()
2581            .inst_id_code(10459u64)
2582            .td_mode(OKXTradeMode::Cash)
2583            .side(OKXSide::Buy)
2584            .ord_type(OKXOrderType::Limit)
2585            .sz("10".to_string())
2586            .px("0.42".to_string())
2587            .outcome("yes")
2588            .build()
2589            .unwrap();
2590
2591        let json: serde_json::Value = serde_json::to_value(&params).unwrap();
2592
2593        assert!(json.get("speedBump").is_none());
2594        assert_eq!(json["outcome"], "yes");
2595    }
2596
2597    #[rstest]
2598    fn test_ws_amend_order_params_omits_speed_bump() {
2599        use super::WsAmendOrderParamsBuilder;
2600
2601        let params = WsAmendOrderParamsBuilder::default()
2602            .inst_id_code(10459u64)
2603            .cl_ord_id("event-1".to_string())
2604            .new_px("0.43".to_string())
2605            .build()
2606            .unwrap();
2607
2608        let json: serde_json::Value = serde_json::to_value(&params).unwrap();
2609
2610        assert_eq!(
2611            json,
2612            serde_json::json!({
2613                "instIdCode": 10459,
2614                "clOrdId": "event-1",
2615                "newPx": "0.43",
2616            })
2617        );
2618    }
2619
2620    #[rstest]
2621    fn test_ws_attach_algo_ord_params_serializes_trailing_fields() {
2622        use super::WsAttachAlgoOrdParamsBuilder;
2623
2624        let params = WsAttachAlgoOrdParamsBuilder::default()
2625            .attach_algo_cl_ord_id("trail-1")
2626            .callback_ratio("0.01")
2627            .active_px("64000")
2628            .new_callback_ratio("0.02")
2629            .new_callback_spread("25")
2630            .new_active_px("65000")
2631            .build()
2632            .unwrap();
2633
2634        let json: serde_json::Value = serde_json::to_value(&params).unwrap();
2635
2636        assert_eq!(json["callbackRatio"], "0.01");
2637        assert_eq!(json["activePx"], "64000");
2638        assert_eq!(json["newCallbackRatio"], "0.02");
2639        assert_eq!(json["newCallbackSpread"], "25");
2640        assert_eq!(json["newActivePx"], "65000");
2641        assert!(json.get("callbackSpread").is_none());
2642    }
2643
2644    #[rstest]
2645    fn test_subscription_arg_serializes_sprd_id_for_spread_channels() {
2646        let arg = OKXSubscriptionArg {
2647            channel: OKXWsChannel::SprdBooks5,
2648            inst_type: None,
2649            inst_family: None,
2650            inst_id: Some(Ustr::from("ETH-USD-260925_ETH-USD-261225")),
2651        };
2652        let json = serde_json::to_value(&arg).unwrap();
2653        assert_eq!(json["channel"], "sprd-books5");
2654        assert_eq!(json["sprdId"], "ETH-USD-260925_ETH-USD-261225");
2655        assert!(json.get("instId").is_none());
2656    }
2657
2658    #[rstest]
2659    fn test_subscription_arg_serializes_inst_id_for_standard_channels() {
2660        let arg = OKXSubscriptionArg {
2661            channel: OKXWsChannel::BboTbt,
2662            inst_type: None,
2663            inst_family: None,
2664            inst_id: Some(Ustr::from("BTC-USDT")),
2665        };
2666        let json = serde_json::to_value(&arg).unwrap();
2667        assert_eq!(json["instId"], "BTC-USDT");
2668        assert!(json.get("sprdId").is_none());
2669    }
2670
2671    #[rstest]
2672    fn test_websocket_arg_resolves_sprd_id_into_inst_id() {
2673        let arg: OKXWebSocketArg = serde_json::from_value(serde_json::json!({
2674            "channel": "sprd-bbo-tbt",
2675            "sprdId": "ETH-USD-260925_ETH-USD-261225",
2676        }))
2677        .unwrap();
2678        assert_eq!(arg.channel, OKXWsChannel::SprdBboTbt);
2679        assert_eq!(
2680            arg.inst_id,
2681            Some(Ustr::from("ETH-USD-260925_ETH-USD-261225"))
2682        );
2683    }
2684
2685    #[rstest]
2686    fn test_book_msg_parses_three_element_spread_levels() {
2687        // sprd-books5 levels are [price, size, count] (3 elements), unlike the
2688        // 4-element standard book levels.
2689        let msg: OKXBookMsg = serde_json::from_value(serde_json::json!({
2690            "asks": [["16.7", "100", "1"]],
2691            "bids": [["16.65", "100", "1"]],
2692            "ts": "1780044924909",
2693            "seqId": 1_779_935_772_619_784_u64,
2694        }))
2695        .unwrap();
2696        assert_eq!(msg.asks[0].price, "16.7");
2697        assert_eq!(msg.asks[0].size, "100");
2698        assert_eq!(msg.bids[0].price, "16.65");
2699    }
2700
2701    #[rstest]
2702    fn test_trade_msg_parses_spread_public_trade() {
2703        // sprd-public-trades keys the instrument as `sprdId` and omits `count`.
2704        let msg: OKXTradeMsg = serde_json::from_value(serde_json::json!({
2705            "sprdId": "ETH-USD-260925_ETH-USD-261225",
2706            "tradeId": "3392538740127301632",
2707            "px": "16.9",
2708            "sz": "100",
2709            "side": "sell",
2710            "ts": "1780047866507",
2711        }))
2712        .unwrap();
2713        assert_eq!(msg.inst_id, Ustr::from("ETH-USD-260925_ETH-USD-261225"));
2714        assert_eq!(msg.px, "16.9");
2715        assert_eq!(msg.side, OKXSide::Sell);
2716        assert!(msg.count.is_empty());
2717    }
2718}