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
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
// -------------------------------------------------------------------------------------------------
//  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.
// -------------------------------------------------------------------------------------------------

//! Data transfer objects for deserializing OKX HTTP API payloads.

use serde::{Deserialize, Serialize};
use ustr::Ustr;

use crate::common::parse::{
    deserialize_empty_string_as_none, deserialize_empty_ustr_as_none,
    deserialize_target_currency_as_none,
};

/// Represents a trade tick from the GET /api/v5/market/trades endpoint.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OKXTrade {
    /// Instrument ID.
    pub inst_id: Ustr,
    /// Trade price.
    pub px: String,
    /// Trade size.
    pub sz: String,
    /// Trade side: buy or sell.
    pub side: OKXSide,
    /// Trade ID assigned by OKX.
    pub trade_id: Ustr,
    /// Trade timestamp in milliseconds.
    #[serde(deserialize_with = "deserialize_string_to_u64")]
    pub ts: u64,
}

/// Represents a candlestick from the GET /api/v5/market/history-candles endpoint.
/// The tuple contains [timestamp(ms), open, high, low, close, volume, turnover, base_volume, count].
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct OKXCandlestick(
    /// Timestamp in milliseconds.
    pub String,
    /// Open price.
    pub String,
    /// High price.
    pub String,
    /// Low price.
    pub String,
    /// Close price.
    pub String,
    /// Volume.
    pub String,
    /// Turnover in quote currency.
    pub String,
    /// Base volume.
    pub String,
    /// Record count.
    pub String,
);

use crate::common::{
    enums::{
        OKXAlgoOrderType, OKXExecType, OKXInstrumentType, OKXMarginMode, OKXOrderCategory,
        OKXOrderStatus, OKXOrderType, OKXPositionSide, OKXSide, OKXTargetCurrency, OKXTradeMode,
        OKXTriggerType, OKXVipLevel,
    },
    parse::deserialize_string_to_u64,
};

/// Represents a mark price from the GET /api/v5/public/mark-price endpoint.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OKXMarkPrice {
    /// Underlying.
    pub uly: Option<Ustr>,
    /// Instrument ID.
    pub inst_id: Ustr,
    /// The mark price.
    pub mark_px: String,
    /// The timestamp for the mark price.
    #[serde(deserialize_with = "deserialize_string_to_u64")]
    pub ts: u64,
}

/// Represents an option summary row from the GET /api/v5/public/opt-summary endpoint.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OKXOptionSummary {
    /// Instrument type.
    pub inst_type: OKXInstrumentType,
    /// Instrument ID.
    pub inst_id: Ustr,
    /// Underlying index.
    pub uly: Ustr,
    /// Bid volatility.
    pub bid_vol: String,
    /// Ask volatility.
    pub ask_vol: String,
    /// Mark volatility.
    pub mark_vol: String,
    /// Forward price.
    pub fwd_px: String,
    /// Data timestamp in milliseconds.
    #[serde(deserialize_with = "deserialize_string_to_u64")]
    pub ts: u64,
}

/// Represents an index price from the GET /api/v5/public/index-tickers endpoint.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OKXIndexTicker {
    /// Instrument ID.
    pub inst_id: Ustr,
    /// The index price.
    pub idx_px: String,
    /// The timestamp for the index price.
    #[serde(deserialize_with = "deserialize_string_to_u64")]
    pub ts: u64,
}

/// Represents an order book level from the GET /api/v5/market/books endpoint.
/// Each entry is a 4-element tuple: [price, size, liquidated_orders, num_orders].
pub type OKXOrderBookLevel = (String, String, String, String);

/// Represents an order book snapshot from the GET /api/v5/market/books endpoint.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OKXOrderBookSnapshot {
    /// Ask levels [price, size, liquidated_orders_count, orders_count].
    pub asks: Vec<OKXOrderBookLevel>,
    /// Bid levels [price, size, liquidated_orders_count, orders_count].
    pub bids: Vec<OKXOrderBookLevel>,
    /// Timestamp in milliseconds.
    #[serde(deserialize_with = "deserialize_string_to_u64")]
    pub ts: u64,
}

/// Represents a funding rate history entry from the GET /api/v5/public/funding-rate-history endpoint.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OKXFundingRateHistory {
    /// Instrument type.
    pub inst_type: OKXInstrumentType,
    /// Instrument ID.
    pub inst_id: Ustr,
    /// Funding rate.
    pub funding_rate: String,
    /// Realized rate.
    pub realized_rate: String,
    /// Funding time, Unix timestamp in milliseconds.
    #[serde(deserialize_with = "deserialize_string_to_u64")]
    pub funding_time: u64,
    /// Funding rate calculation method.
    #[serde(default)]
    pub method: Option<String>,
}

/// Represents a position tier from the GET /api/v5/public/position-tiers endpoint.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OKXPositionTier {
    /// Underlying.
    pub uly: Ustr,
    /// Instrument family.
    pub inst_family: String,
    /// Instrument ID.
    pub inst_id: Ustr,
    /// Tier level.
    pub tier: String,
    /// Minimum size/amount for the tier.
    pub min_sz: String,
    /// Maximum size/amount for the tier.
    pub max_sz: String,
    /// Maintenance margin requirement rate.
    pub mmr: String,
    /// Initial margin requirement rate.
    pub imr: String,
    /// Maximum available leverage.
    pub max_lever: String,
    /// Option Margin Coefficient (only applicable to options).
    pub opt_mgn_factor: String,
    /// Quote currency borrowing amount.
    pub quote_max_loan: String,
    /// Base currency borrowing amount.
    pub base_max_loan: String,
}

/// Represents an account balance snapshot from `GET /api/v5/account/balance`.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OKXAccount {
    /// Adjusted/Effective equity in USD.
    pub adj_eq: String,
    /// Borrow frozen amount.
    pub borrow_froz: String,
    /// Account details by currency.
    pub details: Vec<OKXBalanceDetail>,
    /// Initial margin requirement.
    pub imr: String,
    /// Isolated margin equity.
    pub iso_eq: String,
    /// Margin ratio.
    pub mgn_ratio: String,
    /// Maintenance margin requirement.
    pub mmr: String,
    /// Notional value in USD for borrow.
    pub notional_usd_for_borrow: String,
    /// Notional value in USD for futures.
    pub notional_usd_for_futures: String,
    /// Notional value in USD for option.
    pub notional_usd_for_option: String,
    /// Notional value in USD for swap.
    pub notional_usd_for_swap: String,
    /// Notional value in USD.
    pub notional_usd: String,
    /// Order frozen.
    pub ord_froz: String,
    /// Total equity in USD.
    pub total_eq: String,
    /// Last update time, Unix timestamp in milliseconds.
    #[serde(deserialize_with = "deserialize_string_to_u64")]
    pub u_time: u64,
    /// Unrealized profit and loss.
    pub upl: String,
}

