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
// -------------------------------------------------------------------------------------------------
//  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.
// -------------------------------------------------------------------------------------------------

//! Parsing utilities for converting Interactive Brokers data to Nautilus types.

use std::{collections::HashMap, str::FromStr, sync::LazyLock};

use ibapi::contracts::{Contract, Currency, Exchange, OptionRight, SecurityType, Symbol};
use nautilus_core::UnixNanos;
use nautilus_model::identifiers::{InstrumentId, Symbol as NautilusSymbol, TradeId, Venue};

use crate::common::enums::{IbOptionRight, IbSecurityType};

fn ib_option_right_to_option_right(right: IbOptionRight) -> OptionRight {
    match right {
        IbOptionRight::Call => OptionRight::Call,
        IbOptionRight::Put => OptionRight::Put,
    }
}

/// Generate a unique trade ID for Interactive Brokers trades.
///
/// This format matches the Python adapter: "{secs}-{price}-{size}"
pub fn generate_ib_trade_id(ts_event: UnixNanos, price: f64, size: f64) -> TradeId {
    let ts_secs = ts_event.as_i64() / 1_000_000_000;
    TradeId::new(format!("{ts_secs}-{price}-{size}"))
}

/// Convert an IB Contract to an InstrumentId using simplified symbology.
///
/// This implements IB_SIMPLIFIED symbology: clean, readable symbols.
/// For example:
/// - STK: "AAPL" -> "AAPL.SMART"
/// - CASH: "EUR.USD" -> "EUR/USD.IDEALPRO"
/// - FUT: "ESM23" -> "ESM23.GLOBEX"
/// - OPT: "AAPL230120C00150000" -> "AAPL230120C00150000.SMART"
/// - IND: "SPX" -> "^SPX.SMART"
///
/// # Errors
///
/// Returns an error if the instrument ID cannot be constructed.
pub fn ib_contract_to_instrument_id_simplified(
    contract: &Contract,
    venue: Option<Venue>,
) -> anyhow::Result<InstrumentId> {
    let venue = venue.unwrap_or_else(|| {
        // For Index and Future, use contract exchange when set (e.g. ESTX50 -> EUREX, FESX -> EUREX).
        match contract.security_type {
            SecurityType::Index => {
                if !contract.exchange.as_str().is_empty() && contract.exchange.as_str() != "SMART" {
                    Venue::from(contract.exchange.as_str())
                } else {
                    Venue::from("SMART")
                }
            }
            SecurityType::Future => {
                if !contract.exchange.as_str().is_empty() && contract.exchange.as_str() != "SMART" {
                    Venue::from(contract.exchange.as_str())
                } else {
                    Venue::from("GLOBEX")
                }
            }
            SecurityType::ForexPair => Venue::from("IDEALPRO"),
            SecurityType::Crypto => derive_crypto_venue(contract),
            SecurityType::Stock => Venue::from("SMART"),
            SecurityType::Option | SecurityType::FuturesOption => {
                if !contract.exchange.as_str().is_empty() && contract.exchange.as_str() != "SMART" {
                    Venue::from(contract.exchange.as_str())
                } else {
                    Venue::from("SMART")
                }
            }
            SecurityType::CFD => Venue::from("SMART"),
            SecurityType::Commodity => Venue::from("SMART"),
            SecurityType::Bond => Venue::from("SMART"),
            _ => Venue::from("SMART"),
        }
    });

    let symbol = match contract.security_type {
        SecurityType::Stock => {
            // STK: Use localSymbol with spaces replaced by hyphens, fallback to symbol
            let symbol_str = if contract.local_symbol.is_empty() {
                contract.symbol.as_str().to_string()
            } else {
                contract.local_symbol.as_str().replace(' ', "-")
            };
            NautilusSymbol::from(symbol_str.as_str())
        }
        SecurityType::Index => {
            // IND: Prefix with ^
            let base = if contract.local_symbol.is_empty() {
                contract.symbol.as_str()
            } else {
                contract.local_symbol.as_str()
            };
            NautilusSymbol::from(format!("^{base}").as_str())
        }
        SecurityType::Option => {
            // OPT: Preserve OCC 6-character root padding when present.
            let symbol_str = if contract.local_symbol.is_empty() {
                format!(
                    "{} {} {} {}",
                    contract.right.map_or("", |right| right.as_str()),
                    contract.trading_class.as_str(),
                    contract.last_trade_date_or_contract_month.as_str(),
                    format_option_strike(contract.strike),
                )
            } else {
                normalize_option_symbol(contract.local_symbol.as_str())
            };
            NautilusSymbol::from(symbol_str.as_str())
        }
        SecurityType::ForexPair | SecurityType::Crypto => {
            // CASH/CRYPTO: Replace dots with slashes (e.g., "EUR.USD" -> "EUR/USD")
            let symbol_str = if contract.local_symbol.is_empty() {
                format!(
                    "{}/{}",
                    contract.symbol.as_str(),
                    contract.currency.as_str()
                )
            } else {
                contract.local_symbol.as_str().replace('.', "/")
            };
            NautilusSymbol::from(symbol_str.as_str())
        }
        SecurityType::Future => {
            // FUT: Use localSymbol if available; else symbol + trading_class + expiry (e.g. ESTX50 FESX 20240315).
            if contract.local_symbol.is_empty() {
                if !contract.trading_class.is_empty()
                    && !contract.last_trade_date_or_contract_month.is_empty()
                {
                    let symbol_str = format!(
                        "{} {} {}",
                        contract.symbol.as_str(),
                        contract.trading_class.as_str(),
                        contract.last_trade_date_or_contract_month.as_str()
                    );
                    NautilusSymbol::from(symbol_str.as_str())
                } else if !contract.last_trade_date_or_contract_month.is_empty() {
                    let expiry = contract.last_trade_date_or_contract_month.as_str();
                    let symbol_str = format!("{}{}", contract.symbol.as_str(), expiry);
                    NautilusSymbol::from(symbol_str.as_str())
                } else {
                    NautilusSymbol::from(contract.symbol.as_str())
                }
            } else {
                NautilusSymbol::from(contract.local_symbol.as_str())
            }
        }
        SecurityType::FuturesOption => {
            // FOP: Preserve IB local symbol spacing, matching Python simplified symbology.
            if contract.local_symbol.is_empty() {
                // Fallback construction
                let expiry = contract.last_trade_date_or_contract_month.as_str();
                let right = contract.right.map_or("P", |right| right.as_str());
                let strike_str = format!("{}", contract.strike as i64);
                let symbol_str = format!(
                    "{}{} {}{}",
                    contract.symbol.as_str(),
                    expiry,
                    right,
                    strike_str
                );
                NautilusSymbol::from(symbol_str.as_str())
            } else {
                NautilusSymbol::from(contract.local_symbol.as_str())
            }
        }
        SecurityType::CFD => {
            // CFD: If localSymbol matches EUR.USD pattern, convert to EUR/USD, else use symbol with spaces as hyphens
            if !contract.local_symbol.is_empty() && contract.local_symbol.contains('.') {
                let cash_like = contract.local_symbol.as_str().replace('.', "/");
                NautilusSymbol::from(cash_like.as_str())
            } else {
                let symbol_str = contract.symbol.as_str().replace(' ', "-");
                NautilusSymbol::from(symbol_str.as_str())
            }
        }
        SecurityType::Commodity => {
            // CMDTY: Replace spaces with hyphens
            let symbol_str = contract.symbol.as_str().replace(' ', "-");
            NautilusSymbol::from(symbol_str.as_str())
        }
        SecurityType::Bond => {
            // BOND: Use localSymbol or symbol
            let symbol_str = if contract.local_symbol.is_empty() {
                contract.symbol.as_str()
            } else {
                contract.local_symbol.as_str()
            };
            NautilusSymbol::from(symbol_str)
        }
        _ => {
            // Default: use localSymbol or symbol
            let symbol_str = if contract.local_symbol.is_empty() {
                contract.symbol.as_str()
            } else {
                contract.local_symbol.as_str()
            };
            NautilusSymbol::from(symbol_str)
        }
    };

    Ok(InstrumentId::new(symbol, venue))
}

