nautilus-okx 0.56.0

OKX exchange integration adapter for the Nautilus trading engine
Documentation
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
// -------------------------------------------------------------------------------------------------
//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
//  https://nautechsystems.io
//
//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
//  You may not use this file except in compliance with the License.
//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
// -------------------------------------------------------------------------------------------------

//! Request parameter structures for the OKX **v5 REST API**.
//!
//! Each struct corresponds 1-to-1 with an OKX REST endpoint and is annotated
//! using `serde` so that it can be serialized directly into the query string
//! or request body expected by the exchange.
//!
//! The inline documentation repeats the required/optional fields described in
//! the [official OKX documentation](https://www.okx.com/docs-v5/en/) and, where
//! beneficial, links to the exact endpoint section.  All links point to the
//! English version.
//!
//! Parameter structs are built using the builder pattern and then passed to
//! `OKXHttpClient::get`/`post` where they are automatically serialized.

use derive_builder::Builder;
use serde::{self, Deserialize, Serialize};

use crate::{
    common::enums::{
        OKXAlgoOrderType, OKXInstrumentType, OKXOrderStatus, OKXOrderType, OKXPositionMode,
        OKXPositionSide, OKXTradeMode,
    },
    http::error::BuildError,
};

/// Parameters for the POST /api/v5/account/set-position-mode endpoint.
#[derive(Clone, Debug, Deserialize, Serialize, Builder)]
#[builder(setter(into, strip_option))]
#[serde(rename_all = "camelCase")]
pub struct SetPositionModeParams {
    /// Position mode: "net_mode" or "long_short_mode".
    #[serde(rename = "posMode")]
    pub pos_mode: OKXPositionMode,
}

/// Parameters for the GET /api/v5/public/position-tiers endpoint.
#[derive(Clone, Debug, Deserialize, Serialize, Default, Builder)]
#[builder(default)]
#[builder(setter(into, strip_option))]
#[serde(rename_all = "camelCase")]
pub struct GetPositionTiersParams {
    /// Instrument type: MARGIN, SWAP, FUTURES, OPTION.
    pub inst_type: OKXInstrumentType,
    /// Trading mode, valid values: cross, isolated.
    pub td_mode: OKXTradeMode,
    /// Underlying, required for SWAP/FUTURES/OPTION
    /// Single underlying or multiple underlyings (no more than 3) separated with comma.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub uly: Option<String>,
    /// Instrument family, required for SWAP/FUTURES/OPTION
    /// Single instrument family or multiple families (no more than 5) separated with comma.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub inst_family: Option<String>,
    /// Specific instrument ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub inst_id: Option<String>,
    /// Margin currency, only applicable to cross MARGIN.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ccy: Option<String>,
    /// Tiers.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tier: Option<String>,
}

/// Parameters for the GET /api/v5/public/instruments endpoint.
#[derive(Clone, Debug, Deserialize, Serialize, Default, Builder)]
#[builder(default)]
#[builder(setter(into, strip_option))]
#[serde(rename_all = "camelCase")]
pub struct GetInstrumentsParams {
    /// Instrument type: SPOT, MARGIN, SWAP, FUTURES, OPTION.
    pub inst_type: OKXInstrumentType,
    /// Underlying. Only applicable to FUTURES/SWAP/OPTION.
    /// If instType is OPTION, either uly or instFamily is required.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub uly: Option<String>,
    /// Instrument family. Only applicable to FUTURES/SWAP/OPTION.
    /// If instType is OPTION, either uly or instFamily is required.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub inst_family: Option<String>,
    /// Instrument ID, e.g. BTC-USD-SWAP.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub inst_id: Option<String>,
}

/// Parameters for the GET /api/v5/public/opt-summary endpoint.
#[derive(Clone, Debug, Deserialize, Serialize, Default, Builder)]
#[builder(default)]
#[builder(setter(into, strip_option))]
#[serde(rename_all = "camelCase")]
pub struct GetOptionSummaryParams {
    /// Instrument family. Only applicable to OPTION.
    pub inst_family: String,
    /// Contract expiry date in YYMMDD format, e.g. "250328".
    #[serde(skip_serializing_if = "Option::is_none")]
    pub exp_time: Option<String>,
}