/// Represents a balance detail for a single currency in an OKX account.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "python", pyo3::pyclass(from_py_object))]
#[cfg_attr(
    feature = "python",
    pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.okx")
)]
pub struct OKXBalanceDetail {
    /// Available balance.
    pub avail_bal: String,
    /// Available equity.
    pub avail_eq: String,
    /// Borrow frozen amount.
    pub borrow_froz: String,
    /// Cash balance.
    pub cash_bal: String,
    /// Currency.
    pub ccy: Ustr,
    /// Cross liability.
    pub cross_liab: String,
    /// Discount equity in USD.
    pub dis_eq: String,
    /// Equity.
    pub eq: String,
    /// Equity in USD.
    pub eq_usd: String,
    /// Same-token equity.
    pub smt_sync_eq: String,
    /// Copy trading equity.
    pub spot_copy_trading_eq: String,
    /// Fixed balance.
    pub fixed_bal: String,
    /// Frozen balance.
    pub frozen_bal: String,
    /// Initial margin requirement.
    pub imr: String,
    /// Interest.
    pub interest: String,
    /// Isolated margin equity.
    pub iso_eq: String,
    /// Isolated margin liability.
    pub iso_liab: String,
    /// Isolated unrealized profit and loss.
    pub iso_upl: String,
    /// Liability.
    pub liab: String,
    /// Maximum loan amount.
    pub max_loan: String,
    /// Margin ratio.
    pub mgn_ratio: String,
    /// Maintenance margin requirement.
    pub mmr: String,
    /// Notional leverage.
    pub notional_lever: String,
    /// Order frozen.
    pub ord_frozen: String,
    /// Reward balance.
    pub reward_bal: String,
    /// Spot in use amount.
    #[serde(alias = "spotInUse")]
    pub spot_in_use_amt: String,
    /// Cross liability spot in use amount.
    #[serde(alias = "clSpotInUse")]
    pub cl_spot_in_use_amt: String,
    /// Maximum spot in use amount.
    #[serde(alias = "maxSpotInUse")]
    pub max_spot_in_use_amt: String,
    /// Spot isolated balance.
    pub spot_iso_bal: String,
    /// Strategy equity.
    pub stgy_eq: String,
    /// Time-weighted average price.
    pub twap: String,
    /// Last update time, Unix timestamp in milliseconds.
    #[serde(deserialize_with = "deserialize_string_to_u64")]
    pub u_time: u64,
    /// Unrealized profit and loss.
    pub upl: String,
    /// Unrealized profit and loss liability.
    pub upl_liab: String,
    /// Spot balance.
    pub spot_bal: String,
    /// Open average price.
    pub open_avg_px: String,
    /// Accumulated average price.
    pub acc_avg_px: String,
    /// Spot unrealized profit and loss.
    pub spot_upl: String,
    /// Spot unrealized profit and loss ratio.
    pub spot_upl_ratio: String,
    /// Total profit and loss.
    pub total_pnl: String,
    /// Total profit and loss ratio.
    pub total_pnl_ratio: String,
}

/// Represents a single open position from `GET /api/v5/account/positions`.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OKXPosition {
    /// Instrument ID.
    pub inst_id: Ustr,
    /// Instrument type.
    pub inst_type: OKXInstrumentType,
    /// Margin mode: isolated/cross.
    pub mgn_mode: OKXMarginMode,
    /// Position ID.
    #[serde(default, deserialize_with = "deserialize_empty_ustr_as_none")]
    pub pos_id: Option<Ustr>,
    /// Position side: long/short.
    pub pos_side: OKXPositionSide,
    /// Position size.
    pub pos: String,
    /// Base currency balance.
    pub base_bal: String,
    /// Position currency.
    pub ccy: String,
    /// Trading fee.
    pub fee: String,
    /// Position leverage.
    pub lever: String,
    /// Last traded price.
    pub last: String,
    /// Mark price.
    pub mark_px: String,
    /// Liquidation price.
    pub liq_px: String,
    /// Maintenance margin requirement.
    pub mmr: String,
    /// Interest.
    pub interest: String,
    /// Trade ID.
    pub trade_id: Ustr,
    /// Notional value of position in USD.
    pub notional_usd: String,
    /// Average entry price.
    pub avg_px: String,
    /// Unrealized profit and loss.
    pub upl: String,
    /// Unrealized profit and loss ratio.
    pub upl_ratio: String,
    /// Last update time, Unix timestamp in milliseconds.
    #[serde(deserialize_with = "deserialize_string_to_u64")]
    pub u_time: u64,
    /// Position margin.
    pub margin: String,
    /// Margin ratio.
    pub mgn_ratio: String,
    /// Auto-deleveraging (ADL) ranking.
    pub adl: String,
    /// Creation time, Unix timestamp in milliseconds.
    pub c_time: String,
    /// Realized profit and loss.
    pub realized_pnl: String,
    /// Unrealized profit and loss at last price.
    pub upl_last_px: String,
    /// Unrealized profit and loss ratio at last price.
    pub upl_ratio_last_px: String,
    /// Available position that can be closed.
    pub avail_pos: String,
    /// Breakeven price.
    pub be_px: String,
    /// Funding fee.
    pub funding_fee: String,
    /// Index price.
    pub idx_px: String,
    /// Liquidation penalty.
    pub liq_penalty: String,
    /// Option value.
    pub opt_val: String,
    /// Pending close order liability value.
    pub pending_close_ord_liab_val: String,
    /// Total profit and loss.
    pub pnl: String,
    /// Position currency.
    pub pos_ccy: String,
    /// Quote currency balance.
    pub quote_bal: String,
    /// Borrowed amount in quote currency.
    pub quote_borrowed: String,
    /// Interest on quote currency.
    pub quote_interest: String,
    /// Amount in use for spot trading.
    #[serde(alias = "spotInUse")]
    pub spot_in_use_amt: String,
    /// Currency in use for spot trading.
    pub spot_in_use_ccy: String,
    /// USD price.
    pub usd_px: String,
    /// Black-Scholes delta in dollars, only applicable to OPTION.
    #[serde(default)]
    pub delta_bs: String,
    /// Black-Scholes gamma in dollars, only applicable to OPTION.
    #[serde(default)]
    pub gamma_bs: String,
    /// Black-Scholes theta in dollars, only applicable to OPTION.
    #[serde(default)]
    pub theta_bs: String,
    /// Black-Scholes vega in dollars, only applicable to OPTION.
    #[serde(default)]
    pub vega_bs: String,
}