/// Convert an IB Contract to an InstrumentId using raw symbology.
///
/// This implements IB_RAW symbology: preserves IB raw format with security type suffix.
/// For example:
/// - "AAPL=STK.SMART"
/// - "EUR.USD=CASH.IDEALPRO"
/// - "ESM23=FUT.GLOBEX"
///
/// # Errors
///
/// Returns an error if the instrument ID cannot be constructed.
pub fn ib_contract_to_instrument_id_raw(
    contract: &Contract,
    venue: Option<Venue>,
) -> anyhow::Result<InstrumentId> {
    let venue = venue.unwrap_or_else(|| match contract.security_type {
        SecurityType::ForexPair => Venue::from("IDEALPRO"),
        SecurityType::Crypto => derive_crypto_venue(contract),
        SecurityType::Stock => Venue::from("SMART"),
        SecurityType::Option => Venue::from("SMART"),
        SecurityType::FuturesOption => Venue::from("SMART"),
        SecurityType::Future => Venue::from("GLOBEX"),
        SecurityType::Index => Venue::from("SMART"),
        SecurityType::CFD => Venue::from("SMART"),
        SecurityType::Commodity => Venue::from("SMART"),
        SecurityType::Bond => Venue::from("SMART"),
        _ => Venue::from("SMART"),
    });

    let local_symbol = if contract.local_symbol.is_empty() {
        contract.symbol.as_str()
    } else {
        contract.local_symbol.as_str()
    };

    let sec_type_str = IbSecurityType::try_from(&contract.security_type).map_or_else(
        |_| "OTHER".to_string(),
        |security_type| security_type.to_string(),
    );

    let symbol_str = format!("{local_symbol}={sec_type_str}");
    let symbol = NautilusSymbol::from(symbol_str.as_str());
    Ok(InstrumentId::new(symbol, venue))
}

/// Convert an IB Contract to an InstrumentId (simple version using contract fields).
///
/// This is a convenience wrapper that uses simplified symbology by default.
/// For more accurate mapping, use the instrument provider which has contract details.
///
/// # Errors
///
/// Returns an error if the instrument ID cannot be constructed.
pub fn ib_contract_to_instrument_id_simple(contract: &Contract) -> anyhow::Result<InstrumentId> {
    ib_contract_to_instrument_id_simplified(contract, None)
}

/// Venue to IB exchange mappings.
/// Maps MIC venue codes to lists of IB exchange codes used by Interactive Brokers.
pub static VENUE_MEMBERS: LazyLock<HashMap<&'static str, Vec<&'static str>>> =
    LazyLock::new(|| {
        let mut map = HashMap::new();
        // ICE Endex
        map.insert("NDEX", vec!["ENDEX"]);
        // CME Group Exchanges
        map.insert("XCME", vec!["CME"]);
        map.insert("XCEC", vec!["CME"]);
        map.insert("XFXS", vec!["CME"]);
        // Chicago Board of Trade Segments
        map.insert("XCBT", vec!["CBOT"]);
        map.insert("CBCM", vec!["CBOT"]);
        // New York Mercantile Exchange Segments
        map.insert("XNYM", vec!["NYMEX"]);
        map.insert("NYUM", vec!["NYMEX"]);
        // ICE Futures US (formerly NYBOT)
        map.insert("IFUS", vec!["NYBOT"]);
        // GLBX, Name used by databento
        map.insert("GLBX", vec!["CBOT", "CME", "NYBOT", "NYMEX"]);
        // US Major Exchanges & Index Venues
        map.insert("XNAS", vec!["NASDAQ"]);
        map.insert("XNYS", vec!["NYSE"]);
        map.insert("ARCX", vec!["ARCA"]);
        map.insert("BATS", vec!["BATS"]);
        map.insert("IEXG", vec!["IEX"]);
        map.insert("XCBO", vec!["CBOE"]);
        map.insert("XCBF", vec!["CFE"]);
        // Canadian Exchanges
        map.insert("XTSE", vec!["TSX"]);
        // ICE Europe Exchanges
        map.insert("IFEU", vec!["ICEEU", "ICEEUSOFT", "IPE"]);
        // European Exchanges
        map.insert("XLON", vec!["LSE"]);
        map.insert("XPAR", vec!["SBF"]);
        map.insert("XETR", vec!["IBIS"]);
        map.insert("XEUR", vec!["DTB", "EUREX", "SOFFEX"]);
        map.insert("XAMS", vec!["AEB"]);
        map.insert("XBRU", vec!["EBS"]);
        map.insert("XBRD", vec!["BELFOX"]);
        map.insert("XLIS", vec!["BVLP"]);
        map.insert("XDUB", vec!["IRE"]);
        map.insert("XOSL", vec!["OSL"]);
        map.insert("XSWX", vec!["EBS", "SIX", "SWX"]);
        map.insert("XSVX", vec!["VRTX"]);
        map.insert("XMIL", vec!["BIT", "BVME", "IDEM"]);
        map.insert("XMAD", vec!["MDRD", "BME"]);
        map.insert("DXEX", vec!["BATEEN"]);
        map.insert("XWBO", vec!["WBAG"]);
        map.insert("XBUD", vec!["BUX"]);
        map.insert("XPRA", vec!["PRA"]);
        map.insert("XWAR", vec!["WSE"]);
        map.insert("XIST", vec!["ISE"]);
        // Nasdaq Nordic Exchanges
        map.insert("XSTO", vec!["SFB"]);
        map.insert("XCSE", vec!["KFB"]);
        map.insert("XHEL", vec!["HMB"]);
        map.insert("XICE", vec!["ISB"]);
        // Asia-Pacific Exchanges
        map.insert("XASX", vec!["ASX"]);
        map.insert("XHKG", vec!["SEHK"]);
        map.insert("XHKF", vec!["HKFE"]);
        map.insert("XSES", vec!["SGX"]);
        map.insert("XOSE", vec!["OSE.JPN"]);
        map.insert("XTKS", vec!["TSEJ", "TSE.JPN"]);
        map.insert("XKRX", vec!["KSE", "KRX"]);
        map.insert("XTAI", vec!["TASE", "TWSE"]);
        map.insert("XSHG", vec!["SEHKNTL", "SSE"]);
        map.insert("XSHE", vec!["SEHKSZSE"]);
        map.insert("XNSE", vec!["NSE"]);
        map.insert("XBOM", vec!["BSE"]);
        // Other Derivatives Exchanges
        map.insert("XSFE", vec!["SNFE"]);
        map.insert("XMEX", vec!["MEXDER"]);
        // African, Middle Eastern, South American Exchanges
        map.insert("XJSE", vec!["JSE"]);
        map.insert("XBOG", vec!["BVC"]);
        map.insert("XTAE", vec!["TASE"]);
        map.insert("BVMF", vec!["BVMF"]);
        map
    });

/// Returns `true` if the contract is a cryptocurrency contract.
///
/// Centralizes the crypto check used to gate crypto-specific request handling
/// (e.g. the `AGGTRADES` `whatToShow` rule - see
/// [`crate::data::convert::price_type_to_ib_what_to_show_for_security`]).
#[must_use]
pub fn is_crypto_contract(contract: &Contract) -> bool {
    matches!(contract.security_type, SecurityType::Crypto)
}

