nautilus-interactive-brokers 0.62.0

Interactive Brokers integration adapter for the Nautilus trading engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
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
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
// -------------------------------------------------------------------------------------------------
//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
//  https://nautechsystems.io
//
//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
//  You may not use this file except in compliance with the License.
//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
// -------------------------------------------------------------------------------------------------

//! Interactive Brokers instrument provider implementation.

use std::{collections::HashMap, fs, path::Path, str::FromStr, sync::Arc};

use anyhow::Context;
use dashmap::DashMap;
use ibapi::{
    contracts::{ComboLegOpenClose, Contract, Exchange, LegAction, SecurityType, Symbol},
    prelude::StreamExt,
    subscriptions::SubscriptionItem,
};
use jiff::{Span, Timestamp, tz::Offset};
use nautilus_model::{
    identifiers::{InstrumentId, Venue},
    instruments::{Instrument, InstrumentAny},
};
use serde::{Deserialize, Serialize};

use crate::{
    common::{
        contracts::parse_contract_from_json,
        enums::IbAction,
        parse::{
            create_spread_instrument_id, determine_venue_from_contract, exchange_to_mic_venue,
            ib_contract_to_instrument_id_raw, ib_contract_to_instrument_id_simplified,
            instrument_id_to_ib_contract, is_spread_instrument_id,
            parse_spread_instrument_id_to_legs, possible_exchanges_for_venue,
        },
    },
    config::{InteractiveBrokersInstrumentProviderConfig, SymbologyMethod},
    providers::parse::{parse_ib_contract_to_instrument, parse_spread_instrument_any},
};

/// Cache structure for persistent instrument caching.
#[derive(Debug, Clone, Serialize, Deserialize)]
struct InstrumentCache {
    /// Timestamp when cache was created.
    cache_timestamp: Timestamp,
    /// Contract ID to Instrument ID mappings.
    contract_id_to_instrument_id: Vec<(i32, String)>,
    /// Instrument ID to Price Magnifier mappings.
    price_magnifiers: Vec<(String, i32)>,
    /// Instrument ID to IB contracts.
    #[serde(default)]
    contracts: Vec<(String, Contract)>,
    /// Instrument ID to IB contract details.
    #[serde(default)]
    contract_details: Vec<(String, ibapi::contracts::ContractDetails)>,
    /// Instruments serialized as JSON strings (since InstrumentAny is serializable).
    instruments: Vec<(String, String)>, // (instrument_id, json)
}

/// Interactive Brokers instrument provider.
///
/// This provider fetches contract details from Interactive Brokers using the `rust-ibapi` library
/// and converts them to NautilusTrader instruments.
#[cfg_attr(
    feature = "python",
    pyo3::pyclass(
        module = "nautilus_trader.adapters.interactive_brokers",
        unsendable,
        from_py_object
    )
)]
#[cfg_attr(
    feature = "python",
    pyo3_stub_gen::derive::gen_stub_pyclass(
        module = "nautilus_trader.adapters.interactive_brokers"
    )
)]
#[derive(Debug, Clone)]
pub struct InteractiveBrokersInstrumentProvider {
    /// Configuration for the provider.
    config: InteractiveBrokersInstrumentProviderConfig,
    /// Cache mapping contract IDs to instrument IDs.
    contract_id_to_instrument_id: Arc<DashMap<i32, InstrumentId>>,
    /// Cache mapping instrument IDs to instruments.
    instruments: Arc<DashMap<InstrumentId, InstrumentAny>>,
    /// Cache mapping instrument IDs to contract details.
    contract_details: Arc<DashMap<InstrumentId, ibapi::contracts::ContractDetails>>,
    /// Cache mapping instrument IDs to IB contracts.
    contracts: Arc<DashMap<InstrumentId, Contract>>,
    /// Dedicated cache for price magnifiers for fast lookups.
    price_magnifiers: Arc<DashMap<InstrumentId, i32>>,
    /// Guards startup loading and records whether every configured input resolved.
    startup_initialized: Arc<tokio::sync::Mutex<bool>>,
}

trait StartupInstrumentLoader {
    async fn load_instrument_id(
        &self,
        instrument_id: InstrumentId,
    ) -> anyhow::Result<Option<InstrumentId>>;

    async fn load_contract(
        &self,
        contract_spec: &serde_json::Value,
    ) -> anyhow::Result<Vec<InstrumentId>>;
}

struct IbStartupInstrumentLoader<'a> {
    provider: &'a InteractiveBrokersInstrumentProvider,
    client: &'a ibapi::Client,
}

impl StartupInstrumentLoader for IbStartupInstrumentLoader<'_> {
    async fn load_instrument_id(
        &self,
        instrument_id: InstrumentId,
    ) -> anyhow::Result<Option<InstrumentId>> {
        self.provider
            .load_with_return_async(self.client, instrument_id, None)
            .await
    }

    async fn load_contract(
        &self,
        contract_spec: &serde_json::Value,
    ) -> anyhow::Result<Vec<InstrumentId>> {
        let contract = parse_contract_from_json(contract_spec)
            .context("Failed to parse configured IB contract")?;
        self.provider
            .load_contract_spec(self.client, &contract, Some(contract_spec))
            .await
    }
}

impl InteractiveBrokersInstrumentProvider {
    /// Create a new `InteractiveBrokersInstrumentProvider`.
    ///
    /// # Arguments
    ///
    /// * `config` - Configuration for the provider
    pub fn new(config: InteractiveBrokersInstrumentProviderConfig) -> Self {
        Self {
            config,
            contract_id_to_instrument_id: Arc::new(DashMap::new()),
            instruments: Arc::new(DashMap::new()),
            contract_details: Arc::new(DashMap::new()),
            contracts: Arc::new(DashMap::new()),
            price_magnifiers: Arc::new(DashMap::new()),
            startup_initialized: Arc::new(tokio::sync::Mutex::new(false)),
        }
    }

    #[cfg(test)]
    pub(crate) fn insert_test_instrument(
        &self,
        instrument: InstrumentAny,
        contract_id: i32,
        price_magnifier: i32,
    ) {
        let instrument_id = instrument.id();
        self.instruments.insert(instrument_id, instrument);
        self.contract_id_to_instrument_id
            .insert(contract_id, instrument_id);
        self.contracts.insert(
            instrument_id,
            Contract {
                contract_id,
                ..Default::default()
            },
        );
        self.price_magnifiers.insert(instrument_id, price_magnifier);
    }

    #[cfg(test)]
    pub(crate) fn insert_test_contract_id_mapping(
        &self,
        contract_id: i32,
        instrument_id: InstrumentId,
    ) {
        self.contract_id_to_instrument_id
            .insert(contract_id, instrument_id);
    }

    /// Initialize the provider by loading cache if configured.
    ///
    /// This is equivalent to Python's `provider.initialize()` method.
    /// It loads instruments from cache if `cache_path` is configured and cache is valid.
    ///
    /// # Errors
    ///
    /// Returns an error if cache loading fails.
    pub async fn initialize(&self) -> anyhow::Result<()> {
        if let Some(ref cache_path) = self.config.cache_path {
            match self.load_cache(cache_path).await {
                Ok(cache_loaded) => {
                    if cache_loaded {
                        tracing::debug!(
                            "Initialized provider with {} instruments from cache",
                            self.count()
                        );
                    } else {
                        tracing::debug!(
                            "Cache file not found or expired, starting with empty cache"
                        );
                    }
                }
                Err(e) => {
                    tracing::warn!("Failed to load cache during initialization: {}", e);
                }
            }
        }
        Ok(())
    }

    /// Initializes the provider and resolves every configured startup input.
    ///
    /// Successful initialization is idempotent. A failed attempt remains retryable.
    ///
    /// # Errors
    ///
    /// Returns an error if initialization fails or any configured input cannot be loaded.
    pub async fn initialize_with_client(
        &self,
        client: &ibapi::Client,
    ) -> anyhow::Result<Vec<InstrumentId>> {
        let loader = IbStartupInstrumentLoader {
            provider: self,
            client,
        };
        self.initialize_with_loader(&loader).await
    }

    async fn initialize_with_loader<L>(&self, loader: &L) -> anyhow::Result<Vec<InstrumentId>>
    where
        L: StartupInstrumentLoader + Sync,
    {
        let mut initialized = self.startup_initialized.lock().await;
        if *initialized {
            return Ok(Vec::new());
        }

        self.initialize().await?;
        let loaded_ids = self.load_configured_instruments(loader).await?;
        *initialized = true;
        Ok(loaded_ids)
    }

    async fn load_configured_instruments<L>(&self, loader: &L) -> anyhow::Result<Vec<InstrumentId>>
    where
        L: StartupInstrumentLoader + Sync,
    {
        let mut loaded_ids = Vec::new();
        let mut unresolved = Vec::new();
        let mut configured_ids: Vec<_> = self.config.load_ids.iter().copied().collect();
        configured_ids.sort_unstable();

        for instrument_id in configured_ids {
            match loader
                .load_instrument_id(instrument_id)
                .await
                .with_context(|| {
                    format!("Failed to load configured IB instrument ID {instrument_id}")
                })? {
                Some(loaded_id) => loaded_ids.push(loaded_id),
                None => unresolved.push(format!("instrument ID {instrument_id}")),
            }
        }

        for (index, contract_spec) in self.config.load_contracts.iter().enumerate() {
            let mut contract_ids =
                loader.load_contract(contract_spec).await.with_context(|| {
                    format!(
                        "Failed to load configured IB contract at index {index}: {contract_spec}"
                    )
                })?;

            if contract_ids.is_empty() {
                unresolved.push(format!("contract at index {index}: {contract_spec}"));
            } else {
                loaded_ids.append(&mut contract_ids);
            }
        }

        if !unresolved.is_empty() {
            anyhow::bail!(
                "Unable to resolve configured Interactive Brokers instruments: {}",
                unresolved.join(", ")
            );
        }

        loaded_ids.sort_unstable();
        loaded_ids.dedup();
        Ok(loaded_ids)
    }

    /// Adds instruments already held by the Nautilus cache into the provider cache.
    ///
    /// This mirrors the Python provider's use of `client._cache` for venue resolution and for
    /// recovering stored IB contract metadata from `instrument.info["contract"]`.
    pub fn add_cached_instruments<I>(&self, instruments: I) -> usize
    where
        I: IntoIterator<Item = InstrumentAny>,
    {
        let mut added = 0;

        for instrument in instruments {
            let instrument_id = instrument.id();
            let Some(contract) = contract_from_instrument_info(&instrument) else {
                continue;
            };
            let price_magnifier = price_magnifier_from_instrument_info(&instrument);

            if self.cache_instrument(
                instrument_id,
                instrument,
                None,
                Some(contract),
                price_magnifier,
                false,
            ) {
                added += 1;
            }
        }
        added
    }

    /// Determine venue from contract using provider configuration.
    ///
    /// This is equivalent to Python's `determine_venue_from_contract` method.
    /// It uses the config's symbol-to-venue mapping and exchange-to-venue conversion settings.
    ///
    /// # Arguments
    ///
    /// * `contract` - The IB contract
    ///
    /// # Returns
    ///
    /// The determined venue.
    pub fn determine_venue(
        &self,
        contract: &Contract,
        contract_details: Option<&ibapi::contracts::ContractDetails>,
    ) -> Venue {
        if matches!(contract.security_type, SecurityType::Stock) {
            return Venue::from(self.resolve_stock_exchange_from_contract(contract).as_str());
        }

        let valid_exchanges = contract_details.map(|details| details.valid_exchanges.join(","));
        let venue_str = determine_venue_from_contract(
            contract,
            &self.config.symbol_to_mic_venue,
            self.config.convert_exchange_to_mic_venue,
            valid_exchanges.as_deref(),
        );
        Venue::from(venue_str.as_str())
    }

    fn resolve_stock_exchange_from_contract(&self, contract: &Contract) -> String {
        let cached_venue = self.resolve_cached_symbol_venue(contract);
        if let Some(venue) = cached_venue.as_deref()
            && Self::is_compatible_cached_stock_venue(venue, contract.primary_exchange.as_str())
        {
            return venue.to_string();
        }

        if !contract.primary_exchange.as_str().is_empty()
            && contract.primary_exchange.as_str() != "SMART"
        {
            return if self.config.convert_exchange_to_mic_venue {
                exchange_to_mic_venue(contract.primary_exchange.as_str())
                    .unwrap_or_else(|| contract.primary_exchange.as_str().to_string())
            } else {
                contract.primary_exchange.as_str().to_string()
            };
        }

        if contract.exchange.as_str() == "SMART"
            && let Some(venue) = cached_venue
        {
            return venue;
        }

        let exchange = contract.exchange.as_str();
        if self.config.convert_exchange_to_mic_venue {
            exchange_to_mic_venue(exchange).unwrap_or_else(|| exchange.to_string())
        } else {
            exchange.to_string()
        }
    }

