-
Notifications
You must be signed in to change notification settings - Fork 395
/
instruments.py
669 lines (608 loc) · 24.7 KB
/
instruments.py
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
# -------------------------------------------------------------------------------------------------
# Copyright (C) 2015-2024 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.
# -------------------------------------------------------------------------------------------------
import datetime
import re
import time
from decimal import Decimal
import pandas as pd
from ibapi.contract import ContractDetails
# fmt: off
from nautilus_trader.adapters.interactive_brokers.common import IBContract
from nautilus_trader.adapters.interactive_brokers.common import IBContractDetails
from nautilus_trader.core.correctness import PyCondition
from nautilus_trader.model.enums import AssetClass
from nautilus_trader.model.enums import OptionKind
from nautilus_trader.model.enums import asset_class_from_str
from nautilus_trader.model.identifiers import InstrumentId
from nautilus_trader.model.identifiers import Symbol
from nautilus_trader.model.identifiers import Venue
from nautilus_trader.model.instruments import Cfd
from nautilus_trader.model.instruments import Commodity
from nautilus_trader.model.instruments import CryptoPerpetual
from nautilus_trader.model.instruments import CurrencyPair
from nautilus_trader.model.instruments import Equity
from nautilus_trader.model.instruments import FuturesContract
from nautilus_trader.model.instruments import IndexInstrument
from nautilus_trader.model.instruments import Instrument
from nautilus_trader.model.instruments import OptionsContract
from nautilus_trader.model.objects import Currency
from nautilus_trader.model.objects import Price
from nautilus_trader.model.objects import Quantity
# fmt: on
FUTURES_MONTH_TO_CODE: dict[str, str] = {
"JAN": "F",
"FEB": "G",
"MAR": "H",
"APR": "J",
"MAY": "K",
"JUN": "M",
"JUL": "N",
"AUG": "Q",
"SEP": "U",
"OCT": "V",
"NOV": "X",
"DEC": "Z",
}
FUTURES_CODE_TO_MONTH = dict(zip(FUTURES_MONTH_TO_CODE.values(), FUTURES_MONTH_TO_CODE.keys()))
VENUES_CASH = ["IDEALPRO"]
VENUES_CRYPTO = ["PAXOS"]
VENUES_OPT = ["SMART"]
VENUES_FUT = [
"CBOT", # US
"CME", # US
"COMEX", # US
"KCBT", # US
"MGE", # US
"NYMEX", # US
"NYBOT", # US
"SNFE", # AU
]
VENUES_CFD = [
"IBCFD", # self named, in fact mapping to "SMART" when parsing
]
VENUES_CMDTY = ["IBCMDTY"] # self named, in fact mapping to "SMART" when parsing
RE_CASH = re.compile(r"^(?P<symbol>[A-Z]{3})\/(?P<currency>[A-Z]{3})$")
RE_CFD_CASH = re.compile(r"^(?P<symbol>[A-Z]{3})\.(?P<currency>[A-Z]{3})$")
RE_OPT = re.compile(
r"^(?P<symbol>^[A-Z]{1,6})(?P<expiry>\d{6})(?P<right>[CP])(?P<strike>\d{5})(?P<decimal>\d{3})$",
)
RE_FUT_UNDERLYING = re.compile(r"^(?P<symbol>\w{1,3})$")
RE_FUT = re.compile(r"^(?P<symbol>\w{1,3})(?P<month>[FGHJKMNQUVXZ])(?P<year>\d{2})$")
RE_FUT_ORIGINAL = re.compile(r"^(?P<symbol>\w{1,3})(?P<month>[FGHJKMNQUVXZ])(?P<year>\d)$")
RE_FUT2 = re.compile(
r"^(?P<symbol>\w{1,4})(?P<month>(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC))(?P<year>\d{2})$",
)
RE_FUT2_ORIGINAL = re.compile(
r"^(?P<symbol>\w{1,4}) *(?P<month>(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)) (?P<year>\d{2})$",
)
RE_FOP = re.compile(
r"^(?P<symbol>\w{1,3})(?P<month>[FGHJKMNQUVXZ])(?P<year>\d{2})(?P<right>[CP])(?P<strike>.{4,5})$",
)
RE_FOP_ORIGINAL = re.compile(
r"^(?P<symbol>\w{1,3})(?P<month>[FGHJKMNQUVXZ])(?P<year>\d) (?P<right>[CP])(?P<strike>.{4,5})$",
)
RE_CRYPTO = re.compile(r"^(?P<symbol>[A-Z]*)\/(?P<currency>[A-Z]{3})$")
def _extract_isin(details: IBContractDetails) -> int:
if details.secIdList:
for tag_value in details.secIdList:
if tag_value.tag == "ISIN":
return tag_value.value
raise ValueError("No ISIN found")
def _tick_size_to_precision(tick_size: float | Decimal) -> int:
tick_size_str = f"{tick_size:.10f}"
return len(tick_size_str.partition(".")[2].rstrip("0"))
def sec_type_to_asset_class(sec_type: str) -> AssetClass:
mapping = {
"STK": "EQUITY",
"IND": "INDEX",
"CASH": "FX",
"BOND": "DEBT",
"CMDTY": "COMMODITY",
}
return asset_class_from_str(mapping.get(sec_type, sec_type))
def contract_details_to_ib_contract_details(details: ContractDetails) -> IBContractDetails:
details.contract = IBContract(**details.contract.__dict__)
details = IBContractDetails(**details.__dict__)
return details
def parse_instrument(
contract_details: IBContractDetails,
strict_symbology: bool = False,
) -> Instrument:
security_type = contract_details.contract.secType
instrument_id = ib_contract_to_instrument_id(
contract=contract_details.contract,
strict_symbology=strict_symbology,
)
if security_type == "STK":
return parse_equity_contract(details=contract_details, instrument_id=instrument_id)
elif security_type == "IND":
return parse_index_contract(details=contract_details, instrument_id=instrument_id)
elif security_type in ("FUT", "CONTFUT"):
return parse_futures_contract(details=contract_details, instrument_id=instrument_id)
elif security_type == "OPT":
return parse_options_contract(details=contract_details, instrument_id=instrument_id)
elif security_type == "CASH":
return parse_forex_contract(details=contract_details, instrument_id=instrument_id)
elif security_type == "CRYPTO":
return parse_crypto_contract(details=contract_details, instrument_id=instrument_id)
elif security_type == "CFD":
return parse_cfd_contract(details=contract_details, instrument_id=instrument_id)
elif security_type == "CMDTY":
return parse_commodity_contract(details=contract_details, instrument_id=instrument_id)
else:
raise ValueError(f"Unknown {security_type=}")
def contract_details_to_dict(details: IBContractDetails) -> dict:
dict_details = details.dict().copy()
dict_details["contract"] = details.contract.dict().copy()
if dict_details.get("secIdList"):
dict_details["secIdList"] = {
tag_value.tag: tag_value.value for tag_value in dict_details["secIdList"]
}
return dict_details
def parse_equity_contract(
details: IBContractDetails,
instrument_id: InstrumentId,
) -> Equity:
price_precision: int = _tick_size_to_precision(details.minTick)
timestamp = time.time_ns()
return Equity(
instrument_id=instrument_id,
raw_symbol=Symbol(details.contract.localSymbol),
currency=Currency.from_str(details.contract.currency),
price_precision=price_precision,
price_increment=Price(details.minTick, price_precision),
lot_size=Quantity.from_int(100),
isin=_extract_isin(details),
ts_event=timestamp,
ts_init=timestamp,
info=contract_details_to_dict(details),
)
def parse_index_contract(
details: IBContractDetails,
instrument_id: InstrumentId,
) -> IndexInstrument:
price_precision: int = _tick_size_to_precision(details.minTick)
size_precision: int = _tick_size_to_precision(details.minSize)
timestamp = time.time_ns()
return IndexInstrument(
instrument_id=instrument_id,
raw_symbol=Symbol(details.contract.localSymbol),
currency=Currency.from_str(details.contract.currency),
price_precision=price_precision,
price_increment=Price(details.minTick, price_precision),
size_precision=size_precision,
size_increment=Quantity(details.sizeIncrement, size_precision),
ts_event=timestamp,
ts_init=timestamp,
info=contract_details_to_dict(details),
)
def expiry_timestring_to_datetime(expiry: str) -> pd.Timestamp:
"""
Most contract expirations are %Y%m%d format some exchanges have expirations in
%Y%m%d %H:%M:%S %Z.
"""
if len(expiry) == 8:
return pd.Timestamp(expiry, tz="UTC")
else:
dt, tz = expiry.rsplit(" ", 1)
ts = pd.Timestamp(dt, tz=tz)
return ts.tz_convert("UTC")
def parse_futures_contract(
details: IBContractDetails,
instrument_id: InstrumentId,
) -> FuturesContract:
price_precision: int = _tick_size_to_precision(details.minTick)
timestamp = time.time_ns()
expiration = expiry_timestring_to_datetime(details.contract.lastTradeDateOrContractMonth)
activation = expiration - pd.Timedelta(days=90) # TODO: Make this more accurate
return FuturesContract(
instrument_id=instrument_id,
raw_symbol=Symbol(details.contract.localSymbol),
asset_class=sec_type_to_asset_class(details.underSecType),
currency=Currency.from_str(details.contract.currency),
price_precision=price_precision,
price_increment=Price(details.minTick, price_precision),
multiplier=Quantity.from_str(details.contract.multiplier),
lot_size=Quantity.from_int(1),
underlying=details.underSymbol,
activation_ns=activation.value,
expiration_ns=expiration.value,
ts_event=timestamp,
ts_init=timestamp,
info=contract_details_to_dict(details),
)
def parse_options_contract(
details: IBContractDetails,
instrument_id: InstrumentId,
) -> OptionsContract:
price_precision: int = _tick_size_to_precision(details.minTick)
timestamp = time.time_ns()
asset_class = sec_type_to_asset_class(details.underSecType)
option_kind = {
"C": OptionKind.CALL,
"P": OptionKind.PUT,
}[details.contract.right]
expiration = expiry_timestring_to_datetime(details.contract.lastTradeDateOrContractMonth)
activation = expiration - pd.Timedelta(days=90) # TODO: Make this more accurate
return OptionsContract(
instrument_id=instrument_id,
raw_symbol=Symbol(details.contract.localSymbol),
asset_class=asset_class,
currency=Currency.from_str(details.contract.currency),
price_precision=price_precision,
price_increment=Price(details.minTick, price_precision),
multiplier=Quantity.from_str(details.contract.multiplier),
lot_size=Quantity.from_int(1),
underlying=details.underSymbol,
strike_price=Price(details.contract.strike, price_precision),
activation_ns=activation.value,
expiration_ns=expiration.value,
option_kind=option_kind,
ts_event=timestamp,
ts_init=timestamp,
info=contract_details_to_dict(details),
)
def parse_forex_contract(
details: IBContractDetails,
instrument_id: InstrumentId,
) -> CurrencyPair:
price_precision: int = _tick_size_to_precision(details.minTick)
size_precision: int = _tick_size_to_precision(details.minSize)
timestamp = time.time_ns()
return CurrencyPair(
instrument_id=instrument_id,
raw_symbol=Symbol(details.contract.localSymbol),
base_currency=Currency.from_str(details.contract.symbol),
quote_currency=Currency.from_str(details.contract.currency),
price_precision=price_precision,
size_precision=size_precision,
price_increment=Price(details.minTick, price_precision),
size_increment=Quantity(details.sizeIncrement, size_precision),
lot_size=None,
max_quantity=None,
min_quantity=None,
max_notional=None,
min_notional=None,
max_price=None,
min_price=None,
margin_init=Decimal(0),
margin_maint=Decimal(0),
maker_fee=Decimal(0),
taker_fee=Decimal(0),
ts_event=timestamp,
ts_init=timestamp,
info=contract_details_to_dict(details),
)
def parse_crypto_contract(
details: IBContractDetails,
instrument_id: InstrumentId,
) -> CryptoPerpetual:
price_precision: int = _tick_size_to_precision(details.minTick)
size_precision: int = _tick_size_to_precision(details.minSize)
timestamp = time.time_ns()
return CryptoPerpetual(
instrument_id=instrument_id,
raw_symbol=Symbol(details.contract.localSymbol),
base_currency=Currency.from_str(details.contract.symbol),
quote_currency=Currency.from_str(details.contract.currency),
settlement_currency=Currency.from_str(details.contract.currency),
is_inverse=True,
price_precision=price_precision,
size_precision=size_precision,
price_increment=Price(details.minTick, price_precision),
size_increment=Quantity(details.sizeIncrement, size_precision),
max_quantity=None,
min_quantity=Quantity(details.minSize, size_precision),
max_notional=None,
min_notional=None,
max_price=None,
min_price=None,
margin_init=Decimal(0),
margin_maint=Decimal(0),
maker_fee=Decimal(0),
taker_fee=Decimal(0),
ts_event=timestamp,
ts_init=timestamp,
info=contract_details_to_dict(details),
)
def parse_cfd_contract(
details: IBContractDetails,
instrument_id: InstrumentId,
) -> Cfd:
price_precision: int = _tick_size_to_precision(details.minTick)
size_precision: int = _tick_size_to_precision(details.minSize)
timestamp = time.time_ns()
if RE_CFD_CASH.match(details.contract.localSymbol):
return Cfd(
instrument_id=instrument_id,
raw_symbol=Symbol(details.contract.localSymbol),
asset_class=sec_type_to_asset_class(details.underSecType),
base_currency=Currency.from_str(details.contract.symbol),
quote_currency=Currency.from_str(details.contract.currency),
price_precision=price_precision,
size_precision=size_precision,
price_increment=Price(details.minTick, price_precision),
size_increment=Quantity(details.sizeIncrement, size_precision),
lot_size=None,
max_quantity=None,
min_quantity=None,
max_notional=None,
min_notional=None,
max_price=None,
min_price=None,
margin_init=Decimal(0),
margin_maint=Decimal(0),
maker_fee=Decimal(0),
taker_fee=Decimal(0),
ts_event=timestamp,
ts_init=timestamp,
info=contract_details_to_dict(details),
)
else:
return Cfd(
instrument_id=instrument_id,
raw_symbol=Symbol(details.contract.localSymbol),
asset_class=sec_type_to_asset_class(details.underSecType),
quote_currency=Currency.from_str(details.contract.currency),
price_precision=price_precision,
size_precision=size_precision,
price_increment=Price(details.minTick, price_precision),
size_increment=Quantity(details.sizeIncrement, size_precision),
lot_size=None,
max_quantity=None,
min_quantity=None,
max_notional=None,
min_notional=None,
max_price=None,
min_price=None,
margin_init=Decimal(0),
margin_maint=Decimal(0),
maker_fee=Decimal(0),
taker_fee=Decimal(0),
ts_event=timestamp,
ts_init=timestamp,
info=contract_details_to_dict(details),
)
def parse_commodity_contract(
details: IBContractDetails,
instrument_id: InstrumentId,
) -> Commodity:
price_precision: int = _tick_size_to_precision(details.minTick)
size_precision: int = _tick_size_to_precision(details.minSize)
timestamp = time.time_ns()
return Commodity(
instrument_id=instrument_id,
raw_symbol=Symbol(details.contract.localSymbol),
asset_class=AssetClass.COMMODITY,
quote_currency=Currency.from_str(details.contract.currency),
price_precision=price_precision,
size_precision=size_precision,
price_increment=Price(details.minTick, price_precision),
size_increment=Quantity(details.sizeIncrement, size_precision),
lot_size=None,
max_quantity=None,
min_quantity=None,
max_notional=None,
min_notional=None,
max_price=None,
min_price=None,
margin_init=Decimal(0),
margin_maint=Decimal(0),
maker_fee=Decimal(0),
taker_fee=Decimal(0),
ts_event=timestamp,
ts_init=timestamp,
info=contract_details_to_dict(details),
)
def decade_digit(last_digit: str, contract: IBContract) -> int:
if year := contract.lastTradeDateOrContractMonth[:4]:
return int(year[2:3])
elif int(last_digit) > int(repr(datetime.datetime.now().year)[-1]):
return int(repr(datetime.datetime.now().year)[-2]) - 1
else:
return int(repr(datetime.datetime.now().year)[-2])
def ib_contract_to_instrument_id(
contract: IBContract,
strict_symbology: bool = False,
) -> InstrumentId:
PyCondition.type(contract, IBContract, "IBContract")
if strict_symbology:
return ib_contract_to_instrument_id_strict_symbology(contract)
else:
return ib_contract_to_instrument_id_simplified_symbology(contract)
def ib_contract_to_instrument_id_strict_symbology(contract: IBContract) -> InstrumentId:
if contract.secType == "CFD":
symbol = f"{contract.localSymbol}={contract.secType}"
venue = "IBCFD"
elif contract.secType == "CMDTY":
symbol = f"{contract.localSymbol}={contract.secType}"
venue = "IBCMDTY"
else:
symbol = f"{contract.localSymbol}={contract.secType}"
venue = (contract.primaryExchange or contract.exchange).replace(".", "/")
return InstrumentId.from_str(f"{symbol}.{venue}")
def ib_contract_to_instrument_id_simplified_symbology( # noqa: C901 (too complex)
contract: IBContract,
) -> InstrumentId:
security_type = contract.secType
if security_type == "STK":
symbol = (contract.localSymbol or contract.symbol).replace(" ", "-")
venue = contract.primaryExchange if contract.exchange == "SMART" else contract.exchange
elif security_type == "IND":
symbol = f"^{(contract.localSymbol or contract.symbol)}"
venue = contract.exchange
elif security_type == "OPT":
symbol = contract.localSymbol.replace(" ", "") or contract.symbol.replace(" ", "")
venue = contract.exchange
elif security_type == "CONTFUT":
symbol = contract.localSymbol.replace(" ", "") or contract.symbol.replace(" ", "")
venue = contract.exchange
elif security_type == "FUT" and (m := RE_FUT_ORIGINAL.match(contract.localSymbol)):
symbol = f"{m['symbol']}{m['month']}{decade_digit(m['year'], contract)}{m['year']}"
venue = contract.exchange
elif security_type == "FUT" and (m := RE_FUT2_ORIGINAL.match(contract.localSymbol)):
symbol = f"{m['symbol']}{FUTURES_MONTH_TO_CODE[m['month']]}{m['year']}"
venue = contract.exchange
elif security_type == "FOP" and (m := RE_FOP_ORIGINAL.match(contract.localSymbol)):
symbol = f"{m['symbol']}{m['month']}{decade_digit(m['year'], contract)}{m['year']}{m['right']}{m['strike']}"
venue = contract.exchange
elif security_type in ["CASH", "CRYPTO"]:
symbol = (
f"{contract.localSymbol}".replace(".", "/") or f"{contract.symbol}/{contract.currency}"
)
venue = contract.exchange
elif security_type == "CFD":
if m := RE_CFD_CASH.match(contract.localSymbol):
symbol = (
f"{contract.localSymbol}".replace(".", "/")
or f"{contract.symbol}/{contract.currency}"
)
venue = "IBCFD"
else:
symbol = (contract.symbol).replace(" ", "-")
venue = "IBCFD"
elif security_type == "CMDTY":
symbol = (contract.symbol).replace(" ", "-")
venue = "IBCMDTY"
else:
symbol = None
venue = None
if symbol and venue:
return InstrumentId(Symbol(symbol), Venue(venue))
raise ValueError(f"Unknown {contract=}")
def instrument_id_to_ib_contract(
instrument_id: InstrumentId,
strict_symbology: bool = False,
) -> IBContract:
PyCondition.type(instrument_id, InstrumentId, "InstrumentId")
if strict_symbology:
return instrument_id_to_ib_contract_strict_symbology(instrument_id)
else:
return instrument_id_to_ib_contract_simplified_symbology(instrument_id)
def instrument_id_to_ib_contract_strict_symbology(instrument_id: InstrumentId) -> IBContract:
local_symbol, security_type = instrument_id.symbol.value.rsplit("=", 1)
exchange = instrument_id.venue.value.replace("/", ".")
if security_type == "STK":
return IBContract(
secType=security_type,
exchange="SMART",
primaryExchange=exchange,
localSymbol=local_symbol,
)
elif security_type == "CFD":
return IBContract(
secType=security_type,
exchange="SMART",
localSymbol=local_symbol, # by IB is a cfd's local symbol of STK with a "n" as tail, e.g. "NVDAn". "
)
elif security_type == "CMDTY":
return IBContract(
secType=security_type,
exchange="SMART",
localSymbol=local_symbol,
)
elif security_type == "IND":
return IBContract(
secType=security_type,
exchange=exchange,
localSymbol=local_symbol,
)
else:
return IBContract(
secType=security_type,
exchange=exchange,
localSymbol=local_symbol,
)
def instrument_id_to_ib_contract_simplified_symbology( # noqa: C901 (too complex)
instrument_id: InstrumentId,
) -> IBContract:
if instrument_id.venue.value in VENUES_CASH and (
m := RE_CASH.match(instrument_id.symbol.value)
):
return IBContract(
secType="CASH",
exchange=instrument_id.venue.value,
localSymbol=f"{m['symbol']}.{m['currency']}",
)
elif instrument_id.venue.value in VENUES_CRYPTO and (
m := RE_CRYPTO.match(instrument_id.symbol.value)
):
return IBContract(
secType="CRYPTO",
exchange=instrument_id.venue.value,
localSymbol=f"{m['symbol']}.{m['currency']}",
)
elif instrument_id.venue.value in VENUES_OPT and (
m := RE_OPT.match(instrument_id.symbol.value)
):
return IBContract(
secType="OPT",
exchange=instrument_id.venue.value,
localSymbol=f"{m['symbol'].ljust(6)}{m['expiry']}{m['right']}{m['strike']}{m['decimal']}",
)
elif instrument_id.venue.value in VENUES_FUT:
if m := RE_FUT.match(instrument_id.symbol.value):
return IBContract(
secType="FUT",
exchange=instrument_id.venue.value,
localSymbol=f"{m['symbol']}{m['month']}{m['year'][-1]}",
)
elif m := RE_FUT_UNDERLYING.match(instrument_id.symbol.value):
return IBContract(
secType="CONTFUT",
exchange=instrument_id.venue.value,
symbol=m["symbol"],
)
elif m := RE_FOP.match(instrument_id.symbol.value):
return IBContract(
secType="FOP",
exchange=instrument_id.venue.value,
localSymbol=f"{m['symbol']}{m['month']}{m['year'][-1]} {m['right']}{m['strike']}",
)
else:
raise ValueError(f"Cannot parse {instrument_id}, use 2-digit year for FUT and FOP")
elif instrument_id.venue.value in VENUES_CFD:
if m := RE_CASH.match(instrument_id.symbol.value):
return IBContract(
secType="CFD",
exchange="SMART",
symbol=m["symbol"],
localSymbol=f"{m['symbol']}.{m['currency']}",
)
else:
return IBContract(
secType="CFD",
exchange="SMART",
symbol=f"{instrument_id.symbol.value}".replace("-", " "),
)
elif instrument_id.venue.value in VENUES_CMDTY:
return IBContract(
secType="CMDTY",
exchange="SMART",
symbol=f"{instrument_id.symbol.value}".replace("-", " "),
)
elif str(instrument_id.symbol).startswith("^"):
return IBContract(
secType="IND",
exchange=instrument_id.venue.value,
localSymbol=instrument_id.symbol.value[1:],
)
# Default to Stock
return IBContract(
secType="STK",
exchange="SMART",
primaryExchange=instrument_id.venue.value,
localSymbol=f"{instrument_id.symbol.value}".replace("-", " "),
)