/// Derives the venue for a crypto contract.
///
/// IB routes crypto to multiple venues; both PAXOS and ZEROHASH are live (which one
/// applies depends on the account/region). Uses the contract's actual exchange when
/// set (e.g. ZEROHASH or PAXOS), falling back to PAXOS when it is unspecified.
#[must_use]
pub fn derive_crypto_venue(contract: &Contract) -> Venue {
    if !contract.exchange.as_str().is_empty() && contract.exchange.as_str() != "SMART" {
        Venue::from(contract.exchange.as_str())
    } else {
        Venue::from("PAXOS")
    }
}

#[must_use]
pub fn possible_exchanges_for_venue(venue: &str) -> Vec<String> {
    if venue == "OPRA" {
        return vec!["SMART".to_string()];
    }

    if let Some(exchanges) = VENUE_MEMBERS.get(venue) {
        return exchanges
            .iter()
            .map(|exchange| (*exchange).to_string())
            .collect();
    }

    vec![venue.to_string()]
}

/// Venue lists for different asset classes
const VENUES_CASH: &[&str] = &["IDEALPRO"];
// IB routes crypto to both PAXOS and ZEROHASH (which one applies depends on the
// account/region); accept both.
const VENUES_CRYPTO: &[&str] = &["PAXOS", "ZEROHASH"];
const VENUES_OPT: &[&str] = &["SMART", "EUREX"];
const VENUES_FUT: &[&str] = &[
    "BELFOX",
    "GLOBEX",
    "CBOT",
    "CFE",
    "CME",
    "COMEX",
    "CBOE",
    "DTB",
    "EUREX",
    "HKFE",
    "ICE",
    "ICEEU",
    "ICEEUSOFT",
    "IDEM",
    "IPE",
    "KCBT",
    "MEXDER",
    "MGE",
    "NYBOT",
    "NYMEX",
    "OSE.JPN",
    "SNFE",
    "SOFFEX",
    "VRTX",
    "CMECRYPTO",
    "NYMEXMETALS",
    "NYMEXNG",
    "NYMEXENERGY",
    "CMEPRECIOUS",
    "CMECURRENCY",
    "CMEINDEX",
    "CMEWEATHER",
    "CMEINTEREST",
    "CMEFLOOR",
    "CBOTFLOOR",
    "NYMEXFLOOR",
    "NYBOTFLOOR",
    "CFEFLOOR",
    "CMEOPTIONS",
    "CBOTOPTIONS",
    "NYMEXOPTIONS",
    "NYBOTOPTIONS",
    "ECBOT",
];
const VENUES_CFD: &[&str] = &["IBCFD", "SMART"];
const VENUES_CMDTY: &[&str] = &["IBCMDTY"];

fn venue_matches(venue_str: &str, venues: &[&str]) -> bool {
    venues.contains(&venue_str)
        || VENUE_MEMBERS
            .get(venue_str)
            .is_some_and(|exchanges| exchanges.iter().any(|exchange| venues.contains(exchange)))
}

fn is_option_venue(venue: &str) -> bool {
    venue == "OPRA" || venue_matches(venue, VENUES_OPT)
}

fn is_canonical_occ_option_symbol(symbol: &str) -> bool {
    let bytes = symbol.as_bytes();
    if bytes.len() != 21 || !symbol.is_ascii() {
        return false;
    }

    let root = &bytes[..6];
    let root_len = root.iter().position(|byte| *byte == b' ').unwrap_or(6);

    root_len > 0
        && root[..root_len].iter().all(u8::is_ascii_graphic)
        && root[root_len..].iter().all(|byte| *byte == b' ')
        && bytes[6..12].iter().all(u8::is_ascii_digit)
        && matches!(bytes[12], b'C' | b'P')
        && bytes[13..].iter().all(u8::is_ascii_digit)
}

/// Futures month codes mapping (F=Jan, G=Feb, H=Mar, J=Apr, K=May, M=Jun, N=Jul, Q=Aug, U=Sep, V=Oct, X=Nov, Z=Dec)
/// This constant is kept for potential future use in more complex parsing scenarios.
#[allow(dead_code)]
const FUTURES_MONTH_CODES: &[(char, &str)] = &[
    ('F', "01"),
    ('G', "02"),
    ('H', "03"),
    ('J', "04"),
    ('K', "05"),
    ('M', "06"),
    ('N', "07"),
    ('Q', "08"),
    ('U', "09"),
    ('V', "10"),
    ('X', "11"),
    ('Z', "12"),
];

/// Determine venue from contract using provider configuration.
///
/// This implements the same logic as Python's `determine_venue_from_contract`:
/// 1. Check symbol-specific venue mapping first (prefix matching)
/// 2. Use VENUE_MEMBERS mapping if convert_exchange_to_mic_venue is enabled
/// 3. Fall back to exchange
pub fn determine_venue_from_contract(
    contract: &Contract,
    symbol_to_mic_venue: &std::collections::HashMap<String, String>,
    convert_exchange_to_mic_venue: bool,
    valid_exchanges: Option<&str>,
) -> String {
    if matches!(contract.security_type, SecurityType::CFD) {
        return "IBCFD".to_string();
    }

    if matches!(contract.security_type, SecurityType::Commodity) {
        return "IBCMDTY".to_string();
    }

    if !symbol_to_mic_venue.is_empty() {
        let symbol = contract.symbol.as_str();
        for (symbol_prefix, symbol_venue) in symbol_to_mic_venue {
            if symbol.starts_with(symbol_prefix) {
                return symbol_venue.clone();
            }
        }
    }

    // Use the exchange from the contract (primaryExchange if exchange is SMART)
    let mut exchange = if contract.exchange.as_str() == "SMART"
        && !contract.primary_exchange.as_str().is_empty()
        && contract.primary_exchange.as_str() != "SMART"
    {
        contract.primary_exchange.as_str().to_string()
    } else {
        contract.exchange.as_str().to_string()
    };

    if exchange == "SMART"
        && let Some(valid_exchanges) = valid_exchanges
    {
        let parts: Vec<&str> = valid_exchanges
            .split(',')
            .map(str::trim)
            .filter(|part| !part.is_empty())
            .collect();

        if let Some(chosen) = parts.iter().find(|part| **part != "SMART") {
            exchange = (*chosen).to_string();
        } else if let Some(first) = parts.first() {
            exchange = (*first).to_string();
        }
    }

    if convert_exchange_to_mic_venue {
        if let Some(venue) = exchange_to_mic_venue(&exchange) {
            return venue;
        }
    }

    exchange
}

/// Convert an Interactive Brokers exchange code to a MIC venue when known.
#[must_use]
pub fn exchange_to_mic_venue(exchange: &str) -> Option<String> {
    VENUE_MEMBERS.iter().find_map(|(venue_member, exchanges)| {
        exchanges
            .contains(&exchange)
            .then(|| (*venue_member).to_string())
    })
}

