rustrade-execution 0.17.0

Stream private account data from financial venues, and execute (live or mock) orders.
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
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
use crate::order::{
    Order as RustradeOrder, OrderKind, TimeInForce, TrailingOffsetType,
    id::{ClientOrderId, StrategyId},
    state::UnindexedOrderState,
};
use fnv::{FnvHashMap, FnvHashSet};
use ibapi::orders::{
    Action, OcaType, Order, TimeInForce as IbTimeInForce, builder::BracketPrices, order_builder,
};
use parking_lot::{Mutex, RwLock};
use rust_decimal::Decimal;
use rustrade_instrument::{Side, exchange::ExchangeId, instrument::name::InstrumentNameExchange};
use std::{sync::Arc, time::Instant};
use thiserror::Error;

// ============================================================================
// Bracket Order Types
// ============================================================================

/// Request to place a bracket order (entry + take-profit + stop-loss).
///
/// A bracket order consists of three linked orders:
/// 1. **Entry**: Limit order to enter the position
/// 2. **Take Profit**: Limit order to exit at profit target
/// 3. **Stop Loss**: Stop order to exit at loss limit
///
/// The entry order is submitted with `transmit=false`, holding all orders until
/// the stop-loss (with `transmit=true`) triggers atomic submission of all three.
///
/// Take-profit and stop-loss are linked via OCA (One-Cancels-All) group, so when
/// one fills, IB automatically cancels the other.
#[derive(Debug, Clone)]
pub struct BracketOrderRequest {
    /// Instrument to trade.
    pub instrument: InstrumentNameExchange,
    /// Strategy identifier for order correlation.
    pub strategy: StrategyId,
    /// Client order ID for the parent (entry) order.
    /// Child orders will have IDs derived from this (parent_cid + "_tp", parent_cid + "_sl").
    pub parent_cid: ClientOrderId,
    /// Buy or Sell for the entry order (exits use opposite side).
    pub side: Side,
    /// Number of shares/contracts.
    pub quantity: Decimal,
    /// Entry limit price.
    pub entry_price: Decimal,
    /// Take profit limit price.
    pub take_profit_price: Decimal,
    /// Stop loss trigger price.
    pub stop_loss_price: Decimal,
    /// Time-in-force for all three orders.
    pub time_in_force: TimeInForce,
}

/// Result of placing a bracket order.
///
/// Contains the three orders with their states. Use the `ClientOrderId` from each
/// order's key to cancel individual legs or correlate stream events.
///
/// # Invariant
///
/// Either all three orders are `Active(Open)` or all three are `Inactive`, except
/// that a leg of a failed placement whose fate at TWS is unknown is `Active(Open)`.
/// See [`IbkrClient::open_bracket_order`](super::IbkrClient::open_bracket_order).
#[derive(Debug, Clone)]
pub struct BracketOrderResult {
    /// Parent (entry) order.
    pub parent: RustradeOrder<ExchangeId, InstrumentNameExchange, UnindexedOrderState>,
    /// Take profit order (opposite side, limit).
    pub take_profit: RustradeOrder<ExchangeId, InstrumentNameExchange, UnindexedOrderState>,
    /// Stop loss order (opposite side, stop).
    pub stop_loss: RustradeOrder<ExchangeId, InstrumentNameExchange, UnindexedOrderState>,
}

// ============================================================================
// Order Context
// ============================================================================

/// Order context stored when placing orders.
///
/// IB's `OrderStatus` callback doesn't include instrument/side/price/kind,
/// so we store this context at order placement time to reconstruct full
/// `Order` structs from status updates.
///
/// # Invariant
///
/// This data is immutable after order placement. IB doesn't support in-flight
/// order modification — amendments are cancel+replace (new order ID, new entry).
#[derive(Debug, Clone)]
pub struct OrderContext {
    pub instrument: InstrumentNameExchange,
    pub side: Side,
    /// Limit price. `None` for Market/Stop/TrailingStop orders.
    pub price: Option<Decimal>,
    pub quantity: Decimal,
    pub kind: OrderKind,
    pub time_in_force: TimeInForce,
}

/// Bidirectional mapping between rustrade ClientOrderId and IB order IDs.
///
/// IB uses `i32` order IDs from a sequence. Barter uses `ClientOrderId` (SmolStr).
/// This map maintains the bidirectional relationship and stores order context
/// for reconstructing full `Order` structs from `OrderStatus` callbacks.
///
/// # A client order id names one live order at a time
///
/// TWS receives a [`ClientOrderId`] only as the order's reference ([`order_ref`]), whose uniqueness
/// it does not check, so this map is the only place it can be kept.
/// An id is held from [`register`](Self::register) until its order ends, and registering an id
/// already held is refused with [`ClientOrderIdInUse`]. Once its order has ended the id may name a
/// new order.
///
/// An order ends here when the account stream reports it `Filled`, `Cancelled` or `Inactive`, or
/// when [`clear_stale`](Self::clear_stale) reaps it. A `Filled` order releases its id
/// ([`release_client_id`](Self::release_client_id)) but keeps its IB-id entry, so the executions
/// and commissions IB may still send for it resolve to the id it was placed under. That entry is
/// reaped by `clear_stale`.
///
/// Every removal is conditional on the id still naming the order removed, so an earlier order
/// under a reused id cannot take the mapping of the order now under it. Its late executions and
/// commissions still resolve to the id, carrying its own IB order ID, while a status IB re-sends
/// for it is dropped by the account stream ([`names_other_order`](Self::names_other_order)).
#[derive(Debug, Clone)]
pub struct OrderIdMap {
    inner: Arc<RwLock<OrderIdMapInner>>,
}

/// When and how an order came to be tracked by an [`OrderIdMap`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Registration {
    /// How long ago it was registered or adopted.
    pub(crate) age: std::time::Duration,
    /// Whether it was adopted from a listing rather than placed through this client.
    pub(crate) adopted: bool,
}

/// Why [`OrderIdMap::adopt`] refused to track a listed order.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
pub(crate) enum AdoptionRefused {
    #[error("its client order id names another live order")]
    ClientOrderIdInUse,
    #[error("its IB order id names another tracked order")]
    IbOrderIdTracked,
}

/// [`OrderIdMap::register`] refused an id because a live order already holds it.
#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[error("client order id {0} already names a live IBKR order")]
pub struct ClientOrderIdInUse(pub ClientOrderId);

#[derive(Debug, Default)]
struct OrderIdMapInner {
    /// The live orders: each id held by an order that has not ended.
    cid_to_ib: FnvHashMap<ClientOrderId, i32>,
    /// Merged map: IB order ID → (ClientOrderId, OrderContext, registration time) for single-lookup on hot path.
    /// The Instant tracks when the order was registered, enabling age-based cleanup.
    ///
    /// Holds the live orders and the filled ones not yet reaped, which no longer hold their id.
    ib_to_entry: FnvHashMap<i32, (ClientOrderId, OrderContext, Instant)>,
    /// The IB order ids of the entries adopted from a listing ([`OrderIdMap::adopt`]) rather than
    /// placed through this client, whose registration time says nothing of when they were placed.
    adopted: FnvHashSet<i32>,
}

impl OrderIdMapInner {
    /// Removes `ib_id`'s entry, and its id's mapping if that still names `ib_id`.
    fn remove(&mut self, ib_id: i32) -> Option<(ClientOrderId, OrderContext)> {
        let (client_id, ctx, _) = self.ib_to_entry.remove(&ib_id)?;
        self.adopted.remove(&ib_id);
        self.release(&client_id, ib_id);
        Some((client_id, ctx))
    }

    /// Whether `client_id` is held by a live order, or named twice among `orders`: the refusal
    /// [`OrderIdMap::register_all`] and [`OrderIdMap::adopt`] make.
    fn in_use<'a>(
        &self,
        mut orders: impl Iterator<Item = &'a ClientOrderId>,
        client_id: &ClientOrderId,
    ) -> bool {
        orders.any(|earlier| earlier == client_id) || self.cid_to_ib.contains_key(client_id)
    }

    fn insert(
        &mut self,
        client_id: ClientOrderId,
        ib_id: i32,
        context: OrderContext,
        now: Instant,
    ) {
        self.adopted.remove(&ib_id);
        self.cid_to_ib.insert(client_id.clone(), ib_id);
        self.ib_to_entry.insert(ib_id, (client_id, context, now));
    }

    /// Frees `client_id` if it still names `ib_id`, rather than a later order under the same id.
    fn release(&mut self, client_id: &ClientOrderId, ib_id: i32) {
        if self.cid_to_ib.get(client_id) == Some(&ib_id) {
            self.cid_to_ib.remove(client_id);
        }
    }
}

impl OrderIdMap {
    pub fn new() -> Self {
        Self {
            inner: Arc::new(RwLock::new(OrderIdMapInner::default())),
        }
    }

    /// Register a mapping between ClientOrderId and IB order ID with order context.
    ///
    /// # Errors
    /// [`ClientOrderIdInUse`] if a live order already holds `client_id`. Nothing is registered.
    pub fn register(
        &self,
        client_id: ClientOrderId,
        ib_id: i32,
        context: OrderContext,
    ) -> Result<(), ClientOrderIdInUse> {
        self.register_all([(client_id, ib_id, context)])
    }

    /// Register several orders at once, such as the legs of a bracket: all of them or none.
    ///
    /// # Errors
    /// [`ClientOrderIdInUse`], naming the first id at fault, if a live order already holds one of
    /// the ids or two of `orders` share one. Nothing is registered.
    pub fn register_all<const N: usize>(
        &self,
        orders: [(ClientOrderId, i32, OrderContext); N],
    ) -> Result<(), ClientOrderIdInUse> {
        let mut inner = self.inner.write();
        for (index, (client_id, _, _)) in orders.iter().enumerate() {
            if inner.in_use(
                orders[..index].iter().map(|(earlier, _, _)| earlier),
                client_id,
            ) {
                return Err(ClientOrderIdInUse(client_id.clone()));
            }
        }
        let now = Instant::now();
        for (client_id, ib_id, context) in orders {
            inner.insert(client_id, ib_id, context, now);
        }
        Ok(())
    }

    /// Track an order this client did not place, found in IB's listing under `client_id`, the id
    /// its order reference carries: one placed before a restart, say. Its
    /// [`registration`](Self::registration) says it was adopted.
    ///
    /// # Errors
    /// [`AdoptionRefused`] if a live order already holds `client_id`, or `ib_id` already names
    /// an order here. Nothing is tracked.
    pub(crate) fn adopt(
        &self,
        client_id: ClientOrderId,
        ib_id: i32,
        context: OrderContext,
    ) -> Result<(), AdoptionRefused> {
        let mut inner = self.inner.write();
        if inner.ib_to_entry.contains_key(&ib_id) {
            return Err(AdoptionRefused::IbOrderIdTracked);
        }
        if inner.in_use(std::iter::empty(), &client_id) {
            return Err(AdoptionRefused::ClientOrderIdInUse);
        }
        inner.insert(client_id, ib_id, context, Instant::now());
        inner.adopted.insert(ib_id);
        Ok(())
    }