    fn is_compatible_cached_stock_venue(venue: &str, primary_exchange: &str) -> bool {
        if primary_exchange.is_empty() || primary_exchange == "SMART" {
            return true;
        }

        venue == primary_exchange
            || exchange_to_mic_venue(primary_exchange).is_some_and(|mic| mic == venue)
    }

    fn resolve_cached_symbol_venue(&self, contract: &Contract) -> Option<String> {
        self.instruments.iter().find_map(|entry| {
            let instrument = entry.value();
            let instrument_id = instrument.id();
            (instrument_id.symbol.as_str() == contract.symbol.as_str())
                .then(|| instrument_id.venue.to_string())
        })
    }

    /// Get the symbology method from the provider configuration.
    pub fn symbology_method(&self) -> crate::config::SymbologyMethod {
        self.config.symbology_method
    }

    /// Get an instrument by its ID.
    ///
    /// # Arguments
    ///
    /// * `instrument_id` - The instrument ID to look up
    ///
    /// # Returns
    ///
    /// Returns the instrument if found, `None` otherwise.
    #[must_use]
    pub fn find(&self, instrument_id: &InstrumentId) -> Option<InstrumentAny> {
        self.instruments
            .get(instrument_id)
            .map(|entry| entry.value().clone())
    }

    #[must_use]
    pub(crate) fn find_all(&self, instrument_ids: &[InstrumentId]) -> Vec<InstrumentAny> {
        instrument_ids
            .iter()
            .filter_map(|instrument_id| self.find(instrument_id))
            .collect()
    }

    /// Get an instrument by contract ID.
    ///
    /// # Arguments
    ///
    /// * `contract_id` - The IB contract ID to look up
    ///
    /// # Returns
    ///
    /// Returns the instrument if found, `None` otherwise.
    #[must_use]
    pub fn find_by_contract_id(&self, contract_id: i32) -> Option<InstrumentAny> {
        self.contract_id_to_instrument_id
            .get(&contract_id)
            .and_then(|entry| self.find(entry.value()))
    }

    /// Get an instrument ID by contract ID.
    ///
    /// # Arguments
    ///
    /// * `contract_id` - The IB contract ID to look up
    ///
    /// # Returns
    ///
    /// Returns the instrument ID if found, `None` otherwise.
    #[must_use]
    pub fn get_instrument_id_by_contract_id(&self, contract_id: i32) -> Option<InstrumentId> {
        self.contract_id_to_instrument_id
            .get(&contract_id)
            .map(|entry| *entry.value())
    }

    /// Resolve an instrument ID from an IB contract using provider symbology and venue rules.
    ///
    /// This first checks the provider's contract ID cache, then derives the instrument ID using the
    /// configured symbology method and `determine_venue`.
    ///
    /// # Errors
    ///
    /// Returns an error if the contract cannot be converted to an instrument ID.
    pub fn resolve_instrument_id_for_contract(
        &self,
        contract: &Contract,
    ) -> anyhow::Result<InstrumentId> {
        if contract.contract_id != 0
            && let Some(instrument_id) = self.get_instrument_id_by_contract_id(contract.contract_id)
        {
            return Ok(instrument_id);
        }

        if contract.security_type == SecurityType::Spread {
            return self.resolve_spread_instrument_id_for_contract(contract);
        }

        let venue = self.determine_venue(contract, None);

        match self.config.symbology_method {
            SymbologyMethod::Simplified => {
                ib_contract_to_instrument_id_simplified(contract, Some(venue))
            }
            SymbologyMethod::Raw => ib_contract_to_instrument_id_raw(contract, Some(venue)),
        }
    }

    fn resolve_spread_instrument_id_for_contract(
        &self,
        contract: &Contract,
    ) -> anyhow::Result<InstrumentId> {
        if contract.combo_legs.is_empty() {
            anyhow::bail!("Cannot resolve BAG contract without combo legs or cached contract ID");
        }

        let mut leg_tuples = Vec::with_capacity(contract.combo_legs.len());

        for combo_leg in &contract.combo_legs {
            let leg_instrument_id = self
                .get_instrument_id_by_contract_id(combo_leg.contract_id)
                .with_context(|| {
                    format!(
                        "Cannot resolve BAG leg con_id {} to cached instrument ID",
                        combo_leg.contract_id
                    )
                })?;
            let ratio = IbAction::from_str(combo_leg.action.as_str())
                .context("Invalid BAG combo leg action")?
                .signed_multiplier()
                * combo_leg.ratio;

            leg_tuples.push((leg_instrument_id, ratio));
        }

        let spread_instrument_id = create_spread_instrument_id(&leg_tuples)
            .context("Failed to create spread instrument ID from BAG combo legs")?;

        if self.find(&spread_instrument_id).is_none() {
            anyhow::bail!("Resolved BAG spread {spread_instrument_id} is not cached");
        }

        Ok(spread_instrument_id)
    }

    /// Check if a security type should be filtered.
    ///
    /// # Arguments
    ///
    /// * `sec_type` - The security type to check
    ///
    /// # Returns
    ///
    /// Returns `true` if the security type should be filtered.
    #[must_use]
    pub fn is_filtered_sec_type(&self, sec_type: &str) -> bool {
        self.config
            .filter_sec_types
            .iter()
            .any(|filtered| filtered.eq_ignore_ascii_case(sec_type))
    }

    /// Get all cached instruments.
    ///
    /// # Returns
    ///
    /// Returns a vector of all cached instruments.
    #[must_use]
    pub fn get_all(&self) -> Vec<InstrumentAny> {
        self.instruments
            .iter()
            .map(|entry| entry.value().clone())
            .collect()
    }

    /// Get the number of cached instruments.
    ///
    /// # Returns
    ///
    /// Returns the number of cached instruments.
    #[must_use]
    pub fn count(&self) -> usize {
        self.instruments.len()
    }

    /// Get price magnifier for an instrument ID.
    ///
    /// Price magnifier allows execution and strike prices to be reported consistently
    /// with market data and historical data.
    ///
    /// This method first checks the dedicated price magnifier cache for fast lookup.
    /// If not found, it falls back to checking contract details. If still not found,
    /// it returns the default value of 1 and logs a warning if the instrument exists.
    ///
    /// # Arguments
    ///
    /// * `instrument_id` - The instrument ID to look up
    ///
    /// # Returns
    ///
    /// Returns the price magnifier if found, otherwise 1.
    #[must_use]
    pub fn get_price_magnifier(&self, instrument_id: &InstrumentId) -> i32 {
        // First try dedicated price magnifier cache for fast lookup
        if let Some(magnifier) = self.price_magnifiers.get(instrument_id) {
            return normalize_price_magnifier(*magnifier.value());
        }

        // Fall back to contract details lookup
        if let Some(details) = self.contract_details.get(instrument_id) {
            let magnifier = normalize_price_magnifier(details.value().price_magnifier);
            // Cache it for future fast lookups
            self.price_magnifiers.insert(*instrument_id, magnifier);
            return magnifier;
        }

        // Not found - check if instrument exists (might not have contract details loaded yet)
        if self.instruments.contains_key(instrument_id) {
            tracing::debug!(
                "Price magnifier not found for instrument {} (has instrument but no contract details), using default 1",
                instrument_id
            );
        } else {
            tracing::trace!(
                "Price magnifier not found for instrument {} (instrument not loaded), using default 1",
                instrument_id
            );
        }

        // Default to 1 if not found
        1
    }

    /// Get an instrument by IB Contract.
    ///
    /// This is equivalent to Python's `get_instrument` method.
    /// Supports BAG contracts by auto-loading legs.
    ///
    /// # Arguments
    ///
    /// * `client` - The IB API client
    /// * `contract` - The IB contract to get instrument for
    ///
    /// # Returns
    ///
    /// Returns the instrument if found, `None` otherwise.
    ///
    /// # Errors
    ///
    /// Returns an error if fetching fails.
    pub async fn get_instrument(
        &self,
        client: &ibapi::Client,
        contract: &Contract,
    ) -> anyhow::Result<Option<InstrumentAny>> {
        log::debug!(
            "IB get_instrument request sec_type={:?} con_id={} symbol={} local_symbol={} exchange={} expiry={}",
            contract.security_type,
            contract.contract_id,
            contract.symbol.as_str(),
            contract.local_symbol.as_str(),
            contract.exchange.as_str(),
            contract.last_trade_date_or_contract_month.as_str()
        );
        // Check if security type is filtered
        let sec_type_str = security_type_code(&contract.security_type);
        if self.is_filtered_sec_type(&sec_type_str) {
            tracing::warn!(
                "Skipping filtered security type {} for contract",
                sec_type_str
            );
            return Ok(None);
        }

        let contract_id = contract.contract_id;

        // Check if we already have this instrument by contract ID
        if let Some(cached_instrument_id) = self.contract_id_to_instrument_id.get(&contract_id) {
            log::debug!(
                "IB get_instrument cache hit for contract_id={} -> {}",
                contract_id,
                cached_instrument_id.value()
            );

            if let Some(instrument) = self.find(cached_instrument_id.value()) {
                return Ok(Some(instrument));
            }
        }

        // Special handling for BAG contracts
        if contract.security_type == SecurityType::Spread && !contract.combo_legs.is_empty() {
            // Load BAG contract (which auto-loads legs and creates spread instrument)
            self.fetch_bag_contract(client, contract).await?;

            // Get the spread instrument ID that was created
            if let Some(spread_instrument_id) = self.contract_id_to_instrument_id.get(&contract_id)
            {
                return Ok(self.find(spread_instrument_id.value()));
            }

            if let Ok(spread_instrument_id) =
                self.resolve_spread_instrument_id_for_contract(contract)
            {
                return Ok(self.find(&spread_instrument_id));
            }
        }

        // For non-BAG contracts, fetch contract details and load
        let details_vec = client
            .contract_details(contract)
            .await
            .context("Failed to fetch contract details from IB")?;

        log::debug!(
            "IB get_instrument received {} contract details for sec_type={:?} symbol={} local_symbol={}",
            details_vec.len(),
            contract.security_type,
            contract.symbol.as_str(),
            contract.local_symbol.as_str()
        );

        if details_vec.is_empty() {
            tracing::warn!("No contract details returned for contract {}", contract_id);
            return Ok(None);
        }

        let loaded_ids = self.process_contract_details(details_vec, None, false);

        if contract_id != 0
            && let Some(instrument) = self.find_by_contract_id(contract_id)
        {
            return Ok(Some(instrument));
        }

        Ok(loaded_ids
            .first()
            .and_then(|instrument_id| self.find(instrument_id)))
    }

    pub(crate) async fn load_contract_spec(
        &self,
        client: &ibapi::Client,
        contract: &Contract,
        spec: Option<&serde_json::Value>,
    ) -> anyhow::Result<Vec<InstrumentId>> {
        let mut loaded_ids = Vec::new();
        let build_futures_chain = json_bool(spec, "build_futures_chain")
            || self.config.build_futures_chain.unwrap_or(false);
        let build_options_chain = json_bool(spec, "build_options_chain")
            || self.config.build_options_chain.unwrap_or(false);
        let min_expiry_days = json_u32(spec, "min_expiry_days").or(self.config.min_expiry_days);
        let max_expiry_days = json_u32(spec, "max_expiry_days").or(self.config.max_expiry_days);
        let options_chain_exchange = json_string(spec, "options_chain_exchange")
            .or_else(|| json_string(spec, "optionsChainExchange"));
        let chain_contract = if contract.security_type == SecurityType::ContinuousFuture
            && (build_futures_chain || build_options_chain)
        {
            match client.contract_details(contract).await {
                Ok(details_vec) => details_vec
                    .into_iter()
                    .next()
                    .map(|details| {
                        tracing::debug!(
                            "Qualified continuous future contract {}.{} as local_symbol={} trading_class={} con_id={}",
                            contract.symbol.as_str(),
                            contract.exchange.as_str(),
                            details.contract.local_symbol.as_str(),
                            details.contract.trading_class.as_str(),
                            details.contract.contract_id,
                        );
                        details.contract
                    })
                    .unwrap_or_else(|| contract.clone()),
                Err(e) if e.is_connection_lost() => {
                    return Err(e).context("Failed to qualify continuous future contract");
                }
                Err(e) => {
                    tracing::warn!(
                        "Failed to qualify continuous future contract {:?}: {}",
                        contract,
                        e
                    );
                    contract.clone()
                }
            }
        } else {
            contract.clone()
        };
        let chain_trading_class = (!chain_contract.trading_class.is_empty())
            .then_some(chain_contract.trading_class.as_str());

        if build_futures_chain {
            let loaded = self
                .fetch_futures_chain(
                    client,
                    chain_contract.symbol.as_str(),
                    chain_contract.exchange.as_str(),
                    chain_contract.currency.as_str(),
                    chain_trading_class,
                    contract.security_type == SecurityType::ContinuousFuture,
                    min_expiry_days,
                    max_expiry_days,
                )
                .await?;
            tracing::debug!(
                "Loaded {} futures instruments for chain request {}.{}",
                loaded,
                chain_contract.symbol.as_str(),
                chain_contract.exchange.as_str(),
            );
            loaded_ids.extend(self.cached_contract_ids_for(
                chain_contract.symbol.as_str(),
                chain_contract.exchange.as_str(),
                &[SecurityType::Future],
            ));
        }

        if build_options_chain {
            let expiry_min = expiry_bound_from_days(min_expiry_days);
            let expiry_max = expiry_bound_from_days(max_expiry_days);
            let mut underlyings = Vec::new();

            if contract.security_type == SecurityType::ContinuousFuture {
                if !build_futures_chain {
                    self.fetch_futures_chain(
                        client,
                        chain_contract.symbol.as_str(),
                        chain_contract.exchange.as_str(),
                        chain_contract.currency.as_str(),
                        chain_trading_class,
                        true,
                        min_expiry_days,
                        max_expiry_days,
                    )
                    .await?;
                }

                underlyings.extend(
                    self.cached_contracts_for(
                        contract.symbol.as_str(),
                        chain_contract.exchange.as_str(),
                        &[SecurityType::Future],
                    )
                    .into_iter()
                    .map(|(_, contract)| contract),
                );
            } else if let Some(instrument) = self.get_instrument(client, contract).await? {
                let instrument_id = instrument.id();
                loaded_ids.push(instrument_id);
                if let Some(underlying) = self.instrument_id_to_ib_contract(&instrument_id) {
                    underlyings.push(underlying);
                }
            }

            for underlying in underlyings {
                let loaded = self
                    .fetch_option_chain_by_range(
                        client,
                        &underlying,
                        expiry_min.as_deref(),
                        expiry_max.as_deref(),
                        options_chain_exchange.as_deref(),
                    )
                    .await?;
                tracing::debug!(
                    "Loaded {} option instruments for chain request {}.{}",
                    loaded,
                    underlying.symbol.as_str(),
                    underlying.exchange.as_str(),
                );
            }

            loaded_ids.extend(
                self.cached_contract_ids_for(
                    contract.symbol.as_str(),
                    options_chain_exchange
                        .as_deref()
                        .unwrap_or_else(|| contract.exchange.as_str()),
                    &[SecurityType::Option, SecurityType::FuturesOption],
                ),
            );
        }

        if !build_futures_chain
            && !build_options_chain
            && let Some(instrument) = self.get_instrument(client, contract).await?
        {
            loaded_ids.push(instrument.id());
        }

        loaded_ids.sort_unstable();
        loaded_ids.dedup();
        Ok(loaded_ids)
    }

