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::{OrderType, TimeInForce},
23    identifiers::{ClientId, Venue},
24};
25use ustr::Ustr;
26
27use super::enums::{OKXBookChannel, OKXInstrumentType, OKXVipLevel};
28
29/// Venue identifier string.
30pub const OKX: &str = "OKX";
31
32/// Static venue instance.
33pub static OKX_VENUE: LazyLock<Venue> = LazyLock::new(|| Venue::new(Ustr::from(OKX)));
34
35/// Static client ID instance.
36pub static OKX_CLIENT_ID: LazyLock<ClientId> = LazyLock::new(|| ClientId::new(Ustr::from(OKX)));
37
38/// See <https://www.okx.com/docs-v5/en/#overview-broker-program> for further details.
39pub const OKX_NAUTILUS_BROKER_ID: &str = "5328c82e5542BCDE";
40
41/// Default lookback for terminal orders and fills during reconciliation.
42///
43/// Active orders and current positions are requested independently of this window. The three-day
44/// default matches the retention of `GET /api/v5/trade/fills`.
45pub const OKX_RECONCILIATION_LOOKBACK_DEFAULT_MINS: u64 = 3 * 24 * 60;
46
47/// Maximum lookback for terminal orders and fills during reconciliation.
48///
49/// Seven days is the longest complete window across the regular order history and spread trade
50/// history endpoints used for reconciliation.
51pub const OKX_RECONCILIATION_LOOKBACK_MAX_MINS: u64 = 7 * 24 * 60;
52
53// Use the canonical host with www to avoid cross-domain redirects which may
54// strip authentication headers in some HTTP clients and middleboxes.
55pub const OKX_HTTP_URL: &str = "https://www.okx.com";
56pub const OKX_WS_PUBLIC_URL: &str = "wss://ws.okx.com:8443/ws/v5/public";
57pub const OKX_WS_PRIVATE_URL: &str = "wss://ws.okx.com:8443/ws/v5/private";
58pub const OKX_WS_BUSINESS_URL: &str = "wss://ws.okx.com:8443/ws/v5/business";
59pub const OKX_WS_DEMO_PUBLIC_URL: &str = "wss://wspap.okx.com:8443/ws/v5/public";
60pub const OKX_WS_DEMO_PRIVATE_URL: &str = "wss://wspap.okx.com:8443/ws/v5/private";
61pub const OKX_WS_DEMO_BUSINESS_URL: &str = "wss://wspap.okx.com:8443/ws/v5/business";
62
63pub const OKX_WS_TOPIC_DELIMITER: char = ':';
64
65/// WebSocket heartbeat (ping/pong) interval in seconds.
66pub const OKX_WS_HEARTBEAT_SECS: u64 = 20;
67
68/// OKX success response code for WebSocket operations.
69pub const OKX_SUCCESS_CODE: &str = "0";
70
71/// OKX WebSocket code indicating a service upgrade and required reconnect.
72pub const OKX_SERVICE_UPGRADE_RECONNECT_CODE: &str = "64008";
73
74/// JSON field key for sub-error code in order operation responses.
75pub const OKX_FIELD_SCODE: &str = "sCode";
76
77/// JSON field key for sub-error message in order operation responses.
78pub const OKX_FIELD_SMSG: &str = "sMsg";
79
80/// JSON field key for detailed sub-error code in order operation responses.
81pub const OKX_FIELD_SUBCODE: &str = "subCode";
82
83/// JSON field key for client order ID in order operation responses.
84pub const OKX_FIELD_CLORDID: &str = "clOrdId";
85
86/// Maximum length of a `clOrdId` accepted by OKX.
87///
88/// OKX requires `clOrdId` to be 1-32 case-sensitive alphanumeric characters.
89/// See <https://www.okx.com/docs-v5/en/#order-book-trading-trade>.
90pub const OKX_MAX_CLORDID_LEN: usize = 32;
91
92/// Validates a `clOrdId` against OKX's length and charset rules.
93///
94/// # Errors
95///
96/// Returns a human-readable reason when the ID exceeds
97/// [`OKX_MAX_CLORDID_LEN`] characters or contains non-alphanumeric characters
98/// (such as hyphens or underscores).
99pub fn validate_okx_client_order_id(cl_ord_id: &str) -> Result<(), String> {
100    let len = cl_ord_id.len();
101    if len > OKX_MAX_CLORDID_LEN {
102        return Err(format!(
103            "OKX requires clOrdId to be at most {OKX_MAX_CLORDID_LEN} characters, was {len} ({cl_ord_id:?}); \
104             set `use_uuid_client_order_ids=True` and `use_hyphens_in_client_order_ids=False` on the strategy config"
105        ));
106    }
107
108    if !cl_ord_id.bytes().all(|b| b.is_ascii_alphanumeric()) {
109        return Err(format!(
110            "OKX requires clOrdId to be alphanumeric only, was {cl_ord_id:?}; \
111             set `use_hyphens_in_client_order_ids=False` on the strategy config"
112        ));
113    }
114
115    Ok(())
116}
117
118/// OKX supported order time in force.
119///
120/// # Notes
121///
122/// - OKX implements IOC and FOK as order types rather than separate time-in-force parameters.
123/// - FOK is only supported with Limit orders (Market + FOK is not supported).
124/// - IOC with Market orders uses OptimalLimitIoc, with Limit orders uses Ioc.
125/// - GTD is supported via expire_time parameter.
126pub const OKX_SUPPORTED_TIME_IN_FORCE: &[TimeInForce] = &[
127    TimeInForce::Gtc, // Good Till Cancel (default)
128    TimeInForce::Ioc, // Immediate or Cancel (mapped to OKXOrderType::Ioc or OptimalLimitIoc)
129    TimeInForce::Fok, // Fill or Kill (only with Limit orders, mapped to OKXOrderType::Fok)
130];
131
132/// OKX supported order types.
133///
134/// # Notes
135///
136/// - PostOnly is supported as a flag on limit orders.
137/// - Conditional orders (stop/trigger) are supported via algo orders.
138pub const OKX_SUPPORTED_ORDER_TYPES: &[OrderType] = &[
139    OrderType::Market,
140    OrderType::Limit,
141    OrderType::MarketToLimit,   // Mapped to IOC when no price is specified
142    OrderType::StopMarket,      // Supported via algo order API
143    OrderType::StopLimit,       // Supported via algo order API
144    OrderType::MarketIfTouched, // Supported via algo order API
145    OrderType::LimitIfTouched,  // Supported via algo order API
146    OrderType::TrailingStopMarket, // Supported via algo order API (move_order_stop)
147];
148
149/// Conditional order types that require the OKX algo order API.
150pub const OKX_CONDITIONAL_ORDER_TYPES: &[OrderType] = &[
151    OrderType::StopMarket,
152    OrderType::StopLimit,
153    OrderType::MarketIfTouched,
154    OrderType::LimitIfTouched,
155    OrderType::TrailingStopMarket,
156];
157
158/// Advance algo order types that require `cancel-advance-algos` for cancellation.
159/// These cannot be cancelled via the standard `cancel-algos` endpoint.
160pub const OKX_ADVANCE_ALGO_ORDER_TYPES: &[OrderType] = &[OrderType::TrailingStopMarket];
161
162/// OKX error codes that should trigger retries.
163///
164/// Only retry on temporary network/system issues. Retries never apply to
165/// order submission POSTs: OKX rejects a duplicate `clOrdId` only while the
166/// first order rests open, so a submit whose response was lost can already
167/// have filled, and retrying could place a second live order. Submits are
168/// sent once, and an ambiguous outcome resolves through stream updates and
169/// reconciliation.
170///
171/// # References
172///
173/// Based on OKX API documentation: <https://www.okx.com/docs-v5/en/#error-codes>
174pub static OKX_RETRY_ERROR_CODES: LazyLock<AHashSet<&'static str>> = LazyLock::new(|| {
175    let mut codes = AHashSet::new();
176
177    // Temporary system errors
178    codes.insert("50001"); // Service temporarily unavailable
179    codes.insert("50004"); // API endpoint request timeout (does not mean that the request was successful or failed, please check the request result)
180    codes.insert("50005"); // API is offline or unavailable
181    codes.insert("50013"); // System busy, please try again later
182    codes.insert("50026"); // System error, please try again later
183
184    // Rate limit errors (temporary)
185    codes.insert("50011"); // Request too frequent
186    codes.insert("50113"); // API requests exceed the limit
187
188    // WebSocket connection issues (temporary)
189    codes.insert("60001"); // OK not received in time
190    codes.insert("60005"); // Connection closed as there was no data transmission in the last 30 seconds
191    codes.insert(OKX_SERVICE_UPGRADE_RECONNECT_CODE); // Service upgrade, please reconnect
192
193    codes
194});
195
196/// Determines if an OKX error code should trigger a retry.
197pub fn should_retry_error_code(error_code: &str) -> bool {
198    OKX_RETRY_ERROR_CODES.contains(error_code)
199}
200
201/// OKX error code returned when an order request timed out and the outcome is unknown.
202pub const OKX_ORDER_REQUEST_TIMEOUT_CODE: &str = "51149";
203
204/// OKX error code returned when a post-only order would immediately take liquidity.
205pub const OKX_POST_ONLY_ERROR_CODE: &str = "51019";
206
207/// OKX cancel source code used when a post-only order is auto-cancelled for taking liquidity.
208pub const OKX_POST_ONLY_CANCEL_SOURCE: &str = "31";
209
210/// Human-readable reason used when a post-only order is auto-cancelled for taking liquidity.
211pub const OKX_POST_ONLY_CANCEL_REASON: &str = "POST_ONLY would take liquidity";
212
213/// OKX error code returned when a market order's `slippagePct` would be exceeded by the
214/// projected fill, so the order is rejected.
215pub const OKX_SLIPPAGE_EXCEEDED_ERROR_CODE: &str = "54084";
216
217/// OKX error code returned when the supplied `slippagePct` value is outside the
218/// venue-permitted range.
219pub const OKX_SLIPPAGE_INVALID_ERROR_CODE: &str = "54085";
220
221/// Returns `true` if the OKX `sCode` identifies a slippage-related rejection emitted
222/// in response to the `slippagePct` parameter on market orders.
223#[must_use]
224pub fn is_slippage_rejection(error_code: &str) -> bool {
225    matches!(
226        error_code,
227        OKX_SLIPPAGE_EXCEEDED_ERROR_CODE | OKX_SLIPPAGE_INVALID_ERROR_CODE
228    )
229}
230
231/// Target currency literal for base currency.
232pub const OKX_TARGET_CCY_BASE: &str = "base_ccy";
233
234/// Target currency literal for quote currency.
235pub const OKX_TARGET_CCY_QUOTE: &str = "quote_ccy";
236
237/// Resolves instrument families for a given instrument type.
238///
239/// Returns `Some(families)` when the type supports family filtering, or `None`
240/// to skip the instrument type entirely (Option without configured families).
241/// An empty vec means no family filter is needed (Spot, Margin), or all
242/// discoverable families should be loaded (Events).
243pub fn resolve_instrument_families(
244    configured: &Option<Vec<String>>,
245    inst_type: OKXInstrumentType,
246) -> Option<Vec<String>> {
247    match (configured, inst_type) {
248        (Some(families), OKXInstrumentType::Option) => Some(families.clone()),
249        (
250            Some(families),
251            OKXInstrumentType::Futures | OKXInstrumentType::Swap | OKXInstrumentType::Events,
252        ) => Some(families.clone()),
253        (None, OKXInstrumentType::Option) => {
254            log::warn!("Skipping OPTION type: instrument_families required but not configured");
255            None
256        }
257        _ => Some(vec![]),
258    }
259}
260
261/// Clamps a requested book depth to the nearest OKX-supported value.
262///
263/// OKX WebSocket channels support depths of 50 and 400. Depth 0 means
264/// auto-select based on VIP level. Any other value rounds up to the nearest
265/// supported depth so the subscription succeeds and the data engine can
266/// truncate to the originally requested depth.
267pub fn resolve_book_depth(raw_depth: usize) -> usize {
268    match raw_depth {
269        0 | 400 => raw_depth,
270        1..=50 => 50,
271        _ => 400,
272    }
273}
274
275pub(crate) fn select_book_channel(depth: usize, vip: OKXVipLevel) -> OKXBookChannel {
276    match depth {
277        50 if vip >= OKXVipLevel::Vip4 => OKXBookChannel::Books50L2Tbt,
278        0 | 400 if vip >= OKXVipLevel::Vip5 => OKXBookChannel::BookL2Tbt,
279        0 | 50 | 400 => OKXBookChannel::Book,
280        _ => unreachable!("book depth must be resolved before channel selection"),
281    }
282}
283
284#[cfg(test)]
285mod tests {
286    use rstest::rstest;
287
288    use super::*;
289
290    #[rstest]
291    #[case::auto_default(0, OKXVipLevel::Vip0, OKXBookChannel::Book)]
292    #[case::auto_vip4(0, OKXVipLevel::Vip4, OKXBookChannel::Book)]
293    #[case::auto_vip5(0, OKXVipLevel::Vip5, OKXBookChannel::BookL2Tbt)]
294    #[case::depth_50_vip3(50, OKXVipLevel::Vip3, OKXBookChannel::Book)]
295    #[case::depth_50_vip4(50, OKXVipLevel::Vip4, OKXBookChannel::Books50L2Tbt)]
296    #[case::depth_400_vip4(400, OKXVipLevel::Vip4, OKXBookChannel::Book)]
297    #[case::depth_400_vip5(400, OKXVipLevel::Vip5, OKXBookChannel::BookL2Tbt)]
298    fn test_select_book_channel(
299        #[case] depth: usize,
300        #[case] vip: OKXVipLevel,
301        #[case] expected: OKXBookChannel,
302    ) {
303        assert_eq!(select_book_channel(depth, vip), expected);
304    }
305
306    #[rstest]
307    #[case("54084", true)]
308    #[case("54085", true)]
309    #[case("51019", false)]
310    #[case("", false)]
311    fn test_is_slippage_rejection(#[case] code: &str, #[case] expected: bool) {
312        assert_eq!(is_slippage_rejection(code), expected);
313    }
314
315    #[rstest]
316    #[case("50001", true)]
317    #[case("60005", true)]
318    #[case(OKX_SERVICE_UPGRADE_RECONNECT_CODE, true)]
319    #[case("60012", false)]
320    fn test_should_retry_error_code(#[case] code: &str, #[case] expected: bool) {
321        assert_eq!(should_retry_error_code(code), expected);
322    }
323
324    #[rstest]
325    #[case("O20260101000000ABC1", true)]
326    #[case("aB9", true)]
327    #[case("abcdefghij0123456789ABCDEFGHIJ12", true)] // exactly 32 chars
328    #[case("abcdefghij0123456789ABCDEFGHIJ123", false)] // 33 chars
329    #[case("O-20260101-000000-001-001-1", false)] // hyphens
330    #[case("O_20260101_000000", false)] // underscores
331    #[case("", true)] // empty: OKX rejects, but core ClientOrderId never produces empty
332    fn test_validate_okx_client_order_id(#[case] cl_ord_id: &str, #[case] expected_ok: bool) {
333        assert_eq!(validate_okx_client_order_id(cl_ord_id).is_ok(), expected_ok);
334    }
335
336    #[rstest]
337    fn test_validate_okx_client_order_id_length_message() {
338        // 35-char compact ID (the shape reported in the original bug report).
339        let cl_ord_id = "O20260522145501532392555aceLTCUSDT5";
340        let err = validate_okx_client_order_id(cl_ord_id).unwrap_err();
341        assert!(err.contains("at most 32"));
342        assert!(err.contains("was 35"));
343        assert!(err.contains("use_uuid_client_order_ids"));
344    }
345}