/// Convert a NautilusTrader `InstrumentId` to an Interactive Brokers `Contract`.
///
/// This function handles all instrument types:
/// - Stocks (STK)
/// - Options (OPT)
/// - Futures (FUT, CONTFUT)
/// - Futures Options (FOP)
/// - Forex (CASH)
/// - Crypto (CRYPTO)
/// - CFDs (CFD)
/// - Commodities (CMDTY)
/// - Indices (IND)
/// - Option Spreads (BAG) - requires contract details map
///
/// # Errors
///
/// Returns an error if the conversion fails (e.g., unsupported instrument type, invalid format).
pub fn instrument_id_to_ib_contract(
    instrument_id: InstrumentId,
    exchange: Option<&str>,
) -> anyhow::Result<Contract> {
    let venue_str = instrument_id.venue.to_string();
    let derived_exchange = if venue_str == "OPRA" {
        "SMART"
    } else {
        VENUE_MEMBERS
            .get(venue_str.as_str())
            .and_then(|exchanges| exchanges.first().copied())
            .or_else(|| {
                if venue_matches(venue_str.as_str(), VENUES_CASH)
                    || venue_matches(venue_str.as_str(), VENUES_CRYPTO)
                    || venue_matches(venue_str.as_str(), VENUES_OPT)
                    || venue_matches(venue_str.as_str(), VENUES_FUT)
                {
                    Some(venue_str.as_str())
                } else {
                    None
                }
            })
            .unwrap_or("SMART")
    };
    let exchange_str = exchange.unwrap_or(derived_exchange);
    let symbol_str = instrument_id.symbol.as_str();

    if let Some(contract) = instrument_id_to_ib_contract_raw(&instrument_id, exchange) {
        return Ok(contract);
    }

    // Handle spreads (BAG contracts) - requires contract details, so we skip for now
    // This should be handled by the instrument provider which has access to contract details
    // if symbol_str.contains(":") {
    //     return create_bag_contract(instrument_id, exchange_str);
    // }

    // Handle Forex (CASH)
    if venue_matches(venue_str.as_str(), VENUES_CASH)
        && let Some(captures) = parse_cash_symbol(symbol_str)
    {
        return Ok(Contract {
            contract_id: 0,
            symbol: Symbol::from(&captures.base),
            security_type: SecurityType::ForexPair,
            exchange: Exchange::from(exchange_str),
            currency: Currency::from(&captures.quote),
            local_symbol: format!("{}.{}", captures.base, captures.quote),
            ..Default::default()
        });
    }

    // Handle Crypto
    if venue_matches(venue_str.as_str(), VENUES_CRYPTO)
        && let Some(captures) = parse_crypto_symbol(symbol_str)
    {
        return Ok(Contract {
            contract_id: 0,
            symbol: Symbol::from(&captures.base),
            security_type: SecurityType::Crypto,
            exchange: Exchange::from(exchange_str),
            currency: Currency::from(&captures.quote),
            local_symbol: format!("{}.{}", captures.base, captures.quote),
            ..Default::default()
        });
    }

    // Handle Options (OPT)
    if is_option_venue(venue_str.as_str()) {
        if venue_str == "OPRA" {
            if !is_canonical_occ_option_symbol(symbol_str) {
                anyhow::bail!("Invalid OPRA option symbol: {symbol_str}");
            }

            return Ok(Contract {
                contract_id: 0,
                security_type: SecurityType::Option,
                exchange: Exchange::from(exchange_str),
                currency: Currency::from("USD"),
                local_symbol: symbol_str.to_string(),
                ..Default::default()
            });
        }

        if let Some(opt) = parse_option_symbol(symbol_str) {
            return Ok(Contract {
                contract_id: 0,
                symbol: Symbol::from(&opt.symbol),
                security_type: SecurityType::Option,
                exchange: Exchange::from(exchange_str),
                currency: Currency::from("USD"), // Will be resolved from contract details
                local_symbol: opt.local_symbol,
                last_trade_date_or_contract_month: opt.expiry,
                strike: opt.strike_value,
                right: Some(opt.right),
                ..Default::default()
            });
        }

        if let Some(opt) = parse_named_option_symbol(symbol_str) {
            return Ok(Contract {
                contract_id: 0,
                symbol: Symbol::from(&opt.trading_class),
                security_type: SecurityType::Option,
                exchange: Exchange::from(exchange_str),
                currency: Currency::from("USD"),
                trading_class: opt.trading_class,
                last_trade_date_or_contract_month: opt.expiry,
                strike: opt.strike_value,
                right: Some(opt.right),
                ..Default::default()
            });
        }
    }

    // Handle Futures and Futures Options
    if venue_matches(venue_str.as_str(), VENUES_FUT) {
        if let Some(fut) = parse_named_futures_symbol(symbol_str) {
            return Ok(Contract {
                contract_id: 0,
                symbol: Symbol::from(&fut.underlying),
                security_type: SecurityType::Future,
                exchange: Exchange::from(exchange_str),
                currency: Currency::from("USD"),
                trading_class: fut.trading_class,
                last_trade_date_or_contract_month: fut.expiry,
                ..Default::default()
            });
        }

        // Check for continuous futures (underlying only, no expiry)
        // IB uses FUT with no expiry date to represent continuous futures
        if let Some(underlying) = parse_futures_underlying(symbol_str) {
            return Ok(Contract {
                contract_id: 0,
                symbol: Symbol::from(&underlying),
                security_type: SecurityType::ContinuousFuture,
                exchange: Exchange::from(exchange_str),
                currency: Currency::from("USD"), // Will be resolved from contract details
                ..Default::default()
            });
        }

        // Check for Futures Options (FOP)
        if let Some(local_symbol) = parse_futures_option_symbol(symbol_str) {
            return Ok(Contract {
                contract_id: 0,
                security_type: SecurityType::FuturesOption,
                exchange: Exchange::from(exchange_str),
                currency: Currency::from("USD"),
                local_symbol,
                ..Default::default()
            });
        }

        // Check for regular Futures (FUT)
        if let Some(fut) = parse_futures_symbol(symbol_str) {
            return Ok(Contract {
                contract_id: 0,
                security_type: SecurityType::Future,
                exchange: Exchange::from(exchange_str),
                currency: Currency::from("USD"),
                local_symbol: fut.local_symbol,
                ..Default::default()
            });
        }
    }

    // Handle CFDs
    if venue_matches(venue_str.as_str(), VENUES_CFD) {
        if let Some(captures) =
            parse_cash_symbol(symbol_str).or_else(|| parse_cfd_cash_symbol(symbol_str))
        {
            return Ok(Contract {
                contract_id: 0,
                symbol: Symbol::from(&captures.base),
                security_type: SecurityType::CFD,
                exchange: Exchange::from("SMART"),
                currency: Currency::from(&captures.quote),
                local_symbol: format!("{}.{}", captures.base, captures.quote),
                ..Default::default()
            });
        } else {
            // CFD with space-separated symbol
            let symbol_clean = symbol_str.replace('-', " ");
            return Ok(Contract {
                contract_id: 0,
                symbol: Symbol::from(&symbol_clean),
                security_type: SecurityType::CFD,
                exchange: Exchange::from("SMART"),
                currency: Currency::from("USD"),
                ..Default::default()
            });
        }
    }

    // Handle Commodities
    if VENUES_CMDTY.contains(&venue_str.as_str()) {
        let symbol_clean = symbol_str.replace('-', " ");
        return Ok(Contract {
            contract_id: 0,
            symbol: Symbol::from(&symbol_clean),
            security_type: SecurityType::Commodity,
            exchange: Exchange::from("SMART"),
            currency: Currency::from("USD"),
            ..Default::default()
        });
    }

    // Handle Indices (symbols starting with ^)
    if let Some(local_symbol) = symbol_str.strip_prefix('^') {
        return Ok(Contract {
            contract_id: 0,
            symbol: Symbol::from(local_symbol),
            security_type: SecurityType::Index,
            exchange: Exchange::from(exchange_str),
            currency: Currency::from("USD"),
            local_symbol: local_symbol.into(),
            ..Default::default()
        });
    }

    // Default to Stock (STK)
    let symbol_clean = symbol_str.replace('-', " ");
    Ok(Contract {
        contract_id: 0,
        symbol: Symbol::from(&symbol_clean),
        security_type: SecurityType::Stock,
        exchange: Exchange::from("SMART"),
        currency: Currency::from(""), // Will be resolved from contract details
        primary_exchange: Exchange::from(exchange_str),
        ..Default::default()
    })
}