    /// Look up the IB order ID of the live order under `client_id`.
    pub fn get_ib_id(&self, client_id: &ClientOrderId) -> Option<i32> {
        self.inner.read().cid_to_ib.get(client_id).copied()
    }

    /// How long ago the live order under `client_id` came to be tracked here, and whether it was
    /// [adopted](Self::adopt) from a listing rather than placed through this client. A placed
    /// order is registered just before it is sent, so its age is how long ago it was placed; an
    /// adopted one's says only that it was open by then.
    ///
    /// `None` when no live order holds `client_id`.
    pub(crate) fn registration(&self, client_id: &ClientOrderId) -> Option<Registration> {
        let inner = self.inner.read();
        let ib_id = inner.cid_to_ib.get(client_id)?;
        let (_, _, registered_at) = inner.ib_to_entry.get(ib_id)?;
        Some(Registration {
            age: registered_at.elapsed(),
            adopted: inner.adopted.contains(ib_id),
        })
    }

    /// Whether IB order `ib_id` has an entry: a live order, or a filled one not yet reaped.
    pub fn contains(&self, ib_id: i32) -> bool {
        self.inner.read().ib_to_entry.contains_key(&ib_id)
    }

    /// Look up ClientOrderId by IB order ID.
    pub fn get_client_id(&self, ib_id: i32) -> Option<ClientOrderId> {
        self.inner
            .read()
            .ib_to_entry
            .get(&ib_id)
            .map(|(cid, _, _)| cid.clone())
    }

    /// Look up ClientOrderId and OrderContext together by IB order ID (single lookup).
    pub fn get_client_id_and_context(&self, ib_id: i32) -> Option<(ClientOrderId, OrderContext)> {
        self.inner
            .read()
            .ib_to_entry
            .get(&ib_id)
            .map(|(cid, ctx, _)| (cid.clone(), ctx.clone()))
    }

    /// Whether `client_id` now names a live order other than `ib_id`: the id was freed when `ib_id`
    /// ended and has since been registered again.
    pub fn names_other_order(&self, client_id: &ClientOrderId, ib_id: i32) -> bool {
        self.inner
            .read()
            .cid_to_ib
            .get(client_id)
            .is_some_and(|live| *live != ib_id)
    }

    /// Free the id of the filled order `ib_id`, keeping its entry, and return both, in a single
    /// write lock acquisition.
    ///
    /// Use this for a `Filled` status: the id may then name a new order, while the executions and
    /// commissions IB may still send for this one resolve to it by IB id.
    pub fn release_client_id(&self, ib_id: i32) -> Option<(ClientOrderId, OrderContext)> {
        let mut inner = self.inner.write();
        let (client_id, ctx, _) = inner.ib_to_entry.get(&ib_id)?;
        let (client_id, ctx) = (client_id.clone(), ctx.clone());
        inner.release(&client_id, ib_id);
        Some((client_id, ctx))
    }

    /// Remove mapping and return context in a single write lock acquisition.
    ///
    /// Use this for terminal status events (Cancelled/Inactive) to avoid the
    /// read-then-write pattern of `get_client_id_and_context` + `remove_by_ib_id`.
    /// The id's mapping is removed only if it still names `ib_id`.
    pub fn remove_and_get_context(&self, ib_id: i32) -> Option<(ClientOrderId, OrderContext)> {
        self.inner.write().remove(ib_id)
    }

    /// Remove a mapping by IB order ID (used when an order failed or was rolled back).
    ///
    /// The id's mapping is removed only if it still names `ib_id`.
    pub fn remove_by_ib_id(&self, ib_id: i32) -> Option<ClientOrderId> {
        self.inner
            .write()
            .remove(ib_id)
            .map(|(client_id, _)| client_id)
    }

    /// Clear order ID mappings older than the given duration.
    ///
    /// Returns the number of cleared entries.
    ///
    /// # Why This Is Needed
    ///
    /// IB does not guarantee event ordering between `OrderStatus("Filled")` and
    /// `ExecutionData`/`CommissionReport`. For fast-filling orders (especially
    /// market orders), execution data may arrive AFTER the filled status — or
    /// the filled status may not arrive at all. So a `Filled` status frees the
    /// order's client id but keeps its IB-id entry, and an order whose terminal
    /// status never arrives keeps both.
    ///
    /// Call this method periodically to clean up old mappings. A
    /// reasonable interval is 5-10 minutes with a max_age of 1 hour. An order
    /// still working past `max_age` is cleared too, freeing its id.
    pub fn clear_stale(&self, max_age: std::time::Duration) -> usize {
        let mut inner = self.inner.write();
        let before = inner.ib_to_entry.len();

        // Collect IB IDs to remove (can't mutate while iterating)
        let stale_ids: Vec<i32> = inner
            .ib_to_entry
            .iter()
            .filter(|(_, (_, _, registered_at))| registered_at.elapsed() >= max_age)
            .map(|(ib_id, _)| *ib_id)
            .collect();

        for ib_id in stale_ids {
            inner.remove(ib_id);
        }

        before - inner.ib_to_entry.len()
    }

    /// Number of live orders: those holding a client id.
    pub fn len(&self) -> usize {
        self.inner.read().cid_to_ib.len()
    }

    /// Check if no order is live.
    pub fn is_empty(&self) -> bool {
        self.inner.read().cid_to_ib.is_empty()
    }
}

impl Default for OrderIdMap {
    fn default() -> Self {
        Self::new()
    }
}

/// Tracks IB order IDs with pending cancel requests.
///
/// Used to differentiate user-initiated cancellation from time-based expiration.
/// IBKR sends `"Cancelled"` status for both cases; this map tracks which cancels
/// were user-initiated via `cancel_order()`.
#[derive(Debug, Clone)]
pub struct PendingCancels {
    inner: Arc<Mutex<FnvHashMap<i32, Instant>>>,
}

impl PendingCancels {
    pub fn new() -> Self {
        Self {
            inner: Arc::new(Mutex::new(FnvHashMap::with_capacity_and_hasher(
                8,
                Default::default(),
            ))),
        }
    }

    /// Record a pending cancel request for the given IB order ID.
    pub fn insert(&self, ib_id: i32) {
        self.inner.lock().insert(ib_id, Instant::now());
    }

    /// Check if a cancel was user-initiated and remove from tracking.
    ///
    /// Returns `true` if the order ID was in the pending set (user-initiated cancel).
    #[must_use]
    pub fn remove(&self, ib_id: i32) -> bool {
        self.inner.lock().remove(&ib_id).is_some()
    }

    /// Whether a cancel of IB order `ib_id` was requested through this client and is still
    /// tracked: not yet seen to end the order, nor cleared as stale.
    pub(crate) fn contains(&self, ib_id: i32) -> bool {
        self.inner.lock().contains_key(&ib_id)
    }

    /// Clear entries older than the given duration.
    ///
    /// Returns the number of cleared entries. Call periodically to prevent
    /// memory leaks from orphaned cancel requests (e.g., network issues).
    #[must_use]
    pub fn clear_stale(&self, max_age: std::time::Duration) -> usize {
        let mut map = self.inner.lock();
        let before = map.len();
        map.retain(|_, registered_at| registered_at.elapsed() < max_age);
        before - map.len()
    }

    /// Number of pending cancel requests being tracked.
    #[must_use]
    pub fn len(&self) -> usize {
        self.inner.lock().len()
    }

    /// Check if there are no pending cancel requests.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.inner.lock().is_empty()
    }
}

impl Default for PendingCancels {
    fn default() -> Self {
        Self::new()
    }
}

/// Convert rustrade Side to IB Action.
pub(crate) fn side_to_action(side: rustrade_instrument::Side) -> Action {
    match side {
        rustrade_instrument::Side::Buy => Action::Buy,
        rustrade_instrument::Side::Sell => Action::Sell,
    }
}

/// Convert an IB Action to a rustrade Side. A short sale is a sell.
pub(crate) fn action_to_side(action: &Action) -> rustrade_instrument::Side {
    match action {
        Action::Buy => rustrade_instrument::Side::Buy,
        Action::Sell | Action::SellShort | Action::SellLong => rustrade_instrument::Side::Sell,
    }
}

/// What kind of order an IB order is, as [`build_ib_order`] would have built it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct OrderShape {
    pub(crate) kind: OrderKind,
    /// The limit price, for the kinds that have one.
    pub(crate) price: Option<Decimal>,
    pub(crate) time_in_force: TimeInForce,
}

/// Read back the shape of an order IB lists, the inverse of [`build_ib_order`].
///
/// For an order this client did not place, or no longer tracks, such as one placed before a
/// restart. A tracked order's shape is the one it was placed with.
///
/// # Errors
/// A description of what does not map: an order type or time in force [`build_ib_order`] never
/// sends, a price the type needs that IB did not list, or a good-till-date time that does not
/// parse.
pub(crate) fn order_shape_from_ib(order: &Order) -> Result<OrderShape, String> {
    let order_type = order.order_type.as_str();
    let decimal = |value: Option<f64>, field: &str| -> Result<Decimal, String> {
        let value = value.ok_or_else(|| format!("{order_type} order without {field}"))?;
        Decimal::try_from(value).map_err(|e| format!("{order_type} order's {field} {value}: {e}"))
    };

    let time_in_force = match &order.tif {
        IbTimeInForce::Day => TimeInForce::GoodUntilEndOfDay,
        IbTimeInForce::GoodTillCanceled => TimeInForce::GoodUntilCancelled { post_only: false },
        IbTimeInForce::ImmediateOrCancel => TimeInForce::ImmediateOrCancel,
        IbTimeInForce::FillOrKill => TimeInForce::FillOrKill,
        IbTimeInForce::OnOpen => TimeInForce::AtOpen,
        IbTimeInForce::GoodTillDate => TimeInForce::GoodTillDate {
            expiry: parse_gtd_datetime(&order.good_till_date).ok_or_else(|| {
                format!(
                    "good-till-date time {:?} does not parse",
                    order.good_till_date
                )
            })?,
        },
        other => return Err(format!("time in force {other:?}")),
    };

    // A trailing order is by percentage when IB lists a percentage, else by an amount in
    // `aux_price`, as `build_ib_order` sends them.
    let trailing = || -> Result<(Decimal, TrailingOffsetType), String> {
        match order.trailing_percent {
            Some(_) => Ok((
                decimal(order.trailing_percent, "trailing_percent")?,
                TrailingOffsetType::Percentage,
            )),
            None => Ok((
                decimal(order.aux_price, "aux_price")?,
                TrailingOffsetType::Absolute,
            )),
        }
    };

    let (kind, price, time_in_force) = match order_type {
        "MKT" => (OrderKind::Market, None, time_in_force),
        "LMT" => (
            OrderKind::Limit,
            Some(decimal(order.limit_price, "limit_price")?),
            time_in_force,
        ),
        // At-close orders are typed, not timed, at IB (see `build_at_close_order`).
        "MOC" => (OrderKind::Market, None, TimeInForce::AtClose),
        "LOC" => (
            OrderKind::Limit,
            Some(decimal(order.limit_price, "limit_price")?),
            TimeInForce::AtClose,
        ),
        "STP" => (
            OrderKind::Stop {
                trigger_price: decimal(order.aux_price, "aux_price")?,
            },
            None,
            time_in_force,
        ),
        "STP LMT" => (
            OrderKind::StopLimit {
                trigger_price: decimal(order.aux_price, "aux_price")?,
            },
            Some(decimal(order.limit_price, "limit_price")?),
            time_in_force,
        ),
        "TRAIL" => {
            let (offset, offset_type) = trailing()?;
            (
                OrderKind::TrailingStop {
                    offset,
                    offset_type,
                    activation_price: None,
                },
                None,
                time_in_force,
            )
        }
        "TRAIL LIMIT" => {
            let (offset, offset_type) = trailing()?;
            let stop_price = decimal(order.trail_stop_price, "trail_stop_price")?;
            if stop_price <= Decimal::ZERO {
                return Err(format!(
                    "{order_type} order's trail_stop_price {stop_price} is not positive"
                ));
            }
            (
                OrderKind::TrailingStopLimit {
                    offset,
                    offset_type,
                    stop_price,
                    limit_offset: decimal(order.limit_price_offset, "limit_price_offset")?,
                },
                None,
                time_in_force,
            )
        }
        other => return Err(format!("order type {other:?}")),
    };

    Ok(OrderShape {
        kind,
        price,
        time_in_force,
    })
}

