longbridge 4.4.3

Longbridge OpenAPI SDK for Rust
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
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
use num_enum::{FromPrimitive, IntoPrimitive};
use rust_decimal::Decimal;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use strum_macros::{Display, EnumString};
use time::{Date, OffsetDateTime};

use crate::{Market, serde_utils};

/// Order type
#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, EnumString, Display)]
#[allow(clippy::upper_case_acronyms)]
pub enum OrderType {
    /// Unknown
    Unknown,
    /// Limit Order
    #[strum(serialize = "LO")]
    LO,
    /// Enhanced Limit Order
    #[strum(serialize = "ELO")]
    ELO,
    /// Market Order
    #[strum(serialize = "MO")]
    MO,
    /// At-auction Order
    #[strum(serialize = "AO")]
    AO,
    /// At-auction Limit Order
    #[strum(serialize = "ALO")]
    ALO,
    /// Odd Lots
    #[strum(serialize = "ODD")]
    ODD,
    /// Limit If Touched
    #[strum(serialize = "LIT")]
    LIT,
    /// Market If Touched
    #[strum(serialize = "MIT")]
    MIT,
    /// Trailing Limit If Touched (Trailing Amount)
    #[strum(serialize = "TSLPAMT")]
    TSLPAMT,
    /// Trailing Limit If Touched (Trailing Percent)
    #[strum(serialize = "TSLPPCT")]
    TSLPPCT,
    /// Trailing Market If Touched (Trailing Amount)
    #[strum(serialize = "TSMAMT")]
    TSMAMT,
    /// Trailing Market If Touched (Trailing Percent)
    #[strum(serialize = "TSMPCT")]
    TSMPCT,
    /// Special Limit Order
    #[strum(serialize = "SLO")]
    SLO,
}

/// Order status
#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, EnumString, Display)]
pub enum OrderStatus {
    /// Unknown
    Unknown,
    /// Not reported
    #[strum(serialize = "NotReported")]
    NotReported,
    /// Not reported (Replaced Order)
    #[strum(serialize = "ReplacedNotReported")]
    ReplacedNotReported,
    /// Not reported (Protected Order)
    #[strum(serialize = "ProtectedNotReported")]
    ProtectedNotReported,
    /// Not reported (Conditional Order)
    #[strum(serialize = "VarietiesNotReported")]
    VarietiesNotReported,
    /// Filled
    #[strum(serialize = "FilledStatus")]
    Filled,
    /// Wait To New
    #[strum(serialize = "WaitToNew")]
    WaitToNew,
    /// New
    #[strum(serialize = "NewStatus")]
    New,
    /// Wait To Replace
    #[strum(serialize = "WaitToReplace")]
    WaitToReplace,
    /// Pending Replace
    #[strum(serialize = "PendingReplaceStatus")]
    PendingReplace,
    /// Replaced
    #[strum(serialize = "ReplacedStatus")]
    Replaced,
    /// Partial Filled
    #[strum(serialize = "PartialFilledStatus")]
    PartialFilled,
    /// Wait To Cancel
    #[strum(serialize = "WaitToCancel")]
    WaitToCancel,
    /// Pending Cancel
    #[strum(serialize = "PendingCancelStatus")]
    PendingCancel,
    /// Rejected
    #[strum(serialize = "RejectedStatus")]
    Rejected,
    /// Canceled
    #[strum(serialize = "CanceledStatus")]
    Canceled,
    /// Expired
    #[strum(serialize = "ExpiredStatus")]
    Expired,
    /// Partial Withdrawal
    #[strum(serialize = "PartialWithdrawal")]
    PartialWithdrawal,
}

/// Execution
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Execution {
    /// Order ID
    pub order_id: String,
    /// Execution ID
    pub trade_id: String,
    /// Security code
    pub symbol: String,
    /// Trade done time
    #[serde(
        serialize_with = "time::serde::rfc3339::serialize",
        deserialize_with = "serde_utils::timestamp::deserialize"
    )]
    pub trade_done_at: OffsetDateTime,
    /// Executed quantity
    pub quantity: Decimal,
    /// Executed price
    pub price: Decimal,
}

/// Response for get all executions request
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AllExecutionsResponse {
    /// Has more records
    pub has_more: bool,
    /// Execution list
    #[serde(default)]
    pub trades: Vec<Execution>,
}

/// Order side
#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, EnumString, Display)]
pub enum OrderSide {
    /// Unknown
    Unknown,
    /// Buy
    #[strum(serialize = "Buy")]
    Buy,
    /// Sell
    #[strum(serialize = "Sell")]
    Sell,
}

/// Order trigger price type
#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, EnumString, Display)]
pub enum TriggerPriceType {
    /// Unknown
    Unknown,
    /// Limit If Touched
    #[strum(serialize = "LIT")]
    LimitIfTouched,
    /// Market If Touched
    #[strum(serialize = "MIT")]
    MarketIfTouched,
}

/// Order tag
#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, EnumString, Display)]
pub enum OrderTag {
    /// Unknown
    Unknown,
    /// Normal Order
    #[strum(serialize = "Normal")]
    Normal,
    /// Long term Order
    #[strum(serialize = "Gtc")]
    LongTerm,
    /// Grey Order
    #[strum(serialize = "Grey")]
    Grey,
}

/// Time in force Type
#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, EnumString, Display)]
pub enum TimeInForceType {
    /// Unknown
    Unknown,
    /// Day Order
    #[strum(serialize = "Day")]
    Day,
    /// Good Til Canceled Order
    #[strum(serialize = "GTC")]
    GoodTilCanceled,
    /// Good Til Date Order
    #[strum(serialize = "GTD")]
    GoodTilDate,
}

/// Trigger status
#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, EnumString, Display)]
pub enum TriggerStatus {
    /// Unknown
    Unknown,
    /// Deactive
    #[strum(serialize = "DEACTIVE")]
    Deactive,
    /// Active
    #[strum(serialize = "ACTIVE")]
    Active,
    /// Released
    #[strum(serialize = "RELEASED")]
    Released,
}

/// Enable or disable outside regular trading hours
#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, EnumString, Display)]
pub enum OutsideRTH {
    /// Unknown
    Unknown,
    /// Regular trading hour only
    #[strum(serialize = "RTH_ONLY")]
    RTHOnly,
    /// Any time
    #[strum(serialize = "ANY_TIME")]
    AnyTime,
    /// Overnight
    #[strum(serialize = "OVERNIGHT")]
    Overnight,
    /// Overnight option
    #[strum(serialize = "OPTION_PRE_MARKET")]
    OptionPreMarket,
}

/// Attached order type
#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, EnumString, Display)]
pub enum AttachedOrderType {
    /// Unknown
    Unknown,
    /// Take profit
    #[strum(serialize = "PROFIT_TAKER")]
    ProfitTaker,
    /// Stop loss
    #[strum(serialize = "STOP_LOSS")]
    StopLoss,
    /// Bracket order
    #[strum(serialize = "BRACKET")]
    Bracket,
}