fn instrument_id_to_ib_contract_raw(
    instrument_id: &InstrumentId,
    exchange: Option<&str>,
) -> Option<Contract> {
    let (local_symbol, sec_type_code) = instrument_id.symbol.as_str().rsplit_once('=')?;

    let venue_exchange = instrument_id.venue.as_str().replace('/', ".");
    let security_type = IbSecurityType::from_str(sec_type_code)
        .ok()
        .map(IbSecurityType::ibapi_security_type)?;
    let default_exchange =
        if security_type == SecurityType::Option && instrument_id.venue.as_str() == "OPRA" {
            "SMART"
        } else {
            venue_exchange.as_str()
        };
    let exchange_str = exchange.unwrap_or(default_exchange);

    let contract = match security_type {
        SecurityType::Stock => Contract {
            contract_id: 0,
            security_type,
            exchange: Exchange::from("SMART"),
            primary_exchange: Exchange::from(exchange_str),
            local_symbol: local_symbol.to_string(),
            ..Default::default()
        },
        SecurityType::CFD | SecurityType::Commodity => Contract {
            contract_id: 0,
            security_type,
            exchange: Exchange::from("SMART"),
            local_symbol: local_symbol.to_string(),
            ..Default::default()
        },
        SecurityType::Index => Contract {
            contract_id: 0,
            security_type,
            exchange: Exchange::from(exchange_str),
            local_symbol: local_symbol.to_string(),
            ..Default::default()
        },
        _ => Contract {
            contract_id: 0,
            security_type,
            exchange: Exchange::from(exchange_str),
            local_symbol: local_symbol.to_string(),
            ..Default::default()
        },
    };

    Some(contract)
}

/// Currency pair captures
struct CurrencyPair {
    base: String,
    quote: String,
}

/// Parse cash/forex symbol like "EUR/USD"
fn parse_cash_symbol(symbol: &str) -> Option<CurrencyPair> {
    if let Some((base, quote)) = symbol.split_once('/')
        && base.len() == 3
        && quote.len() == 3
    {
        return Some(CurrencyPair {
            base: base.to_string(),
            quote: quote.to_string(),
        });
    }
    None
}

/// Parse crypto symbol like "BTC/USD".
fn parse_crypto_symbol(symbol: &str) -> Option<CurrencyPair> {
    if let Some((base, quote)) = symbol.split_once('/')
        && !base.is_empty()
        && base.chars().all(|ch| ch.is_ascii_uppercase())
        && quote.len() == 3
        && quote.chars().all(|ch| ch.is_ascii_uppercase())
    {
        return Some(CurrencyPair {
            base: base.to_string(),
            quote: quote.to_string(),
        });
    }
    None
}

/// Parse CFD cash symbol like "EUR.USD"
fn parse_cfd_cash_symbol(symbol: &str) -> Option<CurrencyPair> {
    if let Some((base, quote)) = symbol.split_once('.')
        && base.len() == 3
        && quote.len() == 3
    {
        return Some(CurrencyPair {
            base: base.to_string(),
            quote: quote.to_string(),
        });
    }
    None
}

/// Option symbol captures
struct OptionSymbol {
    symbol: String,
    expiry: String,
    right: OptionRight,
    local_symbol: String,
    strike_value: f64,
}

/// Parse option symbol like "AAPL230120C00150000" (6-char symbol, 6-char expiry YYMMDD, 1-char right, 8-char strike)
fn parse_option_symbol(symbol: &str) -> Option<OptionSymbol> {
    // Pattern: SYMBOL + YYMMDD + C/P + STRIKE (8 digits, could have decimal)
    // Minimum: 6 (symbol) + 6 (date) + 1 (right) + 8 (strike) = 21 chars
    if symbol.len() < 21 {
        return None;
    }

    // Try to match: 6-char symbol, 6-char date, 1-char right (C/P), remainder is strike
    let symbol_part = symbol[..6.min(symbol.len())].trim();
    let remaining = &symbol[6.min(symbol.len())..];

    if remaining.len() < 15 {
        return None;
    }

    let expiry = &remaining[..6];
    let right_char = remaining.chars().nth(6)?;
    let right = IbOptionRight::from_str(&right_char.to_string()).ok()?;

    let strike_str = &remaining[7..];
    if strike_str.len() < 8 {
        return None;
    }

    // Strike is typically 8 digits with possible decimal
    let strike_value = if strike_str.contains('.') {
        strike_str.parse().ok()?
    } else {
        // 8-digit integer strike, divide by 1000 for typical option strikes
        let strike_int: i32 = strike_str.parse().ok()?;
        strike_int as f64 / 1000.0
    };

    Some(OptionSymbol {
        symbol: symbol_part.to_string(),
        expiry: expiry.to_string(),
        right: ib_option_right_to_option_right(right),
        local_symbol: symbol.to_string(),
        strike_value,
    })
}

/// Named option symbol captures for formats like "C OESX 20260213 4775".
struct NamedOptionSymbol {
    trading_class: String,
    expiry: String,
    right: OptionRight,
    strike_value: f64,
}

/// Named futures symbol captures for formats like "ESTX50 FESX 20240315".
struct NamedFuturesSymbol {
    underlying: String,
    trading_class: String,
    expiry: String,
}

fn parse_named_futures_symbol(symbol: &str) -> Option<NamedFuturesSymbol> {
    let parts: Vec<&str> = symbol.split_whitespace().collect();
    if parts.len() != 3 {
        return None;
    }

    let expiry = parts[2];
    if expiry.len() != 8 || !expiry.chars().all(|c| c.is_ascii_digit()) {
        return None;
    }

    Some(NamedFuturesSymbol {
        underlying: parts[0].to_string(),
        trading_class: parts[1].to_string(),
        expiry: expiry.to_string(),
    })
}

fn parse_named_option_symbol(symbol: &str) -> Option<NamedOptionSymbol> {
    let parts: Vec<&str> = symbol.split_whitespace().collect();
    if !(parts.len() == 4 || parts.len() == 5) {
        return None;
    }

    let right = IbOptionRight::from_str(parts[0]).ok()?;

    let expiry = parts[2];
    if expiry.len() != 8 || !expiry.chars().all(|c| c.is_ascii_digit()) {
        return None;
    }

    Some(NamedOptionSymbol {
        trading_class: parts[1].to_string(),
        expiry: expiry.to_string(),
        right: ib_option_right_to_option_right(right),
        strike_value: parts[3].parse::<f64>().ok()?,
    })
}

fn normalize_option_symbol(local_symbol: &str) -> String {
    if local_symbol.len() >= 15 {
        let (root, suffix) = local_symbol.split_at(local_symbol.len() - 15);
        let is_occ_suffix = suffix[..6].chars().all(|c| c.is_ascii_digit())
            && matches!(suffix.chars().nth(6), Some('C' | 'P'))
            && suffix[7..].chars().all(|c| c.is_ascii_digit());

        if !root.is_empty() && root.len() <= 6 && is_occ_suffix {
            return format!("{:<6}{}", root.trim_end(), suffix);
        }
    }

    local_symbol.to_string()
}

fn format_option_strike(strike: f64) -> String {
    if strike.fract() == 0.0 {
        format!("{strike:.0}")
    } else {
        format!("{strike}")
    }
}

/// Futures symbol captures
struct FuturesSymbol {
    local_symbol: String,
}

/// Parse futures underlying (continuous) - just the symbol without expiry
fn parse_futures_underlying(symbol: &str) -> Option<String> {
    // If it's just 1-3 characters, it's likely an underlying
    if symbol.len() <= 3 && symbol.chars().all(|c| c.is_alphabetic()) {
        Some(symbol.to_string())
    } else {
        None
    }
}

fn is_futures_month_code(ch: char) -> bool {
    matches!(
        ch,
        'F' | 'G' | 'H' | 'J' | 'K' | 'M' | 'N' | 'Q' | 'U' | 'V' | 'X' | 'Z'
    )
}

