ib-underscore-async-underscore-modules-ib-underscore-async-contract.md
"""Financial instrument types used by Interactive Brokers."""import datetime as dtfrom dataclasses importdataclass,fieldfrom typing importNamedTuple,Optionalimport ib\_async.util as util
[[docs]](../../api.html#ib_async.contract.Contract)@dataclassclass Contract:""" ``Contract(\*\*kwargs)`` can create any contract using keyword arguments. To simplify working with contracts, there are also more specialized contracts that take optional positional arguments. Some examples:: Contract(conId=270639) Stock('AMD', 'SMART', 'USD') Stock('INTC', 'SMART', 'USD', primaryExchange='NASDAQ') Forex('EURUSD') CFD('IBUS30') Future('ES', '20180921', 'GLOBEX') Option('SPY', '20170721', 240, 'C', 'SMART') Bond(secIdType='ISIN', secId='US03076KAA60') Crypto('BTC', 'PAXOS', 'USD') Args: conId (int): The unique IB contract identifier. symbol (str): The contract (or its underlying) symbol. secType (str): The security type: \* 'STK' = Stock (or ETF) \* 'OPT' = Option \* 'FUT' = Future \* 'IND' = Index \* 'FOP' = Futures option \* 'CASH' = Forex pair \* 'CFD' = CFD \* 'BAG' = Combo \* 'WAR' = Warrant \* 'BOND' = Bond \* 'CMDTY' = Commodity \* 'NEWS' = News \* 'FUND' = Mutual fund \* 'CRYPTO' = Crypto currency \* 'EVENT' = Bet on an event lastTradeDateOrContractMonth (str): The contract's last trading day or contract month (for Options and Futures). Strings with format YYYYMM will be interpreted as the Contract Month whereas YYYYMMDD will be interpreted as Last Trading Day. strike (float): The option's strike price. right (str): Put or Call. Valid values are 'P', 'PUT', 'C', 'CALL', or '' for non-options. multiplier (str): The instrument's multiplier (i.e. options, futures). exchange (str): The destination exchange. currency (str): The underlying's currency. localSymbol (str): The contract's symbol within its primary exchange. For options, this will be the OCC symbol. primaryExchange (str): The contract's primary exchange. For smart routed contracts, used to define contract in case of ambiguity. Should be defined as native exchange of contract, e.g. ISLAND for MSFT. For exchanges which contain a period in name, will only be part of exchange name prior to period, i.e. ENEXT for ENEXT.BE. tradingClass (str): The trading class name for this contract. Available in TWS contract description window as well. For example, GBL Dec '13 future's trading class is "FGBL". includeExpired (bool): If set to true, contract details requests and historical data queries can be performed pertaining to expired futures contracts. Expired options or other instrument types are not available. secIdType (str): Security identifier type. Examples for Apple: \* secIdType='ISIN', secId='US0378331005' \* secIdType='CUSIP', secId='037833100' secId (str): Security identifier. comboLegsDescription (str): Description of the combo legs. comboLegs (List[ComboLeg]): The legs of a combined contract definition. deltaNeutralContract (DeltaNeutralContract): Delta and underlying price for Delta-Neutral combo orders. """secType: str = ""conId: int = 0symbol: str = ""lastTradeDateOrContractMonth: str = ""strike: float = 0.0right: str = ""multiplier: str = ""exchange: str = ""primaryExchange: str = ""currency: str = ""localSymbol: str = ""tradingClass: str = ""includeExpired: bool = FalsesecIdType: str = ""secId: str = ""description: str = ""issuerId: str = ""comboLegsDescrip: str = ""comboLegs: list["ComboLeg"] = field(default\_factory=list)deltaNeutralContract: Optional["DeltaNeutralContract"] = None
[[docs]](../../api.html#ib_async.contract.Contract.create)@staticmethoddef create(\*\*kwargs) -\> "Contract":""" Create and a return a specialized contract based on the given secType, or a general Contract if secType is not given. """secType = kwargs.get("secType", "")cls = {"": Contract,"STK": Stock,"OPT": Option,"FUT": Future,"CONTFUT": ContFuture,"CASH": Forex,"IND": Index,"CFD": CFD,"BOND": Bond,"CMDTY": Commodity,"FOP": FuturesOption,"FUND": MutualFund,"WAR": Warrant,"IOPT": Warrant,"BAG": Bag,"CRYPTO": Crypto,"NEWS": Contract,"EVENT": Contract,"EC": Contract,# Event Contracts (binary yes/no results)}.get(secType, Contract)if cls is not Contract:kwargs.pop("secType", "")return cls(\*\*kwargs)
[[docs]](../../api.html#ib_async.contract.Contract.recreate)@staticmethoddef recreate(c) -\> "Contract":"""Comply an existing generic Contract into its most specific type."""return Contract.create(\*\*util.dataclassAsDict(c))
[[docs]](../../api.html#ib_async.contract.Contract.isHashable)def isHashable(self) -\> bool:""" See if this contract can be hashed by conId. Note: Bag contracts always get conId=28812380, so they're not hashable by conId, but we generate a synthetic hash for them based on leg details instead. """return bool(self.conId)
def \_\_eq\_\_(self, other):return isinstance(other, Contract) and (self.conIdand self.conId == other.conIdor util.dataclassAsDict(self) == util.dataclassAsDict(other))def \_\_hash\_\_(self) -\> int:if self.secType == "BAG":return hash(tuple([util.dataclassAsTuple(b)for b in sorted(self.comboLegs, key=lambda x: x.conId)]+ [self.symbol, self.exchange]))if not self.isHashable():raise ValueError(f"Contract {self} can't be hashed because no 'conId' value exists. Qualify contract to populate 'conId'.")if self.secType == "CONTFUT":# CONTFUT gets the same conId as the front contract, invert it hereh = -self.conIdelse:h = self.conIdreturn hdef \_\_repr\_\_(self):attrs = util.dataclassNonDefaults(self)if self.\_\_class\_\_ is not Contract:attrs.pop("secType", "")clsName = self.\_\_class\_\_.\_\_qualname\_\_kwargs = ", ".join(f"{k}={v!r}" for k, v in attrs.items())return f"{clsName}({kwargs})"\_\_str\_\_ = \_\_repr\_\_
[[docs]](../../api.html#ib_async.contract.Stock)class Stock(Contract):def \_\_init\_\_(self, symbol: str = "", exchange: str = "", currency: str = "", \*\*kwargs):""" Stock contract. Args: symbol: Symbol name. exchange: Destination exchange. currency: Underlying currency. """Contract.\_\_init\_\_(self,secType="STK",symbol=symbol,exchange=exchange,currency=currency,\*\*kwargs,)
[[docs]](../../api.html#ib_async.contract.Option)class Option(Contract):def \_\_init\_\_(self,symbol: str = "",lastTradeDateOrContractMonth: str = "",strike: float = 0.0,right: str = "",exchange: str = "",multiplier: str = "",currency: str = "",\*\*kwargs,):""" Option contract. Args: symbol: Symbol name. lastTradeDateOrContractMonth: The option's last trading day or contract month. \* YYYYMM format: To specify last month \* YYYYMMDD format: To specify last trading day strike: The option's strike price. right: Put or call option. Valid values are 'P', 'PUT', 'C' or 'CALL'. exchange: Destination exchange. multiplier: The contract multiplier. currency: Underlying currency. """Contract.\_\_init\_\_(self,"OPT",symbol=symbol,lastTradeDateOrContractMonth=lastTradeDateOrContractMonth,strike=strike,right=right,exchange=exchange,multiplier=multiplier,currency=currency,\*\*kwargs,)
[[docs]](../../api.html#ib_async.contract.Future)class Future(Contract):def \_\_init\_\_(self,symbol: str = "",lastTradeDateOrContractMonth: str = "",exchange: str = "",localSymbol: str = "",multiplier: str = "",currency: str = "",\*\*kwargs,):""" Future contract. Args: symbol: Symbol name. lastTradeDateOrContractMonth: The option's last trading day or contract month. \* YYYYMM format: To specify last month \* YYYYMMDD format: To specify last trading day exchange: Destination exchange. localSymbol: The contract's symbol within its primary exchange. multiplier: The contract multiplier. currency: Underlying currency. """Contract.\_\_init\_\_(self,"FUT",symbol=symbol,lastTradeDateOrContractMonth=lastTradeDateOrContractMonth,exchange=exchange,localSymbol=localSymbol,multiplier=multiplier,currency=currency,\*\*kwargs,)
[[docs]](../../api.html#ib_async.contract.ContFuture)class ContFuture(Contract):def \_\_init\_\_(self,symbol: str = "",exchange: str = "",localSymbol: str = "",multiplier: str = "",currency: str = "",\*\*kwargs,):""" Continuous future contract. Args: symbol: Symbol name. exchange: Destination exchange. localSymbol: The contract's symbol within its primary exchange. multiplier: The contract multiplier. currency: Underlying currency. """Contract.\_\_init\_\_(self,"CONTFUT",symbol=symbol,exchange=exchange,localSymbol=localSymbol,multiplier=multiplier,currency=currency,\*\*kwargs,)
[[docs]](../../api.html#ib_async.contract.Forex)class Forex(Contract):def \_\_init\_\_(self,pair: str = "",exchange: str = "IDEALPRO",symbol: str = "",currency: str = "",\*\*kwargs,):""" Foreign exchange currency pair. Args: pair: Shortcut for specifying symbol and currency, like 'EURUSD'. exchange: Destination exchange. symbol: Base currency. currency: Quote currency. """if pair:assert len(pair) == 6symbol = symbol or pair[:3]currency = currency or pair[3:]Contract.\_\_init\_\_(self, "CASH", symbol=symbol, exchange=exchange, currency=currency, \*\*kwargs)def \_\_repr\_\_(self):attrs = util.dataclassNonDefaults(self)attrs.pop("secType")s = "Forex("if "symbol" in attrs and "currency" in attrs:pair = attrs.pop("symbol")pair += attrs.pop("currency")s += "'" + pair + "'" + (", " if attrs else "")s += ", ".join(f"{k}={v!r}" for k, v in attrs.items())s += ")"return s\_\_str\_\_ = \_\_repr\_\_
[[docs]](../../api.html#ib_async.contract.Forex.pair)def pair(self) -\> str:"""Short name of pair."""return self.symbol + self.currency
[[docs]](../../api.html#ib_async.contract.Index)class Index(Contract):def \_\_init\_\_(self, symbol: str = "", exchange: str = "", currency: str = "", \*\*kwargs):""" Index. Args: symbol: Symbol name. exchange: Destination exchange. currency: Underlying currency. """Contract.\_\_init\_\_(self, "IND", symbol=symbol, exchange=exchange, currency=currency, \*\*kwargs)
[[docs]](../../api.html#ib_async.contract.CFD)class CFD(Contract):def \_\_init\_\_(self, symbol: str = "", exchange: str = "", currency: str = "", \*\*kwargs):""" Contract For Difference. Args: symbol: Symbol name. exchange: Destination exchange. currency: Underlying currency. """Contract.\_\_init\_\_(self, "CFD", symbol=symbol, exchange=exchange, currency=currency, \*\*kwargs)
[[docs]](../../api.html#ib_async.contract.Commodity)class Commodity(Contract):def \_\_init\_\_(self, symbol: str = "", exchange: str = "", currency: str = "", \*\*kwargs):""" Commodity. Args: symbol: Symbol name. exchange: Destination exchange. currency: Underlying currency. """Contract.\_\_init\_\_(self, "CMDTY", symbol=symbol, exchange=exchange, currency=currency, \*\*kwargs)
[[docs]](../../api.html#ib_async.contract.Bond)class Bond(Contract):def \_\_init\_\_(self, \*\*kwargs):"""Bond."""Contract.\_\_init\_\_(self, "BOND", \*\*kwargs)
[[docs]](../../api.html#ib_async.contract.FuturesOption)class FuturesOption(Contract):def \_\_init\_\_(self,symbol: str = "",lastTradeDateOrContractMonth: str = "",strike: float = 0.0,right: str = "",exchange: str = "",multiplier: str = "",currency: str = "",\*\*kwargs,):""" Option on a futures contract. Args: symbol: Symbol name. lastTradeDateOrContractMonth: The option's last trading day or contract month. \* YYYYMM format: To specify last month \* YYYYMMDD format: To specify last trading day strike: The option's strike price. right: Put or call option. Valid values are 'P', 'PUT', 'C' or 'CALL'. exchange: Destination exchange. multiplier: The contract multiplier. currency: Underlying currency. """Contract.\_\_init\_\_(self,"FOP",symbol=symbol,lastTradeDateOrContractMonth=lastTradeDateOrContractMonth,strike=strike,right=right,exchange=exchange,multiplier=multiplier,currency=currency,\*\*kwargs,)
[[docs]](../../api.html#ib_async.contract.MutualFund)class MutualFund(Contract):def \_\_init\_\_(self, \*\*kwargs):"""Mutual fund."""Contract.\_\_init\_\_(self, "FUND", \*\*kwargs)
[[docs]](../../api.html#ib_async.contract.Warrant)class Warrant(Contract):def \_\_init\_\_(self, \*\*kwargs):"""Warrant option."""Contract.\_\_init\_\_(self, "WAR", \*\*kwargs)
[[docs]](../../api.html#ib_async.contract.Bag)class Bag(Contract):def \_\_init\_\_(self, \*\*kwargs):"""Bag contract."""Contract.\_\_init\_\_(self, "BAG", \*\*kwargs)
[[docs]](../../api.html#ib_async.contract.Crypto)class Crypto(Contract):def \_\_init\_\_(self, symbol: str = "", exchange: str = "", currency: str = "", \*\*kwargs):""" Crypto currency contract. Args: symbol: Symbol name. exchange: Destination exchange. currency: Underlying currency. """Contract.\_\_init\_\_(self,secType="CRYPTO",symbol=symbol,exchange=exchange,currency=currency,\*\*kwargs,)
[[docs]](../../api.html#ib_async.contract.TagValue)class TagValue(NamedTuple):tag: strvalue: str
[[docs]](../../api.html#ib_async.contract.ComboLeg)@dataclassclass ComboLeg:conId: int = 0ratio: int = 0action: str = ""exchange: str = ""openClose: int = 0shortSaleSlot: int = 0designatedLocation: str = ""exemptCode: int = -1
[[docs]](../../api.html#ib_async.contract.DeltaNeutralContract)@dataclassclass DeltaNeutralContract:conId: int = 0delta: float = 0.0price: float = 0.0
[[docs]](../../api.html#ib_async.contract.TradingSession)class TradingSession(NamedTuple):start: dt.datetimeend: dt.datetime
[[docs]](../../api.html#ib_async.contract.ContractDetails)@dataclassclass ContractDetails:contract: Contract | None = NonemarketName: str = ""minTick: float = 0.0orderTypes: str = ""validExchanges: str = ""priceMagnifier: int = 0underConId: int = 0longName: str = ""contractMonth: str = ""industry: str = ""category: str = ""subcategory: str = ""timeZoneId: str = ""tradingHours: str = ""liquidHours: str = ""evRule: str = ""evMultiplier: int = 0mdSizeMultiplier: int = 1# obsoleteaggGroup: int = 0underSymbol: str = ""underSecType: str = ""marketRuleIds: str = ""secIdList: list[TagValue] = field(default\_factory=list)realExpirationDate: str = ""lastTradeTime: str = ""stockType: str = ""minSize: float = 0.0sizeIncrement: float = 0.0suggestedSizeIncrement: float = 0.0# minCashQtySize: float = 0.0cusip: str = ""ratings: str = ""descAppend: str = ""bondType: str = ""couponType: str = ""callable: bool = Falseputable: bool = Falsecoupon: float = 0convertible: bool = Falsematurity: str = ""issueDate: str = ""nextOptionDate: str = ""nextOptionType: str = ""nextOptionPartial: bool = Falsenotes: str = ""
[[docs]](../../api.html#ib_async.contract.ContractDetails.tradingSessions)def tradingSessions(self) -\> list[TradingSession]:return self.\_parseSessions(self.tradingHours)
[[docs]](../../api.html#ib_async.contract.ContractDetails.liquidSessions)def liquidSessions(self) -\> list[TradingSession]:return self.\_parseSessions(self.liquidHours)
def \_parseSessions(self, s: str) -\> list[TradingSession]:"""Parse the IBKR session date range text format into native Python objects. Note: The IBKR date range format looks like: timeZoneId='US/Eastern', tradingHours='20240721:CLOSED;20240722:0400-20240722:2000;20240723:0400-20240723:' '2000;20240724:0400-20240724:2000;20240725:0400-20240725:2000;' '20240726:0400-20240726:2000', liquidHours='20240721:CLOSED;20240722:0930-20240722:1600;20240723:0930-20240723:' '1600;20240724:0930-20240724:1600;20240725:0930-20240725:1600;' '20240726:0930-20240726:1600', """# if the time values don't exist, we can't parse anything, so return nothing.if not (s or self.timeZoneId):return []tz = util.ZoneInfo(self.timeZoneId)sessions = []for sess in s.split(";"):if not sess or "CLOSED" in sess:continuesessions.append(TradingSession(\*[dt.datetime.strptime(t, "%Y%m%d:%H%M").replace(tzinfo=tz)for t in sess.split("-")]))return sessions
[[docs]](../../api.html#ib_async.contract.ContractDescription)@dataclassclass ContractDescription:contract: Contract | None = NonederivativeSecTypes: list[str] = field(default\_factory=list)
[[docs]](../../api.html#ib_async.contract.ScanData)@dataclassclass ScanData:rank: intcontractDetails: ContractDetailsdistance: strbenchmark: strprojection: strlegsStr: str