/// Parameters for the GET /api/v5/market/history-trades endpoint.
#[derive(Clone, Debug, Deserialize, Serialize, Default, Builder)]
#[builder(default)]
#[builder(setter(into, strip_option))]
#[serde(rename_all = "camelCase")]
pub struct GetTradesParams {
    /// Instrument ID, e.g. "BTC-USDT".
    pub inst_id: String,
    /// Pagination type: 1 = trade ID (default), 2 = timestamp.
    #[serde(rename = "type")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pagination_type: Option<u8>,
    /// Pagination: fetch records after this cursor (trade ID or timestamp).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub after: Option<String>,
    /// Pagination: fetch records before this cursor (trade ID or timestamp).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub before: Option<String>,
    /// Maximum number of records to return (default 100, max 1000).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,
}

/// Parameters for the GET /api/v5/market/history-candles endpoint.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GetCandlesticksParams {
    /// Instrument ID, e.g. "BTC-USDT".
    pub inst_id: String,
    /// Time interval, e.g. "1m", "5m", "1H".
    pub bar: String,
    /// Pagination: fetch records after this timestamp (milliseconds).
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(rename = "after")]
    pub after_ms: Option<i64>,
    /// Pagination: fetch records before this timestamp (milliseconds).
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(rename = "before")]
    pub before_ms: Option<i64>,
    /// Maximum number of records to return (default 100, max 300 for regular candles, max 100 for history).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,
}

/// Builder for GetCandlesticksParams with validation.
#[derive(Debug, Default)]
pub struct GetCandlesticksParamsBuilder {
    inst_id: Option<String>,
    bar: Option<String>,
    after_ms: Option<i64>,
    before_ms: Option<i64>,
    limit: Option<u32>,
}

impl GetCandlesticksParamsBuilder {
    /// Sets the instrument ID.
    pub fn inst_id(&mut self, inst_id: impl Into<String>) -> &mut Self {
        self.inst_id = Some(inst_id.into());
        self
    }

    /// Sets the bar interval.
    pub fn bar(&mut self, bar: impl Into<String>) -> &mut Self {
        self.bar = Some(bar.into());
        self
    }

    /// Sets the after timestamp (milliseconds).
    pub fn after_ms(&mut self, after_ms: i64) -> &mut Self {
        self.after_ms = Some(after_ms);
        self
    }

    /// Sets the before timestamp (milliseconds).
    pub fn before_ms(&mut self, before_ms: i64) -> &mut Self {
        self.before_ms = Some(before_ms);
        self
    }

    /// Sets the limit.
    pub fn limit(&mut self, limit: u32) -> &mut Self {
        self.limit = Some(limit);
        self
    }

    /// Builds the parameters with embedded invariant validation.
    ///
    /// # Errors
    ///
    /// Returns an error if the parameters are invalid.
    pub fn build(&mut self) -> Result<GetCandlesticksParams, BuildError> {
        // Extract values from builder
        let inst_id = self.inst_id.clone().ok_or(BuildError::MissingInstId)?;
        let bar = self.bar.clone().ok_or(BuildError::MissingBar)?;
        let after_ms = self.after_ms;
        let before_ms = self.before_ms;
        let limit = self.limit;

        // ───────── Both cursors validation
        // Note: OKX DOES support both 'after' and 'before' together for time range queries
        // They can only NOT be used together when one is a pagination cursor
        // For now, we allow both and let the API validate
        // if after_ms.is_some() && before_ms.is_some() {
        //     return Err(BuildError::BothCursors);
        // }

        // ───────── Cursor chronological validation
        // IMPORTANT: OKX has counter-intuitive parameter semantics:
        // - before_ms is the START time (lower bound, older) - returns bars > before
        // - after_ms is the END time (upper bound, newer) - returns bars < after
        // Therefore: before_ms < after_ms for valid time ranges
        if let (Some(after), Some(before)) = (after_ms, before_ms)
            && before >= after
        {
            return Err(BuildError::InvalidTimeRange {
                after_ms: after,
                before_ms: before,
            });
        }

        // ───────── Cursor unit (≤ 13 digits ⇒ milliseconds)
        if let Some(nanos) = after_ms
            && nanos.abs() > 9_999_999_999_999
        {
            return Err(BuildError::CursorIsNanoseconds);
        }

        if let Some(nanos) = before_ms
            && nanos.abs() > 9_999_999_999_999
        {
            return Err(BuildError::CursorIsNanoseconds);
        }

        // ───────── Limit validation
        // Note: Regular endpoint supports up to 300, history endpoint up to 100
        // This validation is conservative for safety across both endpoints
        if let Some(limit) = limit
            && limit > 300
        {
            return Err(BuildError::LimitTooHigh);
        }

        Ok(GetCandlesticksParams {
            inst_id,
            bar,
            after_ms,
            before_ms,
            limit,
        })
    }
}