/// Parse IB's good-till-date field: the form [`format_gtd_datetime`] sends, in UTC, or IB's
/// `yyyyMMdd HH:mm:ss` with an optional zone.
fn parse_gtd_datetime(value: &str) -> Option<chrono::DateTime<chrono::Utc>> {
    chrono::NaiveDateTime::parse_from_str(value, GTD_FORMAT)
        .map(|naive| naive.and_utc())
        .ok()
        .or_else(|| super::execution::parse_ib_timestamp(value))
}

/// Error when mapping rustrade order types to IB.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum OrderMappingError {
    PostOnlyNotSupported,
    /// Price conversion to f64 failed (overflow or invalid decimal).
    InvalidPrice(String),
    /// Limit price required for this order type but was None.
    MissingLimitPrice(OrderKind),
    /// A limit price was given for a kind that derives its own, such as `TrailingStopLimit`,
    /// whose limit follows from its stop and `limit_offset`.
    UnexpectedLimitPrice(OrderKind),
    /// The kind's stop price is zero or negative; IB rejects such an order.
    NonPositiveStopPrice(OrderKind),
    /// Trailing offset type not supported by IBKR.
    UnsupportedOffsetType(TrailingOffsetType),
    /// Order kind not supported by IBKR (e.g., TakeProfit).
    UnsupportedOrderKind(OrderKind),
    /// AtClose TIF only valid with Market or Limit orders (becomes MOC/LOC).
    /// Stop orders cannot be combined with at-close execution.
    UnsupportedOrderKindForAtClose(OrderKind),
    /// AtClose TIF reached `time_in_force_to_ib` directly. AtClose changes the
    /// order TYPE (MOC/LOC), not just the TIF; callers must route through
    /// `build_ib_order` which handles the type promotion.
    AtCloseRequiresOrderTypeChange,
    /// `ibapi` rejected a bracket's prices: one is not finite, or the take profit or stop loss is
    /// on the wrong side of the entry (for a buy, the take profit must be above the entry and the
    /// stop loss below; a sell the reverse).
    InvalidBracketPrices(String),
    /// The client order id cannot be sent as the order's IB order reference, which carries it:
    /// IB takes at most [`MAX_ORDER_REF_LEN`] ASCII characters there.
    InvalidClientOrderId(ClientOrderId),
}

impl std::fmt::Display for OrderMappingError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::PostOnlyNotSupported => write!(f, "post_only not supported by IB"),
            Self::InvalidPrice(p) => write!(f, "invalid price for f64 conversion: {p}"),
            Self::MissingLimitPrice(k) => {
                write!(f, "limit price required for {k} but was None")
            }
            Self::UnexpectedLimitPrice(k) => write!(
                f,
                "{k} takes no limit price: it follows from the stop price and limit offset"
            ),
            Self::NonPositiveStopPrice(k) => {
                write!(f, "stop price must be positive for {k}")
            }
            Self::UnsupportedOffsetType(t) => {
                write!(f, "trailing offset type {t:?} not supported by IBKR")
            }
            Self::UnsupportedOrderKind(k) => {
                write!(f, "order kind {k} not supported by IBKR")
            }
            Self::UnsupportedOrderKindForAtClose(k) => {
                write!(
                    f,
                    "AtClose TIF only valid with Market or Limit orders, got {k}"
                )
            }
            Self::AtCloseRequiresOrderTypeChange => write!(
                f,
                "AtClose TIF must be routed through build_ib_order, which promotes \
                 the order to MOC/LOC; time_in_force_to_ib cannot map it directly"
            ),
            Self::InvalidBracketPrices(e) => write!(f, "invalid bracket prices: {e}"),
            Self::InvalidClientOrderId(cid) => write!(
                f,
                "client order id {cid} is not an IB order reference: at most \
                 {MAX_ORDER_REF_LEN} ASCII characters"
            ),
        }
    }
}

/// The longest order reference IB echoes back whole, verified on paper. The client order id
/// travels there, so it is limited to this.
pub const MAX_ORDER_REF_LEN: usize = 128;

/// The IB order reference that carries `cid`: the id itself.
///
/// IB echoes the reference on every open-order, completed-order and execution report, so an order
/// can be named by the id it was placed with even by a client that did not place it.
///
/// # Errors
/// [`OrderMappingError::InvalidClientOrderId`] for an id IB would reject (error 10363 for
/// non-ASCII text) or not echo whole: empty, longer than [`MAX_ORDER_REF_LEN`], or not ASCII.
pub fn order_ref(cid: &ClientOrderId) -> Result<String, OrderMappingError> {
    let id = cid.0.as_str();
    if id.is_empty() || id.len() > MAX_ORDER_REF_LEN || !id.is_ascii() {
        return Err(OrderMappingError::InvalidClientOrderId(cid.clone()));
    }
    Ok(id.to_owned())
}

impl std::error::Error for OrderMappingError {}

/// Convert rustrade TimeInForce to IB TimeInForce.
///
/// Returns [`OrderMappingError::AtCloseRequiresOrderTypeChange`] for
/// [`TimeInForce::AtClose`]: AtClose changes the order TYPE (MOC/LOC), not
/// just the TIF, and is handled by [`build_ib_order`] which promotes the
/// order type. Callers needing AtClose support should route through
/// [`build_ib_order`] rather than this helper.
pub fn time_in_force_to_ib(tif: &TimeInForce) -> Result<IbTimeInForce, OrderMappingError> {
    match tif {
        TimeInForce::GoodUntilCancelled { post_only } => {
            if *post_only {
                Err(OrderMappingError::PostOnlyNotSupported)
            } else {
                Ok(IbTimeInForce::GoodTillCanceled)
            }
        }
        TimeInForce::GoodUntilEndOfDay => Ok(IbTimeInForce::Day),
        TimeInForce::FillOrKill => Ok(IbTimeInForce::FillOrKill),
        TimeInForce::ImmediateOrCancel => Ok(IbTimeInForce::ImmediateOrCancel),
        TimeInForce::GoodTillDate { .. } => Ok(IbTimeInForce::GoodTillDate),
        TimeInForce::AtOpen => Ok(IbTimeInForce::OnOpen),
        // AtClose changes the order TYPE to MOC/LOC, not just the TIF.
        // `build_ib_order` intercepts AtClose; surfacing Err here lets other
        // callers (e.g. the bracket-order path) reject gracefully.
        TimeInForce::AtClose => Err(OrderMappingError::AtCloseRequiresOrderTypeChange),
    }
}

/// Convert a Decimal to f64, returning an error if conversion fails.
fn decimal_to_f64(value: rust_decimal::Decimal) -> Result<f64, OrderMappingError> {
    value.try_into().or_else(|_| {
        value
            .to_string()
            .parse()
            .map_err(|_| OrderMappingError::InvalidPrice(value.to_string()))
    })
}

/// Extract required limit price from Option, returning error if None.
fn require_limit_price(
    price: Option<rust_decimal::Decimal>,
    kind: OrderKind,
) -> Result<f64, OrderMappingError> {
    match price {
        Some(p) => decimal_to_f64(p),
        None => Err(OrderMappingError::MissingLimitPrice(kind)),
    }
}