    fn cached_contract_ids_for(
        &self,
        symbol: &str,
        exchange: &str,
        security_types: &[SecurityType],
    ) -> Vec<InstrumentId> {
        self.cached_contracts_for(symbol, exchange, security_types)
            .into_iter()
            .map(|(instrument_id, _)| instrument_id)
            .collect()
    }

    fn cached_contracts_for(
        &self,
        symbol: &str,
        exchange: &str,
        security_types: &[SecurityType],
    ) -> Vec<(InstrumentId, Contract)> {
        self.contracts
            .iter()
            .filter_map(|entry| {
                let instrument_id = *entry.key();
                let contract = entry.value();
                let exchange_matches =
                    exchange.is_empty() || contract.exchange.as_str() == exchange;
                if contract.symbol.as_str() == symbol
                    && exchange_matches
                    && security_types.contains(&contract.security_type)
                {
                    Some((instrument_id, contract.clone()))
                } else {
                    None
                }
            })
            .collect()
    }

    /// Convert an instrument ID to IB contract details.
    ///
    /// This is equivalent to Python's `instrument_id_to_ib_contract_details` method.
    ///
    /// # Arguments
    ///
    /// * `instrument_id` - The instrument ID to convert
    ///
    /// # Returns
    ///
    /// Returns the contract details if found, `None` otherwise.
    #[must_use]
    pub fn instrument_id_to_ib_contract_details(
        &self,
        instrument_id: &InstrumentId,
    ) -> Option<ibapi::contracts::ContractDetails> {
        self.contract_details
            .get(instrument_id)
            .map(|entry| entry.value().clone())
    }

    #[must_use]
    pub fn instrument_id_to_ib_contract(&self, instrument_id: &InstrumentId) -> Option<Contract> {
        self.contracts
            .get(instrument_id)
            .map(|entry| entry.value().clone())
    }

    pub fn resolve_contract_for_instrument(
        &self,
        instrument_id: InstrumentId,
    ) -> anyhow::Result<Contract> {
        let cached_contract = self.instrument_id_to_ib_contract(&instrument_id);
        if let Some(contract) = cached_contract.as_ref()
            && (contract.contract_id != 0 || is_spread_instrument_id(&instrument_id))
        {
            return Ok(contract.clone());
        }

        if let Some(details) = self.instrument_id_to_ib_contract_details(&instrument_id) {
            return Ok(details.contract);
        }

        if let Some(contract) = cached_contract {
            return Ok(contract);
        }

        instrument_id_to_ib_contract(instrument_id, None)
    }

    pub async fn resolve_contract_for_instrument_async(
        &self,
        client: &ibapi::Client,
        instrument_id: InstrumentId,
    ) -> anyhow::Result<Contract> {
        if let Ok(contract) = self.resolve_contract_for_instrument(instrument_id)
            && (contract.contract_id != 0 || self.contract_details.contains_key(&instrument_id))
        {
            return Ok(contract);
        }

        if is_spread_instrument_id(&instrument_id) {
            self.fetch_spread_instrument(client, instrument_id, false, None)
                .await?;
        } else {
            self.fetch_contract_details(client, instrument_id, false, None)
                .await?;
        }

        self.resolve_contract_for_instrument(instrument_id)
    }

    /// Load a single instrument (does not return loaded IDs).
    ///
    /// This is equivalent to Python's `load_async` method.
    ///
    /// # Arguments
    ///
    /// * `client` - The IB API client
    /// * `instrument_id` - The instrument ID to load
    /// * `force_instrument_update` - If true, force re-fetch even if already cached
    ///
    /// # Errors
    ///
    /// Returns an error if loading fails.
    pub async fn load_async(
        &self,
        client: &ibapi::Client,
        instrument_id: InstrumentId,
        filters: Option<HashMap<String, String>>,
    ) -> anyhow::Result<()> {
        let filters: Option<HashMap<String, String>> = filters;
        let force_instrument_update = filters
            .as_ref()
            .and_then(|f| f.get("force_instrument_update"))
            .map(|v| v == "true")
            .unwrap_or(false);

        self.fetch_contract_details(client, instrument_id, force_instrument_update, filters)
            .await
    }

    /// Load a single instrument and return the loaded instrument ID.
    ///
    /// This is equivalent to Python's `load_with_return_async` method.
    ///
    /// # Arguments
    ///
    /// * `client` - The IB API client
    /// * `instrument_id` - The instrument ID to load
    /// * `force_instrument_update` - If true, force re-fetch even if already cached
    ///
    /// # Returns
    ///
    /// Returns the loaded instrument ID if successful, `None` otherwise.
    ///
    /// # Errors
    ///
    /// Returns an error if loading fails.
    pub async fn load_with_return_async(
        &self,
        client: &ibapi::Client,
        instrument_id: InstrumentId,
        filters: Option<HashMap<String, String>>,
    ) -> anyhow::Result<Option<InstrumentId>> {
        let filters: Option<HashMap<String, String>> = filters;
        let force_instrument_update = filters
            .as_ref()
            .and_then(|f| f.get("force_instrument_update"))
            .map(|v| v == "true")
            .unwrap_or(false);

        if is_spread_instrument_id(&instrument_id) {
            self.fetch_spread_instrument(client, instrument_id, force_instrument_update, filters)
                .await?;
        } else {
            self.fetch_contract_details(client, instrument_id, force_instrument_update, filters)
                .await?;
        }

        if self.instruments.contains_key(&instrument_id) {
            Ok(Some(instrument_id))
        } else {
            Ok(None)
        }
    }

    pub async fn load_contract_with_return_async(
        &self,
        client: &ibapi::Client,
        contract: &Contract,
        spec: Option<&serde_json::Value>,
    ) -> anyhow::Result<Vec<InstrumentId>> {
        self.load_contract_spec(client, contract, spec).await
    }

    /// Load multiple instruments (does not return loaded IDs).
    ///
    /// This is equivalent to Python's `load_ids_async` method.
    ///
    /// # Arguments
    ///
    /// * `client` - The IB API client
    /// * `instrument_ids` - Vector of instrument IDs to load
    /// * `force_instrument_update` - If true, force re-fetch even if already cached
    ///
    /// # Errors
    ///
    /// Returns an error if loading fails.
    pub async fn load_ids_async(
        &self,
        client: &ibapi::Client,
        instrument_ids: Vec<InstrumentId>,
        filters: Option<HashMap<String, String>>,
    ) -> anyhow::Result<()> {
        let filters: Option<HashMap<String, String>> = filters;
        let force_instrument_update = filters
            .as_ref()
            .and_then(|f| f.get("force_instrument_update"))
            .map(|v| v == "true")
            .unwrap_or(false);

        for instrument_id in instrument_ids {
            let load_result = if is_spread_instrument_id(&instrument_id) {
                self.fetch_spread_instrument(
                    client,
                    instrument_id,
                    force_instrument_update,
                    filters.clone(),
                )
                .await
                .map(|_| ())
            } else {
                self.fetch_contract_details(
                    client,
                    instrument_id,
                    force_instrument_update,
                    filters.clone(),
                )
                .await
            };

            if let Err(e) = load_result {
                tracing::warn!("Failed to load instrument {}: {}", instrument_id, e);
            }
        }
        Ok(())
    }

    /// Load multiple instruments and return the loaded instrument IDs.
    ///
    /// This is equivalent to Python's `load_ids_with_return_async` method.
    ///
    /// # Arguments
    ///
    /// * `client` - The IB API client
    /// * `instrument_ids` - Vector of instrument IDs to load
    /// * `force_instrument_update` - If true, force re-fetch even if already cached
    ///
    /// # Returns
    ///
    /// Returns a vector of successfully loaded instrument IDs.
    ///
    /// # Errors
    ///
    /// Returns an error if loading fails.
    pub async fn load_ids_with_return_async(
        &self,
        client: &ibapi::Client,
        instrument_ids: Vec<InstrumentId>,
        filters: Option<HashMap<String, String>>,
    ) -> anyhow::Result<Vec<InstrumentId>> {
        let mut loaded_ids = Vec::new();

        for instrument_id in instrument_ids {
            match self
                .load_with_return_async(client, instrument_id, filters.clone())
                .await
            {
                Ok(Some(loaded_id)) => loaded_ids.push(loaded_id),
                Ok(None) => {}
                Err(e) => {
                    tracing::warn!("Failed to load instrument {}: {}", instrument_id, e);
                }
            }
        }

        Ok(loaded_ids)
    }

    fn create_bag_contract_from_legs(
        &self,
        leg_contract_details: &[(ibapi::contracts::ContractDetails, i32)],
        instrument_id: Option<InstrumentId>,
        bag_contract: Option<&Contract>,
    ) -> anyhow::Result<Contract> {
        if let Some(bag_contract) = bag_contract {
            return Ok(bag_contract.clone());
        }

        let (first_details, _) = leg_contract_details
            .first()
            .ok_or_else(|| anyhow::anyhow!("Cannot create BAG contract without leg details"))?;

        let combo_legs = leg_contract_details
            .iter()
            .map(|(details, ratio)| ibapi::contracts::ComboLeg {
                contract_id: details.contract.contract_id,
                ratio: ratio.abs(),
                action: if *ratio > 0 {
                    LegAction::Buy
                } else {
                    LegAction::Sell
                },
                exchange: details.contract.exchange.to_string(),
                open_close: ComboLegOpenClose::Same,
                short_sale_slot: 0,
                designated_location: String::new(),
                exempt_code: -1,
            })
            .collect();

        Ok(Contract {
            contract_id: 0,
            symbol: first_details.contract.symbol.clone(),
            security_type: SecurityType::Spread,
            exchange: Exchange::from("SMART"),
            currency: first_details.contract.currency.clone(),
            local_symbol: instrument_id.map_or_else(String::new, |id| id.symbol.to_string()),
            combo_legs_description: instrument_id
                .map(|id| format!("Spread: {}", id.symbol))
                .unwrap_or_else(|| "Spread".to_string()),
            combo_legs,
            ..Default::default()
        })
    }