/// Parameters for the GET /api/v5/public/mark-price.
#[derive(Clone, Debug, Deserialize, Serialize, Default, Builder)]
#[builder(default)]
#[builder(setter(into, strip_option))]
#[serde(rename_all = "camelCase")]
pub struct GetMarkPriceParams {
    /// Instrument type: MARGIN, SWAP, FUTURES, OPTION.
    pub inst_type: OKXInstrumentType,
    /// Underlying, required for SWAP/FUTURES/OPTION
    /// Single underlying or multiple underlyings (no more than 3) separated with comma.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub uly: Option<String>,
    /// Instrument family, required for SWAP/FUTURES/OPTION
    /// Single instrument family or multiple families (no more than 5) separated with comma.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub inst_family: Option<String>,
    /// Specific instrument ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub inst_id: Option<String>,
}

/// Parameters for the GET /api/v5/market/index-tickers.
#[derive(Clone, Debug, Deserialize, Serialize, Default, Builder)]
#[builder(default)]
#[builder(setter(into, strip_option))]
#[serde(rename_all = "camelCase")]
pub struct GetIndexTickerParams {
    /// Specific instrument ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub inst_id: Option<String>,
    /// Quote currency.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub quote_ccy: Option<String>,
}

/// Parameters for the GET /api/v5/market/books endpoint.
#[derive(Clone, Debug, Deserialize, Serialize, Default, Builder)]
#[builder(default)]
#[builder(setter(into, strip_option))]
#[serde(rename_all = "camelCase")]
pub struct GetOrderBookParams {
    /// Instrument ID, e.g. "BTC-USDT-SWAP".
    pub inst_id: String,
    /// Order book depth per side. Maximum 400, default 1.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sz: Option<u32>,
}

/// Parameters for the GET /api/v5/public/funding-rate-history endpoint.
#[derive(Clone, Debug, Deserialize, Serialize, Default, Builder)]
#[builder(default)]
#[builder(setter(into, strip_option))]
#[serde(rename_all = "camelCase")]
pub struct GetFundingRateHistoryParams {
    /// Instrument ID, e.g. "BTC-USDT-SWAP".
    pub inst_id: String,
    /// Pagination: records newer than this timestamp (ms).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub before: Option<String>,
    /// Pagination: records older than this timestamp (ms).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub after: Option<String>,
    /// Number of results per request (default 100, max 100).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,
}

/// Parameters for the GET /api/v5/trade/order-history endpoint.
#[derive(Clone, Debug, Deserialize, Serialize, Default, Builder)]
#[builder(default)]
#[builder(setter(into, strip_option))]
#[serde(rename_all = "camelCase")]
pub struct GetOrderHistoryParams {
    /// Instrument type: SPOT, MARGIN, SWAP, FUTURES, OPTION.
    pub inst_type: OKXInstrumentType,
    /// Underlying, for FUTURES, SWAP, OPTION (optional).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub uly: Option<String>,
    /// Instrument family, for FUTURES, SWAP, OPTION (optional).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub inst_family: Option<String>,
    /// Instrument ID, e.g. "BTC-USD-SWAP" (optional).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub inst_id: Option<String>,
    /// Order type: limit, market, post_only, fok, ioc (optional).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ord_type: Option<OKXOrderType>,
    /// Order state: live, filled, canceled (optional).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub state: Option<String>,
    /// Pagination parameter: fetch records after this order ID or timestamp (optional).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub after: Option<String>,
    /// Pagination parameter: fetch records before this order ID or timestamp (optional).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub before: Option<String>,
    /// Maximum number of records to return (default 100, max 100) (optional).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,
}

/// Parameters for the GET /api/v5/trade/orders-pending endpoint.
#[derive(Clone, Debug, Default, Deserialize, Serialize, Builder)]
#[builder(default)]
#[builder(setter(into, strip_option))]
#[serde(rename_all = "camelCase")]
pub struct GetOrderListParams {
    /// Instrument type: SPOT, MARGIN, SWAP, FUTURES, OPTION.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub inst_type: Option<OKXInstrumentType>,
    /// Instrument ID, e.g. "BTC-USDT" (optional).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub inst_id: Option<String>,
    /// Instrument family, e.g. "BTC-USD" (optional).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub inst_family: Option<String>,
    /// State to filter for (optional).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub state: Option<OKXOrderStatus>,
    /// Pagination - fetch records **after** this order ID (optional).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub after: Option<String>,
    /// Pagination - fetch records **before** this order ID (optional).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub before: Option<String>,
    /// Number of results per request (default 100, max 100).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,
}