/// Attached order detail
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AttachedOrderDetail {
    /// Attached order ID
    pub order_id: String,
    /// Attached order type
    pub attached_type_display: AttachedOrderType,
    /// Trigger price
    #[serde(with = "serde_utils::decimal_opt_empty_is_none")]
    pub trigger_price: Option<Decimal>,
    /// Quantity
    pub quantity: Decimal,
    /// Executed quantity
    pub executed_qty: Decimal,
    /// Order status
    pub status: OrderStatus,
    /// Last updated time (unix timestamp seconds)
    #[serde(
        serialize_with = "time::serde::rfc3339::serialize",
        deserialize_with = "serde_utils::timestamp::deserialize"
    )]
    pub updated_at: OffsetDateTime,
    /// Whether withdrawn
    pub withdrawn: bool,
    /// GTD date
    #[serde(with = "serde_utils::date_opt")]
    pub gtd: Option<Date>,
    /// Time in force
    pub time_in_force: TimeInForceType,
    /// Counter order ID
    pub counter_id: String,
    /// Trigger status
    #[serde(with = "serde_utils::trigger_status")]
    pub trigger_status: Option<TriggerStatus>,
    /// Executed amount
    pub executed_amount: Decimal,
    /// Tag
    pub tag: OrderTag,
    /// Submitted time (unix timestamp seconds)
    #[serde(
        serialize_with = "time::serde::rfc3339::serialize",
        deserialize_with = "serde_utils::timestamp::deserialize"
    )]
    pub submitted_at: OffsetDateTime,
    /// Executed price
    #[serde(with = "serde_utils::decimal_opt_empty_is_none")]
    pub executed_price: Option<Decimal>,
    /// Force RTH only
    #[serde(with = "serde_utils::outside_rth")]
    pub force_only_rth: Option<OutsideRTH>,
    /// Whether reviewed
    pub reviewed: bool,
    /// Order type to submit after trigger
    pub activate_order_type: OrderType,
    /// RTH setting for activated order
    #[serde(with = "serde_utils::outside_rth")]
    pub activate_rth: Option<OutsideRTH>,
    /// Submit price (limit price)
    #[serde(with = "serde_utils::decimal_opt_empty_is_none")]
    pub submit_price: Option<Decimal>,
}

/// Order
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Order {
    /// Order ID
    pub order_id: String,
    /// Order status
    pub status: OrderStatus,
    /// Stock name
    pub stock_name: String,
    /// Submitted quantity
    pub quantity: Decimal,
    /// Executed quantity
    pub executed_quantity: Decimal,
    /// Submitted price
    #[serde(with = "serde_utils::decimal_opt_empty_is_none")]
    pub price: Option<Decimal>,
    /// Executed price
    #[serde(with = "serde_utils::decimal_opt_0_is_none")]
    pub executed_price: Option<Decimal>,
    /// Submitted time
    #[serde(
        serialize_with = "time::serde::rfc3339::serialize",
        deserialize_with = "serde_utils::timestamp::deserialize"
    )]
    pub submitted_at: OffsetDateTime,
    /// Order side
    pub side: OrderSide,
    /// Security code
    pub symbol: String,
    /// Order type
    pub order_type: OrderType,
    /// Last done
    #[serde(with = "serde_utils::decimal_opt_empty_is_none")]
    pub last_done: Option<Decimal>,
    /// `LIT` / `MIT` Order Trigger Price
    #[serde(with = "serde_utils::decimal_opt_empty_is_none")]
    pub trigger_price: Option<Decimal>,
    /// Rejected Message or remark
    pub msg: String,
    /// Order tag
    pub tag: OrderTag,
    /// Time in force type
    pub time_in_force: TimeInForceType,
    /// Long term order expire date
    #[serde(with = "serde_utils::date_opt")]
    pub expire_date: Option<Date>,
    /// Last updated time
    #[serde(
        deserialize_with = "serde_utils::timestamp_opt::deserialize",
        serialize_with = "serde_utils::rfc3339_opt::serialize"
    )]
    pub updated_at: Option<OffsetDateTime>,
    /// Conditional order trigger time
    #[serde(
        deserialize_with = "serde_utils::timestamp_opt::deserialize",
        serialize_with = "serde_utils::rfc3339_opt::serialize"
    )]
    pub trigger_at: Option<OffsetDateTime>,
    /// `TSMAMT` / `TSLPAMT` order trailing amount
    #[serde(with = "serde_utils::decimal_opt_empty_is_none")]
    pub trailing_amount: Option<Decimal>,
    /// `TSMPCT` / `TSLPPCT` order trailing percent
    #[serde(with = "serde_utils::decimal_opt_empty_is_none")]
    pub trailing_percent: Option<Decimal>,
    /// `TSLPAMT` / `TSLPPCT` order limit offset amount
    #[serde(with = "serde_utils::decimal_opt_empty_is_none")]
    pub limit_offset: Option<Decimal>,
    /// Conditional order trigger status
    #[serde(with = "serde_utils::trigger_status")]
    pub trigger_status: Option<TriggerStatus>,
    /// Currency
    pub currency: String,
    /// Enable or disable outside regular trading hours
    #[serde(with = "serde_utils::outside_rth")]
    pub outside_rth: Option<OutsideRTH>,
    /// Limit depth level
    #[serde(with = "serde_utils::int32_opt_0_is_none")]
    pub limit_depth_level: Option<i32>,
    /// Trigger count
    #[serde(with = "serde_utils::int32_opt_0_is_none")]
    pub trigger_count: Option<i32>,
    /// Monitor price
    #[serde(with = "serde_utils::decimal_opt_empty_is_none")]
    pub monitor_price: Option<Decimal>,
    /// Remark
    pub remark: String,
    /// Attached orders
    #[serde(default)]
    pub attached_orders: Vec<AttachedOrderDetail>,
}

/// Commission-free Status
#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, EnumString, Display)]
pub enum CommissionFreeStatus {
    /// Unknown
    Unknown,
    /// None
    None,
    /// Commission-free amount to be calculated
    Calculated,
    /// Pending commission-free
    Pending,
    /// Commission-free applied
    Ready,
}

/// Deduction status
#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, EnumString, Display)]
pub enum DeductionStatus {
    /// Unknown
    Unknown,
    /// Pending Settlement
    #[strum(serialize = "NONE")]
    None,
    /// Settled with no data
    #[strum(serialize = "NO_DATA")]
    NoData,
    /// Settled and pending distribution
    #[strum(serialize = "PENDING")]
    Pending,
    /// Settled and distributed
    #[strum(serialize = "DONE")]
    Done,
}

/// Charge category code
#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, EnumString, Display)]
pub enum ChargeCategoryCode {
    /// Unknown
    Unknown,
    /// Broker
    #[strum(serialize = "BROKER_FEES")]
    Broker,
    /// Third
    #[strum(serialize = "THIRD_FEES")]
    Third,
}

/// Order history detail
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OrderHistoryDetail {
    /// Executed price for executed orders, submitted price for expired,
    /// canceled, rejected orders, etc.
    #[serde(with = "serde_utils::decimal_empty_is_0")]
    pub price: Decimal,
    /// Executed quantity for executed orders, remaining quantity for expired,
    /// canceled, rejected orders, etc.
    #[serde(with = "serde_utils::decimal_empty_is_0")]
    pub quantity: Decimal,
    /// Order status
    pub status: OrderStatus,
    /// Execution or error message
    pub msg: String,
    /// Occurrence time
    #[serde(
        serialize_with = "time::serde::rfc3339::serialize",
        deserialize_with = "serde_utils::timestamp::deserialize"
    )]
    pub time: OffsetDateTime,
}

/// Order charge fee
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OrderChargeFee {
    /// Charge code
    pub code: String,
    /// Charge name
    pub name: String,
    /// Charge amount
    #[serde(with = "serde_utils::decimal_empty_is_0")]
    pub amount: Decimal,
    /// Charge currency
    pub currency: String,
}

/// Order charge item
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OrderChargeItem {
    /// Charge category code
    pub code: ChargeCategoryCode,
    /// Charge category name
    pub name: String,
    /// Charge details
    pub fees: Vec<OrderChargeFee>,
}