/// Build an IB Order from rustrade order parameters.
///
/// # Order Type Mapping
///
/// - `Market` → IB "MKT"
/// - `Limit` → IB "LMT" with `limit_price`
/// - `Stop` → IB "STP" with `aux_price` as trigger
/// - `StopLimit` → IB "STP LMT" with `aux_price` as trigger, `limit_price` from Order.price
/// - `TrailingStop` (Percentage) → IB "TRAIL" with `trailing_percent`
/// - `TrailingStop` (Absolute) → IB "TRAIL" with `aux_price`
/// - `TrailingStopLimit` (Absolute) → IB "TRAIL LIMIT" with `aux_price`, `trail_stop_price`,
///   `limit_price_offset`
/// - `TrailingStopLimit` (Percentage) → IB "TRAIL LIMIT" with `trailing_percent`,
///   `trail_stop_price`, `limit_price_offset`
/// - `TakeProfit` → `Err(UnsupportedOrderKind)` (IBKR has no native TP; use bracket orders)
/// - `TakeProfitLimit` → `Err(UnsupportedOrderKind)` (IBKR has no native TP; use bracket orders)
/// - `TrailingStop` with an `activation_price`, and `TrailingStopFixedLimit` →
///   `Err(UnsupportedOrderKind)` (IBKR has neither)
/// - `BasisPoints` offset type → Error (not supported by IBKR)
///
/// # Price Requirements
///
/// - `Market`, `Stop`, `TrailingStop`: `price` should be `None` (ignored if provided)
/// - `Limit`, `StopLimit`: `price` must be `Some(limit_price)`
/// - `TrailingStopLimit`: `price` must be `None` (IB derives the limit from the stop and
///   `limit_offset`), else `Err(UnexpectedLimitPrice)`; `stop_price` must be positive, else
///   `Err(NonPositiveStopPrice)`. IB requires the initial stop and rejects a zero one.
///
/// # Time-in-Force Special Cases
///
/// - `AtClose` + `Market` → IB "MOC" (Market-on-Close)
/// - `AtClose` + `Limit` → IB "LOC" (Limit-on-Close)
/// - `AtClose` + Stop/Trailing → Error (not supported by IBKR)
/// - `GoodTillDate` → Sets both TIF and `good_till_date` field
pub fn build_ib_order(
    side: rustrade_instrument::Side,
    quantity: f64,
    kind: &OrderKind,
    price: Option<rust_decimal::Decimal>,
    tif: &TimeInForce,
) -> Result<Order, OrderMappingError> {
    let action = side_to_action(side);

    // Handle AtClose specially - it changes the order TYPE, not just TIF
    if matches!(tif, TimeInForce::AtClose) {
        return build_at_close_order(action, quantity, kind, price);
    }

    let tif_ib = time_in_force_to_ib(tif)?;

    let mut order = match kind {
        OrderKind::Market => order_builder::market_order(action, quantity),

        OrderKind::Limit => {
            let price_f64 = require_limit_price(price, *kind)?;
            order_builder::limit_order(action, quantity, price_f64)
        }

        OrderKind::Stop { trigger_price } => {
            let trigger_f64 = decimal_to_f64(*trigger_price)?;
            order_builder::stop(action, quantity, trigger_f64)
        }

        OrderKind::StopLimit { trigger_price } => {
            let limit_f64 = require_limit_price(price, *kind)?;
            let trigger_f64 = decimal_to_f64(*trigger_price)?;
            // Built by hand: `ibapi` 5 removed `order_builder::stop_limit`, and its fluent
            // replacement adds nothing our checks above have not done. Same fields as before.
            Order {
                action,
                order_type: "STP LMT".to_owned(),
                total_quantity: quantity,
                limit_price: Some(limit_f64),
                aux_price: Some(trigger_f64),
                ..Order::default()
            }
        }

        OrderKind::TrailingStop {
            offset,
            offset_type,
            activation_price: None,
        } => {
            let offset_f64 = decimal_to_f64(*offset)?;
            match offset_type {
                TrailingOffsetType::Percentage => {
                    // Use the builder for percentage-based trailing stop.
                    // trail_stop_price is None, letting IB derive it from market price.
                    Order {
                        action,
                        order_type: "TRAIL".to_owned(),
                        total_quantity: quantity,
                        trailing_percent: Some(offset_f64),
                        trail_stop_price: None,
                        ..Order::default()
                    }
                }
                TrailingOffsetType::Absolute => {
                    // Manual construction for absolute trailing stop.
                    // aux_price holds the trailing amount.
                    Order {
                        action,
                        order_type: "TRAIL".to_owned(),
                        total_quantity: quantity,
                        aux_price: Some(offset_f64),
                        trail_stop_price: None,
                        ..Order::default()
                    }
                }
                TrailingOffsetType::BasisPoints => {
                    return Err(OrderMappingError::UnsupportedOffsetType(
                        TrailingOffsetType::BasisPoints,
                    ));
                }
            }
        }

        OrderKind::TrailingStopLimit {
            offset,
            offset_type,
            stop_price,
            limit_offset,
        } => {
            // IB sets the limit from the stop and `limit_price_offset`, so a limit price here
            // would be ignored; refuse it rather than place something other than was asked.
            if price.is_some() {
                return Err(OrderMappingError::UnexpectedLimitPrice(*kind));
            }
            // IB refuses a TRAIL LIMIT without an initial stop (error 321), and rejects a zero
            // one as an invalid price once the order reaches the exchange.
            if *stop_price <= Decimal::ZERO {
                return Err(OrderMappingError::NonPositiveStopPrice(*kind));
            }
            let offset_f64 = decimal_to_f64(*offset)?;
            let stop_price_f64 = decimal_to_f64(*stop_price)?;
            let limit_offset_f64 = decimal_to_f64(*limit_offset)?;
            // The trail goes in `aux_price` as an amount, or in `trailing_percent`.
            let (aux_price, trailing_percent) = match offset_type {
                TrailingOffsetType::Absolute => (Some(offset_f64), None),
                TrailingOffsetType::Percentage => (None, Some(offset_f64)),
                TrailingOffsetType::BasisPoints => {
                    return Err(OrderMappingError::UnsupportedOffsetType(
                        TrailingOffsetType::BasisPoints,
                    ));
                }
            };
            Order {
                action,
                order_type: "TRAIL LIMIT".to_owned(),
                total_quantity: quantity,
                aux_price,
                trailing_percent,
                trail_stop_price: Some(stop_price_f64),
                limit_price_offset: Some(limit_offset_f64),
                ..Order::default()
            }
        }

        // IBKR does not have native take-profit order types. Callers should use
        // bracket orders or manage TP logic at the strategy level. Its trailing orders take no
        // activation price, and its trailing limit follows the stop rather than staying fixed.
        // An unresolved kind is only read back from a venue, never placed.
        OrderKind::TakeProfit { .. }
        | OrderKind::TakeProfitLimit { .. }
        | OrderKind::TrailingStop {
            activation_price: Some(_),
            ..
        }
        | OrderKind::TrailingStopFixedLimit { .. }
        | OrderKind::ConditionalUnresolved { .. } => {
            return Err(OrderMappingError::UnsupportedOrderKind(*kind));
        }
    };

    order.tif = tif_ib;

    // Handle GoodTillDate: set the good_till_date string field
    if let TimeInForce::GoodTillDate { expiry } = tif {
        order.good_till_date = format_gtd_datetime(expiry);
    }

    Ok(order)
}

/// Format a `DateTime<Utc>` for IB's good_till_date field.
///
/// IB accepts format: "yyyyMMdd HH:mm:ss" with optional timezone suffix.
/// We use UTC format "yyyyMMdd-HH:mm:ss" which IB interprets as UTC.
fn format_gtd_datetime(dt: &chrono::DateTime<chrono::Utc>) -> String {
    dt.format(GTD_FORMAT).to_string()
}

/// The good-till-date form this client sends, in UTC.
const GTD_FORMAT: &str = "%Y%m%d-%H:%M:%S";

/// Build an at-close order (MOC or LOC).
///
/// Only Market and Limit orders can be combined with at-close execution.
/// Stop orders cannot execute at close due to IBKR's order model constraints.
fn build_at_close_order(
    action: Action,
    quantity: f64,
    kind: &OrderKind,
    price: Option<rust_decimal::Decimal>,
) -> Result<Order, OrderMappingError> {
    match kind {
        OrderKind::Market => Ok(order_builder::market_on_close(action, quantity)),
        OrderKind::Limit => {
            let price_f64 = require_limit_price(price, *kind)?;
            Ok(order_builder::limit_on_close(action, quantity, price_f64))
        }
        // Stop orders cannot be combined with at-close execution
        _ => Err(OrderMappingError::UnsupportedOrderKindForAtClose(*kind)),
    }
}

/// Build a bracket order with proper OCA linking.
///
/// ibapi's `order_builder::bracket_order()` sets `parent_id` on child orders (TP/SL
/// wait for entry fill) but does NOT set `oca_group` or `oca_type`. Without OCA
/// linking, if take-profit fills, stop-loss stays open — dangerous position exposure.
///
/// This function wraps `bracket_order()` and adds OCA group linking so that when
/// either child order fills, the other is automatically cancelled by IB.
///
/// # Arguments
///
/// * `parent_order_id` - The IB order ID for the parent (entry) order
/// * `action` - Buy or Sell for the entry order (children use opposite action)
/// * `quantity` - Number of shares/contracts
/// * `limit_price` - Entry limit price
/// * `take_profit_price` - Take profit limit price (above entry for Buy, below for Sell)
/// * `stop_loss_price` - Stop loss trigger price (below entry for Buy, above for Sell)
///
/// # Returns
///
/// [`OrderMappingError::InvalidBracketPrices`] if `ibapi` rejects the prices: one is not finite,
/// or the take profit or stop loss is on the wrong side of the entry. Otherwise a
/// Vec of 3 orders: `[parent, take_profit, stop_loss]` with:
/// - `parent_id` set on children (IB's bracket linkage)
/// - `oca_group` set on children (OCA linkage between TP and SL)
/// - `oca_type = CancelWithBlock` (safest: one at a time, cancel remaining)
/// - `transmit` flags: parent=false, TP=false, SL=true (atomic submission)
///
/// # Order ID Convention
///
/// ibapi's `bracket_order()` assigns consecutive IDs: parent=N, TP=N+1, SL=N+2.
/// Caller must ensure these IDs are reserved atomically via `allocate_order_id_range(3)`.
pub fn build_ib_bracket_with_oca(
    parent_order_id: i32,
    action: Action,
    quantity: f64,
    limit_price: f64,
    take_profit_price: f64,
    stop_loss_price: f64,
    tif: IbTimeInForce,
) -> Result<Vec<Order>, OrderMappingError> {
    let prices = BracketPrices {
        entry: limit_price,
        take_profit: take_profit_price,
        stop_loss: stop_loss_price,
    };
    let mut orders = order_builder::bracket_order(parent_order_id, action, quantity, prices)
        .map_err(|e| OrderMappingError::InvalidBracketPrices(e.to_string()))?;
    assert_eq!(
        orders.len(),
        3,
        "ibapi bracket_order must return exactly 3 orders (parent, TP, SL)"
    );

    // ibapi's bracket_order() defaults all legs to TimeInForce::Day; override
    // with the caller-specified TIF so it actually reaches the wire.
    orders[0].tif = tif.clone();
    orders[1].tif = tif.clone();
    orders[2].tif = tif;

    // Link TP and SL via OCA group so one cancels the other.
    // CancelWithBlock provides overfill protection by routing only one child at a time.
    let oca_group = format!("bracket_{}", parent_order_id);
    orders[1].oca_group = oca_group.clone();
    orders[1].oca_type = OcaType::CancelWithBlock;
    orders[2].oca_group = oca_group;
    orders[2].oca_type = OcaType::CancelWithBlock;

    Ok(orders)
}

#[cfg(test)]
#[allow(clippy::unwrap_used)] // Test code: panics are the correct failure mode
mod tests {
    use super::*;
    use rust_decimal::Decimal;

    fn test_context() -> OrderContext {
        OrderContext {
            instrument: rustrade_instrument::instrument::name::InstrumentNameExchange::from("AAPL"),
            side: Side::Buy,
            price: Some(Decimal::from(150)),
            quantity: Decimal::from(100),
            kind: OrderKind::Limit,
            time_in_force: TimeInForce::GoodUntilCancelled { post_only: false },
        }
    }

    #[test]
    fn test_order_id_map_basic() {
        let map = OrderIdMap::new();
        let cid = ClientOrderId::new("order-123");
        let ctx = test_context();

        map.register(cid.clone(), 42, ctx.clone()).unwrap();

        assert_eq!(map.get_ib_id(&cid), Some(42));
        assert_eq!(map.get_client_id(42), Some(cid.clone()));
        assert_eq!(map.len(), 1);

        let (retrieved_cid, retrieved_ctx) = map.get_client_id_and_context(42).unwrap();
        assert_eq!(retrieved_cid, cid);
        assert_eq!(retrieved_ctx.side, Side::Buy);
        assert_eq!(retrieved_ctx.price, Some(Decimal::from(150)));
    }

    #[test]
    fn test_order_id_map_remove() {
        let map = OrderIdMap::new();
        let cid = ClientOrderId::new("order-456");

        map.register(cid.clone(), 100, test_context()).unwrap();
        assert_eq!(map.len(), 1);

        let removed = map.remove_by_ib_id(100);
        assert_eq!(removed, Some(cid.clone()));
        assert!(map.is_empty());
        assert!(map.get_ib_id(&cid).is_none());
        assert!(map.get_client_id(100).is_none());
        assert!(map.get_client_id_and_context(100).is_none());
    }

    #[test]
    fn test_side_conversion() {
        assert!(matches!(
            side_to_action(rustrade_instrument::Side::Buy),
            Action::Buy
        ));
        assert!(matches!(
            side_to_action(rustrade_instrument::Side::Sell),
            Action::Sell
        ));
    }