/// Parameters for the GET /api/v5/trade/order-algo-* endpoints.
#[derive(Clone, Debug, Deserialize, Serialize, Default, Builder)]
#[builder(default)]
#[builder(setter(into, strip_option))]
#[serde(rename_all = "camelCase")]
pub struct GetAlgoOrdersParams {
    /// Algo order identifier assigned by OKX (optional).
    #[serde(rename = "algoId", skip_serializing_if = "Option::is_none")]
    pub algo_id: Option<String>,
    /// Client supplied algo order identifier (optional).
    #[serde(rename = "algoClOrdId", skip_serializing_if = "Option::is_none")]
    pub algo_cl_ord_id: Option<String>,
    /// Instrument type: SPOT, MARGIN, SWAP, FUTURES, OPTION.
    pub inst_type: OKXInstrumentType,
    /// Specific instrument identifier (optional).
    #[serde(rename = "instId", skip_serializing_if = "Option::is_none")]
    pub inst_id: Option<String>,
    /// Order type filter (optional).
    #[serde(rename = "ordType", skip_serializing_if = "Option::is_none")]
    pub ord_type: Option<OKXAlgoOrderType>,
    /// State filter (optional).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub state: Option<OKXOrderStatus>,
    /// Pagination cursor – fetch records after this value (optional).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub after: Option<String>,
    /// Pagination cursor – fetch records before this value (optional).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub before: Option<String>,
    /// Maximum number of records to return (optional, default 100).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,
}

/// Parameters for the GET /api/v5/trade/fills endpoint (transaction details).
#[derive(Clone, Debug, Default, Deserialize, Serialize, Builder)]
#[builder(default)]
#[builder(setter(into, strip_option))]
#[serde(rename_all = "camelCase")]
pub struct GetTransactionDetailsParams {
    /// Instrument type: SPOT, MARGIN, SWAP, FUTURES, OPTION (optional).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub inst_type: Option<OKXInstrumentType>,
    /// Instrument ID, e.g. "BTC-USDT" (optional).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub inst_id: Option<String>,
    /// Order ID (optional).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ord_id: Option<String>,
    /// Pagination of data to return records earlier than the requested ID (optional).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub after: Option<String>,
    /// Pagination of data to return records newer than the requested ID (optional).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub before: Option<String>,
    /// Number of results per request (optional, default 100, max 100).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,
}

/// Parameters for the GET /api/v5/public/positions endpoint.
#[derive(Clone, Debug, Deserialize, Serialize, Default, Builder)]
#[builder(default)]
#[builder(setter(into, strip_option))]
#[serde(rename_all = "camelCase")]
pub struct GetPositionsParams {
    /// Instrument type: MARGIN, SWAP, FUTURES, OPTION.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub inst_type: Option<OKXInstrumentType>,
    /// Specific instrument ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub inst_id: Option<String>,
    /// Single position ID or multiple position IDs (no more than 20) separated with comma.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pos_id: Option<String>,
}

/// Parameters for the GET /api/v5/account/positions-history endpoint.
#[derive(Clone, Debug, Deserialize, Serialize, Default, Builder)]
#[builder(default)]
#[builder(setter(into, strip_option))]
#[serde(rename_all = "camelCase")]
pub struct GetPositionsHistoryParams {
    /// Instrument type: MARGIN, SWAP, FUTURES, OPTION.
    pub inst_type: OKXInstrumentType,
    /// Instrument ID, e.g. "BTC-USD-SWAP" (optional).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub inst_id: Option<String>,
    /// One or more position IDs, separated by commas (optional).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pos_id: Option<String>,
    /// Pagination parameter - requests records **after** this ID or timestamp (optional).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub after: Option<String>,
    /// Pagination parameter - requests records **before** this ID or timestamp (optional).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub before: Option<String>,
    /// Number of results per request (default 100, max 100).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,
}

/// Parameters for the GET /api/v5/trade/order endpoint (fetch order details).
#[derive(Clone, Debug, Default, Deserialize, Serialize, Builder)]
#[builder(default)]
#[builder(setter(into, strip_option))]
#[serde(rename_all = "camelCase")]
pub struct GetOrderParams {
    /// Instrument type: SPOT, MARGIN, SWAP, FUTURES, OPTION.
    pub inst_type: OKXInstrumentType,
    /// Instrument ID, e.g. "BTC-USDT".
    pub inst_id: String,
    /// Exchange-assigned order ID (optional if client order ID is provided).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ord_id: Option<String>,
    /// User-assigned client order ID (optional if order ID is provided).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cl_ord_id: Option<String>,
    /// Position side (optional).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pos_side: Option<OKXPositionSide>,
}