fn parse_futures_month_and_year(symbol: &str) -> Option<(usize, char, String)> {
    for (month_pos, month_char) in symbol.char_indices().rev() {
        if !is_futures_month_code(month_char) {
            continue;
        }

        let remaining = &symbol[month_pos + month_char.len_utf8()..];
        if remaining.is_empty() || !remaining.chars().all(|ch| ch.is_ascii_digit()) {
            continue;
        }

        let year = match remaining.len() {
            1 | 2 => remaining.to_string(),
            4 => remaining[remaining.len() - 2..].to_string(),
            _ => continue,
        };

        if month_pos == 0 {
            continue;
        }

        return Some((month_pos, month_char, year));
    }

    None
}

/// Parse futures symbol like "YMM6", "ESM23", or "ESM2023"
fn parse_futures_symbol(symbol: &str) -> Option<FuturesSymbol> {
    parse_futures_month_and_year(symbol).map(|_| FuturesSymbol {
        local_symbol: symbol.to_string(),
    })
}

/// Parse futures option symbol like "YMM6 C4500", "ESM23 C4500", or "ESM2023 C4500"
fn parse_futures_option_symbol(symbol: &str) -> Option<String> {
    let (futures_symbol, rest) = symbol.split_once(' ')?;
    let (month_pos, _, _) = parse_futures_month_and_year(futures_symbol)?;
    let _fut_symbol = &futures_symbol[..month_pos];

    // Parse right and strike
    let right_char = rest.chars().next()?;
    IbOptionRight::from_str(&right_char.to_string()).ok()?;

    let strike_str = &rest[1..];
    strike_str.parse::<f64>().ok()?;

    Some(symbol.to_string())
}

/// Check if an instrument ID represents a spread.
///
/// This checks if the symbol contains the spread format pattern: `(ratio)symbol_` or `((ratio))symbol_`
#[must_use]
pub fn is_spread_instrument_id(instrument_id: &InstrumentId) -> bool {
    let symbol_str = instrument_id.symbol.as_str();
    // Check if symbol contains spread pattern: (ratio) or ((ratio))
    symbol_str.contains('(') && symbol_str.contains('_')
}

/// Create a spread instrument ID from leg tuples.
///
/// This implements the same logic as Python's `InstrumentId.new_spread`:
/// - Creates a symbol string like `(1)SYMBOL1_((2))SYMBOL2`
/// - Positive ratios: `(ratio)SYMBOL`
/// - Negative ratios: `((abs(ratio)))SYMBOL`
/// - Sorts legs alphabetically by symbol
/// - All legs must have the same venue
///
/// # Errors
///
/// Returns an error if:
/// - Less than 2 legs provided
/// - Any ratio is zero
/// - Venues don't match across legs
pub fn create_spread_instrument_id(
    leg_tuples: &[(InstrumentId, i32)],
) -> anyhow::Result<InstrumentId> {
    if leg_tuples.len() < 2 {
        anyhow::bail!("instrument_ratios list needs to have at least 2 legs");
    }

    let first_venue = leg_tuples[0].0.venue;

    for (instrument_id, ratio) in leg_tuples {
        if *ratio == 0 {
            anyhow::bail!("ratio cannot be zero");
        }

        if instrument_id.venue != first_venue {
            anyhow::bail!(
                "All venues must match. Expected {}, was {}",
                first_venue,
                instrument_id.venue
            );
        }
    }

    let mut sorted_ratios = leg_tuples.to_vec();
    sorted_ratios.sort_by(|a, b| a.0.symbol.as_str().cmp(b.0.symbol.as_str()));

    let symbol_parts = sorted_ratios
        .iter()
        .map(|(instrument_id, ratio)| {
            if *ratio > 0 {
                format!("({}){}", ratio, instrument_id.symbol.as_str())
            } else {
                format!("(({})){}", ratio.abs(), instrument_id.symbol.as_str())
            }
        })
        .collect::<Vec<_>>();

    let composite_symbol = symbol_parts.join("_");
    let symbol = NautilusSymbol::from(composite_symbol.as_str());

    Ok(InstrumentId::new(symbol, first_venue))
}

/// Parse a spread instrument ID back into leg tuples.
///
/// This implements the same logic as Python's `InstrumentId.to_list()`:
/// - Parses symbol string like `(1)SYMBOL1_((2))SYMBOL2`
/// - Positive ratios: `(ratio)SYMBOL`
/// - Negative ratios: `((abs(ratio)))SYMBOL`
/// - Returns sorted list of (instrument_id, ratio) tuples
///
/// # Errors
///
/// Returns an error if the symbol format is invalid.
pub fn parse_spread_instrument_id_to_legs(
    instrument_id: &InstrumentId,
) -> anyhow::Result<Vec<(InstrumentId, i32)>> {
    let symbol_str = instrument_id.symbol.as_str();
    let venue = instrument_id.venue;

    let components: Vec<&str> = symbol_str.split('_').collect();
    let mut result = Vec::new();

    for component in components {
        if component.is_empty() {
            continue;
        }

        // Check for negative ratio: ((ratio))symbol
        if let Some(rest) = component.strip_prefix("((")
            && let Some(pos) = rest.find("))")
        {
            let ratio_str = &rest[..pos];
            let symbol_value = &rest[pos + 2..];

            if let Ok(ratio) = ratio_str.parse::<i32>() {
                let leg_instrument_id =
                    InstrumentId::new(NautilusSymbol::from(symbol_value), venue);
                result.push((leg_instrument_id, -ratio));
                continue;
            }
        }

        // Check for positive ratio: (ratio)symbol
        if let Some(rest) = component.strip_prefix('(')
            && let Some(pos) = rest.find(')')
        {
            let ratio_str = &rest[..pos];
            let symbol_value = &rest[pos + 1..];

            if let Ok(ratio) = ratio_str.parse::<i32>() {
                let leg_instrument_id =
                    InstrumentId::new(NautilusSymbol::from(symbol_value), venue);
                result.push((leg_instrument_id, ratio));
                continue;
            }
        }

        anyhow::bail!("Invalid spread symbol format for component: {component}");
    }

    // Sort result alphabetically by symbol
    result.sort_by(|a, b| a.0.symbol.as_str().cmp(b.0.symbol.as_str()));

    Ok(result)
}

#[cfg(test)]
mod tests {
    use ibapi::contracts::{Contract, Currency, Exchange, OptionRight, SecurityType, Symbol};
    use nautilus_model::identifiers::InstrumentId;
    use rstest::rstest;

    use super::{
        exchange_to_mic_venue, ib_contract_to_instrument_id_simplified,
        instrument_id_to_ib_contract, possible_exchanges_for_venue,
    };

    #[rstest]
    fn test_ib_contract_to_instrument_id_simplified_normalizes_occ_option_root() {
        let contract = Contract {
            symbol: Symbol::from("SPXW"),
            security_type: SecurityType::Option,
            exchange: Exchange::from("SMART"),
            currency: Currency::from("USD"),
            local_symbol: "SPXW260313P06630000".to_string(),
            last_trade_date_or_contract_month: "260313".to_string(),
            right: Some(OptionRight::Put),
            strike: 6630.0,
            ..Default::default()
        };

        let instrument_id = ib_contract_to_instrument_id_simplified(&contract, None).unwrap();

        assert_eq!(
            instrument_id,
            InstrumentId::from("SPXW  260313P06630000.SMART")
        );
    }

    #[rstest]
    fn test_ib_contract_to_instrument_id_simplified_formats_named_option_without_local_symbol() {
        let contract = Contract {
            symbol: Symbol::from("OESX"),
            security_type: SecurityType::Option,
            exchange: Exchange::from("EUREX"),
            currency: Currency::from("EUR"),
            trading_class: "OESX".to_string(),
            local_symbol: String::new(),
            last_trade_date_or_contract_month: "20260213".to_string(),
            right: Some(OptionRight::Call),
            strike: 4775.0,
            ..Default::default()
        };

        let instrument_id = ib_contract_to_instrument_id_simplified(&contract, None).unwrap();

        assert_eq!(
            instrument_id,
            InstrumentId::from("C OESX 20260213 4775.EUREX")
        );
    }