    #[test]
    fn test_time_in_force_conversion() {
        assert_eq!(
            time_in_force_to_ib(&TimeInForce::GoodUntilCancelled { post_only: false }),
            Ok(IbTimeInForce::GoodTillCanceled)
        );

        assert!(matches!(
            time_in_force_to_ib(&TimeInForce::GoodUntilCancelled { post_only: true }),
            Err(OrderMappingError::PostOnlyNotSupported)
        ));

        assert_eq!(
            time_in_force_to_ib(&TimeInForce::GoodUntilEndOfDay),
            Ok(IbTimeInForce::Day)
        );
        assert_eq!(
            time_in_force_to_ib(&TimeInForce::FillOrKill),
            Ok(IbTimeInForce::FillOrKill)
        );
        assert_eq!(
            time_in_force_to_ib(&TimeInForce::ImmediateOrCancel),
            Ok(IbTimeInForce::ImmediateOrCancel)
        );
    }

    #[test]
    fn test_time_in_force_conversion_good_till_date() {
        use chrono::{TimeZone, Utc};

        let expiry = Utc.with_ymd_and_hms(2025, 6, 30, 23, 59, 59).unwrap();
        assert_eq!(
            time_in_force_to_ib(&TimeInForce::GoodTillDate { expiry }),
            Ok(IbTimeInForce::GoodTillDate)
        );
    }

    #[test]
    fn test_time_in_force_conversion_at_open() {
        assert_eq!(
            time_in_force_to_ib(&TimeInForce::AtOpen),
            Ok(IbTimeInForce::OnOpen)
        );
    }

    #[test]
    fn test_time_in_force_conversion_at_close_returns_err() {
        // AtClose changes the order TYPE (MOC/LOC), so callers must route
        // through build_ib_order. Other callers (e.g. bracket orders) get a
        // graceful Err that they can surface as an order rejection.
        assert_eq!(
            time_in_force_to_ib(&TimeInForce::AtClose),
            Err(OrderMappingError::AtCloseRequiresOrderTypeChange)
        );
    }

    #[test]
    fn test_build_market_order() {
        let order = build_ib_order(
            rustrade_instrument::Side::Buy,
            100.0,
            &OrderKind::Market,
            None, // Market orders have no limit price
            &TimeInForce::GoodUntilEndOfDay,
        )
        .unwrap();

        assert_eq!(order.action, Action::Buy);
        assert_eq!(order.total_quantity, 100.0);
        assert_eq!(order.order_type, "MKT");
    }

    #[test]
    fn test_build_limit_order() {
        let order = build_ib_order(
            rustrade_instrument::Side::Sell,
            50.0,
            &OrderKind::Limit,
            Some(Decimal::try_from(150.5).unwrap()),
            &TimeInForce::GoodUntilCancelled { post_only: false },
        )
        .unwrap();

        assert_eq!(order.action, Action::Sell);
        assert_eq!(order.total_quantity, 50.0);
        assert_eq!(order.order_type, "LMT");
    }

    #[test]
    fn test_order_id_map_remove_and_get_context() {
        let map = OrderIdMap::new();
        let cid = ClientOrderId::new("order-789");
        let ctx = test_context();

        map.register(cid.clone(), 50, ctx).unwrap();
        assert_eq!(map.len(), 1);

        // Remove and get context in single operation
        let result = map.remove_and_get_context(50);
        assert!(result.is_some());
        let (retrieved_cid, retrieved_ctx) = result.unwrap();
        assert_eq!(retrieved_cid, cid);
        assert_eq!(retrieved_ctx.side, Side::Buy);

        // Map should be empty now
        assert!(map.is_empty());
        assert!(map.get_client_id(50).is_none());
        assert!(map.get_ib_id(&cid).is_none());

        // Second removal returns None
        assert!(map.remove_and_get_context(50).is_none());
    }

    #[test]
    fn test_order_id_map_clear_stale() {
        use std::time::Duration;

        let map = OrderIdMap::new();

        // Register orders
        map.register(ClientOrderId::new("old-1"), 1, test_context())
            .unwrap();
        map.register(ClientOrderId::new("old-2"), 2, test_context())
            .unwrap();

        // With zero max_age, all entries are stale
        let cleared = map.clear_stale(Duration::ZERO);
        assert_eq!(cleared, 2);
        assert!(map.is_empty());

        // Register new orders
        map.register(ClientOrderId::new("new-1"), 10, test_context())
            .unwrap();
        map.register(ClientOrderId::new("new-2"), 20, test_context())
            .unwrap();

        // With large max_age, nothing is stale
        let cleared = map.clear_stale(Duration::from_secs(3600));
        assert_eq!(cleared, 0);
        assert_eq!(map.len(), 2);
    }

    /// A live order's id is refused to a second order, and the first keeps its mapping.
    #[test]
    fn a_live_orders_id_is_refused_to_a_second_order() {
        let map = OrderIdMap::new();
        let cid = ClientOrderId::new("taken");
        map.register(cid.clone(), 1, test_context()).unwrap();

        assert_eq!(
            map.register(cid.clone(), 2, test_context()),
            Err(ClientOrderIdInUse(cid.clone()))
        );
        assert_eq!(
            map.get_ib_id(&cid),
            Some(1),
            "a cancel by id still reaches the first"
        );
        assert!(
            map.get_client_id(2).is_none(),
            "nothing of the second was registered"
        );
    }

    /// A filled order frees its id at once, while its late executions still resolve to it.
    #[test]
    fn a_filled_order_frees_its_id_and_keeps_resolving_by_ib_id() {
        let map = OrderIdMap::new();
        let cid = ClientOrderId::new("reused");
        map.register(cid.clone(), 1, test_context()).unwrap();

        assert_eq!(
            map.release_client_id(1).map(|(id, _)| id),
            Some(cid.clone())
        );
        assert!(map.is_empty(), "no order is live");
        assert_eq!(
            map.get_client_id(1),
            Some(cid.clone()),
            "a late execution resolves"
        );

        // The id is free again.
        map.register(cid.clone(), 2, test_context()).unwrap();
        assert_eq!(map.get_ib_id(&cid), Some(2));
        assert_eq!(map.get_client_id(1), Some(cid.clone()), "and still does");
    }

    /// An earlier order under a reused id ending, or being reaped, leaves the order now under the
    /// id mapped.
    #[test]
    fn an_earlier_order_ending_leaves_a_reused_ids_mapping() {
        let map = OrderIdMap::new();
        let cid = ClientOrderId::new("reused");
        map.register(cid.clone(), 1, test_context()).unwrap();
        let _ = map.release_client_id(1);
        map.register(cid.clone(), 2, test_context()).unwrap();

        assert!(
            map.remove_and_get_context(1).is_some(),
            "the first order's entry goes"
        );
        assert_eq!(map.get_ib_id(&cid), Some(2), "the second keeps the id");
        assert!(map.remove_by_ib_id(1).is_none());
        assert_eq!(map.get_ib_id(&cid), Some(2));
    }

    /// Reaping a filled order's entry leaves a reused id's mapping too.
    #[test]
    fn reaping_a_filled_order_leaves_a_reused_ids_mapping() {
        use std::time::Duration;

        let map = OrderIdMap::new();
        let cid = ClientOrderId::new("reused");
        map.register(cid.clone(), 1, test_context()).unwrap();
        let _ = map.release_client_id(1);
        std::thread::sleep(Duration::from_millis(5));
        map.register(cid.clone(), 2, test_context()).unwrap();

        assert_eq!(
            map.clear_stale(Duration::from_millis(5)),
            1,
            "only the filled one"
        );
        assert_eq!(map.get_ib_id(&cid), Some(2));
    }

    /// Several orders register all or none: an id already live, or one repeated among them,
    /// registers none of them.
    #[test]
    fn register_all_registers_every_order_or_none() {
        let map = OrderIdMap::new();
        map.register(ClientOrderId::new("live"), 1, test_context())
            .unwrap();

        let clash = map.register_all([
            (ClientOrderId::new("a"), 10, test_context()),
            (ClientOrderId::new("live"), 11, test_context()),
        ]);
        assert_eq!(clash, Err(ClientOrderIdInUse(ClientOrderId::new("live"))));

        let repeated = map.register_all([
            (ClientOrderId::new("b"), 20, test_context()),
            (ClientOrderId::new("b"), 21, test_context()),
        ]);
        assert_eq!(repeated, Err(ClientOrderIdInUse(ClientOrderId::new("b"))));

        assert_eq!(map.len(), 1, "neither registered anything");
        assert!(
            [10, 11, 20, 21]
                .iter()
                .all(|ib_id| map.get_client_id(*ib_id).is_none())
        );

        map.register_all([
            (ClientOrderId::new("a"), 10, test_context()),
            (ClientOrderId::new("b"), 20, test_context()),
        ])
        .unwrap();
        assert_eq!(map.len(), 3);
    }

    /// A listed order is adopted under its client order id: tracked, and marked adopted.
    #[test]
    fn an_adopted_order_is_tracked_and_marked_adopted() {
        let map = OrderIdMap::new();
        let cid = ClientOrderId::new("listed");

        map.adopt(cid.clone(), 7, test_context()).unwrap();

        assert_eq!(map.get_ib_id(&cid), Some(7));
        assert_eq!(map.get_client_id(7), Some(cid.clone()));
        assert!(map.registration(&cid).is_some_and(|r| r.adopted));
    }

    /// An IB order id that already names a tracked order, live or filled and not yet reaped, is
    /// not adopted under another id, and the tracked order is left as it was.
    #[test]
    fn adopting_an_ib_order_id_already_tracked_is_refused_and_changes_nothing() {
        let map = OrderIdMap::new();
        let placed = ClientOrderId::new("placed");
        let adopted = ClientOrderId::new("adopted");
        let filled = ClientOrderId::new("filled");
        map.register(placed.clone(), 1, test_context()).unwrap();
        map.adopt(adopted.clone(), 2, test_context()).unwrap();
        map.register(filled.clone(), 3, test_context()).unwrap();
        let _ = map.release_client_id(3);

        for ib_id in [1, 2, 3] {
            let other = ClientOrderId::new(smol_str::format_smolstr!("other-{ib_id}"));
            assert_eq!(
                map.adopt(other.clone(), ib_id, test_context()),
                Err(AdoptionRefused::IbOrderIdTracked)
            );
            assert!(map.get_ib_id(&other).is_none(), "{other} was not tracked");
        }

        assert_eq!(map.get_client_id(1), Some(placed.clone()));
        assert_eq!(map.get_client_id(2), Some(adopted.clone()));
        assert_eq!(map.get_client_id(3), Some(filled.clone()));
        assert!(map.registration(&placed).is_some_and(|r| !r.adopted));
        assert!(map.registration(&adopted).is_some_and(|r| r.adopted));
        assert!(
            map.registration(&filled).is_none(),
            "the filled order's id stays free"
        );
        assert_eq!(map.len(), 2);
    }