/// Order charge detail
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OrderChargeDetail {
    /// Total charges amount
    pub total_amount: Decimal,
    /// Settlement currency
    pub currency: String,
    /// Order charge items
    pub items: Vec<OrderChargeItem>,
}

/// Order detail
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OrderDetail {
    /// Order ID
    pub order_id: String,
    /// Order status
    pub status: OrderStatus,
    /// Stock name
    pub stock_name: String,
    /// Submitted quantity
    pub quantity: Decimal,
    /// Executed quantity
    pub executed_quantity: Decimal,
    /// Submitted price
    #[serde(with = "serde_utils::decimal_opt_empty_is_none")]
    pub price: Option<Decimal>,
    /// Executed price
    #[serde(with = "serde_utils::decimal_opt_0_is_none")]
    pub executed_price: Option<Decimal>,
    /// Submitted time
    #[serde(
        serialize_with = "time::serde::rfc3339::serialize",
        deserialize_with = "serde_utils::timestamp::deserialize"
    )]
    pub submitted_at: OffsetDateTime,
    /// Order side
    pub side: OrderSide,
    /// Security code
    pub symbol: String,
    /// Order type
    pub order_type: OrderType,
    /// Last done
    #[serde(with = "serde_utils::decimal_opt_empty_is_none")]
    pub last_done: Option<Decimal>,
    /// `LIT` / `MIT` Order Trigger Price
    #[serde(with = "serde_utils::decimal_opt_empty_is_none")]
    pub trigger_price: Option<Decimal>,
    /// Rejected Message or remark
    pub msg: String,
    /// Order tag
    pub tag: OrderTag,
    /// Time in force type
    pub time_in_force: TimeInForceType,
    /// Long term order expire date
    #[serde(with = "serde_utils::date_opt")]
    pub expire_date: Option<Date>,
    /// Last updated time
    #[serde(
        deserialize_with = "serde_utils::timestamp_opt::deserialize",
        serialize_with = "serde_utils::rfc3339_opt::serialize"
    )]
    pub updated_at: Option<OffsetDateTime>,
    /// Conditional order trigger time
    #[serde(
        deserialize_with = "serde_utils::timestamp_opt::deserialize",
        serialize_with = "serde_utils::rfc3339_opt::serialize"
    )]
    pub trigger_at: Option<OffsetDateTime>,
    /// `TSMAMT` / `TSLPAMT` order trailing amount
    #[serde(with = "serde_utils::decimal_opt_empty_is_none")]
    pub trailing_amount: Option<Decimal>,
    /// `TSMPCT` / `TSLPPCT` order trailing percent
    #[serde(with = "serde_utils::decimal_opt_empty_is_none")]
    pub trailing_percent: Option<Decimal>,
    /// `TSLPAMT` / `TSLPPCT` order limit offset amount
    #[serde(with = "serde_utils::decimal_opt_empty_is_none")]
    pub limit_offset: Option<Decimal>,
    /// Conditional order trigger status
    #[serde(with = "serde_utils::trigger_status")]
    pub trigger_status: Option<TriggerStatus>,
    /// Currency
    pub currency: String,
    /// Enable or disable outside regular trading hours
    #[serde(with = "serde_utils::outside_rth")]
    pub outside_rth: Option<OutsideRTH>,
    /// Limit depth level
    #[serde(with = "serde_utils::int32_opt_0_is_none")]
    pub limit_depth_level: Option<i32>,
    /// Trigger count
    #[serde(with = "serde_utils::int32_opt_0_is_none")]
    pub trigger_count: Option<i32>,
    /// Monitor price
    #[serde(with = "serde_utils::decimal_opt_empty_is_none")]
    pub monitor_price: Option<Decimal>,
    /// Remark
    pub remark: String,
    /// Commission-free Status
    pub free_status: CommissionFreeStatus,
    /// Commission-free amount
    #[serde(with = "serde_utils::decimal_opt_empty_is_none")]
    pub free_amount: Option<Decimal>,
    /// Commission-free currency
    #[serde(with = "serde_utils::symbol_opt")]
    pub free_currency: Option<String>,
    /// Deduction status
    pub deductions_status: DeductionStatus,
    /// Deduction amount
    #[serde(with = "serde_utils::decimal_opt_empty_is_none")]
    pub deductions_amount: Option<Decimal>,
    /// Deduction currency
    #[serde(with = "serde_utils::symbol_opt")]
    pub deductions_currency: Option<String>,
    /// Platform fee deduction status
    pub platform_deducted_status: DeductionStatus,
    /// Platform deduction amount
    #[serde(with = "serde_utils::decimal_opt_empty_is_none")]
    pub platform_deducted_amount: Option<Decimal>,
    /// Platform deduction currency
    #[serde(with = "serde_utils::symbol_opt")]
    pub platform_deducted_currency: Option<String>,
    /// Order history details
    pub history: Vec<OrderHistoryDetail>,
    /// Order charges
    pub charge_detail: Option<OrderChargeDetail>,
    /// Attached orders
    #[serde(default)]
    pub attached_orders: Vec<AttachedOrderDetail>,
}

/// Cash info
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CashInfo {
    /// Withdraw cash
    pub withdraw_cash: Decimal,
    /// Available cash
    pub available_cash: Decimal,
    /// Frozen cash
    pub frozen_cash: Decimal,
    /// Cash to be settled
    pub settling_cash: Decimal,
    /// Currency
    pub currency: String,
}

/// Frozen transaction fee
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FrozenTransactionFee {
    /// Currency
    pub currency: String,
    /// Frozen transaction fee amount
    pub frozen_transaction_fee: Decimal,
}

/// Account balance
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AccountBalance {
    /// Total cash
    pub total_cash: Decimal,
    /// Maximum financing amount
    pub max_finance_amount: Decimal,
    /// Remaining financing amount
    pub remaining_finance_amount: Decimal,
    /// Risk control level
    #[serde(with = "serde_utils::risk_level")]
    pub risk_level: i32,
    /// Margin call
    pub margin_call: Decimal,
    /// Currency
    pub currency: String,
    /// Cash details
    #[serde(default)]
    pub cash_infos: Vec<CashInfo>,
    /// Net assets
    #[serde(with = "serde_utils::decimal_empty_is_0")]
    pub net_assets: Decimal,
    /// Initial margin
    #[serde(with = "serde_utils::decimal_empty_is_0")]
    pub init_margin: Decimal,
    /// Maintenance margin
    #[serde(with = "serde_utils::decimal_empty_is_0")]
    pub maintenance_margin: Decimal,
    /// Buy power
    #[serde(with = "serde_utils::decimal_empty_is_0")]
    pub buy_power: Decimal,
    /// Frozen transaction fees
    pub frozen_transaction_fees: Vec<FrozenTransactionFee>,
}

/// Balance type
#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, FromPrimitive, IntoPrimitive)]
#[repr(i32)]
pub enum BalanceType {
    /// Unknown
    #[num_enum(default)]
    Unknown = 0,
    /// Cash
    Cash = 1,
    /// Stock
    Stock = 2,
    /// Fund
    Fund = 3,
}

impl Serialize for BalanceType {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let value: i32 = (*self).into();
        value.serialize(serializer)
    }
}

impl<'de> Deserialize<'de> for BalanceType {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let value = i32::deserialize(deserializer)?;
        Ok(BalanceType::from(value))
    }
}