    /// Fetch a spread instrument by loading its individual legs.
    ///
    /// This is equivalent to Python's `_fetch_spread_instrument` method.
    /// It parses the spread instrument ID to extract leg tuples, loads each leg,
    /// and then creates the spread instrument.
    ///
    /// # Arguments
    ///
    /// * `client` - The IB API client
    /// * `spread_instrument_id` - The spread instrument ID to fetch
    /// * `force_instrument_update` - If true, force re-fetch even if already cached
    ///
    /// # Returns
    ///
    /// Returns `true` if the spread instrument was successfully loaded, `false` otherwise.
    ///
    /// # Errors
    ///
    /// Returns an error if parsing or loading fails.
    pub async fn fetch_spread_instrument(
        &self,
        client: &ibapi::Client,
        spread_instrument_id: InstrumentId,
        force_instrument_update: bool,
        filters: Option<HashMap<String, String>>,
    ) -> anyhow::Result<bool> {
        // Check if already cached (unless forcing update)
        if !force_instrument_update && self.instruments.contains_key(&spread_instrument_id) {
            tracing::debug!("Spread instrument {} already cached", spread_instrument_id);
            return Ok(true);
        }

        // Parse the spread ID to get individual legs
        let leg_tuples = parse_spread_instrument_id_to_legs(&spread_instrument_id)
            .context("Failed to parse spread instrument ID to leg tuples")?;

        if leg_tuples.is_empty() {
            tracing::error!("Spread instrument {} has no legs", spread_instrument_id);
            return Ok(false);
        }

        tracing::debug!(
            "Loading spread instrument {} with {} legs",
            spread_instrument_id,
            leg_tuples.len()
        );

        // First, load all individual leg instruments to get their contract details
        let mut leg_contract_details = Vec::new();

        for (leg_instrument_id, ratio) in &leg_tuples {
            tracing::debug!(
                "Loading leg instrument: {} (ratio: {})",
                leg_instrument_id,
                ratio
            );

            // Load the individual leg instrument
            self.fetch_contract_details(
                client,
                *leg_instrument_id,
                force_instrument_update,
                filters.clone(),
            )
            .await
            .with_context(|| format!("Failed to load leg instrument: {}", leg_instrument_id))?;

            // Get the contract details for this leg
            let leg_details = self
                .contract_details
                .get(leg_instrument_id)
                .map(|entry| entry.value().clone())
                .ok_or_else(|| {
                    anyhow::anyhow!(
                        "Leg instrument {} not found in contract details after loading",
                        leg_instrument_id
                    )
                })?;

            leg_contract_details.push((leg_details, *ratio));
        }

        // Create the spread instrument
        let timestamp = nautilus_core::time::get_atomic_clock_realtime().get_time_ns();
        let leg_details_refs: Vec<(&ibapi::contracts::ContractDetails, i32)> =
            leg_contract_details.iter().map(|(d, r)| (d, *r)).collect();

        let bag_contract = self.create_bag_contract_from_legs(
            &leg_contract_details,
            Some(spread_instrument_id),
            None,
        )?;
        let spread_instrument = parse_spread_instrument_any(
            spread_instrument_id,
            &leg_details_refs,
            Some(&bag_contract),
            Some(timestamp),
        )
        .context("Failed to parse spread instrument")?;

        // Cache the spread instrument
        self.instruments
            .insert(spread_instrument_id, spread_instrument);
        self.contracts.insert(spread_instrument_id, bag_contract);

        if let Some((first_details, _)) = leg_contract_details.first() {
            self.price_magnifiers
                .insert(spread_instrument_id, first_details.price_magnifier);
        }

        tracing::debug!(
            "Successfully loaded spread instrument {}",
            spread_instrument_id
        );
        Ok(true)
    }

    /// Load all instruments from provided IDs and contracts.
    ///
    /// This is equivalent to Python's `load_all_async` method.
    /// Python version loads from config's `_load_ids_on_start` and `_load_contracts_on_start`.
    /// Rust version accepts these as parameters for flexibility.
    ///
    /// # Arguments
    ///
    /// * `client` - The IB API client
    /// * `instrument_ids` - Optional vector of instrument IDs to load
    /// * `contracts` - Optional vector of IB contracts to load
    /// * `force_instrument_update` - If true, force re-fetch even if already cached
    ///
    /// # Errors
    ///
    /// Returns an error if loading fails.
    pub async fn load_all_async(
        &self,
        client: &ibapi::Client,
        instrument_ids: Option<Vec<InstrumentId>>,
        contracts: Option<Vec<Contract>>,
        force_instrument_update: bool,
    ) -> anyhow::Result<Vec<InstrumentId>> {
        let mut loaded_ids = Vec::new();

        // Load from instrument IDs
        let ids_to_load =
            instrument_ids.unwrap_or_else(|| self.config.load_ids.iter().cloned().collect());

        if !ids_to_load.is_empty() {
            let mut filters = std::collections::HashMap::new();

            if force_instrument_update {
                filters.insert("force_instrument_update".to_string(), "true".to_string());
            }
            let filters = if filters.is_empty() {
                None
            } else {
                Some(filters)
            };

            let ids_result = self
                .load_ids_with_return_async(client, ids_to_load, filters)
                .await
                .context("Failed to load instruments from IDs")?;
            loaded_ids.extend(ids_result);
        }

        // Load from contracts
        if let Some(contracts_to_load) = contracts {
            for contract in contracts_to_load {
                match self.load_contract_spec(client, &contract, None).await {
                    Ok(mut instrument_ids) => {
                        loaded_ids.append(&mut instrument_ids);
                    }
                    Err(e) => {
                        tracing::warn!(
                            "Error loading instrument from contract {:?}: {}",
                            contract,
                            e
                        );
                    }
                }
            }
        } else {
            for contract_json in &self.config.load_contracts {
                match crate::common::contracts::parse_contract_from_json(contract_json)
                    .context("Failed to parse contract from config JSON")
                {
                    Ok(contract) => match self
                        .load_contract_spec(client, &contract, Some(contract_json))
                        .await
                    {
                        Ok(mut instrument_ids) => {
                            loaded_ids.append(&mut instrument_ids);
                        }
                        Err(e) => {
                            tracing::warn!(
                                "Error loading instrument from contract {:?}: {}",
                                contract,
                                e
                            );
                        }
                    },
                    Err(e) => {
                        tracing::warn!(
                            "Error parsing load contract spec {:?}: {}",
                            contract_json,
                            e
                        );
                    }
                }
            }
        }

        if loaded_ids.is_empty() {
            tracing::debug!("load_all_async called but no instruments were loaded");
        } else {
            tracing::debug!("load_all_async loaded {} instruments", loaded_ids.len());
        }

        Ok(loaded_ids)
    }
}

fn normalize_price_magnifier(price_magnifier: i32) -> i32 {
    if price_magnifier > 0 {
        price_magnifier
    } else {
        1
    }
}

fn security_type_code(security_type: &SecurityType) -> String {
    security_type.to_string()
}

fn json_bool(spec: Option<&serde_json::Value>, key: &str) -> bool {
    spec.and_then(|value| value.get(key))
        .and_then(serde_json::Value::as_bool)
        .unwrap_or(false)
}

fn json_u32(spec: Option<&serde_json::Value>, key: &str) -> Option<u32> {
    spec.and_then(|value| value.get(key))
        .and_then(serde_json::Value::as_u64)
        .and_then(|value| u32::try_from(value).ok())
}

fn json_string(spec: Option<&serde_json::Value>, key: &str) -> Option<String> {
    spec.and_then(|value| value.get(key))
        .and_then(serde_json::Value::as_str)
        .filter(|value| !value.is_empty())
        .map(ToString::to_string)
}

fn contract_from_instrument_info(instrument: &InstrumentAny) -> Option<Contract> {
    let value = serde_json::to_value(instrument).ok()?;
    let contract_json = find_contract_json(&value)?;
    parse_contract_from_json(contract_json).ok()
}

fn price_magnifier_from_instrument_info(instrument: &InstrumentAny) -> Option<i32> {
    let value = serde_json::to_value(instrument).ok()?;
    let price_magnifier = find_price_magnifier_json(&value)?;
    parse_i32_json(price_magnifier)
}

fn find_contract_json(value: &serde_json::Value) -> Option<&serde_json::Value> {
    if let Some(contract_json) = value.get("info").and_then(|info| info.get("contract")) {
        return Some(contract_json);
    }

    value.as_object()?.values().find_map(find_contract_json)
}

fn find_price_magnifier_json(value: &serde_json::Value) -> Option<&serde_json::Value> {
    if let Some(info) = value.get("info")
        && let Some(price_magnifier) = info
            .get("priceMagnifier")
            .or_else(|| info.get("price_magnifier"))
    {
        return Some(price_magnifier);
    }

    value
        .as_object()?
        .values()
        .find_map(find_price_magnifier_json)
}

fn parse_i32_json(value: &serde_json::Value) -> Option<i32> {
    if let Some(value) = value.as_i64() {
        return i32::try_from(value).ok();
    }

    if let Some(value) = value.as_u64() {
        return i32::try_from(value).ok();
    }

    value.as_str()?.parse::<i32>().ok()
}

fn expiry_bound_from_days(days: Option<u32>) -> Option<String> {
    days.map(|days| {
        Offset::UTC
            .to_datetime(Timestamp::now())
            .date()
            .checked_add(Span::new().days(i64::from(days)))
            .expect("expiry bound date in range")
            .strftime("%Y%m%d")
            .to_string()
    })
}

impl InteractiveBrokersInstrumentProvider {
    /// Fetch and cache contract details for an instrument ID using the provided IB client.
    ///
    /// # Arguments
    ///
    /// * `client` - The IB API client
    /// * `instrument_id` - The instrument ID to fetch
    ///
    /// # Errors
    ///
    /// Returns an error if fetching fails.
    pub async fn fetch_contract_details(
        &self,
        client: &ibapi::Client,
        instrument_id: InstrumentId,
        force_instrument_update: bool,
        filters: Option<HashMap<String, String>>,
    ) -> anyhow::Result<()> {
        if !force_instrument_update {
            if self.instruments.contains_key(&instrument_id)
                && (self.contract_details.contains_key(&instrument_id)
                    || self.contracts.contains_key(&instrument_id))
            {
                tracing::debug!(
                    "Instrument {} already cached, skipping fetch",
                    instrument_id
                );
                return Ok(());
            }
        }
        // Convert instrument ID to IB contract
        let exchange = filters
            .as_ref()
            .and_then(|f| f.get("exchange"))
            .map(|s| s.as_str());

        let exchanges_to_try: Vec<String> = if let Some(exchange) = exchange {
            vec![exchange.to_string()]
        } else {
            possible_exchanges_for_venue(instrument_id.venue.as_str())
        };

        let mut details_vec = Vec::new();
        let mut last_error = None;

        for candidate_exchange in exchanges_to_try {
            let contract = instrument_id_to_ib_contract(instrument_id, Some(candidate_exchange.as_str()))
                .with_context(|| format!("Failed to convert instrument_id {} to IB contract. Check that the instrument ID format is correct and the venue/symbol are valid.", instrument_id))?;

            match client.contract_details(&contract).await {
                Ok(result) if !result.is_empty() => {
                    details_vec = result;
                    break;
                }
                Ok(_) => {}
                Err(e) => {
                    last_error = Some((candidate_exchange.clone(), e));
                }
            }
        }

        if details_vec.is_empty() {
            if let Some((candidate_exchange, e)) = last_error {
                return Err(e).with_context(|| {
                    format!(
                        "Failed to fetch contract details for {instrument_id} on {candidate_exchange}"
                    )
                });
            } else {
                tracing::warn!(
                    "No contract details returned for {} - instrument may not exist in IB or contract specification is incomplete",
                    instrument_id
                );
            }
            return Ok(());
        }

        let loaded_ids = self.process_contract_details(
            details_vec,
            Some(instrument_id.venue),
            force_instrument_update,
        );

        if loaded_ids.is_empty() {
            tracing::warn!("No contract details were processed for {}", instrument_id);
        } else {
            tracing::debug!(
                "Successfully loaded {} instrument(s) for {}",
                loaded_ids.len(),
                instrument_id
            );
        }
        Ok(())
    }

    fn process_contract_details(
        &self,
        details_vec: Vec<ibapi::contracts::ContractDetails>,
        venue: Option<Venue>,
        force_instrument_update: bool,
    ) -> Vec<InstrumentId> {
        let mut processed_ids = Vec::new();

        for details in details_vec {
            match self.process_contract_detail(&details, venue, force_instrument_update) {
                Ok(Some(instrument_id)) => processed_ids.push(instrument_id),
                Ok(None) => {}
                Err(e) => {
                    tracing::warn!(
                        "Failed to process IB contract details con_id={} sec_type={}: {}",
                        details.contract.contract_id,
                        security_type_code(&details.contract.security_type),
                        e
                    );
                }
            }
        }

        processed_ids
    }

    fn process_contract_detail(
        &self,
        details: &ibapi::contracts::ContractDetails,
        venue: Option<Venue>,
        force_instrument_update: bool,
    ) -> anyhow::Result<Option<InstrumentId>> {
        let sec_type = security_type_code(&details.contract.security_type);
        if self.is_filtered_sec_type(&sec_type) {
            tracing::warn!(
                "Skipping filtered security type {} for contract {:?}",
                sec_type,
                details.contract
            );
            return Ok(None);
        }

        let resolved_venue =
            venue.unwrap_or_else(|| self.determine_venue(&details.contract, Some(details)));
        let instrument_id = self
            .instrument_id_from_contract(&details.contract, resolved_venue)
            .context("Failed to convert IB contract to instrument ID")?;
        let instrument = match parse_ib_contract_to_instrument(details, instrument_id) {
            Ok(instrument) => instrument,
            Err(e) => {
                tracing::warn!(
                    "Failed to parse IB contract details for {}: {}",
                    instrument_id,
                    e
                );
                return Ok(None);
            }
        };

        if !self.passes_filter_callable(&instrument)? {
            return Ok(None);
        }

        self.cache_instrument(
            instrument_id,
            instrument,
            Some(details.clone()),
            None,
            None,
            force_instrument_update,
        );

        Ok(Some(instrument_id))
    }