    /// A client order id a live order holds is not adopted for another IB order, and the live
    /// order is left as it was.
    #[test]
    fn adopting_a_client_order_id_a_live_order_holds_is_refused_and_changes_nothing() {
        let map = OrderIdMap::new();
        let placed = ClientOrderId::new("placed");
        let adopted = ClientOrderId::new("adopted");
        map.register(placed.clone(), 1, test_context()).unwrap();
        map.adopt(adopted.clone(), 2, test_context()).unwrap();
        let before = [
            map.registration(&placed).map(|r| r.adopted),
            map.registration(&adopted).map(|r| r.adopted),
        ];

        for (cid, ib_id) in [(&placed, 10), (&adopted, 20)] {
            assert_eq!(
                map.adopt(cid.clone(), ib_id, test_context()),
                Err(AdoptionRefused::ClientOrderIdInUse)
            );
            assert!(!map.contains(ib_id), "IB order {ib_id} was not tracked");
        }

        assert_eq!(map.get_ib_id(&placed), Some(1));
        assert_eq!(map.get_ib_id(&adopted), Some(2));
        assert_eq!(
            [
                map.registration(&placed).map(|r| r.adopted),
                map.registration(&adopted).map(|r| r.adopted),
            ],
            before
        );
        assert_eq!(map.len(), 2);
    }

    /// A client order id whose earlier order ended, cancelled or filled, may name an adopted
    /// order. A filled order keeps its entry, so its late executions still resolve.
    #[test]
    fn an_order_is_adopted_under_an_id_whose_earlier_order_ended() {
        let map = OrderIdMap::new();
        let cancelled = ClientOrderId::new("cancelled");
        let filled = ClientOrderId::new("filled");
        map.register(cancelled.clone(), 1, test_context()).unwrap();
        map.register(filled.clone(), 2, test_context()).unwrap();
        let _ = map.remove_and_get_context(1);
        let _ = map.release_client_id(2);

        map.adopt(cancelled.clone(), 11, test_context()).unwrap();
        map.adopt(filled.clone(), 12, test_context()).unwrap();

        assert_eq!(map.get_ib_id(&cancelled), Some(11));
        assert_eq!(map.get_ib_id(&filled), Some(12));
        assert!(map.registration(&cancelled).is_some_and(|r| r.adopted));
        assert!(map.registration(&filled).is_some_and(|r| r.adopted));
        assert_eq!(
            map.get_client_id(2),
            Some(filled),
            "the filled order's executions resolve"
        );
    }

    #[test]
    fn test_pending_cancels_insert_remove() {
        let cancels = PendingCancels::new();
        assert!(cancels.is_empty());

        // Insert a cancel request
        cancels.insert(42);
        assert_eq!(cancels.len(), 1);
        assert!(!cancels.is_empty());

        // Remove returns true for tracked ID
        assert!(cancels.remove(42));
        assert!(cancels.is_empty());

        // Remove returns false for untracked ID
        assert!(!cancels.remove(42));
        assert!(!cancels.remove(999));
    }

    #[test]
    fn test_pending_cancels_multiple() {
        let cancels = PendingCancels::new();

        cancels.insert(1);
        cancels.insert(2);
        cancels.insert(3);
        assert_eq!(cancels.len(), 3);

        // Remove middle one
        assert!(cancels.remove(2));
        assert_eq!(cancels.len(), 2);

        // Other IDs still tracked
        assert!(cancels.remove(1));
        assert!(cancels.remove(3));
        assert!(cancels.is_empty());
    }

    #[test]
    fn test_pending_cancels_clear_stale() {
        use std::time::Duration;

        let cancels = PendingCancels::new();

        cancels.insert(1);
        cancels.insert(2);

        // With zero max_age, all entries are stale
        let cleared = cancels.clear_stale(Duration::ZERO);
        assert_eq!(cleared, 2);
        assert!(cancels.is_empty());

        // Insert new ones
        cancels.insert(10);
        cancels.insert(20);

        // With large max_age, nothing is stale
        let cleared = cancels.clear_stale(Duration::from_secs(3600));
        assert_eq!(cleared, 0);
        assert_eq!(cancels.len(), 2);
    }

    #[test]
    fn test_pending_cancels_duplicate_insert() {
        let cancels = PendingCancels::new();

        cancels.insert(42);
        cancels.insert(42);

        // HashMap deduplicates by ID; second insert updates timestamp
        assert_eq!(cancels.len(), 1);
        assert!(cancels.remove(42));
        assert!(cancels.is_empty());
    }

    #[test]
    fn test_build_stop_order() {
        let order = build_ib_order(
            rustrade_instrument::Side::Sell,
            100.0,
            &OrderKind::Stop {
                trigger_price: Decimal::from(45),
            },
            None, // Stop orders have no limit price
            &TimeInForce::GoodUntilCancelled { post_only: false },
        )
        .unwrap();

        assert_eq!(order.action, Action::Sell);
        assert_eq!(order.total_quantity, 100.0);
        assert_eq!(order.order_type, "STP");
        assert_eq!(order.aux_price, Some(45.0));
        assert_eq!(order.limit_price, None);
    }

    #[test]
    fn test_build_stop_limit_order() {
        let order = build_ib_order(
            rustrade_instrument::Side::Sell,
            100.0,
            &OrderKind::StopLimit {
                trigger_price: Decimal::from(44),
            },
            Some(Decimal::from(45)), // limit price
            &TimeInForce::GoodUntilCancelled { post_only: false },
        )
        .unwrap();

        assert_eq!(order.action, Action::Sell);
        assert_eq!(order.total_quantity, 100.0);
        assert_eq!(order.order_type, "STP LMT");
        assert_eq!(order.aux_price, Some(44.0)); // trigger/stop price
        assert_eq!(order.limit_price, Some(45.0)); // limit price
    }

    #[test]
    fn test_build_trailing_stop_percentage() {
        let order = build_ib_order(
            rustrade_instrument::Side::Sell,
            100.0,
            &OrderKind::TrailingStop {
                offset: Decimal::from(5),
                offset_type: TrailingOffsetType::Percentage,
                activation_price: None,
            },
            None, // Trailing stop orders have no limit price
            &TimeInForce::GoodUntilCancelled { post_only: false },
        )
        .unwrap();

        assert_eq!(order.action, Action::Sell);
        assert_eq!(order.total_quantity, 100.0);
        assert_eq!(order.order_type, "TRAIL");
        assert_eq!(order.trailing_percent, Some(5.0));
        assert_eq!(order.aux_price, None); // percentage uses trailing_percent, not aux_price
        assert_eq!(order.trail_stop_price, None); // let IB derive from market
    }

    #[test]
    fn test_build_trailing_stop_absolute() {
        let order = build_ib_order(
            rustrade_instrument::Side::Sell,
            100.0,
            &OrderKind::TrailingStop {
                offset: Decimal::from(2),
                offset_type: TrailingOffsetType::Absolute,
                activation_price: None,
            },
            None, // Trailing stop orders have no limit price
            &TimeInForce::GoodUntilCancelled { post_only: false },
        )
        .unwrap();

        assert_eq!(order.action, Action::Sell);
        assert_eq!(order.total_quantity, 100.0);
        assert_eq!(order.order_type, "TRAIL");
        assert_eq!(order.aux_price, Some(2.0)); // absolute uses aux_price
        assert_eq!(order.trailing_percent, None);
        assert_eq!(order.trail_stop_price, None);
    }

    #[test]
    fn test_build_trailing_stop_limit_absolute() {
        let order = build_ib_order(
            rustrade_instrument::Side::Sell,
            100.0,
            &OrderKind::TrailingStopLimit {
                offset: Decimal::from(2),
                offset_type: TrailingOffsetType::Absolute,
                stop_price: Decimal::from(95),
                limit_offset: Decimal::try_from(0.5).unwrap(),
            },
            None, // Trailing stop limit uses limit_offset, not a fixed price
            &TimeInForce::GoodUntilCancelled { post_only: false },
        )
        .unwrap();

        assert_eq!(order.action, Action::Sell);
        assert_eq!(order.total_quantity, 100.0);
        assert_eq!(order.order_type, "TRAIL LIMIT");
        assert_eq!(order.aux_price, Some(2.0)); // trailing amount
        assert_eq!(order.limit_price_offset, Some(0.5)); // limit offset from stop
        assert_eq!(order.trailing_percent, None);
        assert_eq!(order.trail_stop_price, Some(95.0)); // initial stop
        assert_eq!(order.limit_price, None); // IB derives it from the stop
    }

    #[test]
    fn test_build_trailing_stop_limit_percentage() {
        let order = build_ib_order(
            rustrade_instrument::Side::Sell,
            100.0,
            &OrderKind::TrailingStopLimit {
                offset: Decimal::from(5),
                offset_type: TrailingOffsetType::Percentage,
                stop_price: Decimal::from(95),
                limit_offset: Decimal::try_from(0.5).unwrap(),
            },
            None, // Trailing stop limit uses limit_offset, not a fixed price
            &TimeInForce::GoodUntilCancelled { post_only: false },
        )
        .unwrap();

        assert_eq!(order.action, Action::Sell);
        assert_eq!(order.total_quantity, 100.0);
        assert_eq!(order.order_type, "TRAIL LIMIT");
        assert_eq!(order.trailing_percent, Some(5.0));
        assert_eq!(order.limit_price_offset, Some(0.5));
        assert_eq!(order.aux_price, None); // percentage doesn't use aux_price
        assert_eq!(order.trail_stop_price, Some(95.0)); // initial stop
        assert_eq!(order.limit_price, None); // IB derives it from the stop
    }

    /// IB refuses a TRAIL LIMIT without a stop, and rejects a zero one; neither is sent.
    #[test]
    fn test_build_trailing_stop_limit_rejects_non_positive_stop_price() {
        for offset_type in [TrailingOffsetType::Absolute, TrailingOffsetType::Percentage] {
            for stop_price in [Decimal::ZERO, Decimal::from(-1)] {
                let kind = OrderKind::TrailingStopLimit {
                    offset: Decimal::from(2),
                    offset_type,
                    stop_price,
                    limit_offset: Decimal::from(1),
                };
                assert_eq!(
                    build_ib_order(
                        rustrade_instrument::Side::Sell,
                        1.0,
                        &kind,
                        None,
                        &TimeInForce::GoodUntilCancelled { post_only: false },
                    ),
                    Err(OrderMappingError::NonPositiveStopPrice(kind)),
                    "{kind}"
                );
            }
        }
    }

    /// The limit follows from the stop and limit offset, so a limit price is refused, not
    /// silently dropped.
    #[test]
    fn test_build_trailing_stop_limit_rejects_limit_price() {
        for offset_type in [TrailingOffsetType::Absolute, TrailingOffsetType::Percentage] {
            let kind = OrderKind::TrailingStopLimit {
                offset: Decimal::from(2),
                offset_type,
                stop_price: Decimal::from(95),
                limit_offset: Decimal::from(1),
            };
            assert_eq!(
                build_ib_order(
                    rustrade_instrument::Side::Sell,
                    1.0,
                    &kind,
                    Some(Decimal::from(94)),
                    &TimeInForce::GoodUntilCancelled { post_only: false },
                ),
                Err(OrderMappingError::UnexpectedLimitPrice(kind)),
                "{kind}"
            );
        }
    }