/// Cash flow direction
#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, FromPrimitive, Serialize)]
#[repr(i32)]
pub enum CashFlowDirection {
    /// Unknown
    #[num_enum(default)]
    Unknown,
    /// Out
    Out = 1,
    /// In
    In = 2,
}

impl<'de> Deserialize<'de> for CashFlowDirection {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let value = i32::deserialize(deserializer)?;
        Ok(CashFlowDirection::from(value))
    }
}

/// Cash flow
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CashFlow {
    /// Cash flow name
    pub transaction_flow_name: String,
    /// Outflow direction
    pub direction: CashFlowDirection,
    /// Balance type
    pub business_type: BalanceType,
    /// Cash amount
    pub balance: Decimal,
    /// Cash currency
    pub currency: String,
    /// Business time
    #[serde(
        serialize_with = "time::serde::rfc3339::serialize",
        deserialize_with = "serde_utils::timestamp::deserialize"
    )]
    pub business_time: OffsetDateTime,
    /// Associated Stock code information
    #[serde(with = "serde_utils::symbol_opt")]
    pub symbol: Option<String>,
    /// Cash flow description
    pub description: String,
}

/// Fund positions response
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FundPositionsResponse {
    /// Channels
    #[serde(rename = "list")]
    pub channels: Vec<FundPositionChannel>,
}

/// Fund position channel
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FundPositionChannel {
    /// Account type
    pub account_channel: String,

    /// Fund positions
    #[serde(default, rename = "fund_info")]
    pub positions: Vec<FundPosition>,
}

/// Fund position
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FundPosition {
    /// Fund ISIN code
    pub symbol: String,
    /// Current equity
    #[serde(with = "serde_utils::decimal_empty_is_0")]
    pub current_net_asset_value: Decimal,
    /// Current equity time
    #[serde(
        serialize_with = "time::serde::rfc3339::serialize",
        deserialize_with = "serde_utils::timestamp::deserialize"
    )]
    pub net_asset_value_day: OffsetDateTime,
    /// Fund name
    pub symbol_name: String,
    /// Currency
    pub currency: String,
    /// Net cost
    #[serde(with = "serde_utils::decimal_empty_is_0")]
    pub cost_net_asset_value: Decimal,
    /// Holding units
    #[serde(with = "serde_utils::decimal_empty_is_0")]
    pub holding_units: Decimal,
}

/// Stock positions response
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StockPositionsResponse {
    /// Channels
    #[serde(rename = "list")]
    pub channels: Vec<StockPositionChannel>,
}

/// Stock position channel
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StockPositionChannel {
    /// Account type
    pub account_channel: String,

    /// Stock positions
    #[serde(default, rename = "stock_info")]
    pub positions: Vec<StockPosition>,
}

/// Stock position
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StockPosition {
    /// Stock code
    pub symbol: String,
    /// Stock name
    pub symbol_name: String,
    /// The number of holdings
    pub quantity: Decimal,
    /// Available quantity
    pub available_quantity: Decimal,
    /// Currency
    pub currency: String,
    /// Cost Price(According to the client's choice of average purchase or
    /// diluted cost)
    #[serde(with = "serde_utils::decimal_empty_is_0")]
    pub cost_price: Decimal,
    /// Market
    pub market: Market,
    /// Initial position before market opening
    #[serde(with = "serde_utils::decimal_opt_empty_is_none")]
    pub init_quantity: Option<Decimal>,
}

/// Margin ratio
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MarginRatio {
    /// Initial margin ratio
    pub im_factor: Decimal,
    /// Maintain the initial margin ratio
    pub mm_factor: Decimal,
    /// Forced close-out margin ratio
    pub fm_factor: Decimal,
}

impl_serde_for_enum_string!(
    OrderType,
    OrderStatus,
    OrderSide,
    TriggerPriceType,
    OrderTag,
    TimeInForceType,
    TriggerStatus,
    OutsideRTH,
    CommissionFreeStatus,
    DeductionStatus,
    ChargeCategoryCode
);
impl_serde_for_enum_string!(AttachedOrderType);
impl_default_for_enum_string!(AttachedOrderType);
impl_default_for_enum_string!(
    OrderType,
    OrderStatus,
    OrderSide,
    TriggerPriceType,
    OrderTag,
    TimeInForceType,
    TriggerStatus,
    OutsideRTH,
    CommissionFreeStatus,
    DeductionStatus,
    ChargeCategoryCode
);

// ── US-market types
// ───────────────────────────────────────────────────────────

/// Request for [`crate::TradeContext::us_query_orders`], modelled after
/// [`crate::GetHistoryOrdersOptions`] for HK/CN orders.
///
/// `query_type`: 0 = all (includes Rejected), 1 = pending, 2 = history (filled
/// only). Default 0 matches what the app shows as "past orders".
///
/// `symbol` accepts a user-facing symbol e.g. `"AAPL.US"` or `"DOGEUSD.BKKT"`.
/// The SDK converts it to the internal `counter_id` format automatically.
#[derive(Debug, Clone, Default)]
pub struct GetUSHistoryOrders {
    /// Optional symbol filter, e.g. `"AAPL.US"`. Converted to counter_id
    /// internally.
    pub symbol: Option<String>,
    /// Direction filter. [`crate::OrderSide::Unknown`] = all (default).
    pub side: OrderSide,
    /// Start timestamp (seconds). Defaults to 90 days ago.
    pub start_at: i64,
    /// End timestamp (seconds). Defaults to now.
    pub end_at: i64,
    /// 0 = all, 1 = pending, 2 = history (filled only). Default 0.
    pub query_type: i32,
    /// Page number, 1-based. Default 1.
    pub page: i32,
    /// Page size. Default 20.
    pub limit: i32,
}

/// Alias kept for backward compatibility.
pub type QueryUSOrdersOptions = GetUSHistoryOrders;

/// Internal JSON body sent to POST /v1/us/orders/query.
#[derive(Debug, Clone, Serialize)]
pub(crate) struct USQueryOrdersBody {
    pub account_channel: String,
    pub action: i32,
    pub start_at: f64,
    pub end_at: f64,
    pub counter_ids: Vec<String>,
    pub security_types: Vec<String>,
    pub query_type: i32,
    pub page: i32,
    pub limit: i32,
    pub query_version: f64,
}

/// Response for [`crate::TradeContext::us_query_orders`].
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct QueryUSOrdersResponse {
    /// Order list (raw JSON for forward compatibility).
    /// Order ID field is `id` (not `order_id`).
    #[serde(default)]
    pub orders: Vec<serde_json::Value>,
    /// Total number of orders matching the query.
    #[serde(default)]
    pub total_count: i32,
}

/// One order state-transition entry within [`USOrderDetail`].
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct USOrderHistory {
    #[serde(default)]
    pub exec_type: i32,
    #[serde(default)]
    pub status: String,
    #[serde(default)]
    pub price: String,
    #[serde(default)]
    pub qty: String,
    #[serde(default)]
    pub time: String,
    #[serde(default)]
    pub msg: String,
    #[serde(default)]
    pub is_manually: bool,
    #[serde(default)]
    pub opp_party_id: String,
    #[serde(default)]
    pub trd_match_id: String,
    #[serde(default)]
    pub operator: String,
    #[serde(default)]
    pub op_entrust_way: String,
    #[serde(default)]
    pub cxl_rej_response_to: i32,
    #[serde(default)]
    pub withdrawal_reason: String,
    #[serde(default)]
    pub opp_name: String,
    #[serde(default)]
    pub exec_id: String,
}

/// Action-button state for an order.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct USButtonControl {
    #[serde(default)]
    pub withdraw: i32,
    #[serde(default)]
    pub replace: i32,
    #[serde(default)]
    pub exceptionable: Vec<String>,
}