    fn instrument_id_from_contract(
        &self,
        contract: &Contract,
        venue: Venue,
    ) -> anyhow::Result<InstrumentId> {
        match self.config.symbology_method {
            SymbologyMethod::Simplified => {
                ib_contract_to_instrument_id_simplified(contract, Some(venue))
            }
            SymbologyMethod::Raw => ib_contract_to_instrument_id_raw(contract, Some(venue)),
        }
    }

    fn cache_instrument(
        &self,
        instrument_id: InstrumentId,
        instrument: InstrumentAny,
        details: Option<ibapi::contracts::ContractDetails>,
        contract: Option<Contract>,
        price_magnifier: Option<i32>,
        force_instrument_update: bool,
    ) -> bool {
        let should_update =
            force_instrument_update || !self.instruments.contains_key(&instrument_id);

        if should_update {
            self.instruments.insert(instrument_id, instrument);
        }

        if let Some(details) = details {
            let contract_id = details.contract.contract_id;
            self.contracts
                .insert(instrument_id, details.contract.clone());
            self.contract_details.insert(instrument_id, details.clone());

            if contract_id != 0 {
                self.contract_id_to_instrument_id
                    .insert(contract_id, instrument_id);
            }
            self.price_magnifiers.insert(
                instrument_id,
                normalize_price_magnifier(details.price_magnifier),
            );
        } else if let Some(contract) = contract {
            if contract.contract_id != 0 {
                self.contract_id_to_instrument_id
                    .insert(contract.contract_id, instrument_id);
            }
            self.contracts.insert(instrument_id, contract);
        }

        if let Some(price_magnifier) = price_magnifier {
            self.price_magnifiers
                .insert(instrument_id, normalize_price_magnifier(price_magnifier));
        }

        should_update
    }

    fn passes_filter_callable(&self, instrument: &InstrumentAny) -> anyhow::Result<bool> {
        let Some(filter_callable) = self.config.filter_callable.as_deref() else {
            return Ok(true);
        };

        #[cfg(feature = "python")]
        {
            use nautilus_model::python::instruments::instrument_any_to_pyobject;
            use pyo3::{prelude::*, types::PyModule};

            Python::attach(|py| {
                let (module_name, callable_name) =
                    filter_callable.rsplit_once('.').ok_or_else(|| {
                        anyhow::anyhow!(
                            "Invalid filter_callable path {filter_callable:?}; expected module.callable"
                        )
                    })?;
                let callable = PyModule::import(py, module_name)
                    .map_err(|e| anyhow::anyhow!("Failed to import {module_name}: {e}"))?
                    .getattr(callable_name)
                    .map_err(|e| anyhow::anyhow!("Failed to resolve {filter_callable}: {e}"))?;
                let py_instrument = instrument_any_to_pyobject(py, instrument.clone())
                    .map_err(|e| anyhow::anyhow!("Failed to convert instrument to Python: {e}"))?;
                callable
                    .call1((py_instrument,))
                    .and_then(|result| result.extract::<bool>())
                    .map_err(|e| anyhow::anyhow!("filter_callable {filter_callable} failed: {e}"))
            })
        }

        #[cfg(not(feature = "python"))]
        {
            let _ = instrument;
            anyhow::bail!(
                "filter_callable {filter_callable:?} requires the Interactive Brokers adapter to be built with the python feature"
            );
        }
    }

    /// Batch load multiple instrument IDs.
    ///
    /// This method fetches and caches contract details for multiple instrument IDs in parallel.
    ///
    /// # Arguments
    ///
    /// * `client` - The IB API client
    /// * `instrument_ids` - Vector of instrument IDs to load
    /// * `filters` - Optional filters to apply (not yet implemented, reserved for future use)
    ///
    /// # Returns
    ///
    /// Returns a vector of successfully loaded instrument IDs.
    ///
    /// # Errors
    ///
    /// Returns an error if fetching fails.
    pub async fn batch_load(
        &self,
        client: &ibapi::Client,
        instrument_ids: Vec<InstrumentId>,
        filters: Option<&[String]>,
    ) -> anyhow::Result<Vec<InstrumentId>> {
        let mut loaded_ids = Vec::new();

        // Apply filters if provided
        let filtered_ids: Vec<InstrumentId> = if let Some(filter_list) = filters {
            // Filter instrument IDs by matching against filter patterns
            // Filters can be:
            // - Security type filters (e.g., "STK", "OPT", "FUT")
            // - Venue filters (e.g., "SMART", "NASDAQ")
            // - Symbol patterns (partial matching)
            instrument_ids
                .into_iter()
                .filter(|instrument_id| {
                    // Check if instrument matches any filter
                    for filter in filter_list {
                        // Check symbol match (case-insensitive partial match)
                        if instrument_id
                            .symbol
                            .as_str()
                            .to_lowercase()
                            .contains(&filter.to_lowercase())
                        {
                            return true;
                        }

                        // Check venue match
                        if instrument_id.venue.as_str() == filter {
                            return true;
                        }

                        // Check security type (try to infer from instrument)
                        if let Some(contract_details) = self.contract_details.get(instrument_id) {
                            let sec_type_str =
                                security_type_code(&contract_details.contract.security_type);

                            if sec_type_str.to_uppercase().contains(&filter.to_uppercase()) {
                                return true;
                            }
                        }
                    }
                    false
                })
                .collect()
        } else {
            instrument_ids
        };

        // Load instruments sequentially (can be parallelized in future if needed)
        let filtered_count = filtered_ids.len();
        for instrument_id in filtered_ids {
            match self
                .fetch_contract_details(client, instrument_id, false, None)
                .await
            {
                Ok(()) => loaded_ids.push(instrument_id),
                Err(e) => {
                    tracing::warn!("Failed to load instrument {}: {}", instrument_id, e);
                }
            }
        }

        tracing::debug!(
            "Batch loaded {} instruments ({} after filtering)",
            loaded_ids.len(),
            filtered_count
        );

        // Save cache if cache_path is configured
        if !loaded_ids.is_empty()
            && let Some(ref cache_path) = self.config.cache_path
            && let Err(e) = self.save_cache(cache_path).await
        {
            tracing::warn!("Failed to save instrument cache to {}: {}", cache_path, e);
        }

        Ok(loaded_ids)
    }

    /// Fetch option chain for a given underlying contract with expiry filtering.
    ///
    /// This is equivalent to Python's `get_option_chain_details_by_range`.
    /// It uses `contract_details` to fetch options with precise expiry filtering,
    /// which is more flexible than the basic `option_chain` API.
    ///
    /// # Arguments
    ///
    /// * `client` - The IB API client
    /// * `underlying` - The underlying contract
    /// * `expiry_min` - Minimum expiry date string (YYYYMMDD format, can be None for no min)
    /// * `expiry_max` - Maximum expiry date string (YYYYMMDD format, can be None for no max)
    ///
    /// # Returns
    ///
    /// Returns the number of option instruments loaded.
    ///
    /// # Errors
    ///
    /// Returns an error if fetching fails.
    pub async fn fetch_option_chain_by_range(
        &self,
        client: &ibapi::Client,
        underlying: &Contract,
        expiry_min: Option<&str>,
        expiry_max: Option<&str>,
        option_chain_exchange: Option<&str>,
    ) -> anyhow::Result<usize> {
        let exchange = option_chain_exchange.unwrap_or_else(|| underlying.exchange.as_str());
        tracing::debug!(
            "Building option chain for {}.{} (sec_type={:?}, contract_id={}, expiry_min={:?}, expiry_max={:?}, config_min_days={:?}, config_max_days={:?})",
            underlying.symbol.as_str(),
            exchange,
            underlying.security_type,
            underlying.contract_id,
            expiry_min,
            expiry_max,
            self.config.min_expiry_days,
            self.config.max_expiry_days,
        );

        // First, get option chain metadata to determine expirations
        let symbol = underlying.symbol.as_str();
        let mut option_chain_stream = client
            .option_chain(
                symbol,
                exchange,
                underlying.security_type.clone(),
                underlying.contract_id,
            )
            .await
            .context("Failed to request option chain from IB")?;

        let mut total_loaded = 0;

        // Get current time for expiry day calculation
        let now = nautilus_core::time::get_atomic_clock_realtime().get_time_ns();

        // Collect all expirations from the metadata
        let mut all_expirations = Vec::new();

        while let Some(result) = option_chain_stream.next().await {
            match result {
                Ok(SubscriptionItem::Data(chain)) => {
                    tracing::debug!(
                        "Received option chain metadata exchange={} trading_class={} expirations={} strikes={}",
                        chain.exchange,
                        chain.trading_class,
                        chain.expirations.len(),
                        chain.strikes.len(),
                    );

                    for expiration in &chain.expirations {
                        // Filter by expiry date string if specified
                        let date_filter_pass = match (expiry_min, expiry_max) {
                            (Some(min), Some(max)) => {
                                expiration.as_str() >= min && expiration.as_str() <= max
                            }
                            (Some(min), None) => expiration.as_str() >= min,
                            (None, Some(max)) => expiration.as_str() <= max,
                            (None, None) => true,
                        };

                        // Filter by expiry days from config if specified
                        let days_filter_pass = {
                            let expiry_ns =
                                crate::providers::parse::expiry_timestring_to_unix_nanos(
                                    expiration.as_str(),
                                    None,
                                )
                                .unwrap_or(now);
                            let days_until_expiry =
                                (expiry_ns.as_u64().saturating_sub(now.as_u64()))
                                    / (24 * 60 * 60 * 1_000_000_000);

                            let min_days_ok = self
                                .config
                                .min_expiry_days
                                .is_none_or(|min| days_until_expiry >= min as u64);
                            let max_days_ok = self
                                .config
                                .max_expiry_days
                                .is_none_or(|max| days_until_expiry <= max as u64);

                            min_days_ok && max_days_ok
                        };

                        if date_filter_pass
                            && days_filter_pass
                            && !all_expirations.contains(expiration)
                        {
                            all_expirations.push(expiration.clone());
                        }
                    }
                }
                Ok(SubscriptionItem::Notice(notice)) => {
                    tracing::debug!("Received option chain notice: {notice:?}");
                }
                Err(e) => {
                    tracing::warn!("Error receiving option chain metadata: {e}");
                }
            }
        }

        all_expirations.sort_unstable();

        tracing::debug!(
            "Filtered {} option expirations for {}.{}",
            all_expirations.len(),
            underlying.symbol.as_str(),
            exchange,
        );

        // Now fetch contract details for each expiry using contract_details
        for expiration in all_expirations {
            tracing::debug!(
                "Requesting option contract details for {}.{} expiry {}",
                underlying.symbol.as_str(),
                exchange,
                expiration,
            );

            let option_contract = Contract {
                contract_id: 0,
                symbol: underlying.symbol.clone(),
                security_type: if underlying.security_type == SecurityType::Future {
                    SecurityType::FuturesOption
                } else {
                    SecurityType::Option
                },
                last_trade_date_or_contract_month: expiration.clone(),
                strike: f64::MAX,
                right: None,
                multiplier: String::new(),
                exchange: Exchange::from(exchange),
                currency: underlying.currency.clone(),
                local_symbol: String::new(),
                primary_exchange: Exchange::from(""),
                trading_class: String::new(),
                include_expired: false,
                security_id_type: None,
                security_id: String::new(),
                combo_legs_description: String::new(),
                combo_legs: Vec::new(),
                delta_neutral_contract: None,
                issuer_id: String::new(),
                description: String::new(),
                last_trade_date: None,
            };

            match client.contract_details(&option_contract).await {
                Ok(details_vec) => {
                    tracing::debug!(
                        "Received {} raw option contract details for {}.{} expiry {}",
                        details_vec.len(),
                        underlying.symbol.as_str(),
                        exchange,
                        expiration,
                    );

                    for details in details_vec {
                        // Filter by underlying contract ID
                        if details.under_contract_id != underlying.contract_id {
                            continue;
                        }

                        let contract_id = details.contract.contract_id;

                        if self.contract_id_to_instrument_id.contains_key(&contract_id) {
                            continue;
                        }

                        match self.process_contract_detail(&details, None, false) {
                            Ok(Some(_instrument_id)) => {
                                total_loaded += 1;
                            }
                            Ok(None) => {}
                            Err(e) => {
                                tracing::warn!("Failed to parse option instrument: {}", e);
                            }
                        }
                    }
                }
                Err(e) => {
                    tracing::warn!(
                        "Failed to fetch contract details for expiration {}: {}",
                        expiration,
                        e
                    );
                }
            }
        }

        tracing::debug!(
            "Successfully loaded {} option instruments from chain for {}.{}",
            total_loaded,
            underlying.symbol.as_str(),
            exchange,
        );

        // Save cache if cache_path is configured
        if total_loaded > 0
            && let Some(ref cache_path) = self.config.cache_path
            && let Err(e) = self.save_cache(cache_path).await
        {
            tracing::warn!("Failed to save instrument cache to {}: {}", cache_path, e);
        }

        Ok(total_loaded)
    }