/// Parameters for the GET /api/v5/account/trade-fee endpoint.
#[derive(Clone, Debug, Deserialize, Serialize, Builder)]
#[builder(setter(into, strip_option))]
#[serde(rename_all = "camelCase")]
pub struct GetTradeFeeParams {
    /// Instrument type: SPOT, MARGIN, SWAP, FUTURES, OPTION.
    pub inst_type: OKXInstrumentType,
    /// Underlying, required for SWAP/FUTURES/OPTION (optional).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub uly: Option<String>,
    /// Instrument family, required for SWAP/FUTURES/OPTION (optional).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub inst_family: Option<String>,
}

#[cfg(test)]
mod tests {
    use rstest::rstest;

    use super::*;

    #[rstest]
    fn test_optional_parameters_are_omitted_when_none() {
        let mut builder = GetCandlesticksParamsBuilder::default();
        builder.inst_id("BTC-USDT-SWAP");
        builder.bar("1m");

        let params = builder.build().unwrap();
        let qs = serde_urlencoded::to_string(&params).unwrap();
        assert_eq!(
            qs, "instId=BTC-USDT-SWAP&bar=1m",
            "unexpected optional parameters were serialized: {qs}",
        );
    }

    #[rstest]
    fn test_no_literal_none_strings_leak_into_query_string() {
        let mut builder = GetCandlesticksParamsBuilder::default();
        builder.inst_id("BTC-USDT-SWAP");
        builder.bar("1m");

        let params = builder.build().unwrap();
        let qs = serde_urlencoded::to_string(&params).unwrap();
        assert!(
            !qs.contains("None"),
            "found literal \"None\" in query string: {qs}",
        );
        assert!(
            !qs.contains("after=") && !qs.contains("before=") && !qs.contains("limit="),
            "empty optional parameters must be omitted entirely: {qs}",
        );
    }

    #[rstest]
    fn test_cursor_nanoseconds_rejected() {
        // 2025-07-01T00:00:00Z in *nanoseconds* on purpose.
        let after_nanos = 1_725_307_200_000_000_000i64;

        let mut builder = GetCandlesticksParamsBuilder::default();
        builder.inst_id("BTC-USDT-SWAP");
        builder.bar("1m");
        builder.after_ms(after_nanos);

        // This should fail because nanoseconds > 13 digits
        let result = builder.build();
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("nanoseconds"));
    }

    #[rstest]
    fn test_both_cursors_rejected() {
        let mut builder = GetCandlesticksParamsBuilder::default();
        builder.inst_id("BTC-USDT-SWAP");
        builder.bar("1m");
        // OKX backwards semantics: before=lower bound, after=upper bound
        // This creates invalid range where before >= after
        builder.after_ms(1725307200000);
        builder.before_ms(1725393600000);

        let result = builder.build();
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("time range"));
    }

    #[rstest]
    fn test_limit_exceeds_maximum_rejected() {
        let mut builder = GetCandlesticksParamsBuilder::default();
        builder.inst_id("BTC-USDT-SWAP");
        builder.bar("1m");
        builder.limit(301u32); // Exceeds maximum limit

        // Limit should be rejected
        let result = builder.build();
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("300"));
    }

    #[rstest]
    #[case(1725307200000, "after=1725307200000")] // 13 digits = milliseconds
    #[case(1725307200, "after=1725307200")] // 10 digits = seconds
    #[case(1725307, "after=1725307")] // 7 digits = also valid
    fn test_valid_millisecond_cursor_passes(#[case] timestamp: i64, #[case] expected: &str) {
        let mut builder = GetCandlesticksParamsBuilder::default();
        builder.inst_id("BTC-USDT-SWAP");
        builder.bar("1m");
        builder.after_ms(timestamp);

        let params = builder.build().unwrap();
        let qs = serde_urlencoded::to_string(&params).unwrap();
        assert!(qs.contains(expected));
    }

    #[rstest]
    #[case(1, "limit=1")]
    #[case(50, "limit=50")]
    #[case(100, "limit=100")]
    #[case(300, "limit=300")] // Maximum allowed limit
    fn test_valid_limit_passes(#[case] limit: u32, #[case] expected: &str) {
        let mut builder = GetCandlesticksParamsBuilder::default();
        builder.inst_id("BTC-USDT-SWAP");
        builder.bar("1m");
        builder.limit(limit);

        let params = builder.build().unwrap();
        let qs = serde_urlencoded::to_string(&params).unwrap();
        assert!(qs.contains(expected));
    }
}