1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
//! OKX exchange implementation.
//!
//! Supports spot trading and futures trading (USDT-M and Coin-M) with REST API and WebSocket support.
//! OKX uses V5 unified API with HMAC-SHA256 + Base64 authentication.
use ccxt_core::types::default_type::{DefaultSubType, DefaultType};
use ccxt_core::{BaseExchange, ExchangeConfig, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
pub mod auth;
pub mod builder;
pub mod endpoint_router;
pub mod error;
pub mod exchange_impl;
pub mod margin_impl;
pub mod parser;
pub mod rest;
pub mod signed_request;
pub mod symbol;
pub mod ws;
pub mod ws_exchange_impl;
pub use auth::OkxAuth;
pub use builder::OkxBuilder;
pub use endpoint_router::{OkxChannelType, OkxEndpointRouter};
pub use error::{OkxErrorCode, is_error_response, parse_error};
pub use signed_request::{HttpMethod, OkxSignedRequestBuilder};
/// OKX exchange structure.
#[derive(Debug)]
pub struct Okx {
/// Base exchange instance.
base: BaseExchange,
/// OKX-specific options.
options: OkxOptions,
}
/// OKX-specific options.
///
/// # Example
///
/// ```rust
/// use ccxt_exchanges::okx::OkxOptions;
/// use ccxt_core::types::default_type::{DefaultType, DefaultSubType};
///
/// let options = OkxOptions {
/// default_type: DefaultType::Swap,
/// default_sub_type: Some(DefaultSubType::Linear),
/// ..Default::default()
/// };
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OkxOptions {
/// Account mode: cash (spot), cross (cross margin), isolated (isolated margin).
///
/// This is kept for backward compatibility with existing configurations.
pub account_mode: String,
/// Default trading type (spot/margin/swap/futures/option).
///
/// This determines which instrument type (instType) to use for API calls.
/// OKX uses a unified V5 API, so this primarily affects market filtering
/// rather than endpoint selection.
#[serde(default)]
pub default_type: DefaultType,
/// Default sub-type for contract settlement (linear/inverse).
///
/// - `Linear`: USDT-margined contracts
/// - `Inverse`: Coin-margined contracts
///
/// Only applicable when `default_type` is `Swap`, `Futures`, or `Option`.
/// Ignored for `Spot` and `Margin` types.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub default_sub_type: Option<DefaultSubType>,
/// Enables demo trading environment.
pub testnet: bool,
}
impl Default for OkxOptions {
fn default() -> Self {
Self {
account_mode: "cash".to_string(),
default_type: DefaultType::default(), // Defaults to Spot
default_sub_type: None,
testnet: false,
}
}
}
impl Okx {
/// Creates a new OKX instance using the builder pattern.
///
/// This is the recommended way to create an OKX instance.
///
/// # Example
///
/// ```no_run
/// use ccxt_exchanges::okx::Okx;
///
/// let okx = Okx::builder()
/// .api_key("your-api-key")
/// .secret("your-secret")
/// .passphrase("your-passphrase")
/// .sandbox(true)
/// .build()
/// .unwrap();
/// ```
pub fn builder() -> OkxBuilder {
OkxBuilder::new()
}
/// Creates a new OKX instance.
///
/// # Arguments
///
/// * `config` - Exchange configuration.
pub fn new(config: ExchangeConfig) -> Result<Self> {
let base = BaseExchange::new(config)?;
let options = OkxOptions::default();
Ok(Self { base, options })
}
/// Creates a new OKX instance with custom options.
///
/// This is used internally by the builder pattern.
///
/// # Arguments
///
/// * `config` - Exchange configuration.
/// * `options` - OKX-specific options.
pub fn new_with_options(config: ExchangeConfig, options: OkxOptions) -> Result<Self> {
let base = BaseExchange::new(config)?;
Ok(Self { base, options })
}
/// Returns a reference to the base exchange.
pub fn base(&self) -> &BaseExchange {
&self.base
}
/// Returns a mutable reference to the base exchange.
pub fn base_mut(&mut self) -> &mut BaseExchange {
&mut self.base
}
/// Returns the OKX options.
pub fn options(&self) -> &OkxOptions {
&self.options
}
/// Sets the OKX options.
pub fn set_options(&mut self, options: OkxOptions) {
self.options = options;
}
/// Returns the exchange ID.
pub fn id(&self) -> &'static str {
"okx"
}
/// Returns the exchange name.
pub fn name(&self) -> &'static str {
"OKX"
}
/// Returns the API version.
pub fn version(&self) -> &'static str {
"v5"
}
/// Returns `true` if the exchange is CCXT-certified.
pub fn certified(&self) -> bool {
false
}
/// Returns `true` if Pro version (WebSocket) is supported.
pub fn pro(&self) -> bool {
true
}
/// Returns the rate limit in requests per second.
pub fn rate_limit(&self) -> u32 {
20
}
/// Returns `true` if sandbox/demo mode is enabled.
///
/// Sandbox mode is enabled when either:
/// - `config.sandbox` is set to `true`
/// - `options.demo` is set to `true`
///
/// # Returns
///
/// `true` if sandbox mode is enabled, `false` otherwise.
///
/// # Example
///
/// ```no_run
/// use ccxt_exchanges::okx::Okx;
/// use ccxt_core::ExchangeConfig;
///
/// let config = ExchangeConfig {
/// sandbox: true,
/// ..Default::default()
/// };
/// let okx = Okx::new(config).unwrap();
/// assert!(okx.is_sandbox());
/// ```
pub fn is_sandbox(&self) -> bool {
self.base().config.sandbox || self.options.testnet
}
/// Returns `true` if demo trading mode is enabled.
///
/// This is an OKX-specific alias for `is_sandbox()`. Demo trading mode
/// is enabled when either:
/// - `config.sandbox` is set to `true`
/// - `options.demo` is set to `true`
///
/// When demo trading is enabled, the client will:
/// - Add the `x-simulated-trading: 1` header to all REST API requests
/// - Use demo WebSocket URLs (`wss://wspap.okx.com:8443/ws/v5/*?brokerId=9999`)
/// - Continue using the production REST domain (`https://www.okx.com`)
///
/// # Returns
///
/// `true` if demo trading mode is enabled, `false` otherwise.
///
/// # Example
///
/// ```no_run
/// use ccxt_exchanges::okx::Okx;
/// use ccxt_core::ExchangeConfig;
///
/// let config = ExchangeConfig {
/// sandbox: true,
/// ..Default::default()
/// };
/// let okx = Okx::new(config).unwrap();
/// assert!(okx.is_testnet_trading());
/// ```
pub fn is_testnet_trading(&self) -> bool {
self.base().config.sandbox || self.options.testnet
}
/// Returns the supported timeframes.
pub fn timeframes(&self) -> HashMap<String, String> {
let mut timeframes = HashMap::new();
timeframes.insert("1m".to_string(), "1m".to_string());
timeframes.insert("3m".to_string(), "3m".to_string());
timeframes.insert("5m".to_string(), "5m".to_string());
timeframes.insert("15m".to_string(), "15m".to_string());
timeframes.insert("30m".to_string(), "30m".to_string());
timeframes.insert("1h".to_string(), "1H".to_string());
timeframes.insert("2h".to_string(), "2H".to_string());
timeframes.insert("4h".to_string(), "4H".to_string());
timeframes.insert("6h".to_string(), "6Hutc".to_string());
timeframes.insert("12h".to_string(), "12Hutc".to_string());
timeframes.insert("1d".to_string(), "1Dutc".to_string());
timeframes.insert("1w".to_string(), "1Wutc".to_string());
timeframes.insert("1M".to_string(), "1Mutc".to_string());
timeframes
}
/// Returns the API URLs.
pub fn urls(&self) -> OkxUrls {
if self.base().config.sandbox || self.options.testnet {
OkxUrls::demo()
} else {
OkxUrls::production()
}
}
/// Returns the default type configuration.
pub fn default_type(&self) -> DefaultType {
self.options.default_type
}
/// Returns the default sub-type configuration.
pub fn default_sub_type(&self) -> Option<DefaultSubType> {
self.options.default_sub_type
}
/// Checks if the current default_type is a contract type (Swap, Futures, or Option).
///
/// This is useful for determining whether contract-specific API parameters should be used.
///
/// # Returns
///
/// `true` if the default_type is Swap, Futures, or Option; `false` otherwise.
pub fn is_contract_type(&self) -> bool {
self.options.default_type.is_contract()
}
/// Checks if the current configuration uses inverse (coin-margined) contracts.
///
/// # Returns
///
/// `true` if default_sub_type is Inverse; `false` otherwise.
pub fn is_inverse(&self) -> bool {
matches!(self.options.default_sub_type, Some(DefaultSubType::Inverse))
}
/// Checks if the current configuration uses linear (USDT-margined) contracts.
///
/// # Returns
///
/// `true` if default_sub_type is Linear or not specified (defaults to Linear); `false` otherwise.
pub fn is_linear(&self) -> bool {
!self.is_inverse()
}
/// Creates a new WebSocket client for OKX.
///
/// Returns an `OkxWs` instance configured with the appropriate WebSocket URL
/// based on the exchange configuration (production or demo).
///
/// # Example
/// ```no_run
/// use ccxt_exchanges::okx::Okx;
/// use ccxt_core::ExchangeConfig;
///
/// # async fn example() -> ccxt_core::error::Result<()> {
/// let okx = Okx::new(ExchangeConfig::default())?;
/// let ws = okx.create_ws();
/// ws.connect().await?;
/// # Ok(())
/// # }
/// ```
pub fn create_ws(&self) -> ws::OkxWs {
let urls = self.urls();
ws::OkxWs::new(urls.ws_public)
}
/// Creates a new private WebSocket client for OKX.
///
/// Returns an `OkxWs` instance configured with the private WebSocket URL.
/// The caller must call `login()` on the returned client before subscribing
/// to private channels.
pub fn create_private_ws(&self) -> ws::OkxWs {
let urls = self.urls();
ws::OkxWs::new(urls.ws_private)
}
/// Creates a new signed request builder for authenticated API requests.
///
/// This builder encapsulates the common signing workflow for OKX API requests,
/// including credential validation, timestamp generation, HMAC-SHA256 signing,
/// and authentication header injection.
///
/// # Arguments
///
/// * `endpoint` - API endpoint path (e.g., "/api/v5/account/balance")
///
/// # Returns
///
/// A `OkxSignedRequestBuilder` instance for fluent API construction.
///
/// # Example
///
/// ```no_run
/// use ccxt_exchanges::okx::Okx;
/// use ccxt_exchanges::okx::signed_request::HttpMethod;
/// use ccxt_core::ExchangeConfig;
///
/// # async fn example() -> ccxt_core::Result<()> {
/// let okx = Okx::new(ExchangeConfig::default())?;
///
/// // Simple GET request
/// let data = okx.signed_request("/api/v5/account/balance")
/// .execute()
/// .await?;
///
/// // POST request with parameters
/// let data = okx.signed_request("/api/v5/trade/order")
/// .method(HttpMethod::Post)
/// .param("instId", "BTC-USDT")
/// .param("tdMode", "cash")
/// .param("side", "buy")
/// .execute()
/// .await?;
/// # Ok(())
/// # }
/// ```
pub fn signed_request(
&self,
endpoint: impl Into<String>,
) -> signed_request::OkxSignedRequestBuilder<'_> {
signed_request::OkxSignedRequestBuilder::new(self, endpoint)
}
}
/// OKX API URLs.
#[derive(Debug, Clone)]
pub struct OkxUrls {
/// REST API base URL.
pub rest: String,
/// Public WebSocket URL.
pub ws_public: String,
/// Private WebSocket URL.
pub ws_private: String,
/// Business WebSocket URL.
pub ws_business: String,
}
impl OkxUrls {
/// Returns production environment URLs.
pub fn production() -> Self {
Self {
rest: "https://www.okx.com".to_string(),
ws_public: "wss://ws.okx.com:8443/ws/v5/public".to_string(),
ws_private: "wss://ws.okx.com:8443/ws/v5/private".to_string(),
ws_business: "wss://ws.okx.com:8443/ws/v5/business".to_string(),
}
}
/// Returns demo environment URLs.
pub fn demo() -> Self {
Self {
rest: "https://www.okx.com".to_string(),
ws_public: "wss://wspap.okx.com:8443/ws/v5/public?brokerId=9999".to_string(),
ws_private: "wss://wspap.okx.com:8443/ws/v5/private?brokerId=9999".to_string(),
ws_business: "wss://wspap.okx.com:8443/ws/v5/business?brokerId=9999".to_string(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_okx_creation() {
let config = ExchangeConfig {
id: "okx".to_string(),
name: "OKX".to_string(),
..Default::default()
};
let okx = Okx::new(config);
assert!(okx.is_ok());
let okx = okx.unwrap();
assert_eq!(okx.id(), "okx");
assert_eq!(okx.name(), "OKX");
assert_eq!(okx.version(), "v5");
assert!(!okx.certified());
assert!(okx.pro());
}
#[test]
fn test_timeframes() {
let config = ExchangeConfig::default();
let okx = Okx::new(config).unwrap();
let timeframes = okx.timeframes();
assert!(timeframes.contains_key("1m"));
assert!(timeframes.contains_key("1h"));
assert!(timeframes.contains_key("1d"));
assert_eq!(timeframes.len(), 13);
}
#[test]
fn test_urls() {
let config = ExchangeConfig::default();
let okx = Okx::new(config).unwrap();
let urls = okx.urls();
assert!(urls.rest.contains("okx.com"));
assert!(urls.ws_public.contains("ws.okx.com"));
}
#[test]
fn test_sandbox_urls() {
let config = ExchangeConfig {
sandbox: true,
..Default::default()
};
let okx = Okx::new(config).unwrap();
let urls = okx.urls();
assert!(urls.ws_public.contains("wspap.okx.com"));
assert!(urls.ws_public.contains("brokerId=9999"));
}
#[test]
fn test_demo_rest_url_uses_production_domain() {
// Verify that OKX demo mode uses the production REST domain
// OKX uses the same REST domain for demo trading, but adds a special header
let demo_urls = OkxUrls::demo();
let production_urls = OkxUrls::production();
// REST URL should be the same (production domain)
assert_eq!(demo_urls.rest, production_urls.rest);
assert_eq!(demo_urls.rest, "https://www.okx.com");
// WebSocket URLs should be different (demo uses wspap.okx.com)
assert_ne!(demo_urls.ws_public, production_urls.ws_public);
assert!(demo_urls.ws_public.contains("wspap.okx.com"));
assert!(demo_urls.ws_public.contains("brokerId=9999"));
}
#[test]
fn test_sandbox_mode_rest_url_is_production() {
// When sandbox mode is enabled, REST URL should still be production domain
let config = ExchangeConfig {
sandbox: true,
..Default::default()
};
let okx = Okx::new(config).unwrap();
let urls = okx.urls();
// REST URL should be production domain
assert_eq!(urls.rest, "https://www.okx.com");
}
#[test]
fn test_is_sandbox_with_config_sandbox() {
let config = ExchangeConfig {
sandbox: true,
..Default::default()
};
let okx = Okx::new(config).unwrap();
assert!(okx.is_sandbox());
}
#[test]
fn test_is_sandbox_with_options_demo() {
let config = ExchangeConfig::default();
let options = OkxOptions {
testnet: true,
..Default::default()
};
let okx = Okx::new_with_options(config, options).unwrap();
assert!(okx.is_sandbox());
}
#[test]
fn test_is_sandbox_false_by_default() {
let config = ExchangeConfig::default();
let okx = Okx::new(config).unwrap();
assert!(!okx.is_sandbox());
}
#[test]
fn test_is_demo_trading_with_config_sandbox() {
let config = ExchangeConfig {
sandbox: true,
..Default::default()
};
let okx = Okx::new(config).unwrap();
assert!(okx.is_testnet_trading());
}
#[test]
fn test_is_demo_trading_with_options_demo() {
let config = ExchangeConfig::default();
let options = OkxOptions {
testnet: true,
..Default::default()
};
let okx = Okx::new_with_options(config, options).unwrap();
assert!(okx.is_testnet_trading());
}
#[test]
fn test_is_demo_trading_false_by_default() {
let config = ExchangeConfig::default();
let okx = Okx::new(config).unwrap();
assert!(!okx.is_testnet_trading());
}
#[test]
fn test_is_demo_trading_equals_is_sandbox() {
// Test that is_demo_trading() and is_sandbox() return the same value
let config = ExchangeConfig::default();
let okx = Okx::new(config).unwrap();
assert_eq!(okx.is_testnet_trading(), okx.is_sandbox());
let config_sandbox = ExchangeConfig {
sandbox: true,
..Default::default()
};
let okx_sandbox = Okx::new(config_sandbox).unwrap();
assert_eq!(okx_sandbox.is_testnet_trading(), okx_sandbox.is_sandbox());
}
#[test]
fn test_default_options() {
let options = OkxOptions::default();
assert_eq!(options.account_mode, "cash");
assert_eq!(options.default_type, DefaultType::Spot);
assert_eq!(options.default_sub_type, None);
assert!(!options.testnet);
}
#[test]
fn test_okx_options_with_default_type() {
let options = OkxOptions {
default_type: DefaultType::Swap,
default_sub_type: Some(DefaultSubType::Linear),
..Default::default()
};
assert_eq!(options.default_type, DefaultType::Swap);
assert_eq!(options.default_sub_type, Some(DefaultSubType::Linear));
}
#[test]
fn test_okx_options_serialization() {
let options = OkxOptions {
default_type: DefaultType::Swap,
default_sub_type: Some(DefaultSubType::Linear),
..Default::default()
};
let json = serde_json::to_string(&options).unwrap();
assert!(json.contains("\"default_type\":\"swap\""));
assert!(json.contains("\"default_sub_type\":\"linear\""));
}
#[test]
fn test_okx_options_deserialization() {
let json = r#"{
"account_mode": "cross",
"default_type": "swap",
"default_sub_type": "inverse",
"testnet": true
}"#;
let options: OkxOptions = serde_json::from_str(json).unwrap();
assert_eq!(options.account_mode, "cross");
assert_eq!(options.default_type, DefaultType::Swap);
assert_eq!(options.default_sub_type, Some(DefaultSubType::Inverse));
assert!(options.testnet);
}
#[test]
fn test_okx_options_deserialization_without_default_type() {
// Test backward compatibility - default_type should default to Spot
let json = r#"{
"account_mode": "cash",
"testnet": false
}"#;
let options: OkxOptions = serde_json::from_str(json).unwrap();
assert_eq!(options.default_type, DefaultType::Spot);
assert_eq!(options.default_sub_type, None);
}
}