/// One fee category within [`USChargeDetail`].
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct USChargeItem {
    #[serde(default)]
    pub code: i32,
    #[serde(default)]
    pub name: String,
    #[serde(default)]
    pub fees: Vec<String>,
}

/// Fee breakdown for an order.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct USChargeDetail {
    #[serde(default)]
    pub currency: String,
    #[serde(default)]
    pub total_amount: String,
    #[serde(default)]
    pub items: Vec<USChargeItem>,
}

/// One bracket/conditional sub-order attached to a main order.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct USAttachedOrder {
    #[serde(default)]
    pub attached_type_display: i32,
    #[serde(default)]
    pub executed_qty: String,
    #[serde(default)]
    pub quantity: String,
    #[serde(default)]
    pub status: String,
    #[serde(default)]
    pub trigger_price: String,
    #[serde(default)]
    pub order_id: String,
    #[serde(default)]
    pub gtd: String,
    #[serde(default)]
    pub time_in_force: i32,
    #[serde(default)]
    pub tag: i32,
    #[serde(default)]
    pub activate_order_type: String,
    #[serde(default)]
    pub activate_rth: i32,
    #[serde(default)]
    pub submit_price: String,
    /// User-facing trading symbol (e.g. `"NKE.US"`), converted from
    /// `counter_id`.
    #[serde(
        default,
        rename = "counter_id",
        deserialize_with = "crate::utils::counter::deserialize_counter_id_as_symbol"
    )]
    pub symbol: String,
    #[serde(default)]
    pub withdrawn: bool,
}

/// Full typed order object within [`USOrderDetailResponse`].
/// `submitted_at` and `done_at` are raw unix-second strings.
/// `order_histories` is nested inside this object, not at the response top
/// level.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct USOrderDetail {
    #[serde(default)]
    pub id: String,
    #[serde(default)]
    pub aaid: String,
    #[serde(default)]
    pub account_channel: String,
    #[serde(default)]
    pub action: i32,
    /// User-facing trading symbol (e.g. `"NKE.US"`), converted from
    /// `counter_id`.
    #[serde(
        default,
        rename = "counter_id",
        deserialize_with = "crate::utils::counter::deserialize_counter_id_as_symbol"
    )]
    pub symbol: String,
    /// User-facing underlying symbol (options only), converted from
    /// `underlying_counter_id`.
    #[serde(
        default,
        rename = "underlying_counter_id",
        deserialize_with = "crate::utils::counter::deserialize_counter_id_as_symbol"
    )]
    pub underlying_symbol: String,
    #[serde(default)]
    pub security_type: String,
    #[serde(default)]
    pub name: String,
    #[serde(default)]
    pub currency: String,
    #[serde(default)]
    pub trade_currency: String,
    #[serde(default)]
    pub order_type: String,
    #[serde(default)]
    pub status: String,
    #[serde(default)]
    pub price: String,
    #[serde(default)]
    pub quantity: String,
    #[serde(default)]
    pub executed_qty: String,
    #[serde(default)]
    pub executed_price: String,
    #[serde(default)]
    pub executed_amount: String,
    #[serde(default)]
    pub operate_direction: String,
    #[serde(default)]
    pub time_in_force: i32,
    #[serde(default)]
    pub gtd: String,
    #[serde(default)]
    pub tag: i32,
    #[serde(default)]
    pub msg: String,
    #[serde(default)]
    pub force_only_rth: i32,
    #[serde(default)]
    pub submitted_at: String,
    #[serde(default)]
    pub done_at: String,
    #[serde(default)]
    pub trigger_price: String,
    #[serde(default)]
    pub trigger_at: String,
    #[serde(default)]
    pub trigger_status: i32,
    #[serde(default)]
    pub trigger_exchange: String,
    #[serde(default)]
    pub trigger_last_done: String,
    #[serde(default)]
    pub trigger_count: i32,
    #[serde(default)]
    pub tailing_amount: String,
    #[serde(default)]
    pub tailing_percent: String,
    #[serde(default)]
    pub limit_offset: String,
    #[serde(default)]
    pub limit_depth_level: i32,
    #[serde(default)]
    pub market_price: String,
    #[serde(default)]
    pub submitted_amount: String,
    #[serde(default)]
    pub estimated_fee: String,
    #[serde(default)]
    pub free_status: i32,
    #[serde(default)]
    pub free_amount: String,
    #[serde(default)]
    pub free_currency: String,
    #[serde(default)]
    pub deductions_status: i32,
    #[serde(default)]
    pub deductions_amount: String,
    #[serde(default)]
    pub deductions_currency: String,
    #[serde(default)]
    pub platform_deductions_status: i32,
    #[serde(default)]
    pub platform_deductions_amount: String,
    #[serde(default)]
    pub platform_deductions_currency: String,
    #[serde(default)]
    pub display_account: String,
    #[serde(default)]
    pub settlement_account: String,
    #[serde(default)]
    pub settlement_channel: String,
    #[serde(default)]
    pub customer_name: String,
    #[serde(default)]
    pub real_name: String,
    #[serde(default)]
    pub en_name: String,
    #[serde(default)]
    pub joint_real_name: String,
    #[serde(default)]
    pub joint_en_name: String,
    #[serde(default)]
    pub org_id: String,
    #[serde(default)]
    pub bcan: String,
    #[serde(default)]
    pub op_entrust_way: i32,
    #[serde(default)]
    pub op_entrust_way_name: String,
    #[serde(default)]
    pub remark: String,
    #[serde(default)]
    pub notice: String,
    #[serde(default)]
    pub short_sell_type: i32,
    #[serde(default)]
    pub ploy_type: String,
    #[serde(default)]
    pub ploy_id: String,
    #[serde(default)]
    pub ploy_status: String,
    #[serde(default)]
    pub trend: i32,
    #[serde(default)]
    pub withdrawal_reason: String,
    #[serde(default)]
    pub activate_order_type: String,
    #[serde(default)]
    pub activate_rth: i32,
    #[serde(default)]
    pub submit_price: String,
    #[serde(default)]
    pub contract_direction: String,
    #[serde(default)]
    pub strike_price: String,
    #[serde(default)]
    pub contract_size: String,
    #[serde(default)]
    pub monitor_price: String,
    #[serde(default)]
    pub button_control: USButtonControl,
    pub charge_detail: Option<USChargeDetail>,
    #[serde(default)]
    pub attached_orders: Vec<USAttachedOrder>,
    #[serde(default)]
    pub order_histories: Vec<USOrderHistory>,
}

/// Response for [`crate::TradeContext::us_order_detail`].
/// Path: `GET /v1/us/orders/{order_id}`
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct USOrderDetailResponse {
    /// Full typed order object; None only on error.
    pub order: Option<USOrderDetail>,
    /// Active bracket/conditional sub-order, or None.
    pub current_attached_order: Option<USOrderDetail>,
    /// Server response timestamp (milliseconds string).
    #[serde(default)]
    pub current_millisecond: String,
}

/// One cash currency entry in [`USAssetOverview`].
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct USCashEntry {
    #[serde(default)]
    pub currency: String,
    #[serde(default)]
    pub frozen_buy_cash: String,
    #[serde(default)]
    pub outstanding: String,
    #[serde(default)]
    pub settled_cash: String,
    #[serde(default)]
    pub total_amount: String,
    #[serde(default)]
    pub total_cash: String,
}