    #[test]
    fn test_build_trailing_stop_basis_points_unsupported() {
        let result = build_ib_order(
            rustrade_instrument::Side::Sell,
            100.0,
            &OrderKind::TrailingStop {
                offset: Decimal::from(50), // 50 basis points
                offset_type: TrailingOffsetType::BasisPoints,
                activation_price: None,
            },
            None, // Trailing stop orders have no limit price
            &TimeInForce::GoodUntilCancelled { post_only: false },
        );

        assert!(matches!(
            result,
            Err(OrderMappingError::UnsupportedOffsetType(
                TrailingOffsetType::BasisPoints
            ))
        ));
    }

    /// An unresolved kind is only read back from a venue, never placed.
    #[test]
    fn test_build_unresolved_kind_unsupported() {
        let kind = OrderKind::ConditionalUnresolved {
            family: crate::order::ConditionalFamily::StopLimit,
            trigger_price: Some(Decimal::from(95)),
        };
        let result = build_ib_order(
            rustrade_instrument::Side::Sell,
            100.0,
            &kind,
            Some(Decimal::from(94)),
            &TimeInForce::GoodUntilCancelled { post_only: false },
        );
        assert!(matches!(result, Err(OrderMappingError::UnsupportedOrderKind(k)) if k == kind));
    }

    #[test]
    fn test_build_trailing_stop_limit_basis_points_unsupported() {
        let result = build_ib_order(
            rustrade_instrument::Side::Sell,
            100.0,
            &OrderKind::TrailingStopLimit {
                offset: Decimal::from(50),
                offset_type: TrailingOffsetType::BasisPoints,
                stop_price: Decimal::from(95),
                limit_offset: Decimal::try_from(0.5).unwrap(),
            },
            None, // Trailing stop limit uses limit_offset, not a fixed price
            &TimeInForce::GoodUntilCancelled { post_only: false },
        );

        assert!(matches!(
            result,
            Err(OrderMappingError::UnsupportedOffsetType(
                TrailingOffsetType::BasisPoints
            ))
        ));
    }

    /// IBKR has no activation price on a trailing stop, and no fixed-limit trailing stop.
    #[test]
    fn test_build_activated_and_fixed_limit_trailing_stops_unsupported() {
        let tif = TimeInForce::GoodUntilCancelled { post_only: false };
        for kind in [
            OrderKind::TrailingStop {
                offset: Decimal::from(2),
                offset_type: TrailingOffsetType::Percentage,
                activation_price: Some(Decimal::from(150)),
            },
            OrderKind::TrailingStopFixedLimit {
                offset: Decimal::from(2),
                offset_type: TrailingOffsetType::Percentage,
                activation_price: None,
            },
        ] {
            let result = build_ib_order(
                rustrade_instrument::Side::Sell,
                100.0,
                &kind,
                Some(Decimal::from(140)),
                &tif,
            );
            assert!(
                matches!(result, Err(OrderMappingError::UnsupportedOrderKind(_))),
                "{kind}: {result:?}"
            );
        }
    }

    #[test]
    fn test_build_take_profit_unsupported() {
        let result = build_ib_order(
            rustrade_instrument::Side::Sell,
            100.0,
            &OrderKind::TakeProfit {
                trigger_price: Decimal::from(150),
            },
            None,
            &TimeInForce::GoodUntilCancelled { post_only: false },
        );

        assert!(matches!(
            result,
            Err(OrderMappingError::UnsupportedOrderKind(
                OrderKind::TakeProfit { .. }
            ))
        ));
    }

    #[test]
    fn test_build_take_profit_limit_unsupported() {
        let result = build_ib_order(
            rustrade_instrument::Side::Sell,
            100.0,
            &OrderKind::TakeProfitLimit {
                trigger_price: Decimal::from(150),
            },
            None,
            &TimeInForce::GoodUntilCancelled { post_only: false },
        );

        assert!(matches!(
            result,
            Err(OrderMappingError::UnsupportedOrderKind(
                OrderKind::TakeProfitLimit { .. }
            ))
        ));
    }

    // =========================================================================
    // Extended Time-in-Force Tests
    // =========================================================================

    #[test]
    fn test_build_market_order_at_open() {
        let order = build_ib_order(
            rustrade_instrument::Side::Buy,
            100.0,
            &OrderKind::Market,
            None, // Market orders have no limit price
            &TimeInForce::AtOpen,
        )
        .unwrap();

        assert_eq!(order.action, Action::Buy);
        assert_eq!(order.total_quantity, 100.0);
        assert_eq!(order.order_type, "MKT");
        assert_eq!(order.tif, IbTimeInForce::OnOpen);
    }

    #[test]
    fn test_build_limit_order_at_open() {
        let order = build_ib_order(
            rustrade_instrument::Side::Sell,
            50.0,
            &OrderKind::Limit,
            Some(Decimal::from(150)),
            &TimeInForce::AtOpen,
        )
        .unwrap();

        assert_eq!(order.action, Action::Sell);
        assert_eq!(order.total_quantity, 50.0);
        assert_eq!(order.order_type, "LMT");
        assert_eq!(order.limit_price, Some(150.0));
        assert_eq!(order.tif, IbTimeInForce::OnOpen);
    }

    #[test]
    fn test_build_stop_order_at_open() {
        // Stop orders can use AtOpen TIF
        let order = build_ib_order(
            rustrade_instrument::Side::Sell,
            100.0,
            &OrderKind::Stop {
                trigger_price: Decimal::from(45),
            },
            None, // Stop orders have no limit price
            &TimeInForce::AtOpen,
        )
        .unwrap();

        assert_eq!(order.order_type, "STP");
        assert_eq!(order.aux_price, Some(45.0));
        assert_eq!(order.tif, IbTimeInForce::OnOpen);
    }

    #[test]
    fn test_build_market_on_close() {
        let order = build_ib_order(
            rustrade_instrument::Side::Buy,
            100.0,
            &OrderKind::Market,
            None, // Market orders have no limit price
            &TimeInForce::AtClose,
        )
        .unwrap();

        assert_eq!(order.action, Action::Buy);
        assert_eq!(order.total_quantity, 100.0);
        assert_eq!(order.order_type, "MOC");
    }

    #[test]
    fn test_build_limit_on_close() {
        let order = build_ib_order(
            rustrade_instrument::Side::Sell,
            50.0,
            &OrderKind::Limit,
            Some(Decimal::from(150)),
            &TimeInForce::AtClose,
        )
        .unwrap();

        assert_eq!(order.action, Action::Sell);
        assert_eq!(order.total_quantity, 50.0);
        assert_eq!(order.order_type, "LOC");
        assert_eq!(order.limit_price, Some(150.0));
    }

    #[test]
    fn test_build_stop_at_close_unsupported() {
        let result = build_ib_order(
            rustrade_instrument::Side::Sell,
            100.0,
            &OrderKind::Stop {
                trigger_price: Decimal::from(45),
            },
            None, // Stop orders have no limit price
            &TimeInForce::AtClose,
        );

        assert!(matches!(
            result,
            Err(OrderMappingError::UnsupportedOrderKindForAtClose(
                OrderKind::Stop { .. }
            ))
        ));
    }

    #[test]
    fn test_build_stop_limit_at_close_unsupported() {
        let result = build_ib_order(
            rustrade_instrument::Side::Sell,
            100.0,
            &OrderKind::StopLimit {
                trigger_price: Decimal::from(44),
            },
            Some(Decimal::from(45)),
            &TimeInForce::AtClose,
        );

        assert!(matches!(
            result,
            Err(OrderMappingError::UnsupportedOrderKindForAtClose(
                OrderKind::StopLimit { .. }
            ))
        ));
    }

    #[test]
    fn test_build_trailing_stop_at_close_unsupported() {
        let result = build_ib_order(
            rustrade_instrument::Side::Sell,
            100.0,
            &OrderKind::TrailingStop {
                offset: Decimal::from(5),
                offset_type: TrailingOffsetType::Percentage,
                activation_price: None,
            },
            None, // Trailing stop orders have no limit price
            &TimeInForce::AtClose,
        );

        assert!(matches!(
            result,
            Err(OrderMappingError::UnsupportedOrderKindForAtClose(
                OrderKind::TrailingStop { .. }
            ))
        ));
    }

    #[test]
    fn test_build_trailing_stop_limit_at_close_unsupported() {
        let result = build_ib_order(
            rustrade_instrument::Side::Sell,
            100.0,
            &OrderKind::TrailingStopLimit {
                offset: Decimal::from(5),
                offset_type: TrailingOffsetType::Absolute,
                stop_price: Decimal::from(95),
                limit_offset: Decimal::from(1),
            },
            None, // Trailing stop limit uses limit_offset, not a fixed price
            &TimeInForce::AtClose,
        );

        assert!(matches!(
            result,
            Err(OrderMappingError::UnsupportedOrderKindForAtClose(
                OrderKind::TrailingStopLimit { .. }
            ))
        ));
    }

    #[test]
    fn test_build_good_till_date_order() {
        use chrono::{TimeZone, Utc};

        let expiry = Utc.with_ymd_and_hms(2025, 6, 30, 23, 59, 59).unwrap();
        let order = build_ib_order(
            rustrade_instrument::Side::Buy,
            100.0,
            &OrderKind::Limit,
            Some(Decimal::from(150)),
            &TimeInForce::GoodTillDate { expiry },
        )
        .unwrap();

        assert_eq!(order.action, Action::Buy);
        assert_eq!(order.total_quantity, 100.0);
        assert_eq!(order.order_type, "LMT");
        assert_eq!(order.tif, IbTimeInForce::GoodTillDate);
        assert_eq!(order.good_till_date, "20250630-23:59:59");
    }

    #[test]
    fn test_format_gtd_datetime() {
        use chrono::{TimeZone, Utc};

        let dt = Utc.with_ymd_and_hms(2024, 12, 25, 14, 30, 0).unwrap();
        assert_eq!(format_gtd_datetime(&dt), "20241225-14:30:00");

        let dt2 = Utc.with_ymd_and_hms(2025, 1, 1, 0, 0, 0).unwrap();
        assert_eq!(format_gtd_datetime(&dt2), "20250101-00:00:00");
    }

    // =========================================================================
    // Bracket Order Tests
    // =========================================================================

    #[test]
    fn test_build_ib_bracket_with_oca_sets_oca_fields() {
        let orders = build_ib_bracket_with_oca(
            1000,
            Action::Buy,
            10.0,
            150.0,
            160.0,
            140.0,
            IbTimeInForce::Day,
        )
        .unwrap();

        assert_eq!(orders.len(), 3);

        // OCA group must be non-empty on both child orders
        assert!(!orders[1].oca_group.is_empty());
        assert_eq!(orders[1].oca_group, orders[2].oca_group);

        // Both children must use CancelWithBlock
        assert_eq!(orders[1].oca_type, OcaType::CancelWithBlock);
        assert_eq!(orders[2].oca_type, OcaType::CancelWithBlock);

        // Parent must NOT be in OCA group (only children are linked)
        assert!(orders[0].oca_group.is_empty());
        assert_eq!(orders[0].oca_type, OcaType::None);
    }