/// Represents the response from `POST /api/v5/trade/order` (place order).
/// This model is designed to be flexible and handle the minimal fields that the API returns.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OKXPlaceOrderResponse {
    /// Order ID.
    #[serde(default)]
    pub ord_id: Option<Ustr>,
    /// Client order ID.
    #[serde(default)]
    pub cl_ord_id: Option<Ustr>,
    /// Order tag.
    #[serde(default)]
    pub tag: Option<String>,
    /// Instrument ID (optional - might not be in response).
    #[serde(default)]
    pub inst_id: Option<Ustr>,
    /// Order side (optional).
    #[serde(default)]
    pub side: Option<OKXSide>,
    /// Order type (optional).
    #[serde(default)]
    pub ord_type: Option<OKXOrderType>,
    /// Order size (optional).
    #[serde(default)]
    pub sz: Option<String>,
    /// Order state (optional).
    pub state: Option<OKXOrderStatus>,
    /// Price (optional).
    #[serde(default)]
    pub px: Option<String>,
    /// Average price (optional).
    #[serde(default)]
    pub avg_px: Option<String>,
    /// Accumulated filled size.
    #[serde(default)]
    pub acc_fill_sz: Option<String>,
    /// Fill size (optional).
    #[serde(default)]
    pub fill_sz: Option<String>,
    /// Fill price (optional).
    #[serde(default)]
    pub fill_px: Option<String>,
    /// Trade ID (optional).
    #[serde(default)]
    pub trade_id: Option<Ustr>,
    /// Fill time (optional).
    #[serde(default)]
    pub fill_time: Option<String>,
    /// Fee (optional).
    #[serde(default)]
    pub fee: Option<String>,
    /// Fee currency (optional).
    #[serde(default)]
    pub fee_ccy: Option<String>,
    /// Request ID (optional).
    #[serde(default)]
    pub req_id: Option<Ustr>,
    /// Position side (optional).
    #[serde(default)]
    pub pos_side: Option<OKXPositionSide>,
    /// Reduce-only flag (optional).
    #[serde(default)]
    pub reduce_only: Option<String>,
    /// Target currency (optional).
    #[serde(default, deserialize_with = "deserialize_target_currency_as_none")]
    pub tgt_ccy: Option<OKXTargetCurrency>,
    /// Creation time.
    #[serde(default)]
    pub c_time: Option<String>,
    /// Last update time (optional).
    #[serde(default)]
    pub u_time: Option<String>,
    /// The result of the request.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub s_code: Option<String>,
    /// Error message if the request failed.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub s_msg: Option<String>,
}

/// Represents an attached TP/SL instruction on `POST /api/v5/trade/order`.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OKXAttachAlgoOrdRequest {
    /// Client order ID for the attached TP/SL OCO object.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub attach_algo_cl_ord_id: Option<String>,
    /// Stop-loss trigger price.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sl_trigger_px: Option<String>,
    /// Stop-loss order price.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sl_ord_px: Option<String>,
    /// Stop-loss trigger price type.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sl_trigger_px_type: Option<OKXTriggerType>,
    /// Take-profit trigger price.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tp_trigger_px: Option<String>,
    /// Take-profit order price.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tp_ord_px: Option<String>,
    /// Take-profit trigger price type.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tp_trigger_px_type: Option<OKXTriggerType>,
}

/// Represents the request body for `POST /api/v5/trade/order` (place order).
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OKXPlaceOrderRequest {
    /// Instrument ID.
    pub inst_id: String,
    /// Trade mode (cash, cross, isolated).
    pub td_mode: OKXTradeMode,
    /// Currency used for margin trading when required by OKX.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ccy: Option<String>,
    /// Client-supplied order ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cl_ord_id: Option<String>,
    /// Order tag.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tag: Option<String>,
    /// Order side (buy, sell).
    pub side: OKXSide,
    /// Position side for derivatives.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pos_side: Option<OKXPositionSide>,
    /// Order type.
    pub ord_type: OKXOrderType,
    /// Order size.
    pub sz: String,
    /// Limit price when required by the order type.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub px: Option<String>,
    /// Price in USD, only applicable to options. Mutually exclusive with `px` and `px_vol`.
    #[serde(rename = "pxUsd", skip_serializing_if = "Option::is_none")]
    pub px_usd: Option<String>,
    /// Price in implied volatility (1 = 100%), only applicable to options.
    /// Mutually exclusive with `px` and `px_usd`.
    #[serde(rename = "pxVol", skip_serializing_if = "Option::is_none")]
    pub px_vol: Option<String>,
    /// Reduce-only flag.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reduce_only: Option<bool>,
    /// Target currency for spot market orders.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tgt_ccy: Option<OKXTargetCurrency>,
    /// Attached TP/SL OCO instructions.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub attach_algo_ords: Option<Vec<OKXAttachAlgoOrdRequest>>,
}

pub use crate::common::models::OKXAttachedAlgoOrd;

/// Represents a single historical order record from `GET /api/v5/trade/orders-history`.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OKXOrderHistory {
    /// Order ID.
    pub ord_id: Ustr,
    /// Client order ID.
    pub cl_ord_id: Ustr,
    /// Algo order ID (for conditional orders).
    #[serde(default)]
    pub algo_id: Option<Ustr>,
    /// Client-supplied algo order ID (for conditional orders).
    #[serde(default)]
    pub algo_cl_ord_id: Option<Ustr>,
    /// Attached child client order ID if OKX surfaces one at the top level.
    #[serde(default, deserialize_with = "deserialize_empty_string_as_none")]
    pub attach_algo_cl_ord_id: Option<String>,
    /// Attached TP/SL child orders associated with the parent order.
    #[serde(default)]
    pub attach_algo_ords: Vec<OKXAttachedAlgoOrd>,
    /// Client account ID (may be omitted by OKX).
    #[serde(default)]
    pub cl_act_id: Option<Ustr>,
    /// Order tag.
    pub tag: String,
    /// Instrument type.
    pub inst_type: OKXInstrumentType,
    /// Underlying (optional).
    pub uly: Option<Ustr>,
    /// Instrument ID.
    pub inst_id: Ustr,
    /// Order type.
    pub ord_type: OKXOrderType,
    /// Order size.
    pub sz: String,
    /// Price (optional).
    pub px: String,
    /// Price in USD (options only).
    #[serde(default)]
    pub px_usd: String,
    /// Price in implied volatility (options only).
    #[serde(default)]
    pub px_vol: String,
    /// Side.
    pub side: OKXSide,
    /// Position side.
    pub pos_side: OKXPositionSide,
    /// Trade mode.
    pub td_mode: OKXTradeMode,
    /// Reduce-only flag.
    pub reduce_only: String,
    /// Target currency (optional).
    #[serde(default, deserialize_with = "deserialize_target_currency_as_none")]
    pub tgt_ccy: Option<OKXTargetCurrency>,
    /// Order state.
    pub state: OKXOrderStatus,
    /// Average price (optional).
    pub avg_px: String,
    /// Execution fee.
    pub fee: String,
    /// Fee currency.
    pub fee_ccy: String,
    /// Filled size (optional).
    pub fill_sz: String,
    /// Fill price (optional).
    pub fill_px: String,
    /// Trade ID (optional).
    pub trade_id: Ustr,
    /// Fill time, Unix timestamp in milliseconds.
    #[serde(deserialize_with = "deserialize_string_to_u64")]
    pub fill_time: u64,
    /// Accumulated filled size.
    pub acc_fill_sz: String,
    /// Fill fee (optional, may be omitted).
    #[serde(default)]
    pub fill_fee: Option<String>,
    /// Request ID (optional).
    #[serde(default)]
    pub req_id: Option<Ustr>,
    /// Cancelled filled size (optional).
    #[serde(default)]
    pub cancel_fill_sz: Option<String>,
    /// Cancelled total size (optional).
    #[serde(default)]
    pub cancel_total_sz: Option<String>,
    /// Fee discount (optional).
    #[serde(default)]
    pub fee_discount: Option<String>,
    /// Order category (normal, liquidation, ADL, etc.).
    pub category: OKXOrderCategory,
    /// Last update time, Unix timestamp in milliseconds.
    #[serde(deserialize_with = "deserialize_string_to_u64")]
    pub u_time: u64,
    /// Creation time.
    #[serde(deserialize_with = "deserialize_string_to_u64")]
    pub c_time: u64,
}