    #[rstest]
    fn test_ib_contract_to_instrument_id_simplified_preserves_fop_spacing() {
        let contract = Contract {
            symbol: Symbol::from("EX2"),
            security_type: SecurityType::FuturesOption,
            exchange: Exchange::from("NYBOT"),
            currency: Currency::from("USD"),
            local_symbol: "EX2G3 P4080".to_string(),
            ..Default::default()
        };

        let instrument_id = ib_contract_to_instrument_id_simplified(&contract, None).unwrap();

        assert_eq!(instrument_id, InstrumentId::from("EX2G3 P4080.NYBOT"));
    }

    #[rstest]
    fn test_instrument_id_to_ib_contract_parses_named_option_symbol() {
        let instrument_id = InstrumentId::from("C OESX 20260213 4775.EUREX");

        let contract = instrument_id_to_ib_contract(instrument_id, None).unwrap();

        assert_eq!(contract.security_type, SecurityType::Option);
        assert_eq!(contract.exchange.as_str(), "EUREX");
        assert_eq!(contract.symbol.as_str(), "OESX");
        assert_eq!(contract.trading_class.as_str(), "OESX");
        assert_eq!(
            contract.last_trade_date_or_contract_month.as_str(),
            "20260213"
        );
        assert_eq!(contract.right.map(|right| right.as_str()), Some("C"));
        assert_eq!(contract.strike, 4775.0);
    }

    #[rstest]
    fn test_instrument_id_to_ib_contract_preserves_occ_local_symbol() {
        let instrument_id = InstrumentId::from("AAPL  230217P00155000.SMART");

        let contract = instrument_id_to_ib_contract(instrument_id, None).unwrap();

        assert_eq!(contract.security_type, SecurityType::Option);
        assert_eq!(contract.exchange.as_str(), "SMART");
        assert_eq!(contract.symbol.as_str(), "AAPL");
        assert_eq!(contract.local_symbol.as_str(), "AAPL  230217P00155000");
        assert_eq!(
            contract.last_trade_date_or_contract_month.as_str(),
            "230217"
        );
        assert_eq!(contract.right.map(|right| right.as_str()), Some("P"));
        assert_eq!(contract.strike, 155.0);
    }

    #[rstest]
    fn test_possible_exchanges_for_opra_routes_to_smart() {
        assert_eq!(
            possible_exchanges_for_venue("OPRA"),
            vec!["SMART".to_string()]
        );
    }

    #[rstest]
    fn test_opra_occ_option_default_contract_routes_to_smart() {
        let instrument_id = InstrumentId::from("SPY   240319P00511000.OPRA");

        let contract = instrument_id_to_ib_contract(instrument_id, None).unwrap();

        assert_eq!(contract.security_type, SecurityType::Option);
        assert_eq!(contract.exchange.as_str(), "SMART");
        assert!(contract.symbol.as_str().is_empty());
        assert_eq!(contract.currency.as_str(), "USD");
        assert_eq!(contract.local_symbol.as_str(), "SPY   240319P00511000");
        assert!(contract.last_trade_date_or_contract_month.is_empty());
        assert!(contract.right.is_none());
        assert_eq!(contract.strike, 0.0);
    }

    #[rstest]
    fn test_opra_occ_option_qualification_contract_uses_opt_smart() {
        let instrument_id = InstrumentId::from("SPY   240319P00511000.OPRA");
        let exchanges = possible_exchanges_for_venue(instrument_id.venue.as_str());

        assert_eq!(exchanges, vec!["SMART".to_string()]);

        let contract =
            instrument_id_to_ib_contract(instrument_id, exchanges.first().map(String::as_str))
                .unwrap();

        assert_eq!(contract.security_type, SecurityType::Option);
        assert_eq!(contract.exchange.as_str(), "SMART");
        assert!(contract.symbol.as_str().is_empty());
        assert_eq!(contract.currency.as_str(), "USD");
        assert_eq!(contract.local_symbol.as_str(), "SPY   240319P00511000");
        assert!(contract.last_trade_date_or_contract_month.is_empty());
        assert!(contract.right.is_none());
        assert_eq!(contract.strike, 0.0);
    }

    #[rstest]
    fn test_opra_raw_option_default_contract_routes_to_smart() {
        let instrument_id = InstrumentId::from("SPY   240319P00511000=OPT.OPRA");

        let contract = instrument_id_to_ib_contract(instrument_id, None).unwrap();

        assert_eq!(contract.security_type, SecurityType::Option);
        assert_eq!(contract.exchange.as_str(), "SMART");
        assert_eq!(contract.local_symbol.as_str(), "SPY   240319P00511000");
    }

    #[rstest]
    #[case("SPY   240319P00511000.OPRA")]
    #[case("SPY   240319P00511000=OPT.OPRA")]
    fn test_opra_option_respects_exchange_override(#[case] value: &str) {
        let instrument_id = InstrumentId::from(value);

        let contract = instrument_id_to_ib_contract(instrument_id, Some("CBOE")).unwrap();

        assert_eq!(contract.security_type, SecurityType::Option);
        assert_eq!(contract.exchange.as_str(), "CBOE");
    }

    #[rstest]
    #[case("AAPL.OPRA")]
    #[case("SPY   abcdefP00511000.OPRA")]
    #[case("P SPY 20240319 511.OPRA")]
    fn test_invalid_opra_occ_option_returns_error(#[case] value: &str) {
        let instrument_id = InstrumentId::from(value);

        let result = instrument_id_to_ib_contract(instrument_id, None);

        assert!(result.is_err());
    }

    #[rstest]
    fn test_opra_route_does_not_create_reverse_smart_mapping() {
        assert_eq!(exchange_to_mic_venue("SMART"), None);
    }

    #[rstest]
    fn test_instrument_id_to_ib_contract_parses_named_futures_symbol() {
        let instrument_id = InstrumentId::from("ESTX50 FESX 20240315.EUREX");

        let contract = instrument_id_to_ib_contract(instrument_id, None).unwrap();

        assert_eq!(contract.security_type, SecurityType::Future);
        assert_eq!(contract.exchange.as_str(), "EUREX");
        assert_eq!(contract.symbol.as_str(), "ESTX50");
        assert_eq!(contract.trading_class.as_str(), "FESX");
        assert_eq!(
            contract.last_trade_date_or_contract_month.as_str(),
            "20240315"
        );
    }

    #[rstest]
    fn test_instrument_id_to_ib_contract_maps_xcbt_to_cbot_exchange() {
        let instrument_id = InstrumentId::from("YMM6.XCBT");

        let contract = instrument_id_to_ib_contract(instrument_id, None).unwrap();

        assert_eq!(contract.security_type, SecurityType::Future);
        assert_eq!(contract.exchange.as_str(), "CBOT");
        assert_eq!(contract.local_symbol.as_str(), "YMM6");
        assert!(contract.symbol.as_str().is_empty());
        assert!(contract.last_trade_date_or_contract_month.is_empty());
    }

    #[rstest]
    fn test_instrument_id_to_ib_contract_maps_mic_future_to_member_exchange() {
        let instrument_id = InstrumentId::from("OESXH6.XEUR");

        let contract = instrument_id_to_ib_contract(instrument_id, None).unwrap();

        assert_eq!(contract.security_type, SecurityType::Future);
        assert_eq!(contract.exchange.as_str(), "DTB");
        assert_eq!(contract.local_symbol.as_str(), "OESXH6");
    }