    /// Fetch and cache futures chain (all futures contracts for a symbol).
    ///
    /// This method fetches all futures contracts for a given underlying symbol
    /// and populates the cache with all individual futures instruments.
    ///
    /// # Arguments
    ///
    /// * `client` - The IB API client
    /// * `symbol` - The underlying symbol
    /// * `exchange` - The exchange (use "" for all exchanges)
    /// * `currency` - The currency (use USD as default)
    ///
    /// # Returns
    ///
    /// Returns the number of futures instruments loaded.
    ///
    /// # Errors
    ///
    /// Returns an error if fetching fails.
    pub async fn fetch_futures_chain(
        &self,
        client: &ibapi::Client,
        symbol: &str,
        exchange: &str,
        currency: &str,
        trading_class: Option<&str>,
        include_expired: bool,
        min_expiry_days: Option<u32>,
        max_expiry_days: Option<u32>,
    ) -> anyhow::Result<usize> {
        tracing::debug!(
            "Building futures chain for {}.{} (currency={}, trading_class={:?}, include_expired={}, min_days={:?}, max_days={:?}, config_min_days={:?}, config_max_days={:?})",
            symbol,
            exchange,
            currency,
            trading_class,
            include_expired,
            min_expiry_days,
            max_expiry_days,
            self.config.min_expiry_days,
            self.config.max_expiry_days,
        );

        // Build futures contract for lookup
        let futures_contract = Contract {
            contract_id: 0, // 0 for lookup by specification
            symbol: Symbol::from(symbol.to_string()),
            security_type: SecurityType::Future,
            last_trade_date_or_contract_month: String::new(),
            strike: f64::MAX,
            right: None,
            multiplier: String::new(),
            exchange: Exchange::from(exchange.to_string()),
            currency: ibapi::contracts::Currency::from(currency.to_string()),
            local_symbol: String::new(),
            primary_exchange: Exchange::from(""),
            trading_class: trading_class.unwrap_or_default().to_string(),
            include_expired,
            security_id_type: None,
            security_id: String::new(),
            combo_legs_description: String::new(),
            combo_legs: Vec::new(),
            delta_neutral_contract: None,
            issuer_id: String::new(),
            description: String::new(),
            last_trade_date: None,
        };

        // Fetch contract details for all matching futures
        let details_vec = client
            .contract_details(&futures_contract)
            .await
            .context("Failed to fetch futures chain from IB")?;

        tracing::debug!(
            "Received {} raw futures contract details for {}.{}",
            details_vec.len(),
            symbol,
            exchange,
        );

        let mut total_loaded = 0;
        let now = nautilus_core::time::get_atomic_clock_realtime().get_time_ns();

        for details in details_vec {
            let contract_id = details.contract.contract_id;

            // Check if already cached
            if self.contract_id_to_instrument_id.contains_key(&contract_id) {
                continue;
            }

            // Check if security type is filtered
            let sec_type_str = security_type_code(&details.contract.security_type);
            if self.is_filtered_sec_type(&sec_type_str) {
                continue;
            }

            // Filter by expiry days for futures
            if !details
                .contract
                .last_trade_date_or_contract_month
                .is_empty()
                && let Ok(expiry_ns) = crate::providers::parse::expiry_timestring_to_unix_nanos(
                    &details.contract.last_trade_date_or_contract_month,
                    Some(&details),
                )
            {
                let days_until_expiry = (expiry_ns.as_u64().saturating_sub(now.as_u64()))
                    / (24 * 60 * 60 * 1_000_000_000);

                let min_days_ok = min_expiry_days
                    .or(self.config.min_expiry_days)
                    .is_none_or(|min| days_until_expiry >= min as u64);
                let max_days_ok = max_expiry_days
                    .or(self.config.max_expiry_days)
                    .is_none_or(|max| days_until_expiry <= max as u64);

                if !min_days_ok || !max_days_ok {
                    continue;
                }
            }

            match self.process_contract_detail(&details, None, false) {
                Ok(Some(_instrument_id)) => {
                    total_loaded += 1;
                }
                Ok(None) => {}
                Err(e) => {
                    tracing::warn!("Failed to parse futures instrument: {}", e);
                }
            }
        }

        tracing::debug!(
            "Successfully loaded {} futures instruments from chain",
            total_loaded
        );

        // Save cache if cache_path is configured
        if total_loaded > 0
            && let Some(ref cache_path) = self.config.cache_path
            && let Err(e) = self.save_cache(cache_path).await
        {
            tracing::warn!("Failed to save instrument cache to {}: {}", cache_path, e);
        }

        Ok(total_loaded)
    }

    /// Fetch and cache a BAG (spread) contract.
    ///
    /// This method fetches contract details for a spread contract by requesting
    /// contract details with a BAG contract. The BAG contract should have its
    /// combo_legs populated with the individual leg contract IDs.
    ///
    /// # Arguments
    ///
    /// * `client` - The IB API client
    /// * `bag_contract` - The BAG contract with populated combo_legs
    ///
    /// # Returns
    ///
    /// Returns the number of spread instruments loaded (0 or 1).
    ///
    /// # Errors
    ///
    /// Returns an error if fetching fails.
    ///
    /// # Notes
    ///
    /// This method now auto-loads all leg instruments from combo_legs and creates
    /// a proper spread instrument, matching Python's `_load_bag_contract` behavior.
    pub async fn fetch_bag_contract(
        &self,
        client: &ibapi::Client,
        bag_contract: &Contract,
    ) -> anyhow::Result<usize> {
        // Validate BAG contract
        if bag_contract.security_type != SecurityType::Spread || bag_contract.combo_legs.is_empty()
        {
            anyhow::bail!(
                "Invalid BAG contract: must have security_type=Spread and non-empty combo_legs"
            );
        }

        tracing::debug!(
            "Loading BAG contract with {} legs",
            bag_contract.combo_legs.len()
        );

        // First, load all individual leg instruments and collect their details
        let mut leg_contract_details = Vec::new();
        let mut leg_tuples = Vec::new();

        for combo_leg in &bag_contract.combo_legs {
            // Create a leg contract using information from the combo leg
            let leg_contract = Contract {
                contract_id: combo_leg.contract_id,  // Use conId from combo_leg
                symbol: bag_contract.symbol.clone(), // Use underlying symbol from BAG
                security_type: SecurityType::Option, // Default to Option, will be determined from contract details
                last_trade_date_or_contract_month: String::new(),
                strike: 0.0,
                right: None,
                multiplier: String::new(),
                exchange: Exchange::from(combo_leg.exchange.as_str()),
                currency: bag_contract.currency.clone(), // Use currency from BAG
                local_symbol: String::new(),
                primary_exchange: Exchange::default(),
                trading_class: String::new(),
                include_expired: false,
                security_id_type: None,
                security_id: String::new(),
                combo_legs_description: String::new(),
                combo_legs: Vec::new(),
                delta_neutral_contract: None,
                issuer_id: String::new(),
                description: String::new(),
                last_trade_date: None,
            };

            // Fetch contract details for this leg
            let leg_details_vec =
                client
                    .contract_details(&leg_contract)
                    .await
                    .with_context(|| {
                        format!(
                            "Failed to fetch contract details for leg conId {}",
                            combo_leg.contract_id
                        )
                    })?;

            if leg_details_vec.is_empty() {
                tracing::warn!(
                    "No contract details returned for leg conId {}",
                    combo_leg.contract_id
                );
                continue;
            }

            let leg_details = &leg_details_vec[0];
            let leg_contract_id = leg_details.contract.contract_id;

            // Check if leg is already cached
            let leg_instrument_id =
                if let Some(cached_id) = self.contract_id_to_instrument_id.get(&leg_contract_id) {
                    *cached_id.value()
                } else {
                    // Load the leg instrument
                    let leg_venue = self.determine_venue(&leg_details.contract, Some(leg_details));
                    let leg_instrument_id = match self.config.symbology_method {
                        crate::config::SymbologyMethod::Simplified => {
                            crate::common::parse::ib_contract_to_instrument_id_simplified(
                                &leg_details.contract,
                                Some(leg_venue),
                            )
                        }
                        crate::config::SymbologyMethod::Raw => {
                            crate::common::parse::ib_contract_to_instrument_id_raw(
                                &leg_details.contract,
                                Some(leg_venue),
                            )
                        }
                    }
                    .context("Failed to convert leg contract to instrument ID")?;

                    // Parse and cache the leg instrument
                    let leg_instrument =
                        parse_ib_contract_to_instrument(leg_details, leg_instrument_id)
                            .context("Failed to parse leg instrument")?;

                    self.instruments.insert(leg_instrument_id, leg_instrument);
                    self.contract_details
                        .insert(leg_instrument_id, leg_details.clone());
                    self.contracts
                        .insert(leg_instrument_id, leg_details.contract.clone());
                    self.contract_id_to_instrument_id
                        .insert(leg_contract_id, leg_instrument_id);
                    self.price_magnifiers
                        .insert(leg_instrument_id, leg_details.price_magnifier);

                    leg_instrument_id
                };

            // Determine ratio (positive for BUY, negative for SELL)
            let ratio = IbAction::from_str(combo_leg.action.as_str())
                .context("Invalid combo leg action")?
                .signed_multiplier()
                * combo_leg.ratio;

            // Get the contract details for this leg (should be cached now)
            let leg_details_clone = self
                .contract_details
                .get(&leg_instrument_id)
                .map(|entry| entry.value().clone())
                .ok_or_else(|| {
                    anyhow::anyhow!(
                        "Contract details not found for leg {} after loading",
                        leg_instrument_id
                    )
                })?;

            leg_contract_details.push((leg_details_clone, ratio));
            leg_tuples.push((leg_instrument_id, ratio));
        }

        if leg_tuples.is_empty() {
            anyhow::bail!("No valid legs loaded for BAG contract");
        }

        // Create spread instrument ID from leg tuples
        let spread_instrument_id = create_spread_instrument_id(&leg_tuples)
            .context("Failed to create spread instrument ID from leg tuples")?;

        // Fetch BAG contract details (for storing the mapping)
        let bag_details_vec = client
            .contract_details(bag_contract)
            .await
            .context("Failed to fetch BAG contract details from IB")?;

        if bag_details_vec.is_empty() {
            tracing::warn!("No contract details returned for BAG contract");

            if bag_contract.contract_id != 0 && self.instruments.contains_key(&spread_instrument_id)
            {
                self.contract_id_to_instrument_id
                    .insert(bag_contract.contract_id, spread_instrument_id);
            }
            return Ok(0);
        }

        let bag_details = &bag_details_vec[0];
        let bag_contract_id = bag_details.contract.contract_id;

        if bag_contract_id != 0 {
            self.contract_id_to_instrument_id
                .insert(bag_contract_id, spread_instrument_id);
        }

        // Check if spread is already cached after ensuring the BAG contract ID is mapped.
        if self.instruments.contains_key(&spread_instrument_id) {
            tracing::debug!("Spread instrument {} already cached", spread_instrument_id);
            self.contract_details
                .insert(spread_instrument_id, bag_details.clone());
            self.contracts
                .insert(spread_instrument_id, bag_details.contract.clone());
            self.price_magnifiers
                .insert(spread_instrument_id, bag_details.price_magnifier);
            return Ok(0);
        }

        // Create the spread instrument
        let timestamp = nautilus_core::time::get_atomic_clock_realtime().get_time_ns();

        // Convert leg_contract_details to the format needed by parse_spread_instrument_id
        let leg_details_refs: Vec<(&ibapi::contracts::ContractDetails, i32)> =
            leg_contract_details.iter().map(|(d, r)| (d, *r)).collect();

        let spread_instrument = parse_spread_instrument_any(
            spread_instrument_id,
            &leg_details_refs,
            Some(&bag_details.contract),
            Some(timestamp),
        )
        .context("Failed to parse spread instrument")?;

        // Cache the spread instrument and mappings
        self.instruments
            .insert(spread_instrument_id, spread_instrument);
        self.contract_details
            .insert(spread_instrument_id, bag_details.clone());
        self.contracts
            .insert(spread_instrument_id, bag_details.contract.clone());
        self.price_magnifiers
            .insert(spread_instrument_id, bag_details.price_magnifier);

        tracing::debug!(
            "Successfully loaded spread instrument {} with {} legs",
            spread_instrument_id,
            leg_tuples.len()
        );

        // Save cache if cache_path is configured
        if let Some(ref cache_path) = self.config.cache_path
            && let Err(e) = self.save_cache(cache_path).await
        {
            tracing::warn!("Failed to save instrument cache to {}: {}", cache_path, e);
        }

        Ok(1)
    }