/// Represents an algo order response from `/trade/order-algo-*` endpoints.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OKXOrderAlgo {
    /// Algo order ID assigned by OKX.
    pub algo_id: String,
    /// Client-specified algo order ID.
    #[serde(default)]
    pub algo_cl_ord_id: String,
    /// Client order ID (empty until triggered).
    #[serde(default)]
    pub cl_ord_id: String,
    /// Venue order ID (empty until triggered).
    #[serde(default)]
    pub ord_id: String,
    /// Instrument ID, e.g. `ETH-USDT-SWAP`.
    pub inst_id: Ustr,
    /// Instrument type.
    pub inst_type: OKXInstrumentType,
    /// Algo order type.
    pub ord_type: OKXAlgoOrderType,
    /// Current order state.
    pub state: OKXOrderStatus,
    /// Order side.
    pub side: OKXSide,
    /// Position side.
    pub pos_side: OKXPositionSide,
    /// Submitted size.
    #[serde(default)]
    pub sz: String,
    /// Trigger price (empty for certain algo styles).
    #[serde(default)]
    pub trigger_px: String,
    /// Trigger price type (last/mark/index).
    #[serde(default)]
    pub trigger_px_type: Option<OKXTriggerType>,
    /// Stop-loss trigger price for conditional close orders.
    #[serde(default)]
    pub sl_trigger_px: String,
    /// Stop-loss order price for conditional close orders.
    #[serde(default)]
    pub sl_ord_px: String,
    /// Stop-loss trigger price type (last/mark/index).
    #[serde(default)]
    pub sl_trigger_px_type: Option<OKXTriggerType>,
    /// Take-profit trigger price for conditional close orders.
    #[serde(default)]
    pub tp_trigger_px: String,
    /// Take-profit order price for conditional close orders.
    #[serde(default)]
    pub tp_ord_px: String,
    /// Take-profit trigger price type (last/mark/index).
    #[serde(default)]
    pub tp_trigger_px_type: Option<OKXTriggerType>,
    /// Order price (-1 indicates market execution once triggered).
    #[serde(default)]
    pub ord_px: String,
    /// Trade mode (cash/cross/isolated).
    pub td_mode: OKXTradeMode,
    /// Algo leverage configuration.
    #[serde(default)]
    pub lever: String,
    /// Reduce-only flag.
    #[serde(default)]
    pub reduce_only: String,
    /// Fraction of the position to close for close-order algos.
    #[serde(default)]
    pub close_fraction: String,
    /// Executed price (if triggered).
    #[serde(default)]
    pub actual_px: String,
    /// Executed size (if triggered).
    #[serde(default)]
    pub actual_sz: String,
    /// Notional value in USD.
    #[serde(default)]
    pub notional_usd: String,
    /// Creation time (milliseconds).
    #[serde(deserialize_with = "deserialize_string_to_u64")]
    pub c_time: u64,
    /// Last update time (milliseconds).
    #[serde(deserialize_with = "deserialize_string_to_u64")]
    pub u_time: u64,
    /// Trigger timestamp (if triggered).
    #[serde(default)]
    pub trigger_time: String,
    /// Optional tag supplied during submission.
    #[serde(default)]
    pub tag: String,
    /// Callback price ratio for trailing stop (e.g. "0.01" for 1%).
    #[serde(default)]
    pub callback_ratio: String,
    /// Callback price spread for trailing stop (absolute distance).
    #[serde(default)]
    pub callback_spread: String,
    /// Activation price for trailing stop.
    #[serde(default)]
    pub active_px: String,
}

/// Represents a transaction detail (fill) from `GET /api/v5/trade/fills`.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OKXTransactionDetail {
    /// Product type (SPOT, MARGIN, SWAP, FUTURES, OPTION).
    pub inst_type: OKXInstrumentType,
    /// Instrument ID, e.g. "BTC-USDT".
    pub inst_id: Ustr,
    /// Trade ID.
    pub trade_id: Ustr,
    /// Order ID.
    pub ord_id: Ustr,
    /// Client order ID.
    pub cl_ord_id: Ustr,
    /// Bill ID.
    pub bill_id: Ustr,
    /// Last filled price.
    pub fill_px: String,
    /// Last filled quantity.
    pub fill_sz: String,
    /// Trade side: buy or sell.
    pub side: OKXSide,
    /// Execution type.
    pub exec_type: OKXExecType,
    /// Fee currency.
    pub fee_ccy: String,
    /// Fee amount.
    #[serde(default, deserialize_with = "deserialize_empty_string_as_none")]
    pub fee: Option<String>,
    /// Timestamp, Unix timestamp format in milliseconds.
    #[serde(deserialize_with = "deserialize_string_to_u64")]
    pub ts: u64,
}

