Skip to main content

nautilus_okx/common/
consts.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//! Core constants shared across the OKX adapter components.
17
18use std::sync::LazyLock;
19
20use ahash::AHashSet;
21use nautilus_model::{
22    enums::{OrderSide, OrderType, PositionSide, TimeInForce, TriggerType},
23    events::OrderDeniedReason,
24    identifiers::{ClientId, Venue},
25    instruments::{Instrument, InstrumentAny},
26};
27use ustr::Ustr;
28
29use super::enums::{
30    OKXBookChannel, OKXContractType, OKXInstrumentType, OKXTargetCurrency, OKXTradeMode,
31    OKXVipLevel,
32};
33
34/// Venue identifier string.
35pub const OKX: &str = "OKX";
36
37/// Static venue instance.
38pub static OKX_VENUE: LazyLock<Venue> = LazyLock::new(|| Venue::new(Ustr::from(OKX)));
39
40/// Static client ID instance.
41pub static OKX_CLIENT_ID: LazyLock<ClientId> = LazyLock::new(|| ClientId::new(Ustr::from(OKX)));
42
43/// See the [OKX integration program](https://www.okx.com/docs-v5/en/#overview-broker-program) for details.
44pub const OKX_NAUTILUS_BROKER_ID: &str = "5328c82e5542BCDE";
45
46/// Default lookback for terminal orders and fills during reconciliation.
47///
48/// Active orders and current positions are requested independently of this window. The three-day
49/// default matches the retention of `GET /api/v5/trade/fills`.
50pub const OKX_RECONCILIATION_LOOKBACK_DEFAULT_MINS: u64 = 3 * 24 * 60;
51
52/// Maximum lookback for terminal orders and fills during reconciliation.
53///
54/// Seven days is the longest complete window across the regular order history and spread trade
55/// history endpoints used for reconciliation.
56pub const OKX_RECONCILIATION_LOOKBACK_MAX_MINS: u64 = 7 * 24 * 60;
57
58// Use the canonical host with www to avoid cross-domain redirects which may
59// strip authentication headers in some HTTP clients and middleboxes.
60pub const OKX_HTTP_URL: &str = "https://www.okx.com";
61pub const OKX_WS_PUBLIC_URL: &str = "wss://ws.okx.com/ws/v5/public";
62pub const OKX_WS_PRIVATE_URL: &str = "wss://ws.okx.com/ws/v5/private";
63pub const OKX_WS_BUSINESS_URL: &str = "wss://ws.okx.com/ws/v5/business";
64pub const OKX_WS_DEMO_PUBLIC_URL: &str = "wss://wspap.okx.com/ws/v5/public";
65pub const OKX_WS_DEMO_PRIVATE_URL: &str = "wss://wspap.okx.com/ws/v5/private";
66pub const OKX_WS_DEMO_BUSINESS_URL: &str = "wss://wspap.okx.com/ws/v5/business";
67
68pub const OKX_WS_TOPIC_DELIMITER: char = ':';
69
70/// WebSocket heartbeat (ping/pong) interval in seconds.
71pub const OKX_WS_HEARTBEAT_SECS: u64 = 20;
72
73/// OKX success response code for WebSocket operations.
74pub const OKX_SUCCESS_CODE: &str = "0";
75
76/// OKX WebSocket code indicating a service upgrade and required reconnect.
77pub const OKX_SERVICE_UPGRADE_RECONNECT_CODE: &str = "64008";
78
79/// JSON field key for sub-error code in order operation responses.
80pub const OKX_FIELD_SCODE: &str = "sCode";
81
82/// JSON field key for sub-error message in order operation responses.
83pub const OKX_FIELD_SMSG: &str = "sMsg";
84
85/// JSON field key for detailed sub-error code in order operation responses.
86pub const OKX_FIELD_SUBCODE: &str = "subCode";
87
88/// JSON field key for client order ID in order operation responses.
89pub const OKX_FIELD_CLORDID: &str = "clOrdId";
90
91/// Maximum length of a `clOrdId` accepted by OKX.
92///
93/// OKX requires `clOrdId` to be 1-32 case-sensitive alphanumeric characters.
94/// See <https://www.okx.com/docs-v5/en/#order-book-trading-trade>.
95pub const OKX_MAX_CLORDID_LEN: usize = 32;
96
97/// Validates a `clOrdId` against OKX's length and charset rules.
98///
99/// # Errors
100///
101/// Returns an error if the ID exceeds [`OKX_MAX_CLORDID_LEN`] characters or contains
102/// non-alphanumeric characters (such as hyphens or underscores). The error gives a human-readable
103/// reason.
104pub fn validate_okx_client_order_id(cl_ord_id: &str) -> Result<(), String> {
105    let len = cl_ord_id.len();
106    if len > OKX_MAX_CLORDID_LEN {
107        return Err(format!(
108            "OKX requires clOrdId to be at most {OKX_MAX_CLORDID_LEN} characters, was {len} ({cl_ord_id:?}); \
109             set `use_uuid_client_order_ids=True` and `use_hyphens_in_client_order_ids=False` on the strategy config"
110        ));
111    }
112
113    if !cl_ord_id.bytes().all(|b| b.is_ascii_alphanumeric()) {
114        return Err(format!(
115            "OKX requires clOrdId to be alphanumeric only, was {cl_ord_id:?}; \
116             set `use_hyphens_in_client_order_ids=False` on the strategy config"
117        ));
118    }
119
120    Ok(())
121}
122
123/// Resolves the OKX wire representation for a Nautilus reduce-only instruction.
124///
125/// A closing `side` and `posSide` pair enforces the same intent in OKX long/short mode, where the
126/// literal `reduceOnly` field is not applicable.
127///
128/// # Errors
129///
130/// Returns an error if OKX cannot enforce reduce-only for the selected product or when a
131/// long/short-mode order would increase the selected position side.
132pub(crate) fn okx_reduce_only_wire_value(
133    instrument_type: OKXInstrumentType,
134    td_mode: OKXTradeMode,
135    order_side: OrderSide,
136    position_side: Option<PositionSide>,
137    reduce_only: Option<bool>,
138) -> Result<Option<bool>, String> {
139    if reduce_only != Some(true) {
140        return Ok(None);
141    }
142
143    match instrument_type {
144        OKXInstrumentType::Spot | OKXInstrumentType::Margin => {
145            if td_mode == OKXTradeMode::Cash {
146                Err("OKX cash orders do not support reduce-only instructions".to_string())
147            } else if instrument_type == OKXInstrumentType::Spot {
148                Err("OKX spot orders do not support reduce-only instructions".to_string())
149            } else {
150                Ok(Some(true))
151            }
152        }
153        OKXInstrumentType::Swap | OKXInstrumentType::Futures => match position_side {
154            None => Ok(Some(true)),
155            Some(PositionSide::Long) if order_side == OrderSide::Sell => Ok(None),
156            Some(PositionSide::Short) if order_side == OrderSide::Buy => Ok(None),
157            Some(position_side) => Err(format!(
158                "OKX {order_side} orders on the {position_side} side do not enforce reduce-only"
159            )),
160        },
161        OKXInstrumentType::Option | OKXInstrumentType::Events => Err(format!(
162            "OKX {instrument_type} orders do not support reduce-only instructions"
163        )),
164        OKXInstrumentType::Any => Ok(Some(true)),
165    }
166}
167
168/// Resolves quantity units for ordinary market orders.
169///
170/// # Errors
171///
172/// Returns an error if a margin order requests units other than its native side-dependent units.
173pub(crate) fn okx_market_target_currency(
174    instrument_type: OKXInstrumentType,
175    order_side: OrderSide,
176    order_type: OrderType,
177    quote_quantity: Option<bool>,
178) -> Result<Option<OKXTargetCurrency>, OrderDeniedReason> {
179    if order_type != OrderType::Market {
180        return Ok(None);
181    }
182
183    match instrument_type {
184        OKXInstrumentType::Spot => Ok(match quote_quantity {
185            Some(true) => Some(OKXTargetCurrency::QuoteCcy),
186            Some(false) if order_side == OrderSide::Buy => Some(OKXTargetCurrency::BaseCcy),
187            _ => None,
188        }),
189        OKXInstrumentType::Margin => {
190            let native_quote = order_side == OrderSide::Buy;
191            if quote_quantity.is_some_and(|quote| quote != native_quote) {
192                let unit = if native_quote { "quote" } else { "base" };
193                return Err(OrderDeniedReason::ValidationFailed {
194                    detail: format!(
195                        "OKXInstrumentType::Margin market {order_side} orders require {unit} quantity"
196                    ),
197                });
198            }
199
200            Ok(None)
201        }
202        _ => Ok(None),
203    }
204}
205
206/// Resolves explicit sizing for algo orders.
207///
208/// # Errors
209///
210/// Returns an error if the requested quantity denomination has no supported wire representation.
211pub(crate) fn okx_algo_target_currency(
212    instrument_type: OKXInstrumentType,
213    td_mode: OKXTradeMode,
214    order_side: OrderSide,
215    order_type: OrderType,
216    quote_quantity: bool,
217) -> Result<Option<OKXTargetCurrency>, OrderDeniedReason> {
218    if !OKX_CONDITIONAL_ORDER_TYPES.contains(&order_type) {
219        return Ok(None);
220    }
221
222    if instrument_type == OKXInstrumentType::Spot && order_side == OrderSide::Buy {
223        if matches!(
224            order_type,
225            OrderType::StopMarket | OrderType::MarketIfTouched
226        ) {
227            return Ok(Some(if quote_quantity {
228                OKXTargetCurrency::QuoteCcy
229            } else {
230                OKXTargetCurrency::BaseCcy
231            }));
232        }
233
234        if order_type == OrderType::TrailingStopMarket {
235            return if quote_quantity {
236                Ok(None)
237            } else {
238                Err(OrderDeniedReason::ValidationFailed {
239                    detail: format!(
240                        "OKX {instrument_type} {order_type} algo buys require quote quantity in {td_mode} mode"
241                    ),
242                })
243            };
244        }
245    }
246
247    if quote_quantity {
248        return Err(OrderDeniedReason::unsupported_quote_quantity());
249    }
250
251    Ok(None)
252}
253
254/// Validates a native algo order's trigger feed.
255///
256/// # Errors
257///
258/// Returns an error if OKX cannot represent the requested trigger feed.
259pub(crate) fn validate_algo_trigger_type(
260    instrument_type: OKXInstrumentType,
261    td_mode: OKXTradeMode,
262    order_type: OrderType,
263    trigger_type: Option<TriggerType>,
264) -> Result<(), String> {
265    if !OKX_CONDITIONAL_ORDER_TYPES.contains(&order_type) {
266        return Ok(());
267    }
268
269    let Some(trigger_type) = trigger_type else {
270        return Ok(());
271    };
272
273    let supported = match trigger_type {
274        TriggerType::Default | TriggerType::LastPrice => true,
275        TriggerType::MarkPrice | TriggerType::IndexPrice => {
276            (instrument_type != OKXInstrumentType::Spot || td_mode != OKXTradeMode::Cash)
277                && order_type != OrderType::TrailingStopMarket
278        }
279        _ => false,
280    };
281
282    if !supported {
283        return Err(format!(
284            "OKX {instrument_type} {order_type} algo orders do not support {trigger_type} triggers"
285        ));
286    }
287
288    Ok(())
289}
290
291pub(crate) fn validate_order_time_in_force(
292    time_in_force: Option<TimeInForce>,
293) -> Result<(), String> {
294    if let Some(tif) = time_in_force
295        && !OKX_SUPPORTED_TIME_IN_FORCE.contains(&tif)
296    {
297        return Err(format!("Unsupported time in force: {tif:?}"));
298    }
299
300    Ok(())
301}
302
303pub(crate) fn validate_regular_order_params(
304    instrument_type: OKXInstrumentType,
305    order_type: OrderType,
306    time_in_force: Option<TimeInForce>,
307    post_only: bool,
308    rpi: bool,
309    outcome: Option<&str>,
310) -> Result<(), String> {
311    if rpi && order_type != OrderType::Limit {
312        return Err("OKX RPI orders require a limit order".to_string());
313    }
314
315    if !rpi
316        && !post_only
317        && order_type == OrderType::Market
318        && time_in_force == Some(TimeInForce::Fok)
319    {
320        return Err("Market orders with FOK time-in-force are not supported by OKX. Use Limit order with FOK instead.".to_string());
321    }
322
323    if instrument_type == OKXInstrumentType::Events && outcome.is_none() {
324        return Err("OKX event contract orders require `outcome`".to_string());
325    }
326
327    Ok(())
328}
329
330/// OKX supported order time in force.
331///
332/// # Notes
333///
334/// - OKX implements IOC and FOK as order types rather than separate time-in-force parameters.
335/// - FOK is only supported with Limit orders (Market + FOK is not supported).
336/// - IOC with Market orders uses `OptimalLimitIoc`, with Limit orders uses Ioc.
337/// - GTD is supported via `expire_time` parameter.
338pub const OKX_SUPPORTED_TIME_IN_FORCE: &[TimeInForce] = &[
339    TimeInForce::Gtc, // Good Till Cancel (default)
340    TimeInForce::Ioc, // Immediate or Cancel (mapped to OKXOrderType::Ioc or OptimalLimitIoc)
341    TimeInForce::Fok, // Fill or Kill (only with Limit orders, mapped to OKXOrderType::Fok)
342];
343
344/// OKX supported order types.
345///
346/// # Notes
347///
348/// - `PostOnly` is supported as a flag on limit orders.
349/// - Conditional orders (stop/trigger) are supported via algo orders.
350pub const OKX_SUPPORTED_ORDER_TYPES: &[OrderType] = &[
351    OrderType::Market,
352    OrderType::Limit,
353    OrderType::MarketToLimit,   // Mapped to IOC when no price is specified
354    OrderType::StopMarket,      // Supported via algo order API
355    OrderType::StopLimit,       // Supported via algo order API
356    OrderType::MarketIfTouched, // Supported via algo order API
357    OrderType::LimitIfTouched,  // Supported via algo order API
358    OrderType::TrailingStopMarket, // Supported via algo order API (move_order_stop)
359];
360
361/// Conditional order types that require the OKX algo order API.
362pub const OKX_CONDITIONAL_ORDER_TYPES: &[OrderType] = &[
363    OrderType::StopMarket,
364    OrderType::StopLimit,
365    OrderType::MarketIfTouched,
366    OrderType::LimitIfTouched,
367    OrderType::TrailingStopMarket,
368];
369
370/// Advance algo order types that require `cancel-advance-algos` for cancellation.
371/// These cannot be cancelled via the standard `cancel-algos` endpoint.
372pub const OKX_ADVANCE_ALGO_ORDER_TYPES: &[OrderType] = &[OrderType::TrailingStopMarket];
373
374/// OKX error codes that should trigger retries.
375///
376/// Only retry on temporary network/system issues. Retries never apply to
377/// order submission POSTs: OKX rejects a duplicate `clOrdId` only while the
378/// first order rests open, so a submit whose response was lost can already
379/// have filled, and retrying could place a second live order. Submits are
380/// sent once, and an ambiguous outcome resolves through stream updates and
381/// reconciliation.
382///
383/// # References
384///
385/// Based on OKX API documentation: <https://www.okx.com/docs-v5/en/#error-codes>
386pub static OKX_RETRY_ERROR_CODES: LazyLock<AHashSet<&'static str>> = LazyLock::new(|| {
387    let mut codes = AHashSet::new();
388
389    // Temporary system errors
390    codes.insert("50001"); // Service temporarily unavailable
391    codes.insert("50004"); // API endpoint request timeout (does not mean that the request was successful or failed, please check the request result)
392    codes.insert("50005"); // API is offline or unavailable
393    codes.insert("50013"); // System busy, please try again later
394    codes.insert("50026"); // System error, please try again later
395
396    // Rate limit errors (temporary)
397    codes.insert("50011"); // Request too frequent
398
399    // WebSocket connection issues (temporary)
400    codes.insert("60001"); // OK not received in time
401    codes.insert("60005"); // Connection closed as there was no data transmission in the last 30 seconds
402    codes.insert(OKX_SERVICE_UPGRADE_RECONNECT_CODE); // Service upgrade, please reconnect
403
404    codes
405});
406
407/// Determines if an OKX error code should trigger a retry.
408pub fn should_retry_error_code(error_code: &str) -> bool {
409    OKX_RETRY_ERROR_CODES.contains(error_code)
410}
411
412/// OKX error code returned when an order request timed out and the outcome is unknown.
413pub const OKX_ORDER_REQUEST_TIMEOUT_CODE: &str = "51149";
414
415/// OKX error code returned when a post-only order would immediately take liquidity.
416pub const OKX_POST_ONLY_ERROR_CODE: &str = "51019";
417
418/// OKX cancel source code used when a post-only order is auto-cancelled for taking liquidity.
419pub const OKX_POST_ONLY_CANCEL_SOURCE: &str = "31";
420
421/// Human-readable reason used when a post-only order is auto-cancelled for taking liquidity.
422pub const OKX_POST_ONLY_CANCEL_REASON: &str = "POST_ONLY would take liquidity";
423
424/// OKX error code returned when a market order's `slippagePct` would be exceeded by the
425/// projected fill, so the order is rejected.
426pub const OKX_SLIPPAGE_EXCEEDED_ERROR_CODE: &str = "54084";
427
428/// OKX error code returned when the supplied `slippagePct` value is outside the
429/// venue-permitted range.
430pub const OKX_SLIPPAGE_INVALID_ERROR_CODE: &str = "54085";
431
432/// Returns `true` if the OKX `sCode` identifies a slippage-related rejection emitted
433/// in response to the `slippagePct` parameter on market orders.
434#[must_use]
435pub fn is_slippage_rejection(error_code: &str) -> bool {
436    matches!(
437        error_code,
438        OKX_SLIPPAGE_EXCEEDED_ERROR_CODE | OKX_SLIPPAGE_INVALID_ERROR_CODE
439    )
440}
441
442/// Target currency literal for base currency.
443pub const OKX_TARGET_CCY_BASE: &str = "base_ccy";
444
445/// Target currency literal for quote currency.
446pub const OKX_TARGET_CCY_QUOTE: &str = "quote_ccy";
447
448/// `feature` value for `POST /api/v5/account/activate-feature` USDC order book trading.
449pub const OKX_FEATURE_USDC_ORDER_BOOK: &str = "1";
450
451/// Resolves the optional `tradeQuoteCcy` wire value for a SPOT order.
452///
453/// Non-spot orders omit the field. When `configured` is unset or blank, the venue
454/// default (the quote currency in `instId`) is used. When set, `available` must be
455/// non-empty and contain the value.
456///
457/// # Errors
458///
459/// Returns an error if `configured` is set and `available` is empty, or when `configured` is not
460/// present in `available`.
461pub fn spot_trade_quote_ccy_wire_value(
462    instrument_type: OKXInstrumentType,
463    configured: Option<&str>,
464    available: &[Ustr],
465) -> Result<Option<Ustr>, String> {
466    if instrument_type != OKXInstrumentType::Spot {
467        return Ok(None);
468    }
469
470    let Some(ccy) = configured.map(str::trim).filter(|value| !value.is_empty()) else {
471        return Ok(None);
472    };
473    let ccy = Ustr::from(ccy);
474
475    if available.is_empty() {
476        return Err(format!(
477            "tradeQuoteCcyList is unknown for this instrument; cannot validate tradeQuoteCcy '{ccy}'"
478        ));
479    }
480
481    if !available.contains(&ccy) {
482        let listed = available
483            .iter()
484            .map(Ustr::as_str)
485            .collect::<Vec<_>>()
486            .join(", ");
487        return Err(format!(
488            "tradeQuoteCcy '{ccy}' is not in tradeQuoteCcyList for this instrument, was [{listed}]"
489        ));
490    }
491
492    Ok(Some(ccy))
493}
494
495/// Resolves instrument families for a given instrument type.
496///
497/// Returns `Some(families)` when the type supports family filtering, or `None`
498/// to skip the instrument type entirely (Option without configured families).
499/// An empty vec means no family filter is needed (Spot, Margin), or all
500/// discoverable families should be loaded (Events).
501pub fn resolve_instrument_families(
502    configured: &Option<Vec<String>>,
503    inst_type: OKXInstrumentType,
504) -> Option<Vec<String>> {
505    match (configured, inst_type) {
506        (Some(families), OKXInstrumentType::Option) => Some(families.clone()),
507        (
508            Some(families),
509            OKXInstrumentType::Futures | OKXInstrumentType::Swap | OKXInstrumentType::Events,
510        ) => Some(families.clone()),
511        (None, OKXInstrumentType::Option) => {
512            log::warn!("Skipping OPTION type: instrument_families required but not configured");
513            None
514        }
515        _ => Some(vec![]),
516    }
517}
518
519/// Clamps a requested book depth to the nearest OKX-supported value.
520///
521/// OKX WebSocket channels support depths of 50 and 400. Depth 0 means
522/// auto-select based on VIP level. Any other value rounds up to the nearest
523/// supported depth so the subscription succeeds and the data engine can
524/// truncate to the originally requested depth.
525pub fn resolve_book_depth(raw_depth: usize) -> usize {
526    match raw_depth {
527        0 | 400 => raw_depth,
528        1..=50 => 50,
529        _ => 400,
530    }
531}
532
533pub(crate) fn select_book_channel(depth: usize, vip: OKXVipLevel) -> OKXBookChannel {
534    match depth {
535        50 if vip >= OKXVipLevel::Vip4 => OKXBookChannel::Books50L2Tbt,
536        0 | 400 if vip >= OKXVipLevel::Vip4 => OKXBookChannel::BookL2Tbt,
537        0 | 50 | 400 => OKXBookChannel::Book,
538        _ => unreachable!("book depth must be resolved before channel selection"),
539    }
540}
541
542pub(crate) fn contract_filter_with_config_types(
543    contract_types: Option<&Vec<OKXContractType>>,
544    instrument: &InstrumentAny,
545) -> bool {
546    match contract_types {
547        None => true,
548        Some(filter) if filter.is_empty() => true,
549        Some(filter) => {
550            let is_inverse = instrument.is_inverse();
551            (is_inverse && filter.contains(&OKXContractType::Inverse))
552                || (!is_inverse && filter.contains(&OKXContractType::Linear))
553        }
554    }
555}
556
557#[cfg(test)]
558mod tests {
559    use rstest::rstest;
560
561    use super::*;
562
563    #[rstest]
564    #[case::market_fok(false, Err("Market orders with FOK time-in-force are not supported by OKX. Use Limit order with FOK instead.".to_string()))]
565    #[case::post_only_precedence(true, Ok(()))]
566    fn test_validate_regular_order_params_preserves_post_only_precedence(
567        #[case] post_only: bool,
568        #[case] expected: Result<(), String>,
569    ) {
570        assert_eq!(
571            validate_regular_order_params(
572                OKXInstrumentType::Swap,
573                OrderType::Market,
574                Some(TimeInForce::Fok),
575                post_only,
576                false,
577                None
578            ),
579            expected
580        );
581    }
582
583    #[rstest]
584    #[case::buy_quote(OrderSide::Buy, Some(true))]
585    #[case::sell_base(OrderSide::Sell, Some(false))]
586    #[case::buy_default(OrderSide::Buy, None)]
587    #[case::sell_default(OrderSide::Sell, None)]
588    fn test_market_target_currency_preserves_native_margin_units(
589        #[case] side: OrderSide,
590        #[case] quote_quantity: Option<bool>,
591    ) {
592        assert_eq!(
593            okx_market_target_currency(
594                OKXInstrumentType::Margin,
595                side,
596                OrderType::Market,
597                quote_quantity,
598            ),
599            Ok(None),
600        );
601    }
602
603    #[rstest]
604    #[case::spot_limit(OKXInstrumentType::Spot, OrderType::Limit)]
605    #[case::spot_market_to_limit(OKXInstrumentType::Spot, OrderType::MarketToLimit)]
606    #[case::swap_market(OKXInstrumentType::Swap, OrderType::Market)]
607    #[case::event_market(OKXInstrumentType::Events, OrderType::Market)]
608    fn test_market_target_currency_omits_unrelated_units(
609        #[case] instrument_type: OKXInstrumentType,
610        #[case] order_type: OrderType,
611    ) {
612        assert_eq!(
613            okx_market_target_currency(instrument_type, OrderSide::Buy, order_type, Some(true)),
614            Ok(None),
615        );
616    }
617
618    #[rstest]
619    #[case::auto_default(0, OKXVipLevel::Vip0, OKXBookChannel::Book)]
620    #[case::auto_vip3(0, OKXVipLevel::Vip3, OKXBookChannel::Book)]
621    #[case::auto_vip4(0, OKXVipLevel::Vip4, OKXBookChannel::BookL2Tbt)]
622    #[case::auto_vip5(0, OKXVipLevel::Vip5, OKXBookChannel::BookL2Tbt)]
623    #[case::depth_50_vip3(50, OKXVipLevel::Vip3, OKXBookChannel::Book)]
624    #[case::depth_50_vip4(50, OKXVipLevel::Vip4, OKXBookChannel::Books50L2Tbt)]
625    #[case::depth_400_vip3(400, OKXVipLevel::Vip3, OKXBookChannel::Book)]
626    #[case::depth_400_vip4(400, OKXVipLevel::Vip4, OKXBookChannel::BookL2Tbt)]
627    #[case::depth_400_vip5(400, OKXVipLevel::Vip5, OKXBookChannel::BookL2Tbt)]
628    fn test_select_book_channel(
629        #[case] depth: usize,
630        #[case] vip: OKXVipLevel,
631        #[case] expected: OKXBookChannel,
632    ) {
633        assert_eq!(select_book_channel(depth, vip), expected);
634    }
635
636    #[rstest]
637    #[case("54084", true)]
638    #[case("54085", true)]
639    #[case("51019", false)]
640    #[case("", false)]
641    fn test_is_slippage_rejection(#[case] code: &str, #[case] expected: bool) {
642        assert_eq!(is_slippage_rejection(code), expected);
643    }
644
645    #[rstest]
646    #[case("50001", true)]
647    #[case("50011", true)]
648    #[case("60005", true)]
649    #[case("60014", false)]
650    #[case("64007", false)]
651    #[case(OKX_SERVICE_UPGRADE_RECONNECT_CODE, true)]
652    #[case("50113", false)]
653    #[case("60012", false)]
654    fn test_should_retry_error_code(#[case] code: &str, #[case] expected: bool) {
655        assert_eq!(should_retry_error_code(code), expected);
656    }
657
658    #[rstest]
659    #[case("O20260101000000ABC1", true)]
660    #[case("aB9", true)]
661    #[case("abcdefghij0123456789ABCDEFGHIJ12", true)] // exactly 32 chars
662    #[case("abcdefghij0123456789ABCDEFGHIJ123", false)] // 33 chars
663    #[case("O-20260101-000000-001-001-1", false)] // hyphens
664    #[case("O_20260101_000000", false)] // underscores
665    #[case("", true)] // empty: OKX rejects, but core ClientOrderId never produces empty
666    fn test_validate_okx_client_order_id(#[case] cl_ord_id: &str, #[case] expected_ok: bool) {
667        assert_eq!(validate_okx_client_order_id(cl_ord_id).is_ok(), expected_ok);
668    }
669
670    #[rstest]
671    fn test_validate_okx_client_order_id_length_message() {
672        // 35-char compact ID (the shape reported in the original bug report).
673        let cl_ord_id = "O20260522145501532392555aceLTCUSDT5";
674        let err = validate_okx_client_order_id(cl_ord_id).unwrap_err();
675        assert!(err.contains("at most 32"));
676        assert!(err.contains("was 35"));
677        assert!(err.contains("use_uuid_client_order_ids"));
678    }
679
680    #[rstest]
681    #[case(OrderSide::Buy, false, Some(OKXTargetCurrency::BaseCcy))]
682    #[case(OrderSide::Buy, true, Some(OKXTargetCurrency::QuoteCcy))]
683    #[case(OrderSide::Sell, false, None)]
684    fn test_okx_algo_target_currency_cash_market_orders(
685        #[case] side: OrderSide,
686        #[case] quote_quantity: bool,
687        #[case] expected: Option<OKXTargetCurrency>,
688        #[values(OrderType::StopMarket, OrderType::MarketIfTouched)] order_type: OrderType,
689    ) {
690        assert_eq!(
691            okx_algo_target_currency(
692                OKXInstrumentType::Spot,
693                OKXTradeMode::Cash,
694                side,
695                order_type,
696                quote_quantity,
697            ),
698            Ok(expected),
699        );
700    }
701
702    #[rstest]
703    fn test_okx_algo_target_currency_denies_quote_sells(
704        #[values(
705            OrderType::StopMarket,
706            OrderType::MarketIfTouched,
707            OrderType::TrailingStopMarket
708        )]
709        order_type: OrderType,
710        #[values(OKXTradeMode::Cash, OKXTradeMode::Cross, OKXTradeMode::Isolated)]
711        trade_mode: OKXTradeMode,
712    ) {
713        assert_eq!(
714            okx_algo_target_currency(
715                OKXInstrumentType::Spot,
716                trade_mode,
717                OrderSide::Sell,
718                order_type,
719                true,
720            ),
721            Err(OrderDeniedReason::unsupported_quote_quantity()),
722        );
723    }
724
725    #[rstest]
726    #[case(OKXInstrumentType::Swap, OrderType::StopMarket)]
727    #[case(OKXInstrumentType::Spot, OrderType::StopLimit)]
728    #[case(OKXInstrumentType::Spot, OrderType::LimitIfTouched)]
729    fn test_okx_algo_target_currency_preserves_base_routes(
730        #[case] instrument_type: OKXInstrumentType,
731        #[case] order_type: OrderType,
732    ) {
733        assert_eq!(
734            okx_algo_target_currency(
735                instrument_type,
736                OKXTradeMode::Cash,
737                OrderSide::Buy,
738                order_type,
739                false,
740            ),
741            Ok(None),
742        );
743    }
744
745    #[rstest]
746    fn test_okx_algo_target_currency_spot_trailing_buy_uses_native_quote_size(
747        #[values(OKXTradeMode::Cash, OKXTradeMode::Cross, OKXTradeMode::Isolated)]
748        trade_mode: OKXTradeMode,
749    ) {
750        assert_eq!(
751            okx_algo_target_currency(
752                OKXInstrumentType::Spot,
753                trade_mode,
754                OrderSide::Buy,
755                OrderType::TrailingStopMarket,
756                true,
757            ),
758            Ok(None),
759        );
760    }
761
762    #[rstest]
763    fn test_okx_algo_target_currency_does_not_restrict_ordinary_market_orders(
764        #[values(OrderSide::Buy, OrderSide::Sell)] side: OrderSide,
765        #[values(false, true)] quote_quantity: bool,
766    ) {
767        assert_eq!(
768            okx_algo_target_currency(
769                OKXInstrumentType::Spot,
770                OKXTradeMode::Cash,
771                side,
772                OrderType::Market,
773                quote_quantity,
774            ),
775            Ok(None),
776        );
777    }
778
779    #[rstest]
780    #[case(OKXTradeMode::Cross, false, OKXTargetCurrency::BaseCcy)]
781    #[case(OKXTradeMode::Cross, true, OKXTargetCurrency::QuoteCcy)]
782    #[case(OKXTradeMode::Isolated, false, OKXTargetCurrency::BaseCcy)]
783    #[case(OKXTradeMode::Isolated, true, OKXTargetCurrency::QuoteCcy)]
784    fn test_okx_algo_target_currency_non_cash_spot_buys(
785        #[case] trade_mode: OKXTradeMode,
786        #[case] quote_quantity: bool,
787        #[case] expected: OKXTargetCurrency,
788        #[values(OrderType::StopMarket, OrderType::MarketIfTouched)] order_type: OrderType,
789    ) {
790        assert_eq!(
791            okx_algo_target_currency(
792                OKXInstrumentType::Spot,
793                trade_mode,
794                OrderSide::Buy,
795                order_type,
796                quote_quantity,
797            ),
798            Ok(Some(expected)),
799        );
800    }
801
802    #[rstest]
803    #[case(OKXInstrumentType::Spot, OrderType::StopLimit)]
804    #[case(OKXInstrumentType::Spot, OrderType::LimitIfTouched)]
805    #[case(OKXInstrumentType::Swap, OrderType::StopMarket)]
806    #[case(OKXInstrumentType::Futures, OrderType::MarketIfTouched)]
807    fn test_okx_algo_target_currency_denies_unsupported_quote_orders(
808        #[case] instrument_type: OKXInstrumentType,
809        #[case] order_type: OrderType,
810        #[values(OrderSide::Buy, OrderSide::Sell)] side: OrderSide,
811        #[values(OKXTradeMode::Cash, OKXTradeMode::Cross, OKXTradeMode::Isolated)]
812        trade_mode: OKXTradeMode,
813    ) {
814        assert_eq!(
815            okx_algo_target_currency(instrument_type, trade_mode, side, order_type, true),
816            Err(OrderDeniedReason::unsupported_quote_quantity()),
817        );
818    }
819
820    #[rstest]
821    fn test_okx_algo_target_currency_denies_base_spot_trailing_buy() {
822        assert_eq!(
823            okx_algo_target_currency(
824                OKXInstrumentType::Spot,
825                OKXTradeMode::Cash,
826                OrderSide::Buy,
827                OrderType::TrailingStopMarket,
828                false,
829            ),
830            Err(OrderDeniedReason::ValidationFailed {
831                detail:
832                    "OKX Spot TRAILING_STOP_MARKET algo buys require quote quantity in Cash mode"
833                        .to_string(),
834            }),
835        );
836    }
837
838    #[rstest]
839    #[case(OKXInstrumentType::Spot, OrderType::StopMarket, None)]
840    #[case(
841        OKXInstrumentType::Spot,
842        OrderType::StopLimit,
843        Some(TriggerType::Default)
844    )]
845    #[case(
846        OKXInstrumentType::Spot,
847        OrderType::MarketIfTouched,
848        Some(TriggerType::LastPrice)
849    )]
850    #[case(
851        OKXInstrumentType::Spot,
852        OrderType::TrailingStopMarket,
853        Some(TriggerType::LastPrice)
854    )]
855    #[case(
856        OKXInstrumentType::Swap,
857        OrderType::StopMarket,
858        Some(TriggerType::MarkPrice)
859    )]
860    #[case(
861        OKXInstrumentType::Futures,
862        OrderType::LimitIfTouched,
863        Some(TriggerType::IndexPrice)
864    )]
865    fn test_validate_algo_trigger_type_accepts_supported_feeds(
866        #[case] instrument_type: OKXInstrumentType,
867        #[case] order_type: OrderType,
868        #[case] trigger_type: Option<TriggerType>,
869    ) {
870        assert_eq!(
871            validate_algo_trigger_type(
872                instrument_type,
873                OKXTradeMode::Cash,
874                order_type,
875                trigger_type
876            ),
877            Ok(())
878        );
879    }
880
881    #[rstest]
882    #[case(OKXInstrumentType::Spot, OrderType::StopMarket, TriggerType::MarkPrice)]
883    #[case(
884        OKXInstrumentType::Spot,
885        OrderType::MarketIfTouched,
886        TriggerType::IndexPrice
887    )]
888    #[case(OKXInstrumentType::Spot, OrderType::StopLimit, TriggerType::MarkPrice)]
889    #[case(
890        OKXInstrumentType::Spot,
891        OrderType::LimitIfTouched,
892        TriggerType::IndexPrice
893    )]
894    #[case(OKXInstrumentType::Swap, OrderType::StopMarket, TriggerType::BidAsk)]
895    #[case(
896        OKXInstrumentType::Swap,
897        OrderType::TrailingStopMarket,
898        TriggerType::MarkPrice
899    )]
900    fn test_validate_algo_trigger_type_denies_unsupported_feeds(
901        #[case] instrument_type: OKXInstrumentType,
902        #[case] order_type: OrderType,
903        #[case] trigger_type: TriggerType,
904    ) {
905        assert_eq!(
906            validate_algo_trigger_type(
907                instrument_type,
908                OKXTradeMode::Cash,
909                order_type,
910                Some(trigger_type)
911            ),
912            Err(format!(
913                "OKX {instrument_type} {order_type} algo orders do not support {trigger_type} triggers"
914            )),
915        );
916    }
917
918    #[rstest]
919    fn test_validate_algo_trigger_type_allows_non_cash_margin_feeds(
920        #[values(OKXTradeMode::Cross, OKXTradeMode::Isolated)] trade_mode: OKXTradeMode,
921        #[values(OrderType::StopMarket, OrderType::MarketIfTouched)] order_type: OrderType,
922        #[values(TriggerType::MarkPrice, TriggerType::IndexPrice)] trigger_type: TriggerType,
923    ) {
924        assert_eq!(
925            validate_algo_trigger_type(
926                OKXInstrumentType::Spot,
927                trade_mode,
928                order_type,
929                Some(trigger_type),
930            ),
931            Ok(()),
932        );
933    }
934
935    #[rstest]
936    #[case::cash(
937        OKXInstrumentType::Spot,
938        OKXTradeMode::Cash,
939        OrderSide::Sell,
940        None,
941        Err("OKX cash orders do not support reduce-only instructions".to_string()),
942    )]
943    #[case::spot_cross(
944        OKXInstrumentType::Spot,
945        OKXTradeMode::Cross,
946        OrderSide::Sell,
947        None,
948        Err("OKX spot orders do not support reduce-only instructions".to_string()),
949    )]
950    #[case::spot_isolated(
951        OKXInstrumentType::Spot,
952        OKXTradeMode::Isolated,
953        OrderSide::Sell,
954        None,
955        Err("OKX spot orders do not support reduce-only instructions".to_string()),
956    )]
957    #[case::margin(
958        OKXInstrumentType::Margin,
959        OKXTradeMode::Cross,
960        OrderSide::Sell,
961        None,
962        Ok(Some(true))
963    )]
964    #[case::net(
965        OKXInstrumentType::Swap,
966        OKXTradeMode::Cross,
967        OrderSide::Sell,
968        None,
969        Ok(Some(true))
970    )]
971    #[case::close_long(
972        OKXInstrumentType::Swap,
973        OKXTradeMode::Cross,
974        OrderSide::Sell,
975        Some(PositionSide::Long),
976        Ok(None)
977    )]
978    #[case::close_short(
979        OKXInstrumentType::Futures,
980        OKXTradeMode::Isolated,
981        OrderSide::Buy,
982        Some(PositionSide::Short),
983        Ok(None)
984    )]
985    #[case::increase_long(
986        OKXInstrumentType::Swap,
987        OKXTradeMode::Cross,
988        OrderSide::Buy,
989        Some(PositionSide::Long),
990        Err("OKX BUY orders on the LONG side do not enforce reduce-only".to_string()),
991    )]
992    #[case::option(
993        OKXInstrumentType::Option,
994        OKXTradeMode::Cross,
995        OrderSide::Sell,
996        None,
997        Err("OKX Option orders do not support reduce-only instructions".to_string()),
998    )]
999    fn test_okx_reduce_only_wire_value(
1000        #[case] instrument_type: OKXInstrumentType,
1001        #[case] td_mode: OKXTradeMode,
1002        #[case] order_side: OrderSide,
1003        #[case] position_side: Option<PositionSide>,
1004        #[case] expected: Result<Option<bool>, String>,
1005    ) {
1006        assert_eq!(
1007            okx_reduce_only_wire_value(
1008                instrument_type,
1009                td_mode,
1010                order_side,
1011                position_side,
1012                Some(true),
1013            ),
1014            expected
1015        );
1016    }
1017
1018    #[rstest]
1019    fn test_spot_trade_quote_ccy_wire_value_omits_non_spot() {
1020        assert_eq!(
1021            spot_trade_quote_ccy_wire_value(
1022                OKXInstrumentType::Swap,
1023                Some("USD"),
1024                &[Ustr::from("USD")],
1025            ),
1026            Ok(None)
1027        );
1028    }
1029
1030    #[rstest]
1031    fn test_spot_trade_quote_ccy_wire_value_omits_when_unset() {
1032        assert_eq!(
1033            spot_trade_quote_ccy_wire_value(OKXInstrumentType::Spot, None, &[Ustr::from("USD")]),
1034            Ok(None)
1035        );
1036        assert_eq!(
1037            spot_trade_quote_ccy_wire_value(OKXInstrumentType::Spot, Some("  "), &[]),
1038            Ok(None)
1039        );
1040    }
1041
1042    #[rstest]
1043    fn test_spot_trade_quote_ccy_wire_value_sends_usd_when_listed() {
1044        assert_eq!(
1045            spot_trade_quote_ccy_wire_value(
1046                OKXInstrumentType::Spot,
1047                Some("USD"),
1048                &[Ustr::from("USD"), Ustr::from("USDC")],
1049            ),
1050            Ok(Some(Ustr::from("USD")))
1051        );
1052    }
1053
1054    #[rstest]
1055    fn test_spot_trade_quote_ccy_wire_value_rejects_when_list_unknown() {
1056        let err =
1057            spot_trade_quote_ccy_wire_value(OKXInstrumentType::Spot, Some("USD"), &[]).unwrap_err();
1058        assert!(err.contains("tradeQuoteCcyList is unknown"));
1059        assert!(err.contains("tradeQuoteCcy 'USD'"));
1060    }
1061
1062    #[rstest]
1063    fn test_spot_trade_quote_ccy_wire_value_rejects_unlisted() {
1064        let err = spot_trade_quote_ccy_wire_value(
1065            OKXInstrumentType::Spot,
1066            Some("USD"),
1067            &[Ustr::from("USDC")],
1068        )
1069        .unwrap_err();
1070        assert!(err.contains("tradeQuoteCcy 'USD'"));
1071        assert!(err.contains("was [USDC]"));
1072        assert!(!err.contains(&format!(", {}", "got")));
1073    }
1074}