    /// Save the current instrument cache to disk.
    ///
    /// # Arguments
    ///
    /// * `cache_path` - Path to the cache file
    ///
    /// # Errors
    ///
    /// Returns an error if serialization or file I/O fails.
    pub async fn save_cache(&self, cache_path: &str) -> anyhow::Result<()> {
        let cache = InstrumentCache {
            cache_timestamp: Timestamp::now(),
            contract_id_to_instrument_id: self
                .contract_id_to_instrument_id
                .iter()
                .map(|entry| (*entry.key(), entry.value().to_string()))
                .collect(),
            price_magnifiers: self
                .price_magnifiers
                .iter()
                .map(|entry| (entry.key().to_string(), *entry.value()))
                .collect(),
            contracts: self
                .contracts
                .iter()
                .map(|entry| (entry.key().to_string(), entry.value().clone()))
                .collect(),
            contract_details: self
                .contract_details
                .iter()
                .map(|entry| (entry.key().to_string(), entry.value().clone()))
                .collect(),
            instruments: self
                .instruments
                .iter()
                .map(|entry| {
                    let instrument_id = entry.key().to_string();
                    let json =
                        serde_json::to_string(entry.value()).unwrap_or_else(|_| String::new());
                    (instrument_id, json)
                })
                .collect(),
        };

        // Ensure parent directory exists
        if let Some(parent) = Path::new(cache_path).parent() {
            fs::create_dir_all(parent)?;
        }

        // Write cache to file
        let json = serde_json::to_string_pretty(&cache)?;
        fs::write(cache_path, json)?;
        tracing::debug!(
            "Saved instrument cache to {} ({} instruments)",
            cache_path,
            cache.instruments.len()
        );
        Ok(())
    }

    /// Load instrument cache from disk if valid.
    ///
    /// # Arguments
    ///
    /// * `cache_path` - Path to the cache file
    ///
    /// # Returns
    ///
    /// Returns `true` if cache was loaded successfully and is valid, `false` otherwise.
    ///
    /// # Errors
    ///
    /// Returns an error if deserialization or file I/O fails (but treats missing file as non-error).
    pub async fn load_cache(&self, cache_path: &str) -> anyhow::Result<bool> {
        // Check if cache file exists
        if !Path::new(cache_path).exists() {
            tracing::debug!("Cache file does not exist: {}", cache_path);
            return Ok(false);
        }

        // Load cache from file
        let json = fs::read_to_string(cache_path)?;
        let cache: InstrumentCache = serde_json::from_str(&json)?;

        // Check cache validity
        if let Some(validity_days) = self.config.cache_validity_days {
            let cache_age = cache.cache_timestamp.duration_until(Timestamp::now());
            let max_age = jiff::SignedDuration::from_hours(24 * (validity_days as i64));
            if cache_age > max_age {
                tracing::debug!(
                    "Cache is expired (age: {} days, max: {} days). Ignoring cache",
                    cache_age.as_secs() / (24 * 60 * 60),
                    validity_days
                );
                return Ok(false);
            }
        }

        // Deserialize and restore instruments
        let mut loaded_count = 0;

        for (instrument_id_str, instrument_json) in &cache.instruments {
            match InstrumentId::from_str(instrument_id_str) {
                Ok(instrument_id) => match serde_json::from_str::<InstrumentAny>(instrument_json) {
                    Ok(instrument) => {
                        self.instruments.insert(instrument_id, instrument);

                        if let Ok(value) =
                            serde_json::from_str::<serde_json::Value>(instrument_json)
                            && let Some(contract_json) = find_contract_json(&value)
                            && let Ok(contract) = parse_contract_from_json(contract_json)
                        {
                            if contract.contract_id != 0 {
                                self.contract_id_to_instrument_id
                                    .insert(contract.contract_id, instrument_id);
                            }
                            self.contracts.insert(instrument_id, contract);
                        }
                        loaded_count += 1;
                    }
                    Err(e) => {
                        tracing::warn!(
                            "Failed to deserialize instrument {}: {}",
                            instrument_id_str,
                            e
                        );
                    }
                },
                Err(e) => {
                    tracing::warn!("Failed to parse instrument ID {}: {}", instrument_id_str, e);
                }
            }
        }

        // Restore contracts and contract details
        for (instrument_id_str, contract) in &cache.contracts {
            if let Ok(instrument_id) = InstrumentId::from_str(instrument_id_str) {
                if contract.contract_id != 0 {
                    self.contract_id_to_instrument_id
                        .insert(contract.contract_id, instrument_id);
                }
                self.contracts.insert(instrument_id, contract.clone());
            }
        }

        for (instrument_id_str, details) in &cache.contract_details {
            if let Ok(instrument_id) = InstrumentId::from_str(instrument_id_str) {
                if details.contract.contract_id != 0 {
                    self.contract_id_to_instrument_id
                        .insert(details.contract.contract_id, instrument_id);
                }
                self.contracts
                    .insert(instrument_id, details.contract.clone());
                self.contract_details.insert(instrument_id, details.clone());
            }
        }

        // Restore contract ID mappings
        for (contract_id, instrument_id_str) in &cache.contract_id_to_instrument_id {
            if let Ok(instrument_id) = InstrumentId::from_str(instrument_id_str) {
                self.contract_id_to_instrument_id
                    .insert(*contract_id, instrument_id);
            }
        }

        // Restore price magnifiers
        for (instrument_id_str, magnifier) in &cache.price_magnifiers {
            if let Ok(instrument_id) = InstrumentId::from_str(instrument_id_str) {
                self.price_magnifiers.insert(instrument_id, *magnifier);
            }
        }

        tracing::debug!(
            "Loaded instrument cache from {} ({} instruments, created at {})",
            cache_path,
            loaded_count,
            cache.cache_timestamp
        );
        Ok(true)
    }
}

#[cfg(test)]
mod tests {
    use std::{
        fs,
        sync::atomic::{AtomicBool, AtomicUsize, Ordering},
    };

    use nautilus_core::{Params, UnixNanos};
    use nautilus_model::{
        identifiers::{Symbol, Venue},
        instruments::CurrencyPair,
        types::{Price, Quantity, currency::Currency},
    };
    use rstest::rstest;
    use tempfile::TempDir;

    use super::*;
    use crate::common::contract_to_json_value;

    struct TestStartupLoader {
        id_calls: AtomicUsize,
        contract_calls: AtomicUsize,
        fail_next_id: AtomicBool,
        resolve_ids: AtomicBool,
        resolve_contracts: AtomicBool,
        yield_on_load: bool,
    }

    impl TestStartupLoader {
        fn new(resolve_ids: bool, resolve_contracts: bool) -> Self {
            Self {
                id_calls: AtomicUsize::new(0),
                contract_calls: AtomicUsize::new(0),
                fail_next_id: AtomicBool::new(false),
                resolve_ids: AtomicBool::new(resolve_ids),
                resolve_contracts: AtomicBool::new(resolve_contracts),
                yield_on_load: false,
            }
        }
    }

    impl StartupInstrumentLoader for TestStartupLoader {
        async fn load_instrument_id(
            &self,
            instrument_id: InstrumentId,
        ) -> anyhow::Result<Option<InstrumentId>> {
            self.id_calls.fetch_add(1, Ordering::SeqCst);

            if self.yield_on_load {
                tokio::task::yield_now().await;
            }

            if self.fail_next_id.swap(false, Ordering::SeqCst) {
                anyhow::bail!("Socket disconnected");
            }
            Ok(self
                .resolve_ids
                .load(Ordering::SeqCst)
                .then_some(instrument_id))
        }

        async fn load_contract(
            &self,
            _contract_spec: &serde_json::Value,
        ) -> anyhow::Result<Vec<InstrumentId>> {
            self.contract_calls.fetch_add(1, Ordering::SeqCst);

            if self.yield_on_load {
                tokio::task::yield_now().await;
            }
            Ok(if self.resolve_contracts.load(Ordering::SeqCst) {
                vec![InstrumentId::new(
                    Symbol::from("MSFT"),
                    Venue::from("NASDAQ"),
                )]
            } else {
                Vec::new()
            })
        }
    }

    fn create_test_provider_with_cache() -> (InteractiveBrokersInstrumentProvider, TempDir) {
        let temp_dir = TempDir::new().unwrap();
        let cache_path = temp_dir
            .path()
            .join("test_cache.json")
            .to_str()
            .unwrap()
            .to_string();

        let config = InteractiveBrokersInstrumentProviderConfig::builder()
            .cache_path(cache_path)
            .cache_validity_days(7u32)
            .build();

        let provider = InteractiveBrokersInstrumentProvider::new(config);
        (provider, temp_dir)
    }

    fn opra_option_contract_details(mut contract: Contract) -> ibapi::contracts::ContractDetails {
        contract.contract_id = 12_345;
        contract.symbol = ibapi::contracts::Symbol::from("AAPL");
        contract.security_type = SecurityType::Option;
        contract.exchange = Exchange::from("SMART");
        contract.currency = ibapi::contracts::Currency::from("USD");
        contract.local_symbol = "AAPL  270115P00155000".to_string();
        contract.last_trade_date_or_contract_month = "20270115".to_string();
        contract.strike = 155.0;
        contract.right = Some(ibapi::contracts::OptionRight::Put);
        contract.multiplier = "100".to_string();

        ibapi::contracts::ContractDetails {
            contract,
            min_tick: 0.01,
            under_symbol: "AAPL".to_string(),
            under_security_type: "STK".to_string(),
            valid_exchanges: vec!["SMART".to_string(), "CBOE".to_string()],
            ..Default::default()
        }
    }

    fn create_test_instrument(instrument_id: InstrumentId) -> InstrumentAny {
        create_test_instrument_with_info(instrument_id, None)
    }

    #[rstest]
    fn test_qualified_opra_details_preserve_canonical_instrument_identity() {
        let provider = InteractiveBrokersInstrumentProvider::new(Default::default());
        let requested_id = InstrumentId::from("AAPL  270115P00155000.OPRA");
        let request = instrument_id_to_ib_contract(requested_id, None).unwrap();

        assert_eq!(request.security_type, SecurityType::Option);
        assert_eq!(request.exchange.as_str(), "SMART");
        assert!(request.symbol.as_str().is_empty());
        assert_eq!(request.currency.as_str(), "USD");
        assert_eq!(request.local_symbol, "AAPL  270115P00155000");
        assert!(request.last_trade_date_or_contract_month.is_empty());
        assert!(request.right.is_none());
        assert_eq!(request.strike, 0.0);

        let details = opra_option_contract_details(request);
        let loaded_id = provider
            .process_contract_detail(&details, Some(requested_id.venue), false)
            .unwrap()
            .unwrap();

        assert_eq!(loaded_id, requested_id);
        assert_eq!(provider.count(), 1);
        assert_eq!(
            provider.get_instrument_id_by_contract_id(12_345),
            Some(requested_id)
        );
        assert_eq!(
            provider
                .resolve_instrument_id_for_contract(&details.contract)
                .unwrap(),
            requested_id
        );

        let cached = provider.find(&requested_id).unwrap();
        let InstrumentAny::OptionContract(option) = cached else {
            panic!("expected option contract");
        };
        assert_eq!(option.id, requested_id);
        assert_eq!(option.id.venue.as_str(), "OPRA");
        assert!(
            provider
                .find(&InstrumentId::from("AAPL  270115P00155000.SMART"))
                .is_none()
        );

        let cached_contract = provider
            .instrument_id_to_ib_contract(&requested_id)
            .unwrap();
        assert_eq!(cached_contract.contract_id, 12_345);
        assert_eq!(cached_contract.security_type, SecurityType::Option);
        assert_eq!(cached_contract.exchange.as_str(), "SMART");

        let resolved_contract = provider
            .resolve_contract_for_instrument(requested_id)
            .unwrap();
        assert_eq!(resolved_contract, cached_contract);

        let cached_details = provider
            .instrument_id_to_ib_contract_details(&requested_id)
            .unwrap();
        assert_eq!(cached_details.contract.contract_id, 12_345);
        assert_eq!(
            cached_details.valid_exchanges,
            vec!["SMART".to_string(), "CBOE".to_string()]
        );
    }

    fn create_test_instrument_with_info(
        instrument_id: InstrumentId,
        info: Option<Params>,
    ) -> InstrumentAny {
        CurrencyPair::new(
            instrument_id,
            Symbol::from("EUR/USD"),
            Currency::from("EUR"),
            Currency::from("USD"),
            4,
            0,
            Price::from("0.0001"),
            Quantity::from(1),
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            None,
            info,
            UnixNanos::default(),
            UnixNanos::default(),
        )
        .into()
    }