    #[rstest]
    fn test_instrument_id_to_ib_contract_parses_futures_option_with_month_code_in_symbol() {
        let instrument_id = InstrumentId::from("YMM6 C45000.XCBT");

        let contract = instrument_id_to_ib_contract(instrument_id, None).unwrap();

        assert_eq!(contract.security_type, SecurityType::FuturesOption);
        assert_eq!(contract.exchange.as_str(), "CBOT");
        assert_eq!(contract.local_symbol.as_str(), "YMM6 C45000");
    }

    #[rstest]
    fn test_instrument_id_to_ib_contract_parses_ibcfd_cash_symbol() {
        let instrument_id = InstrumentId::from("EUR/USD.IBCFD");

        let contract = instrument_id_to_ib_contract(instrument_id, None).unwrap();

        assert_eq!(contract.security_type, SecurityType::CFD);
        assert_eq!(contract.exchange.as_str(), "SMART");
        assert_eq!(contract.symbol.as_str(), "EUR");
        assert_eq!(contract.currency.as_str(), "USD");
        assert_eq!(contract.local_symbol.as_str(), "EUR.USD");
    }

    #[rstest]
    fn test_instrument_id_to_ib_contract_parses_long_crypto_symbol() {
        let instrument_id = InstrumentId::from("DOGE/USD.PAXOS");

        let contract = instrument_id_to_ib_contract(instrument_id, None).unwrap();

        assert_eq!(contract.security_type, SecurityType::Crypto);
        assert_eq!(contract.exchange.as_str(), "PAXOS");
        assert_eq!(contract.symbol.as_str(), "DOGE");
        assert_eq!(contract.currency.as_str(), "USD");
        assert_eq!(contract.local_symbol.as_str(), "DOGE.USD");
    }

    #[rstest]
    fn test_instrument_id_to_ib_contract_parses_zerohash_crypto_symbol() {
        // ZEROHASH is one of IB's crypto venues (alongside PAXOS).
        let instrument_id = InstrumentId::from("BTC/USD.ZEROHASH");

        let contract = instrument_id_to_ib_contract(instrument_id, None).unwrap();

        assert_eq!(contract.security_type, SecurityType::Crypto);
        assert_eq!(contract.exchange.as_str(), "ZEROHASH");
        assert_eq!(contract.symbol.as_str(), "BTC");
        assert_eq!(contract.currency.as_str(), "USD");
        assert_eq!(contract.local_symbol.as_str(), "BTC.USD");
    }

    #[rstest]
    fn test_ib_contract_to_instrument_id_simplified_derives_zerohash_crypto_venue() {
        // Contract -> InstrumentId derives the venue from the ZEROHASH exchange.
        let contract = Contract {
            symbol: Symbol::from("BTC"),
            security_type: SecurityType::Crypto,
            exchange: Exchange::from("ZEROHASH"),
            currency: Currency::from("USD"),
            local_symbol: "BTC.USD".to_string(),
            ..Default::default()
        };

        let instrument_id = ib_contract_to_instrument_id_simplified(&contract, None).unwrap();

        assert_eq!(instrument_id, InstrumentId::from("BTC/USD.ZEROHASH"));
    }

    #[rstest]
    fn test_ib_contract_to_instrument_id_simplified_falls_back_to_paxos_crypto_venue() {
        // Contract -> InstrumentId falls back to PAXOS when no exchange is set,
        // preserving backwards compatibility.
        let contract = Contract {
            symbol: Symbol::from("DOGE"),
            security_type: SecurityType::Crypto,
            currency: Currency::from("USD"),
            local_symbol: "DOGE.USD".to_string(),
            ..Default::default()
        };

        let instrument_id = ib_contract_to_instrument_id_simplified(&contract, None).unwrap();

        assert_eq!(instrument_id, InstrumentId::from("DOGE/USD.PAXOS"));
    }

    #[rstest]
    fn test_instrument_id_to_ib_contract_parses_paxos_crypto_symbol() {
        // PAXOS remains a live IB crypto venue alongside ZEROHASH.
        let instrument_id = InstrumentId::from("BTC/USD.PAXOS");

        let contract = instrument_id_to_ib_contract(instrument_id, None).unwrap();

        assert_eq!(contract.security_type, SecurityType::Crypto);
        assert_eq!(contract.exchange.as_str(), "PAXOS");
        assert_eq!(contract.symbol.as_str(), "BTC");
        assert_eq!(contract.currency.as_str(), "USD");
        assert_eq!(contract.local_symbol.as_str(), "BTC.USD");
    }

    #[rstest]
    fn test_ib_contract_to_instrument_id_simplified_derives_paxos_crypto_venue() {
        // A PAXOS contract derives the PAXOS venue from its exchange (not via the
        // fallback), proving both venues are honored when explicitly set.
        let contract = Contract {
            symbol: Symbol::from("BTC"),
            security_type: SecurityType::Crypto,
            exchange: Exchange::from("PAXOS"),
            currency: Currency::from("USD"),
            local_symbol: "BTC.USD".to_string(),
            ..Default::default()
        };

        let instrument_id = ib_contract_to_instrument_id_simplified(&contract, None).unwrap();

        assert_eq!(instrument_id, InstrumentId::from("BTC/USD.PAXOS"));
    }

    #[rstest]
    fn test_instrument_id_to_ib_contract_uses_contfut_for_underlying() {
        let instrument_id = InstrumentId::from("ES.XCME");

        let contract = instrument_id_to_ib_contract(instrument_id, None).unwrap();

        assert_eq!(contract.security_type, SecurityType::ContinuousFuture);
        assert_eq!(contract.exchange.as_str(), "CME");
        assert_eq!(contract.symbol.as_str(), "ES");
    }

    #[rstest]
    fn test_instrument_id_to_ib_contract_parses_raw_stock_symbol() {
        let instrument_id = InstrumentId::from("AAPL=STK.NASDAQ");

        let contract = instrument_id_to_ib_contract(instrument_id, None).unwrap();

        assert_eq!(contract.security_type, SecurityType::Stock);
        assert_eq!(contract.exchange.as_str(), "SMART");
        assert_eq!(contract.primary_exchange.as_str(), "NASDAQ");
        assert_eq!(contract.local_symbol.as_str(), "AAPL");
        assert!(contract.symbol.as_str().is_empty());
    }

    #[rstest]
    fn test_instrument_id_to_ib_contract_parses_raw_forex_symbol() {
        let instrument_id = InstrumentId::from("EUR.USD=CASH.IDEALPRO");

        let contract = instrument_id_to_ib_contract(instrument_id, None).unwrap();

        assert_eq!(contract.security_type, SecurityType::ForexPair);
        assert_eq!(contract.exchange.as_str(), "IDEALPRO");
        assert_eq!(contract.local_symbol.as_str(), "EUR.USD");
        assert!(contract.symbol.as_str().is_empty());
    }

    #[rstest]
    fn test_instrument_id_to_ib_contract_raw_respects_exchange_override() {
        let instrument_id = InstrumentId::from("YMM6=FUT.XCBT");

        let contract = instrument_id_to_ib_contract(instrument_id, Some("CBOT")).unwrap();

        assert_eq!(contract.security_type, SecurityType::Future);
        assert_eq!(contract.exchange.as_str(), "CBOT");
        assert_eq!(contract.local_symbol.as_str(), "YMM6");
    }

    #[rstest]
    fn test_instrument_id_to_ib_contract_default_stock_omits_local_symbol_and_currency() {
        let instrument_id = InstrumentId::from("IUSA.IBIS");

        let contract = instrument_id_to_ib_contract(instrument_id, Some("IBIS")).unwrap();

        assert_eq!(contract.security_type, SecurityType::Stock);
        assert_eq!(contract.symbol.as_str(), "IUSA");
        assert_eq!(contract.exchange.as_str(), "SMART");
        assert_eq!(contract.primary_exchange.as_str(), "IBIS");
        assert!(contract.currency.as_str().is_empty());
        assert!(contract.local_symbol.is_empty());
    }
}