    #[test]
    fn test_build_ib_bracket_with_oca_parent_id_linkage() {
        let orders = build_ib_bracket_with_oca(
            1000,
            Action::Buy,
            10.0,
            150.0,
            160.0,
            140.0,
            IbTimeInForce::Day,
        )
        .unwrap();

        // Children must reference parent via parent_id
        assert_eq!(orders[1].parent_id, 1000); // TP waits for parent fill
        assert_eq!(orders[2].parent_id, 1000); // SL waits for parent fill

        // Parent has no parent
        assert_eq!(orders[0].parent_id, 0);
    }

    #[test]
    fn test_build_ib_bracket_with_oca_transmit_flags() {
        let orders = build_ib_bracket_with_oca(
            1000,
            Action::Buy,
            10.0,
            150.0,
            160.0,
            140.0,
            IbTimeInForce::Day,
        )
        .unwrap();

        // Only the last order triggers transmission of all three
        assert!(!orders[0].transmit); // Parent: don't transmit yet
        assert!(!orders[1].transmit); // TP: don't transmit yet
        assert!(orders[2].transmit); // SL: transmit all
    }

    #[test]
    fn test_build_ib_bracket_with_oca_order_ids_are_consecutive() {
        let orders = build_ib_bracket_with_oca(
            500,
            Action::Sell,
            5.0,
            100.0,
            90.0,
            110.0,
            IbTimeInForce::Day,
        )
        .unwrap();

        assert_eq!(orders[0].order_id, 500); // Parent
        assert_eq!(orders[1].order_id, 501); // Take profit
        assert_eq!(orders[2].order_id, 502); // Stop loss
    }

    #[test]
    fn test_build_ib_bracket_with_oca_rejects_prices_on_the_wrong_side_of_the_entry() {
        // A buy's take profit below its entry.
        let result =
            build_ib_bracket_with_oca(7, Action::Buy, 1.0, 10.0, 9.0, 8.0, IbTimeInForce::Day);
        assert!(matches!(
            result,
            Err(OrderMappingError::InvalidBracketPrices(_))
        ));

        // A sell's stop loss below its entry.
        let result =
            build_ib_bracket_with_oca(7, Action::Sell, 1.0, 10.0, 8.0, 9.0, IbTimeInForce::Day);
        assert!(matches!(
            result,
            Err(OrderMappingError::InvalidBracketPrices(_))
        ));
    }

    #[test]
    fn test_build_ib_bracket_with_oca_group_name_contains_parent_id() {
        let orders =
            build_ib_bracket_with_oca(42, Action::Buy, 1.0, 10.0, 12.0, 8.0, IbTimeInForce::Day)
                .unwrap();

        assert!(orders[1].oca_group.contains("42"));
        assert!(orders[2].oca_group.contains("42"));
    }

    #[test]
    fn test_build_ib_bracket_with_oca_order_types() {
        let orders = build_ib_bracket_with_oca(
            1000,
            Action::Buy,
            100.0,
            150.0,
            160.0,
            140.0,
            IbTimeInForce::Day,
        )
        .unwrap();

        // Parent is limit order
        assert_eq!(orders[0].order_type, "LMT");
        assert_eq!(orders[0].limit_price, Some(150.0));

        // Take profit is limit order
        assert_eq!(orders[1].order_type, "LMT");
        assert_eq!(orders[1].limit_price, Some(160.0));

        // Stop loss is stop order
        assert_eq!(orders[2].order_type, "STP");
        assert_eq!(orders[2].aux_price, Some(140.0));
    }

    #[test]
    fn test_build_ib_bracket_with_oca_actions_reversed_for_children() {
        // Buy bracket: entry=Buy, exits=Sell
        let buy_orders =
            build_ib_bracket_with_oca(100, Action::Buy, 10.0, 50.0, 55.0, 45.0, IbTimeInForce::Day)
                .unwrap();
        assert_eq!(buy_orders[0].action, Action::Buy);
        assert_eq!(buy_orders[1].action, Action::Sell);
        assert_eq!(buy_orders[2].action, Action::Sell);

        // Sell bracket: entry=Sell, exits=Buy
        let sell_orders = build_ib_bracket_with_oca(
            200,
            Action::Sell,
            10.0,
            50.0,
            45.0,
            55.0,
            IbTimeInForce::Day,
        )
        .unwrap();
        assert_eq!(sell_orders[0].action, Action::Sell);
        assert_eq!(sell_orders[1].action, Action::Buy);
        assert_eq!(sell_orders[2].action, Action::Buy);
    }

    #[test]
    fn test_build_ib_bracket_with_oca_applies_tif_to_all_legs() {
        let orders = build_ib_bracket_with_oca(
            1000,
            Action::Buy,
            10.0,
            150.0,
            160.0,
            140.0,
            IbTimeInForce::GoodTillCanceled,
        )
        .unwrap();

        assert_eq!(orders[0].tif, IbTimeInForce::GoodTillCanceled);
        assert_eq!(orders[1].tif, IbTimeInForce::GoodTillCanceled);
        assert_eq!(orders[2].tif, IbTimeInForce::GoodTillCanceled);
    }

    /// A client order id travels as the order reference whole, so one IB would reject or cut is
    /// refused: empty, longer than IB echoes back, or not ASCII (IB error 10363).
    #[test]
    fn order_ref_is_the_client_order_id_when_ib_echoes_it_whole() {
        let longest = "a".repeat(MAX_ORDER_REF_LEN);
        assert_eq!(
            order_ref(&ClientOrderId::new(longest.as_str())).unwrap(),
            longest
        );
        assert_eq!(
            order_ref(&ClientOrderId::new("cid-1_tp")).unwrap(),
            "cid-1_tp"
        );

        let too_long = "a".repeat(MAX_ORDER_REF_LEN + 1);
        for refused in ["", too_long.as_str(), "ordre-é"] {
            let cid = ClientOrderId::new(refused);
            assert_eq!(
                order_ref(&cid),
                Err(OrderMappingError::InvalidClientOrderId(cid.clone()))
            );
        }
    }

    /// Every order this client builds reads back as what it was built from, so an open order it no
    /// longer tracks is reported as placed.
    #[test]
    fn order_shape_from_ib_reads_back_what_build_ib_order_sends() {
        use chrono::TimeZone;
        use rust_decimal_macros::dec;

        let expiry = chrono::Utc.with_ymd_and_hms(2026, 10, 9, 20, 0, 0).unwrap();
        let kinds = [
            (OrderKind::Market, None),
            (OrderKind::Limit, Some(dec!(150.25))),
            (
                OrderKind::Stop {
                    trigger_price: dec!(140.5),
                },
                None,
            ),
            (
                OrderKind::StopLimit {
                    trigger_price: dec!(140.5),
                },
                Some(dec!(140)),
            ),
            (
                OrderKind::TrailingStop {
                    offset: dec!(2.5),
                    offset_type: TrailingOffsetType::Percentage,
                    activation_price: None,
                },
                None,
            ),
            (
                OrderKind::TrailingStop {
                    offset: dec!(1.75),
                    offset_type: TrailingOffsetType::Absolute,
                    activation_price: None,
                },
                None,
            ),
            (
                OrderKind::TrailingStopLimit {
                    offset: dec!(2),
                    offset_type: TrailingOffsetType::Percentage,
                    stop_price: dec!(130.5),
                    limit_offset: dec!(0.5),
                },
                None,
            ),
            (
                OrderKind::TrailingStopLimit {
                    offset: dec!(1.5),
                    offset_type: TrailingOffsetType::Absolute,
                    stop_price: dec!(139.75),
                    limit_offset: dec!(0.25),
                },
                None,
            ),
        ];
        let tifs = [
            TimeInForce::GoodUntilCancelled { post_only: false },
            TimeInForce::GoodUntilEndOfDay,
            TimeInForce::ImmediateOrCancel,
            TimeInForce::FillOrKill,
            TimeInForce::AtOpen,
            TimeInForce::GoodTillDate { expiry },
        ];

        for (kind, price) in kinds {
            for time_in_force in tifs {
                let order = build_ib_order(Side::Buy, 1.0, &kind, price, &time_in_force).unwrap();
                assert_eq!(
                    order_shape_from_ib(&order),
                    Ok(OrderShape {
                        kind,
                        price,
                        time_in_force
                    }),
                    "{kind} {time_in_force}"
                );
            }
        }

        // At-close orders are typed MOC/LOC at IB.
        for (kind, price) in [
            (OrderKind::Market, None),
            (OrderKind::Limit, Some(dec!(99))),
        ] {
            let order =
                build_ib_order(Side::Sell, 1.0, &kind, price, &TimeInForce::AtClose).unwrap();
            assert_eq!(
                order_shape_from_ib(&order),
                Ok(OrderShape {
                    kind,
                    price,
                    time_in_force: TimeInForce::AtClose
                }),
                "{kind}"
            );
        }
    }

    #[test]
    fn order_shape_from_ib_reads_ibs_own_good_till_date_form() {
        use chrono::TimeZone;

        let order = Order {
            order_type: "MKT".to_owned(),
            tif: IbTimeInForce::GoodTillDate,
            good_till_date: "20261009 16:00:00 US/Eastern".to_owned(),
            ..Order::default()
        };
        assert_eq!(
            order_shape_from_ib(&order).unwrap().time_in_force,
            TimeInForce::GoodTillDate {
                expiry: chrono::Utc.with_ymd_and_hms(2026, 10, 9, 20, 0, 0).unwrap()
            }
        );
    }

    #[test]
    fn order_shape_from_ib_refuses_what_this_client_never_sends() {
        let order = |order_type: &str, tif: IbTimeInForce| Order {
            order_type: order_type.to_owned(),
            tif,
            limit_price: Some(1.0),
            ..Order::default()
        };
        for (order, reason) in [
            (order("REL", IbTimeInForce::Day), "order type"),
            (
                order("LMT", IbTimeInForce::DayTillCanceled),
                "time in force",
            ),
            (
                Order {
                    limit_price: None,
                    ..order("LMT", IbTimeInForce::Day)
                },
                "without limit_price",
            ),
            (order("STP", IbTimeInForce::Day), "without aux_price"),
            (order("MKT", IbTimeInForce::GoodTillDate), "good-till-date"),
            (
                Order {
                    aux_price: Some(2.0),
                    limit_price_offset: Some(0.5),
                    ..order("TRAIL LIMIT", IbTimeInForce::Day)
                },
                "without trail_stop_price",
            ),
            (
                Order {
                    aux_price: Some(2.0),
                    trail_stop_price: Some(0.0),
                    limit_price_offset: Some(0.5),
                    ..order("TRAIL LIMIT", IbTimeInForce::Day)
                },
                "not positive",
            ),
            (
                Order {
                    trailing_percent: Some(5.0),
                    trail_stop_price: Some(-1.0),
                    limit_price_offset: Some(0.5),
                    ..order("TRAIL LIMIT", IbTimeInForce::Day)
                },
                "not positive",
            ),
        ] {
            let error = order_shape_from_ib(&order).unwrap_err();
            assert!(error.contains(reason), "{error:?} should name {reason:?}");
        }
    }

    #[test]
    fn action_to_side_reads_a_short_sale_as_a_sell() {
        assert_eq!(action_to_side(&Action::Buy), Side::Buy);
        for action in [Action::Sell, Action::SellShort, Action::SellLong] {
            assert_eq!(action_to_side(&action), Side::Sell, "{action:?}");
        }
    }
}