    fn create_contract_info(contract: &Contract, price_magnifier: Option<i32>) -> Params {
        let mut info = Params::new();
        info.insert(String::from("contract"), contract_to_json_value(contract));
        if let Some(price_magnifier) = price_magnifier {
            info.insert(
                String::from("priceMagnifier"),
                serde_json::Value::from(price_magnifier),
            );
        }
        info
    }

    #[tokio::test]
    async fn test_initialize_loads_all_configured_inputs_once() {
        let instrument_id = InstrumentId::new(Symbol::from("AAPL"), Venue::from("NASDAQ"));
        let contract_spec = serde_json::json!({
            "secType": "STK",
            "symbol": "MSFT",
            "exchange": "NASDAQ",
        });
        let config = InteractiveBrokersInstrumentProviderConfig {
            load_ids: [instrument_id].into_iter().collect(),
            load_contracts: vec![contract_spec],
            ..Default::default()
        };
        let provider = InteractiveBrokersInstrumentProvider::new(config);
        let loader = TestStartupLoader::new(true, true);

        let loaded_ids = provider.initialize_with_loader(&loader).await.unwrap();
        let second_result = provider.initialize_with_loader(&loader).await.unwrap();

        assert_eq!(
            loaded_ids,
            vec![
                instrument_id,
                InstrumentId::new(Symbol::from("MSFT"), Venue::from("NASDAQ")),
            ]
        );
        assert!(second_result.is_empty());
        assert_eq!(loader.id_calls.load(Ordering::SeqCst), 1);
        assert_eq!(loader.contract_calls.load(Ordering::SeqCst), 1);
        assert!(*provider.startup_initialized.lock().await);
    }

    #[tokio::test]
    async fn test_initialize_fails_closed_and_retries_unresolved_input() {
        let instrument_id = InstrumentId::new(Symbol::from("AAPL"), Venue::from("NASDAQ"));
        let contract_spec = serde_json::json!({
            "secType": "STK",
            "symbol": "MSFT",
            "exchange": "NASDAQ",
        });
        let config = InteractiveBrokersInstrumentProviderConfig {
            load_ids: [instrument_id].into_iter().collect(),
            load_contracts: vec![contract_spec],
            ..Default::default()
        };
        let provider = InteractiveBrokersInstrumentProvider::new(config);
        let loader = TestStartupLoader::new(true, false);

        let error = provider.initialize_with_loader(&loader).await.unwrap_err();

        assert!(error.to_string().contains("contract at index 0"));
        assert!(!*provider.startup_initialized.lock().await);

        loader.resolve_contracts.store(true, Ordering::SeqCst);
        provider.initialize_with_loader(&loader).await.unwrap();

        assert_eq!(loader.id_calls.load(Ordering::SeqCst), 2);
        assert_eq!(loader.contract_calls.load(Ordering::SeqCst), 2);
        assert!(*provider.startup_initialized.lock().await);
    }

    #[tokio::test]
    async fn test_initialize_preserves_load_error_and_allows_retry() {
        let instrument_id = InstrumentId::new(Symbol::from("AAPL"), Venue::from("NASDAQ"));
        let config = InteractiveBrokersInstrumentProviderConfig {
            load_ids: [instrument_id].into_iter().collect(),
            ..Default::default()
        };
        let provider = InteractiveBrokersInstrumentProvider::new(config);
        let loader = TestStartupLoader::new(true, true);
        loader.fail_next_id.store(true, Ordering::SeqCst);

        let error = provider.initialize_with_loader(&loader).await.unwrap_err();

        let error_chain = format!("{error:#}");
        assert!(error_chain.contains("Failed to load configured IB instrument ID AAPL.NASDAQ"));
        assert!(error_chain.contains("Socket disconnected"));
        assert!(!*provider.startup_initialized.lock().await);

        provider.initialize_with_loader(&loader).await.unwrap();

        assert_eq!(loader.id_calls.load(Ordering::SeqCst), 2);
        assert!(*provider.startup_initialized.lock().await);
    }

    #[tokio::test]
    async fn test_initialize_serializes_concurrent_calls() {
        let instrument_id = InstrumentId::new(Symbol::from("AAPL"), Venue::from("NASDAQ"));
        let config = InteractiveBrokersInstrumentProviderConfig {
            load_ids: [instrument_id].into_iter().collect(),
            ..Default::default()
        };
        let provider = InteractiveBrokersInstrumentProvider::new(config);
        let mut loader = TestStartupLoader::new(true, true);
        loader.yield_on_load = true;

        let (first, second) = tokio::join!(
            provider.initialize_with_loader(&loader),
            provider.initialize_with_loader(&loader),
        );

        assert_eq!(first.unwrap().len() + second.unwrap().len(), 1);
        assert_eq!(loader.id_calls.load(Ordering::SeqCst), 1);
        assert!(*provider.startup_initialized.lock().await);
    }

    #[tokio::test]
    async fn test_save_cache() {
        let (provider, _temp_dir) = create_test_provider_with_cache();
        let cache_path = provider.config.cache_path.as_ref().unwrap().clone();

        // Add some test instruments
        let instrument_id1 = InstrumentId::new(Symbol::from("EUR/USD"), Venue::from("IDEALPRO"));
        let instrument_id2 = InstrumentId::new(Symbol::from("GBP/USD"), Venue::from("IDEALPRO"));

        let instrument1 = create_test_instrument(instrument_id1);
        let instrument2 = create_test_instrument(instrument_id2);

        provider.instruments.insert(instrument_id1, instrument1);
        provider.instruments.insert(instrument_id2, instrument2);
        provider
            .contract_id_to_instrument_id
            .insert(100, instrument_id1);
        provider
            .contract_id_to_instrument_id
            .insert(200, instrument_id2);
        provider.price_magnifiers.insert(instrument_id1, 1);
        provider.price_magnifiers.insert(instrument_id2, 1);

        // Save cache
        let result = provider.save_cache(&cache_path).await;
        assert!(result.is_ok(), "save_cache should succeed");

        // Verify file exists
        assert!(Path::new(&cache_path).exists(), "Cache file should exist");

        // Verify file contains JSON
        let contents = fs::read_to_string(&cache_path).unwrap();
        assert!(
            contents.contains("EUR/USD"),
            "Cache should contain instrument data"
        );
        assert!(
            contents.contains("cache_timestamp"),
            "Cache should contain timestamp"
        );
    }

    #[tokio::test]
    async fn test_load_cache_valid() {
        let (provider, _temp_dir) = create_test_provider_with_cache();
        let cache_path = provider.config.cache_path.as_ref().unwrap().clone();

        // First save a cache
        let instrument_id = InstrumentId::new(Symbol::from("EUR/USD"), Venue::from("IDEALPRO"));
        let instrument = create_test_instrument(instrument_id);

        provider
            .instruments
            .insert(instrument_id, instrument.clone());
        provider
            .contract_id_to_instrument_id
            .insert(100, instrument_id);
        provider.price_magnifiers.insert(instrument_id, 1);

        provider.save_cache(&cache_path).await.unwrap();

        // Create a new provider and load the cache
        let new_config = InteractiveBrokersInstrumentProviderConfig::builder()
            .cache_path(cache_path.clone())
            .cache_validity_days(7u32)
            .build();

        let new_provider = InteractiveBrokersInstrumentProvider::new(new_config);

        let result = new_provider.load_cache(&cache_path).await;
        assert!(result.is_ok(), "load_cache should succeed");
        assert!(
            result.unwrap(),
            "load_cache should return true for valid cache"
        );

        // Verify instrument was loaded
        assert!(
            new_provider.find(&instrument_id).is_some(),
            "Instrument should be loaded from cache"
        );
        assert_eq!(new_provider.count(), 1, "Provider should have 1 instrument");
    }

    #[tokio::test]
    async fn test_load_cache_reads_chrono_timestamp() {
        let provider = InteractiveBrokersInstrumentProvider::new(
            InteractiveBrokersInstrumentProviderConfig::builder()
                .cache_validity_days(7u32)
                .build(),
        );
        let cache_path = concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/test_data/instrument_cache_chrono.json"
        );

        let loaded = provider.load_cache(cache_path).await.unwrap();

        assert!(loaded);
        assert_eq!(provider.count(), 0);
    }

    #[tokio::test]
    async fn test_load_cache_restores_contract_details() {
        let (provider, _temp_dir) = create_test_provider_with_cache();
        let cache_path = provider.config.cache_path.as_ref().unwrap().clone();
        let instrument_id = InstrumentId::new(Symbol::from("AAPL"), Venue::from("XNAS"));
        let instrument = create_test_instrument(instrument_id);
        let contract = Contract {
            contract_id: 265598,
            symbol: ibapi::contracts::Symbol::from("AAPL"),
            security_type: SecurityType::Stock,
            exchange: Exchange::from("SMART"),
            primary_exchange: Exchange::from("NASDAQ"),
            currency: ibapi::contracts::Currency::from("USD"),
            ..Default::default()
        };
        let details = ibapi::contracts::ContractDetails {
            contract: contract.clone(),
            price_magnifier: 1,
            ..Default::default()
        };

        provider.cache_instrument(
            instrument_id,
            instrument,
            Some(details),
            Some(contract),
            Some(1),
            false,
        );
        provider.save_cache(&cache_path).await.unwrap();

        let new_provider = InteractiveBrokersInstrumentProvider::new(provider.config.clone());

        assert!(new_provider.load_cache(&cache_path).await.unwrap());
        assert_eq!(
            new_provider
                .resolve_contract_for_instrument(instrument_id)
                .unwrap()
                .contract_id,
            265598
        );
        assert_eq!(
            new_provider
                .instrument_id_to_ib_contract_details(&instrument_id)
                .unwrap()
                .contract
                .contract_id,
            265598
        );
    }

    #[rstest]
    fn test_filter_sec_types_uses_ib_codes_case_insensitive() {
        let config = InteractiveBrokersInstrumentProviderConfig {
            filter_sec_types: [String::from("opt")].into_iter().collect(),
            ..Default::default()
        };
        let provider = InteractiveBrokersInstrumentProvider::new(config);

        assert!(provider.is_filtered_sec_type(&security_type_code(&SecurityType::Option)));
        assert!(!provider.is_filtered_sec_type(&security_type_code(&SecurityType::Stock)));
    }

    #[rstest]
    fn test_add_cached_instruments_only_seeds_ib_contracts() {
        let provider = InteractiveBrokersInstrumentProvider::new(Default::default());
        let ib_instrument_id = InstrumentId::new(Symbol::from("AAPL"), Venue::from("XNAS"));
        let non_ib_instrument_id =
            InstrumentId::new(Symbol::from("BTCUSDT"), Venue::from("BINANCE"));
        let contract = Contract {
            contract_id: 265598,
            symbol: ibapi::contracts::Symbol::from("AAPL"),
            security_type: SecurityType::Stock,
            exchange: Exchange::from("SMART"),
            primary_exchange: Exchange::from("NASDAQ"),
            currency: ibapi::contracts::Currency::from("USD"),
            ..Default::default()
        };
        let ib_instrument = create_test_instrument_with_info(
            ib_instrument_id,
            Some(create_contract_info(&contract, Some(100))),
        );
        let non_ib_instrument = create_test_instrument(non_ib_instrument_id);

        let count = provider.add_cached_instruments([ib_instrument, non_ib_instrument]);

        assert_eq!(count, 1);
        assert_eq!(provider.count(), 1);
        assert!(provider.find(&ib_instrument_id).is_some());
        assert!(provider.find(&non_ib_instrument_id).is_none());
        assert_eq!(
            provider
                .resolve_contract_for_instrument(ib_instrument_id)
                .unwrap()
                .contract_id,
            265598
        );
        assert_eq!(provider.get_price_magnifier(&ib_instrument_id), 100);
    }

    #[tokio::test]
    async fn test_load_cache_missing_file() {
        let (provider, _temp_dir) = create_test_provider_with_cache();
        let cache_path = "/nonexistent/path/cache.json";

        let result = provider.load_cache(cache_path).await;
        assert!(
            result.is_ok(),
            "load_cache should not error on missing file"
        );
        assert!(
            !result.unwrap(),
            "load_cache should return false for missing file"
        );
    }

    #[tokio::test]
    async fn test_load_cache_expired() {
        let (provider, _temp_dir) = create_test_provider_with_cache();
        let cache_path = provider.config.cache_path.as_ref().unwrap().clone();

        // Create an expired cache manually
        let old_timestamp = Timestamp::now() - jiff::SignedDuration::from_hours(24 * (10));
        let expired_cache = InstrumentCache {
            cache_timestamp: old_timestamp,
            contract_id_to_instrument_id: vec![],
            price_magnifiers: vec![],
            contracts: vec![],
            contract_details: vec![],
            instruments: vec![],
        };

        let json = serde_json::to_string_pretty(&expired_cache).unwrap();
        fs::write(&cache_path, json).unwrap();

        // Try to load with validity_days = 7
        let result = provider.load_cache(&cache_path).await;
        assert!(
            result.is_ok(),
            "load_cache should not error on expired cache"
        );
        assert!(
            !result.unwrap(),
            "load_cache should return false for expired cache"
        );
    }
}