/// One cryptocurrency holding in [`USAssetOverview`].
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct USCryptoEntry {
    #[serde(default)]
    pub asset_type: String,
    #[serde(default)]
    pub average_cost: String,
    /// User-facing trading-pair symbol (e.g. `"BTCUSD.BKKT"`), converted from
    /// the API's `counter_id` field (e.g. `"VA/BKKT/BTCUSD"`).
    #[serde(
        default,
        rename = "counter_id",
        deserialize_with = "crate::utils::counter::deserialize_counter_id_as_symbol"
    )]
    pub symbol: String,
    #[serde(default)]
    pub currency: String,
    #[serde(default)]
    pub industry_name: String,
}

/// One stock/equity position in [`USAssetOverview`].
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct USStockEntry {
    /// Ticker code returned by the API (e.g. `"AAPL"`). See `full_symbol` for
    /// the qualified form.
    #[serde(default)]
    pub symbol: String,
    /// Qualified user-facing symbol (e.g. `"AAPL.US"`), converted from
    /// `counter_id`.
    #[serde(
        default,
        rename = "counter_id",
        deserialize_with = "crate::utils::counter::deserialize_counter_id_as_symbol"
    )]
    pub full_symbol: String,
    #[serde(default)]
    pub asset_type: String,
    #[serde(default)]
    pub quantity: String,
    #[serde(default)]
    pub currency: String,
    #[serde(default)]
    pub average_cost: String,
    #[serde(default)]
    pub market: String,
    #[serde(default)]
    pub trade_status: String,
    #[serde(default)]
    pub prev_close: String,
    #[serde(default)]
    pub last_done: String,
    #[serde(default)]
    pub market_price: String,
    #[serde(default)]
    pub pretrade_close: String,
    #[serde(default)]
    pub stock_invest_of_today: String,
    #[serde(default)]
    pub today_pl: String,
    #[serde(default)]
    pub pretrade_stock_invest_of_today: String,
    #[serde(default)]
    pub pretrade_today_pl: String,
    #[serde(default)]
    pub night_last_done: String,
    #[serde(default)]
    pub night_prev_close: String,
    #[serde(default)]
    pub position_side: String,
    #[serde(default)]
    pub open_position_time: String,
    #[serde(default)]
    pub name: String,
    #[serde(default)]
    pub industry_counter_id: String,
    #[serde(default)]
    pub industry_name: String,
}

/// Response for [`crate::TradeContext::us_asset_overview`].
/// Field names match the actual API response from `GET /v1/us/assets/overview`.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct USAssetOverview {
    #[serde(default)]
    pub account_type: String,
    /// Account snapshot timestamp (Unix-second string → OffsetDateTime).
    #[serde(default, with = "crate::serde_utils::timestamp_opt")]
    pub asset_timestamp: Option<time::OffsetDateTime>,
    /// Cash buying power (top-level convenience field).
    #[serde(default)]
    pub cash_buy_power: String,
    #[serde(default)]
    pub overnight_buy_power: String,
    #[serde(default)]
    pub currency: String,
    #[serde(default)]
    pub cash_list: Vec<USCashEntry>,
    #[serde(default)]
    pub stock_list: Vec<USStockEntry>,
    #[serde(default)]
    pub option_list: Vec<serde_json::Value>,
    #[serde(default)]
    pub crypto_list: Vec<USCryptoEntry>,
    #[serde(default)]
    pub multi_leg: serde_json::Value,
}

/// One time-period metric in a [`USRealizedPLEntry`].
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct USRealizedPLMetric {
    #[serde(default)]
    pub amount: String,
    /// Period code (server-defined; 2 = current month observed in testing).
    #[serde(default)]
    pub period: i32,
    #[serde(default)]
    pub rate: String,
}

/// One asset-category entry in [`USRealizedPL`].
/// `category`: 0 = all, 1 = stock, 2 = option, 3 = crypto (server-defined).
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct USRealizedPLEntry {
    #[serde(default)]
    pub category: i32,
    #[serde(default)]
    pub currency: String,
    #[serde(default)]
    pub metrics: Vec<USRealizedPLMetric>,
}

/// Request for [`crate::TradeContext::us_realized_pl`], modelled after
/// [`crate::GetUSHistoryOrders`].
#[derive(Debug, Clone, Default)]
pub struct GetUSRealizedPLOptions {
    /// Currency, e.g. `"USD"`. Defaults to `"USD"` if empty.
    pub currency: String,
    /// Asset category filter: `""` = all, `"STOCK"`, `"OPTION"`, `"CRYPTO"`.
    pub category: String,
}

/// Response for [`crate::TradeContext::us_realized_pl`].
/// Field name matches the actual API response from `GET
/// /v1/us/assets/pl/realized`.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct USRealizedPL {
    #[serde(default)]
    pub realized_pl_list: Vec<USRealizedPLEntry>,
}

#[cfg(test)]
mod tests {
    use time::macros::datetime;

    use super::*;

    #[test]
    fn fund_position_response() {
        let data = r#"
        {
            "list": [{
                "account_channel": "lb",
                "fund_info": [{
                    "symbol": "HK0000447943",
                    "symbol_name": "高腾亚洲收益基金",
                    "currency": "USD",
                    "holding_units": "5.000",
                    "current_net_asset_value": "0",
                    "cost_net_asset_value": "0.00",
                    "net_asset_value_day": "1649865600"
                }]
            }]
        }
        "#;

        let resp: FundPositionsResponse = serde_json::from_str(data).unwrap();
        assert_eq!(resp.channels.len(), 1);

        let channel = &resp.channels[0];
        assert_eq!(channel.account_channel, "lb");
        assert_eq!(channel.positions.len(), 1);

        let position = &channel.positions[0];
        assert_eq!(position.symbol, "HK0000447943");
        assert_eq!(position.symbol_name, "高腾亚洲收益基金");
        assert_eq!(position.currency, "USD");
        assert_eq!(position.current_net_asset_value, decimal!(0i32));
        assert_eq!(position.cost_net_asset_value, decimal!(0i32));
        assert_eq!(position.holding_units, decimal!(5i32));
        assert_eq!(position.net_asset_value_day, datetime!(2022-4-14 0:00 +8));
    }

    #[test]
    fn stock_position_response() {
        let data = r#"
        {
            "list": [
              {
                "account_channel": "lb",
                "stock_info": [
                  {
                    "symbol": "700.HK",
                    "symbol_name": "腾讯控股",
                    "currency": "HK",
                    "quantity": "650",
                    "available_quantity": "-450",
                    "cost_price": "457.53",
                    "market": "HK",
                    "init_quantity": "2000"
                  },
                  {
                    "symbol": "9991.HK",
                    "symbol_name": "宝尊电商-SW",
                    "currency": "HK",
                    "quantity": "200",
                    "available_quantity": "0",
                    "cost_price": "32.25",
                    "market": "HK",
                    "init_quantity": ""
                  }
                ]
              }
            ]
          }
        "#;

        let resp: StockPositionsResponse = serde_json::from_str(data).unwrap();
        assert_eq!(resp.channels.len(), 1);

        let channel = &resp.channels[0];
        assert_eq!(channel.account_channel, "lb");
        assert_eq!(channel.positions.len(), 2);

        let position = &channel.positions[0];
        assert_eq!(position.symbol, "700.HK");
        assert_eq!(position.symbol_name, "腾讯控股");
        assert_eq!(position.currency, "HK");
        assert_eq!(position.quantity, decimal!(650));
        assert_eq!(position.available_quantity, decimal!(-450));
        assert_eq!(position.cost_price, decimal!(457.53f32));
        assert_eq!(position.market, Market::HK);
        assert_eq!(position.init_quantity, Some(decimal!(2000)));

        let position = &channel.positions[0];
        assert_eq!(position.symbol, "700.HK");
        assert_eq!(position.symbol_name, "腾讯控股");
        assert_eq!(position.currency, "HK");
        assert_eq!(position.quantity, decimal!(650));
        assert_eq!(position.available_quantity, decimal!(-450));
        assert_eq!(position.cost_price, decimal!(457.53f32));
        assert_eq!(position.market, Market::HK);

        let position = &channel.positions[1];
        assert_eq!(position.symbol, "9991.HK");
        assert_eq!(position.symbol_name, "宝尊电商-SW");
        assert_eq!(position.currency, "HK");
        assert_eq!(position.quantity, decimal!(200));
        assert_eq!(position.available_quantity, decimal!(0));
        assert_eq!(position.cost_price, decimal!(32.25f32));
        assert_eq!(position.init_quantity, None);
    }