/// Represents a single historical position record from `GET /api/v5/account/positions-history`.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OKXPositionHistory {
    /// Instrument type (e.g. "SWAP", "FUTURES", etc.).
    pub inst_type: OKXInstrumentType,
    /// Instrument ID (e.g. "BTC-USD-SWAP").
    pub inst_id: Ustr,
    /// Margin mode: e.g. "cross", "isolated".
    pub mgn_mode: OKXMarginMode,
    /// The type of the last close, e.g. "1" (close partially), "2" (close all), etc.
    /// See OKX docs for the meaning of each numeric code.
    #[serde(rename = "type")]
    pub r#type: Ustr,
    /// Creation time of the position (Unix timestamp in milliseconds).
    pub c_time: String,
    /// Last update time, Unix timestamp in milliseconds.
    #[serde(deserialize_with = "deserialize_string_to_u64")]
    pub u_time: u64,
    /// Average price of opening position.
    pub open_avg_px: String,
    /// Average price of closing position (if applicable).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub close_avg_px: Option<String>,
    /// The position ID.
    #[serde(default, deserialize_with = "deserialize_empty_ustr_as_none")]
    pub pos_id: Option<Ustr>,
    /// Max quantity of the position at open time.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub open_max_pos: Option<String>,
    /// Cumulative closed volume of the position.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub close_total_pos: Option<String>,
    /// Realized profit and loss (only for FUTURES/SWAP/OPTION).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub realized_pnl: Option<String>,
    /// Accumulated fee for the position.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub fee: Option<String>,
    /// Accumulated funding fee (for perpetual swaps).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub funding_fee: Option<String>,
    /// Accumulated liquidation penalty. Negative if there was a penalty.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub liq_penalty: Option<String>,
    /// Profit and loss (realized or unrealized depending on status).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pnl: Option<String>,
    /// PnL ratio.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pnl_ratio: Option<String>,
    /// Position side: "long" / "short" / "net".
    pub pos_side: OKXPositionSide,
    /// Leverage used (the JSON field is "lev", but we rename it in Rust).
    pub lever: String,
    /// Direction: "long" or "short" (only for MARGIN/FUTURES/SWAP/OPTION).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub direction: Option<String>,
    /// Trigger mark price. Populated if `type` indicates liquidation or ADL.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub trigger_px: Option<String>,
    /// The underlying (e.g. "BTC-USD" for futures or swap).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub uly: Option<String>,
    /// Currency (e.g. "BTC"). May or may not appear in all responses.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ccy: Option<String>,
}

/// Represents the request body for `POST /api/v5/trade/order-algo` (place algo order).
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OKXPlaceAlgoOrderRequest {
    /// Instrument ID.
    #[serde(rename = "instId")]
    pub inst_id: String,
    /// Instrument ID code (numeric). May be required per OKX deprecation notice.
    #[serde(rename = "instIdCode", skip_serializing_if = "Option::is_none")]
    pub inst_id_code: Option<u64>,
    /// Trade mode (isolated, cross, cash).
    #[serde(rename = "tdMode")]
    pub td_mode: OKXTradeMode,
    /// Order side (buy, sell).
    pub side: OKXSide,
    /// Algo order type (trigger, conditional, move_order_stop, etc.).
    #[serde(rename = "ordType")]
    pub ord_type: OKXAlgoOrderType,
    /// Order size. Omitted for `closeFraction` close orders.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sz: Option<String>,
    /// Client-supplied algo order ID.
    #[serde(rename = "algoClOrdId", skip_serializing_if = "Option::is_none")]
    pub algo_cl_ord_id: Option<String>,
    /// Trigger price.
    #[serde(rename = "triggerPx", skip_serializing_if = "Option::is_none")]
    pub trigger_px: Option<String>,
    /// Order price (for limit orders).
    #[serde(rename = "orderPx", skip_serializing_if = "Option::is_none")]
    pub order_px: Option<String>,
    /// Trigger type (last, mark, index).
    #[serde(rename = "triggerPxType", skip_serializing_if = "Option::is_none")]
    pub trigger_px_type: Option<OKXTriggerType>,
    /// Stop-loss trigger price for conditional close orders.
    #[serde(rename = "slTriggerPx", skip_serializing_if = "Option::is_none")]
    pub sl_trigger_px: Option<String>,
    /// Stop-loss order price for conditional close orders.
    #[serde(rename = "slOrdPx", skip_serializing_if = "Option::is_none")]
    pub sl_ord_px: Option<String>,
    /// Stop-loss trigger type (last, mark, index).
    #[serde(rename = "slTriggerPxType", skip_serializing_if = "Option::is_none")]
    pub sl_trigger_px_type: Option<OKXTriggerType>,
    /// Take-profit trigger price for conditional close orders.
    #[serde(rename = "tpTriggerPx", skip_serializing_if = "Option::is_none")]
    pub tp_trigger_px: Option<String>,
    /// Take-profit order price for conditional close orders.
    #[serde(rename = "tpOrdPx", skip_serializing_if = "Option::is_none")]
    pub tp_ord_px: Option<String>,
    /// Take-profit trigger type (last, mark, index).
    #[serde(rename = "tpTriggerPxType", skip_serializing_if = "Option::is_none")]
    pub tp_trigger_px_type: Option<OKXTriggerType>,
    /// Target currency (base_ccy or quote_ccy).
    #[serde(rename = "tgtCcy", skip_serializing_if = "Option::is_none")]
    pub tgt_ccy: Option<OKXTargetCurrency>,
    /// Position side (net, long, short).
    #[serde(rename = "posSide", skip_serializing_if = "Option::is_none")]
    pub pos_side: Option<OKXPositionSide>,
    /// Whether to close position.
    #[serde(rename = "closePosition", skip_serializing_if = "Option::is_none")]
    pub close_position: Option<bool>,
    /// Order tag.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tag: Option<String>,
    /// Whether it's a reduce-only order.
    #[serde(rename = "reduceOnly", skip_serializing_if = "Option::is_none")]
    pub reduce_only: Option<bool>,
    /// Fraction of the position to close for eligible algo close orders.
    #[serde(rename = "closeFraction", skip_serializing_if = "Option::is_none")]
    pub close_fraction: Option<String>,
    /// Callback rate for trailing stop (e.g., "0.01" for 1%). Either this or
    /// `callback_spread` is required for `move_order_stop` orders.
    #[serde(rename = "callbackRatio", skip_serializing_if = "Option::is_none")]
    pub callback_ratio: Option<String>,
    /// Callback spread for trailing stop (fixed price distance). Either this or
    /// `callback_ratio` is required for `move_order_stop` orders.
    #[serde(rename = "callbackSpread", skip_serializing_if = "Option::is_none")]
    pub callback_spread: Option<String>,
    /// Activation price for trailing stop. If empty, the trailing stop
    /// activates immediately when placed.
    #[serde(rename = "activePx", skip_serializing_if = "Option::is_none")]
    pub active_px: Option<String>,
}

/// Represents the response from `POST /api/v5/trade/order-algo` (place algo order).
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OKXPlaceAlgoOrderResponse {
    /// Algo order ID.
    pub algo_id: String,
    /// Client-supplied algo order ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub algo_cl_ord_id: Option<String>,
    /// The result of the request.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub s_code: Option<String>,
    /// Error message if the request failed.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub s_msg: Option<String>,
    /// Request ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub req_id: Option<String>,
}

/// Represents the request body for `POST /api/v5/trade/cancel-algos` (cancel algo order).
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OKXCancelAlgoOrderRequest {
    /// Instrument ID.
    pub inst_id: String,
    /// Instrument ID code (numeric). May be required per OKX deprecation notice.
    #[serde(rename = "instIdCode", skip_serializing_if = "Option::is_none")]
    pub inst_id_code: Option<u64>,
    /// Algo order ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub algo_id: Option<String>,
    /// Client-supplied algo order ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub algo_cl_ord_id: Option<String>,
}

/// Represents the response from `POST /api/v5/trade/cancel-algos` (cancel algo order).
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OKXCancelAlgoOrderResponse {
    /// Algo order ID.
    pub algo_id: String,
    /// The result of the request.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub s_code: Option<String>,
    /// Error message if the request failed.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub s_msg: Option<String>,
}

/// Represents the request body for `POST /api/v5/trade/amend-algos` (amend algo order).
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OKXAmendAlgoOrderRequest {
    /// Instrument ID.
    pub inst_id: String,
    /// Algo order ID.
    pub algo_id: String,
    /// Client-supplied algo order ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub algo_cl_ord_id: Option<String>,
    /// New order size.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub new_sz: Option<String>,
    /// New trigger price (for trigger/conditional orders).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub new_trigger_px: Option<String>,
    /// New order price (for limit orders after trigger).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub new_order_px: Option<String>,
    /// New callback ratio for trailing stop (e.g., "0.01" for 1%).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub new_callback_ratio: Option<String>,
    /// New callback spread for trailing stop (fixed price distance).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub new_callback_spread: Option<String>,
    /// New activation price for trailing stop.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub new_active_px: Option<String>,
}

/// Represents the response from `POST /api/v5/trade/amend-algos` (amend algo order).
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OKXAmendAlgoOrderResponse {
    /// Algo order ID.
    pub algo_id: String,
    /// Client-supplied algo order ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub algo_cl_ord_id: Option<String>,
    /// The result of the request.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub s_code: Option<String>,
    /// Error message if the request failed.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub s_msg: Option<String>,
    /// Request ID.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub req_id: Option<String>,
}

/// Represents the response from `GET /api/v5/public/time` (get system time).
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OKXServerTime {
    /// Server timestamp in milliseconds.
    #[serde(deserialize_with = "deserialize_string_to_u64")]
    pub ts: u64,
}