    #[test]
    fn cash_flow() {
        let data = r#"
        {
            "list": [
              {
                "transaction_flow_name": "BuyContract-Stocks",
                "direction": 1,
                "balance": "-248.60",
                "currency": "USD",
                "business_type": 1,
                "business_time": "1621507957",
                "symbol": "AAPL.US",
                "description": "AAPL"
              },
              {
                "transaction_flow_name": "BuyContract-Stocks",
                "direction": 1,
                "balance": "-125.16",
                "currency": "USD",
                "business_type": 2,
                "business_time": "1621504824",
                "symbol": "AAPL.US",
                "description": "AAPL"
              }
            ]
          }
          "#;

        #[derive(Debug, Deserialize)]
        struct Response {
            list: Vec<CashFlow>,
        }

        let resp: Response = serde_json::from_str(data).unwrap();
        assert_eq!(resp.list.len(), 2);

        let cashflow = &resp.list[0];
        assert_eq!(cashflow.transaction_flow_name, "BuyContract-Stocks");
        assert_eq!(cashflow.direction, CashFlowDirection::Out);
        assert_eq!(cashflow.balance, decimal!(-248.60f32));
        assert_eq!(cashflow.currency, "USD");
        assert_eq!(cashflow.business_type, BalanceType::Cash);
        assert_eq!(cashflow.business_time, datetime!(2021-05-20 18:52:37 +8));
        assert_eq!(cashflow.symbol.as_deref(), Some("AAPL.US"));
        assert_eq!(cashflow.description, "AAPL");

        let cashflow = &resp.list[1];
        assert_eq!(cashflow.transaction_flow_name, "BuyContract-Stocks");
        assert_eq!(cashflow.direction, CashFlowDirection::Out);
        assert_eq!(cashflow.balance, decimal!(-125.16f32));
        assert_eq!(cashflow.currency, "USD");
        assert_eq!(cashflow.business_type, BalanceType::Stock);
        assert_eq!(cashflow.business_time, datetime!(2021-05-20 18:00:24 +8));
        assert_eq!(cashflow.symbol.as_deref(), Some("AAPL.US"));
        assert_eq!(cashflow.description, "AAPL");
    }

    #[test]
    fn account_balance() {
        let data = r#"
        {
            "list": [
              {
                "total_cash": "1759070010.72",
                "max_finance_amount": "977582000",
                "remaining_finance_amount": "0",
                "risk_level": "1",
                "margin_call": "2598051051.50",
                "currency": "HKD",
                "cash_infos": [
                  {
                    "withdraw_cash": "97592.30",
                    "available_cash": "195902464.37",
                    "frozen_cash": "11579339.13",
                    "settling_cash": "207288537.81",
                    "currency": "HKD"
                  },
                  {
                    "withdraw_cash": "199893416.74",
                    "available_cash": "199893416.74",
                    "frozen_cash": "28723.76",
                    "settling_cash": "-276806.51",
                    "currency": "USD"
                  }
                ],
                "net_assets": "11111.12",
                "init_margin": "2222.23",
                "maintenance_margin": "3333.45",
                "buy_power": "1234.67",
                "frozen_transaction_fees": [
                    {
                        "currency": "HKD",
                        "frozen_transaction_fee": "123"
                    }
                ]
              }
            ]
          }"#;

        #[derive(Debug, Deserialize)]
        struct Response {
            list: Vec<AccountBalance>,
        }

        let resp: Response = serde_json::from_str(data).unwrap();
        assert_eq!(resp.list.len(), 1);

        let balance = &resp.list[0];
        assert_eq!(balance.total_cash, "1759070010.72".parse().unwrap());
        assert_eq!(balance.max_finance_amount, "977582000".parse().unwrap());
        assert_eq!(balance.remaining_finance_amount, decimal!(0i32));
        assert_eq!(balance.risk_level, 1);
        assert_eq!(balance.margin_call, "2598051051.50".parse().unwrap());
        assert_eq!(balance.currency, "HKD");
        assert_eq!(balance.net_assets, "11111.12".parse().unwrap());
        assert_eq!(balance.init_margin, "2222.23".parse().unwrap());
        assert_eq!(balance.maintenance_margin, "3333.45".parse().unwrap());
        assert_eq!(balance.buy_power, "1234.67".parse().unwrap());

        assert_eq!(balance.cash_infos.len(), 2);

        let cash_info = &balance.cash_infos[0];
        assert_eq!(cash_info.withdraw_cash, "97592.30".parse().unwrap());
        assert_eq!(cash_info.available_cash, "195902464.37".parse().unwrap());
        assert_eq!(cash_info.frozen_cash, "11579339.13".parse().unwrap());
        assert_eq!(cash_info.settling_cash, "207288537.81".parse().unwrap());
        assert_eq!(cash_info.currency, "HKD");

        let cash_info = &balance.cash_infos[1];
        assert_eq!(cash_info.withdraw_cash, "199893416.74".parse().unwrap());
        assert_eq!(cash_info.available_cash, "199893416.74".parse().unwrap());
        assert_eq!(cash_info.frozen_cash, "28723.76".parse().unwrap());
        assert_eq!(cash_info.settling_cash, "-276806.51".parse().unwrap());
        assert_eq!(cash_info.currency, "USD");

        assert_eq!(balance.frozen_transaction_fees.len(), 1);

        let frozen_transaction_fee = &balance.frozen_transaction_fees[0];
        assert_eq!(frozen_transaction_fee.currency, "HKD");
        assert_eq!(
            frozen_transaction_fee.frozen_transaction_fee,
            "123".parse().unwrap()
        );
    }