/// Represents a fee rate entry from `GET /api/v5/account/trade-fee`.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct OKXFeeRate {
    /// Fee level (VIP tier) - indicates the user's VIP tier (0-9).
    #[serde(deserialize_with = "crate::common::parse::deserialize_vip_level")]
    pub level: OKXVipLevel,
    /// Taker fee rate for crypto-margined contracts.
    pub taker: String,
    /// Maker fee rate for crypto-margined contracts.
    pub maker: String,
    /// Taker fee rate for USDT-margined contracts.
    pub taker_u: String,
    /// Maker fee rate for USDT-margined contracts.
    pub maker_u: String,
    /// Delivery fee rate.
    #[serde(default)]
    pub delivery: String,
    /// Option exercise fee rate.
    #[serde(default)]
    pub exercise: String,
    /// Instrument type (SPOT, MARGIN, SWAP, FUTURES, OPTION).
    pub inst_type: OKXInstrumentType,
    /// Fee schedule category (being deprecated).
    #[serde(default)]
    pub category: String,
    /// Data return timestamp (Unix timestamp in milliseconds).
    #[serde(deserialize_with = "deserialize_string_to_u64")]
    pub ts: u64,
}

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

    use super::*;

    #[rstest]
    fn test_algo_order_request_serialization() {
        let request = OKXPlaceAlgoOrderRequest {
            inst_id: "ETH-USDT-SWAP".to_string(),
            inst_id_code: None,
            td_mode: OKXTradeMode::Isolated,
            side: OKXSide::Buy,
            ord_type: OKXAlgoOrderType::Trigger,
            sz: Some("0.01".to_string()),
            algo_cl_ord_id: Some("test123".to_string()),
            trigger_px: Some("3000".to_string()),
            order_px: Some("-1".to_string()),
            trigger_px_type: Some(OKXTriggerType::Last),
            sl_trigger_px: None,
            sl_ord_px: None,
            sl_trigger_px_type: None,
            tp_trigger_px: None,
            tp_ord_px: None,
            tp_trigger_px_type: None,
            tgt_ccy: None,
            pos_side: None,
            close_position: None,
            tag: None,
            reduce_only: None,
            close_fraction: None,
            callback_ratio: None,
            callback_spread: None,
            active_px: None,
        };

        let json = serde_json::to_string(&request).unwrap();

        // Verify that fields are serialized with correct camelCase names
        assert!(json.contains("\"instId\":\"ETH-USDT-SWAP\""));
        assert!(json.contains("\"tdMode\":\"isolated\""));
        assert!(json.contains("\"ordType\":\"trigger\""));
        assert!(json.contains("\"algoClOrdId\":\"test123\""));
        assert!(json.contains("\"triggerPx\":\"3000\""));
        assert!(json.contains("\"orderPx\":\"-1\""));
        assert!(json.contains("\"triggerPxType\":\"last\""));

        // Verify that None fields are not included
        assert!(!json.contains("tgtCcy"));
        assert!(!json.contains("posSide"));
        assert!(!json.contains("closePosition"));
        assert!(!json.contains("closeFraction"));
    }

    #[rstest]
    fn test_algo_order_request_serializes_close_fraction() {
        let request = OKXPlaceAlgoOrderRequest {
            inst_id: "ETH-USDT-SWAP".to_string(),
            inst_id_code: None,
            td_mode: OKXTradeMode::Cross,
            side: OKXSide::Sell,
            ord_type: OKXAlgoOrderType::Conditional,
            sz: None,
            algo_cl_ord_id: Some("close-frac-123".to_string()),
            trigger_px: None,
            order_px: None,
            trigger_px_type: None,
            sl_trigger_px: Some("3000".to_string()),
            sl_ord_px: Some("-1".to_string()),
            sl_trigger_px_type: Some(OKXTriggerType::Last),
            tp_trigger_px: None,
            tp_ord_px: None,
            tp_trigger_px_type: None,
            tgt_ccy: None,
            pos_side: Some(OKXPositionSide::Net),
            close_position: None,
            tag: None,
            reduce_only: Some(true),
            close_fraction: Some("1".to_string()),
            callback_ratio: None,
            callback_spread: None,
            active_px: None,
        };

        let json = serde_json::to_string(&request).unwrap();

        assert!(json.contains("\"ordType\":\"conditional\""));
        assert!(json.contains("\"closeFraction\":\"1\""));
        assert!(json.contains("\"slTriggerPx\":\"3000\""));
        assert!(json.contains("\"slOrdPx\":\"-1\""));
        assert!(json.contains("\"slTriggerPxType\":\"last\""));
        assert!(json.contains("\"reduceOnly\":true"));
        assert!(!json.contains("\"sz\""));
        assert!(!json.contains("triggerPx"));
    }

    #[rstest]
    fn test_algo_order_request_array_serialization() {
        let request = OKXPlaceAlgoOrderRequest {
            inst_id: "BTC-USDT".to_string(),
            inst_id_code: Some(10459),
            td_mode: OKXTradeMode::Cross,
            side: OKXSide::Sell,
            ord_type: OKXAlgoOrderType::Trigger,
            sz: Some("0.1".to_string()),
            algo_cl_ord_id: None,
            trigger_px: Some("50000".to_string()),
            order_px: Some("49900".to_string()),
            trigger_px_type: Some(OKXTriggerType::Mark),
            sl_trigger_px: None,
            sl_ord_px: None,
            sl_trigger_px_type: None,
            tp_trigger_px: None,
            tp_ord_px: None,
            tp_trigger_px_type: None,
            tgt_ccy: Some(OKXTargetCurrency::BaseCcy),
            pos_side: Some(OKXPositionSide::Net),
            close_position: None,
            tag: None,
            reduce_only: Some(true),
            close_fraction: None,
            callback_ratio: None,
            callback_spread: None,
            active_px: None,
        };

        // OKX expects an array of requests
        let json = serde_json::to_string(&[request]).unwrap();

        // Verify array format
        assert!(json.starts_with('['));
        assert!(json.ends_with(']'));

        // Verify correct field names
        assert!(json.contains("\"instId\":\"BTC-USDT\""));
        assert!(json.contains("\"tdMode\":\"cross\""));
        assert!(json.contains("\"triggerPx\":\"50000\""));
        assert!(json.contains("\"orderPx\":\"49900\""));
        assert!(json.contains("\"triggerPxType\":\"mark\""));
        assert!(json.contains("\"tgtCcy\":\"base_ccy\""));
        assert!(json.contains("\"posSide\":\"net\""));
        assert!(json.contains("\"reduceOnly\":true"));
    }

    #[rstest]
    fn test_cancel_algo_order_request_serialization() {
        let request = OKXCancelAlgoOrderRequest {
            inst_id: "ETH-USDT-SWAP".to_string(),
            inst_id_code: None,
            algo_id: Some("123456".to_string()),
            algo_cl_ord_id: None,
        };

        let json = serde_json::to_string(&request).unwrap();

        // Verify correct field names
        assert!(json.contains("\"instId\":\"ETH-USDT-SWAP\""));
        assert!(json.contains("\"algoId\":\"123456\""));
        assert!(!json.contains("algoClOrdId"));
    }

    #[rstest]
    fn test_cancel_algo_order_with_client_id_serialization() {
        let request = OKXCancelAlgoOrderRequest {
            inst_id: "BTC-USDT".to_string(),
            inst_id_code: Some(10459),
            algo_id: None,
            algo_cl_ord_id: Some("client123".to_string()),
        };

        // OKX expects an array of requests
        let json = serde_json::to_string(&[request]).unwrap();

        // Verify array format and field names
        assert!(json.starts_with('['));
        assert!(json.contains("\"instId\":\"BTC-USDT\""));
        assert!(json.contains("\"algoClOrdId\":\"client123\""));
        assert!(!json.contains("\"algoId\""));
    }

    #[rstest]
    fn test_amend_algo_order_trigger_serialization() {
        let request = OKXAmendAlgoOrderRequest {
            inst_id: "ETH-USDT-SWAP".to_string(),
            algo_id: "123456".to_string(),
            algo_cl_ord_id: None,
            new_sz: None,
            new_trigger_px: Some("3500".to_string()),
            new_order_px: Some("3490".to_string()),
            new_callback_ratio: None,
            new_callback_spread: None,
            new_active_px: None,
        };

        let json = serde_json::to_string(&request).unwrap();

        assert!(json.contains("\"instId\":\"ETH-USDT-SWAP\""));
        assert!(json.contains("\"algoId\":\"123456\""));
        assert!(json.contains("\"newTriggerPx\":\"3500\""));
        assert!(json.contains("\"newOrderPx\":\"3490\""));
        assert!(!json.contains("newSz"));
        assert!(!json.contains("algoClOrdId"));
        assert!(!json.contains("newCallbackRatio"));
    }

    #[rstest]
    fn test_amend_algo_order_trailing_stop_serialization() {
        let request = OKXAmendAlgoOrderRequest {
            inst_id: "BTC-USDT-SWAP".to_string(),
            algo_id: "789012".to_string(),
            algo_cl_ord_id: Some("client456".to_string()),
            new_sz: Some("0.1".to_string()),
            new_trigger_px: None,
            new_order_px: None,
            new_callback_ratio: Some("0.02".to_string()),
            new_callback_spread: None,
            new_active_px: Some("50000".to_string()),
        };

        let json = serde_json::to_string(&request).unwrap();

        assert!(json.contains("\"instId\":\"BTC-USDT-SWAP\""));
        assert!(json.contains("\"algoId\":\"789012\""));
        assert!(json.contains("\"algoClOrdId\":\"client456\""));
        assert!(json.contains("\"newSz\":\"0.1\""));
        assert!(json.contains("\"newCallbackRatio\":\"0.02\""));
        assert!(json.contains("\"newActivePx\":\"50000\""));
        assert!(!json.contains("newTriggerPx"));
        assert!(!json.contains("newOrderPx"));
    }

    #[rstest]
    fn test_trailing_stop_request_callback_ratio_serialization() {
        let request = OKXPlaceAlgoOrderRequest {
            inst_id: "BTC-USDT-SWAP".to_string(),
            inst_id_code: None,
            td_mode: OKXTradeMode::Cross,
            side: OKXSide::Buy,
            ord_type: OKXAlgoOrderType::MoveOrderStop,
            sz: Some("0.1".to_string()),
            algo_cl_ord_id: Some("trail-001".to_string()),
            trigger_px: None,
            order_px: None,
            trigger_px_type: None,
            sl_trigger_px: None,
            sl_ord_px: None,
            sl_trigger_px_type: None,
            tp_trigger_px: None,
            tp_ord_px: None,
            tp_trigger_px_type: None,
            tgt_ccy: None,
            pos_side: None,
            close_position: None,
            tag: None,
            reduce_only: None,
            close_fraction: None,
            callback_ratio: Some("0.01".to_string()),
            callback_spread: None,
            active_px: None,
        };

        let json = serde_json::to_string(&request).unwrap();

        assert!(json.contains("\"ordType\":\"move_order_stop\""));
        assert!(json.contains("\"callbackRatio\":\"0.01\""));
        assert!(!json.contains("callbackSpread"));
        assert!(!json.contains("activePx"));
    }

    #[rstest]
    fn test_trailing_stop_request_callback_spread_serialization() {
        let request = OKXPlaceAlgoOrderRequest {
            inst_id: "ETH-USDT-SWAP".to_string(),
            inst_id_code: None,
            td_mode: OKXTradeMode::Isolated,
            side: OKXSide::Sell,
            ord_type: OKXAlgoOrderType::MoveOrderStop,
            sz: Some("1.0".to_string()),
            algo_cl_ord_id: None,
            trigger_px: None,
            order_px: None,
            trigger_px_type: None,
            sl_trigger_px: None,
            sl_ord_px: None,
            sl_trigger_px_type: None,
            tp_trigger_px: None,
            tp_ord_px: None,
            tp_trigger_px_type: None,
            tgt_ccy: None,
            pos_side: None,
            close_position: None,
            tag: None,
            reduce_only: Some(true),
            close_fraction: None,
            callback_ratio: None,
            callback_spread: Some("50.5".to_string()),
            active_px: None,
        };

        let json = serde_json::to_string(&request).unwrap();

        assert!(json.contains("\"callbackSpread\":\"50.5\""));
        assert!(!json.contains("callbackRatio"));
        assert!(!json.contains("activePx"));
    }

    #[rstest]
    fn test_trailing_stop_request_with_activation_price_serialization() {
        let request = OKXPlaceAlgoOrderRequest {
            inst_id: "BTC-USDT-SWAP".to_string(),
            inst_id_code: None,
            td_mode: OKXTradeMode::Cross,
            side: OKXSide::Buy,
            ord_type: OKXAlgoOrderType::MoveOrderStop,
            sz: Some("0.5".to_string()),
            algo_cl_ord_id: None,
            trigger_px: None,
            order_px: None,
            trigger_px_type: None,
            sl_trigger_px: None,
            sl_ord_px: None,
            sl_trigger_px_type: None,
            tp_trigger_px: None,
            tp_ord_px: None,
            tp_trigger_px_type: None,
            tgt_ccy: None,
            pos_side: None,
            close_position: None,
            tag: None,
            reduce_only: None,
            close_fraction: None,
            callback_ratio: Some("0.005".to_string()),
            callback_spread: None,
            active_px: Some("65000".to_string()),
        };

        let json = serde_json::to_string(&request).unwrap();

        assert!(json.contains("\"callbackRatio\":\"0.005\""));
        assert!(json.contains("\"activePx\":\"65000\""));
        assert!(!json.contains("callbackSpread"));
    }

    #[rstest]
    fn test_amend_algo_order_callback_spread_serialization() {
        let request = OKXAmendAlgoOrderRequest {
            inst_id: "ETH-USDT-SWAP".to_string(),
            algo_id: "456789".to_string(),
            algo_cl_ord_id: None,
            new_sz: None,
            new_trigger_px: None,
            new_order_px: None,
            new_callback_ratio: None,
            new_callback_spread: Some("25.0".to_string()),
            new_active_px: Some("4000".to_string()),
        };

        let json = serde_json::to_string(&request).unwrap();

        assert!(json.contains("\"newCallbackSpread\":\"25.0\""));
        assert!(json.contains("\"newActivePx\":\"4000\""));
        assert!(!json.contains("newCallbackRatio"));
        assert!(!json.contains("newTriggerPx"));
        assert!(!json.contains("newSz"));
    }

    #[rstest]
    fn test_amend_algo_order_size_only_serialization() {
        let request = OKXAmendAlgoOrderRequest {
            inst_id: "BTC-USDT-SWAP".to_string(),
            algo_id: "111222".to_string(),
            algo_cl_ord_id: None,
            new_sz: Some("0.5".to_string()),
            new_trigger_px: None,
            new_order_px: None,
            new_callback_ratio: None,
            new_callback_spread: None,
            new_active_px: None,
        };

        let json = serde_json::to_string(&request).unwrap();

        assert!(json.contains("\"newSz\":\"0.5\""));
        assert!(!json.contains("newTriggerPx"));
        assert!(!json.contains("newOrderPx"));
        assert!(!json.contains("newCallbackRatio"));
        assert!(!json.contains("newCallbackSpread"));
        assert!(!json.contains("newActivePx"));
    }

    #[rstest]
    fn test_amend_algo_order_all_fields_serialization() {
        let request = OKXAmendAlgoOrderRequest {
            inst_id: "BTC-USDT-SWAP".to_string(),
            algo_id: "333444".to_string(),
            algo_cl_ord_id: Some("client789".to_string()),
            new_sz: Some("1.0".to_string()),
            new_trigger_px: Some("60000".to_string()),
            new_order_px: Some("59900".to_string()),
            new_callback_ratio: Some("0.015".to_string()),
            new_callback_spread: Some("100".to_string()),
            new_active_px: Some("62000".to_string()),
        };

        let json = serde_json::to_string(&request).unwrap();

        assert!(json.contains("\"instId\":\"BTC-USDT-SWAP\""));
        assert!(json.contains("\"algoId\":\"333444\""));
        assert!(json.contains("\"algoClOrdId\":\"client789\""));
        assert!(json.contains("\"newSz\":\"1.0\""));
        assert!(json.contains("\"newTriggerPx\":\"60000\""));
        assert!(json.contains("\"newOrderPx\":\"59900\""));
        assert!(json.contains("\"newCallbackRatio\":\"0.015\""));
        assert!(json.contains("\"newCallbackSpread\":\"100\""));
        assert!(json.contains("\"newActivePx\":\"62000\""));
    }

    #[rstest]
    fn test_place_order_request_serializes_px_usd() {
        let request = OKXPlaceOrderRequest {
            inst_id: "BTC-USD-250328-50000-C".to_string(),
            td_mode: OKXTradeMode::Cross,
            ccy: None,
            cl_ord_id: Some("test-opt-1".to_string()),
            tag: None,
            side: OKXSide::Buy,
            pos_side: Some(OKXPositionSide::Net),
            ord_type: OKXOrderType::Limit,
            sz: "1".to_string(),
            px: None,
            px_usd: Some("100.5".to_string()),
            px_vol: None,
            reduce_only: None,
            tgt_ccy: None,
            attach_algo_ords: None,
        };

        let json = serde_json::to_string(&request).unwrap();
        assert!(json.contains("\"pxUsd\":\"100.5\""));
        assert!(!json.contains("\"pxVol\""));
        assert!(!json.contains("\"px\":"));
    }

    #[rstest]
    fn test_place_order_request_serializes_px_vol() {
        let request = OKXPlaceOrderRequest {
            inst_id: "BTC-USD-250328-50000-C".to_string(),
            td_mode: OKXTradeMode::Cross,
            ccy: None,
            cl_ord_id: Some("test-opt-2".to_string()),
            tag: None,
            side: OKXSide::Buy,
            pos_side: Some(OKXPositionSide::Net),
            ord_type: OKXOrderType::Limit,
            sz: "1".to_string(),
            px: None,
            px_usd: None,
            px_vol: Some("0.55".to_string()),
            reduce_only: None,
            tgt_ccy: None,
            attach_algo_ords: None,
        };

        let json = serde_json::to_string(&request).unwrap();
        assert!(json.contains("\"pxVol\":\"0.55\""));
        assert!(!json.contains("\"pxUsd\""));
        assert!(!json.contains("\"px\":"));
    }
}