    #[test]
    fn history_orders() {
        let data = r#"
        {
            "orders": [
              {
                "currency": "HKD",
                "executed_price": "0.000",
                "executed_quantity": "0",
                "expire_date": "",
                "last_done": "",
                "limit_offset": "",
                "msg": "",
                "order_id": "706388312699592704",
                "order_type": "ELO",
                "outside_rth": "UnknownOutsideRth",
                "price": "11.900",
                "quantity": "200",
                "side": "Buy",
                "status": "RejectedStatus",
                "stock_name": "Bank of East Asia Ltd/The",
                "submitted_at": "1651644897",
                "symbol": "23.HK",
                "tag": "Normal",
                "time_in_force": "Day",
                "trailing_amount": "",
                "trailing_percent": "",
                "trigger_at": "0",
                "trigger_price": "",
                "trigger_status": "NOT_USED",
                "updated_at": "1651644898",
                "limit_depth_level": 0,
                "trigger_count": 0,
                "monitor_price": "",
                "remark": "abc"
              }
            ]
          }
        "#;

        #[derive(Deserialize)]
        struct Response {
            orders: Vec<Order>,
        }

        let resp: Response = serde_json::from_str(data).unwrap();
        assert_eq!(resp.orders.len(), 1);

        let order = &resp.orders[0];
        assert_eq!(order.currency, "HKD");
        assert!(order.executed_price.is_none());
        assert_eq!(order.executed_quantity, decimal!(0));
        assert!(order.expire_date.is_none());
        assert!(order.last_done.is_none());
        assert!(order.limit_offset.is_none());
        assert_eq!(order.msg, "");
        assert_eq!(order.order_id, "706388312699592704");
        assert_eq!(order.order_type, OrderType::ELO);
        assert!(order.outside_rth.is_none());
        assert_eq!(order.price, Some("11.900".parse().unwrap()));
        assert_eq!(order.quantity, decimal!(200));
        assert_eq!(order.side, OrderSide::Buy);
        assert_eq!(order.status, OrderStatus::Rejected);
        assert_eq!(order.stock_name, "Bank of East Asia Ltd/The");
        assert_eq!(order.submitted_at, datetime!(2022-05-04 14:14:57 +8));
        assert_eq!(order.symbol, "23.HK");
        assert_eq!(order.tag, OrderTag::Normal);
        assert_eq!(order.time_in_force, TimeInForceType::Day);
        assert!(order.trailing_amount.is_none());
        assert!(order.trailing_percent.is_none());
        assert!(order.trigger_at.is_none());
        assert!(order.trigger_price.is_none());
        assert!(order.trigger_status.is_none());
        assert_eq!(order.updated_at, Some(datetime!(2022-05-04 14:14:58 +8)));
        assert_eq!(order.remark, "abc");
    }

    #[test]
    fn today_orders() {
        let data = r#"
        {
            "orders": [
              {
                "currency": "HKD",
                "executed_price": "0.000",
                "executed_quantity": "0",
                "expire_date": "",
                "last_done": "",
                "limit_offset": "",
                "msg": "",
                "order_id": "706388312699592704",
                "order_type": "ELO",
                "outside_rth": "UnknownOutsideRth",
                "price": "11.900",
                "quantity": "200",
                "side": "Buy",
                "status": "RejectedStatus",
                "stock_name": "Bank of East Asia Ltd/The",
                "submitted_at": "1651644897",
                "symbol": "23.HK",
                "tag": "Normal",
                "time_in_force": "Day",
                "trailing_amount": "",
                "trailing_percent": "",
                "trigger_at": "0",
                "trigger_price": "",
                "trigger_status": "NOT_USED",
                "updated_at": "1651644898",
                "limit_depth_level": 0,
                "trigger_count": 0,
                "monitor_price": "",
                "remark": "abc"
              }
            ]
          }
        "#;

        #[derive(Deserialize)]
        struct Response {
            orders: Vec<Order>,
        }

        let resp: Response = serde_json::from_str(data).unwrap();
        assert_eq!(resp.orders.len(), 1);

        let order = &resp.orders[0];
        assert_eq!(order.currency, "HKD");
        assert!(order.executed_price.is_none());
        assert_eq!(order.executed_quantity, decimal!(0));
        assert!(order.expire_date.is_none());
        assert!(order.last_done.is_none());
        assert!(order.limit_offset.is_none());
        assert_eq!(order.msg, "");
        assert_eq!(order.order_id, "706388312699592704");
        assert_eq!(order.order_type, OrderType::ELO);
        assert!(order.outside_rth.is_none());
        assert_eq!(order.price, Some("11.900".parse().unwrap()));
        assert_eq!(order.quantity, decimal!(200));
        assert_eq!(order.side, OrderSide::Buy);
        assert_eq!(order.status, OrderStatus::Rejected);
        assert_eq!(order.stock_name, "Bank of East Asia Ltd/The");
        assert_eq!(order.submitted_at, datetime!(2022-05-04 14:14:57 +8));
        assert_eq!(order.symbol, "23.HK");
        assert_eq!(order.tag, OrderTag::Normal);
        assert_eq!(order.time_in_force, TimeInForceType::Day);
        assert!(order.trailing_amount.is_none());
        assert!(order.trailing_percent.is_none());
        assert!(order.trigger_at.is_none());
        assert!(order.trigger_price.is_none());
        assert!(order.trigger_status.is_none());
        assert_eq!(order.updated_at, Some(datetime!(2022-05-04 14:14:58 +8)));
        assert_eq!(order.remark, "abc");
    }

    #[test]
    fn history_executions() {
        let data = r#"
        {
            "has_more": false,
            "trades": [
              {
                "order_id": "693664675163312128",
                "price": "388",
                "quantity": "100",
                "symbol": "700.HK",
                "trade_done_at": "1648611351",
                "trade_id": "693664675163312128-1648611351433741210"
              }
            ]
          }
        "#;

        #[derive(Deserialize)]
        struct Response {
            trades: Vec<Execution>,
        }

        let resp: Response = serde_json::from_str(data).unwrap();
        assert_eq!(resp.trades.len(), 1);

        let execution = &resp.trades[0];
        assert_eq!(execution.order_id, "693664675163312128");
        assert_eq!(execution.price, "388".parse().unwrap());
        assert_eq!(execution.quantity, decimal!(100));
        assert_eq!(execution.symbol, "700.HK");
        assert_eq!(execution.trade_done_at, datetime!(2022-03-30 11:35:51 +8));
        assert_eq!(execution.trade_id, "693664675163312128-1648611351433741210");
    }

    #[test]
    fn order_detail() {
        let data = r#"
        {
            "order_id": "828940451093708800",
            "status": "FilledStatus",
            "stock_name": "Apple",
            "quantity": "10",
            "executed_quantity": "10",
            "price": "200.000",
            "executed_price": "164.660",
            "submitted_at": "1680863604",
            "side": "Buy",
            "symbol": "AAPL.US",
            "order_type": "LO",
            "last_done": "164.660",
            "trigger_price": "0.0000",
            "msg": "",
            "tag": "Normal",
            "time_in_force": "Day",
            "expire_date": "2023-04-10",
            "updated_at": "1681113000",
            "trigger_at": "0",
            "trailing_amount": "",
            "trailing_percent": "",
            "limit_offset": "",
            "trigger_status": "NOT_USED",
            "outside_rth": "ANY_TIME",
            "currency": "USD",
            "limit_depth_level": 0,
            "trigger_count": 0,
            "monitor_price": "",
            "remark": "1680863603.927165",
            "free_status": "None",
            "free_amount": "",
            "free_currency": "",
            "deductions_status": "NONE",
            "deductions_amount": "",
            "deductions_currency": "",
            "platform_deducted_status": "NONE",
            "platform_deducted_amount": "",
            "platform_deducted_currency": "",
            "history": [{
                "price": "164.6600",
                "quantity": "10",
                "status": "FilledStatus",
                "msg": "Execution of 10",
                "time": "1681113000"
            }, {
                "price": "200.0000",
                "quantity": "10",
                "status": "NewStatus",
                "msg": "",
                "time": "1681113000"
            }],
            "charge_detail": {
                "items": [{
                    "code": "BROKER_FEES",
                    "name": "Broker Fees",
                    "fees": []
                }, {
                    "code": "THIRD_FEES",
                    "name": "Third-party Fees",
                    "fees": []
                }],
                "total_amount": "0",
                "currency": "USD"
            }
        }
        "#;

        _ = serde_json::from_str::<OrderDetail>(data).unwrap();
    }
}