Interactive Brokers
Provides an API integration for Interactive Brokers.
Client
class InteractiveBrokersClient
Bases: Component
, InteractiveBrokersClientConnectionMixin
, InteractiveBrokersClientAccountMixin
, InteractiveBrokersClientMarketDataMixin
, InteractiveBrokersClientOrderMixin
, InteractiveBrokersClientContractMixin
, InteractiveBrokersClientErrorMixin
A client component that interfaces with the Interactive Brokers TWS or Gateway.
This class integrates various mixins to provide functionality for connection management, account management, market data, and order processing with Interactive Brokers. It inherits from both Component and EWrapper to provide event-driven responses and custom component behavior.
async wait_until_ready(timeout: int = 300) → None
Check if the client is running and ready within a given timeout.
- Parameters: timeout (int , default 300) – Time in seconds to wait for the client to be ready.
subscribe_event(name: str, handler: Callable) → None
Subscribe a handler function to a named event.
- Parameters:
- name (str) – The name of the event to subscribe to.
- handler (Callable) – The handler function to be called when the event occurs.
unsubscribe_event(name: str) → None
Unsubscribe a handler from a named event.
- Parameters: name (str) – The name of the event to unsubscribe from.
submit_to_msg_handler_queue(task: Callable[[...], Any]) → None
Submit a task to the message handler’s queue for processing.
This method places a callable task into the message handler task queue, ensuring it’s scheduled for asynchronous execution according to the queue’s order. The operation is non-blocking and immediately returns after queueing the task.
- Parameters: task (Callable [ ... , Any ]) – The task to be queued. This task should be a callable that matches the expected signature for tasks processed by the message handler.
sendMsg(msg)
Override the logging for ibapi EClient.sendMsg.
logRequest(fnName, fnParams)
Override the logging for ibapi EClient.logRequest.
CLIENT_ERRORS : Final[set[int]] = {502, 503, 504, 1100, 2110, 10038, 10182}
CONNECTIVITY_LOST_CODES : Final[set[int]] = {1100, 1300, 2110}
CONNECTIVITY_RESTORED_CODES : Final[set[int]] = {1101, 1102}
ORDER_REJECTION_CODES : Final[set[int]] = {201, 203, 321, 10289, 10293}
SUPPRESS_ERROR_LOGGING_CODES : Final[set[int]] = {200}
WARNING_CODES : Final[set[int]] = {110, 165, 202, 399, 404, 434, 492, 1101, 1102, 10167}
accounts() → set[str]
Return a set of account identifiers managed by this instance.
- Return type: set[str]
cancel_all_orders() → None
Request to cancel all open orders through the EClient.
cancel_order(order_id: int, order_cancel: OrderCancel = None) → None
Cancel an order through the EClient.
- Parameters:
- order_id (int) – The unique identifier for the order to be canceled.
- order_cancel (OrderCancel object , optional.) – The Order cancellation parameters when canceling an order, when subject to CME Rule 576.
degrade(self) → void
Degrade the component.
While executing on_degrade() any exception will be logged and reraised, then the component
will remain in a DEGRADING
state.
WARNING
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
dispose(self) → void
Dispose of the component.
While executing on_dispose() any exception will be logged and reraised, then the component
will remain in a DISPOSING
state.
WARNING
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
fault(self) → void
Fault the component.
Calling this method multiple times has the same effect as calling it once (it is idempotent). Once called, it cannot be reversed, and no other methods should be called on this instance.
While executing on_fault() any exception will be logged and reraised, then the component
will remain in a FAULTING
state.
WARNING
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
classmethod fully_qualified_name(cls) → str
Return the fully qualified name for the components class.
- Return type: str
async get_contract_details(contract: IBContract) → list[IBContractDetails] | None
Request details for a specific contract.
- Parameters: contract (IBContract) – The contract for which details are requested.
- Return type:
IBContractDetails |
None
async get_historical_bars(bar_type: BarType, contract: IBContract, use_rth: bool, end_date_time: Timestamp, duration: str, timeout: int = 60) → list[Bar]
Request and retrieve historical bar data for a specified bar type.
- Parameters:
- bar_type (BarType) – The type of bar for which historical data is requested.
- contract (IBContract) – The Interactive Brokers contract details for the instrument.
- use_rth (bool) – Whether to use regular trading hours (RTH) only for the data.
- end_date_time (pd.Timestamp) – The end time for the historical data request as a pandas Timestamp.
- duration (str) – The duration for which historical data is requested, formatted as a string.
- timeout (int , optional) – The maximum time in seconds to wait for the historical data response.
- Return type: list[Bar]
async get_historical_ticks(instrument_id: InstrumentId, contract: IBContract, tick_type: str, start_date_time: Timestamp | str = '', end_date_time: Timestamp | str = '', use_rth: bool = True, timeout: int = 60) → list[QuoteTick | TradeTick] | None
Request and retrieve historical tick data for a specified contract and tick type.
- Parameters:
- instrument_id (InstrumentId) – The identifier of the instrument for which to request historical ticks.
- contract (IBContract) – The Interactive Brokers contract details for the instrument.
- tick_type (str) – The type of tick data to request (e.g., ‘BID_ASK’, ‘TRADES’).
- start_date_time (pd.Timestamp | str , optional) – The start time for the historical data request. Can be a pandas Timestamp or a string formatted as ‘YYYYMMDD HH:MM:SS [TZ]’.
- end_date_time (pd.Timestamp | str , optional) – The end time for the historical data request. Same format as start_date_time.
- use_rth (bool , optional) – Whether to use regular trading hours (RTH) only for the data.
- timeout (int , optional) – The maximum time in seconds to wait for the historical data response.
- Return type:
list[QuoteTick | TradeTick] |
None
async get_matching_contracts(pattern: str) → list[IBContract] | None
Request contracts matching a specific pattern.
- Parameters: pattern (str) – The pattern to match for contract symbols.
- Return type:
list[IBContract] |
None
async get_open_orders(account_id: str) → list[Order]
Retrieve a list of open orders for a specific account. Once the request is completed, openOrderEnd() will be called.
- Parameters: account_id (str) – The account identifier for which to retrieve open orders.
- Return type: list[IBOrder]
async get_option_chains(underlying: IBContract) → Any | None
Request option chains for a specific underlying contract.
- Parameters: underlying (IBContract) – The underlying contract for which option chains are requested.
- Return type:
list[IBContractDetails] |
None
async get_positions(account_id: str) → list[Position] | None
Fetch open positions for a specified account.
- Parameters: account_id (str) – The account identifier for which to fetch positions.
- Return type:
list[Position] |
None
async get_price(contract, tick_type='MidPoint')
Request market data for a specific contract and tick type.
This method requests market data from Interactive Brokers for the given contract and tick type, waits for the response, and returns the result.
- Parameters:
- contract (IBContract) – The contract details for which market data is requested.
- tick_type (str , optional) – The type of tick data to request (default is “MidPoint”).
- Returns: The market data result.
- Return type: Any
- Raises: asyncio.TimeoutError – If the request times out.
id
The components ID.
- Returns: ComponentId
is_degraded
bool
Return whether the current component state is DEGRADED
.
- Return type: bool
- Type: Component.is_degraded
is_disposed
bool
Return whether the current component state is DISPOSED
.
- Return type: bool
- Type: Component.is_disposed
is_faulted
bool
Return whether the current component state is FAULTED
.
- Return type: bool
- Type: Component.is_faulted
is_initialized
bool
Return whether the component has been initialized (component.state >= INITIALIZED
).
- Return type: bool
- Type: Component.is_initialized
is_running : bool
bool
Return whether the current component state is RUNNING
.
- Return type: bool
- Type: Component.is_running
is_stopped
bool
Return whether the current component state is STOPPED
.
- Return type: bool
- Type: Component.is_stopped
next_order_id() → int
Retrieve the next valid order ID to be used for a new order.
- Return type: int
place_order(order: Order) → None
Place an order through the EClient.
- Parameters: order (IBOrder) – The order object containing details such as the order ID, contract details, and order specifics.
place_order_list(orders: list[Order]) → None
Place a list of orders through the EClient.
- Parameters: orders (list *[*IBOrder ]) – A list of order objects to be placed.
async process_account_summary(, req_id: int, account_id: str, tag: str, value: str, currency: str) → None
Receive account information.
async process_commission_report(, commission_report: CommissionReport) → None
Provide the CommissionReport of an Execution.
process_connection_closed() → None
Indicate the API connection has closed.
Following a API <-> TWS broken socket connection, this function is not called automatically but must be triggered by API client code.
async process_contract_details(, req_id: int, contract_details: ContractDetails) → None
Receive the full contract’s definitions This method will return all contracts matching the requested via EClientSocket::reqContractDetails. For example, one can obtain the whole option chain with it.
async process_contract_details_end(, req_id: int) → None
After all contracts matching the request were returned, this method will mark the end of their reception.
async process_error(, req_id: int, error_code: int, error_string: str, advanced_order_reject_json: str = '') → None
Process an error based on its code, request ID, and message. Depending on the error code, this method delegates to specific error handlers or performs general error handling.
- Parameters:
- req_id (int) – The request ID associated with the error.
- error_code (int) – The error code.
- error_string (str) – The error message string.
- advanced_order_reject_json (str) – The JSON string for advanced order rejection.
async process_exec_details(, req_id: int, contract: Contract, execution: Execution) → None
Provide the executions that happened in the prior 24 hours.
async process_historical_data(, req_id: int, bar: BarData) → None
Return the requested historical data bars.
async process_historical_data_end(, req_id: int, start: str, end: str) → None
Mark the end of receiving historical bars.
async process_historical_data_update(, req_id: int, bar: BarData) → None
Receive bars in real-time if keepUpToDate is set as True in reqHistoricalData.
Similar to realTimeBars function, except returned data is a composite of historical data and real time data that is equivalent to TWS chart functionality to keep charts up to date. Returned bars are successfully updated using real- time data.
async process_historical_ticks(, req_id: int, ticks: list, done: bool) → None
Return the requested historic ticks.
async process_historical_ticks_bid_ask(, req_id: int, ticks: list, done: bool) → None
Return the requested historic bid/ask ticks.
async process_historical_ticks_last(, req_id: int, ticks: list, done: bool) → None
Return the requested historic trades.
async process_managed_accounts(, accounts_list: str) → None
Receive a comma-separated string with the managed account ids.
Occurs automatically on initial API client connection.
async process_market_data_type(, req_id: int, market_data_type: int) → None
Return the market data type (real-time, frozen, delayed, delayed-frozen) of ticker sent by EClientSocket::reqMktData when TWS switches from real-time to frozen and back and from delayed to delayed-frozen and back.
async process_next_valid_id(, order_id: int) → None
Receive the next valid order id.
Will be invoked automatically upon successful API client connection, or after call to EClient::reqIds Important: the next valid order ID is only valid at the time it is received.
async process_open_order(, order_id: int, contract: Contract, order: Order, order_state: OrderState) → None
Feed in currently open orders.
async process_open_order_end() → None
Notifies the end of the open orders’ reception.
async process_order_status(, order_id: int, status: str, filled: Decimal, remaining: Decimal, avg_fill_price: float, perm_id: int, parent_id: int, last_fill_price: float, client_id: int, why_held: str, mkt_cap_price: float) → None
Get the up-to-date information of an order every time it changes.
Note: Often there are duplicate orderStatus messages.
async process_position(, account_id: str, contract: Contract, position: Decimal, avg_cost: float) → None
Provide the portfolio’s open positions.
async process_position_end() → None
Indicate that all the positions have been transmitted.
async process_realtime_bar(, req_id: int, time: int, open_: float, high: float, low: float, close: float, volume: Decimal, wap: Decimal, count: int) → None
Update real-time 5 second bars.
async process_security_definition_option_parameter(, req_id: int, exchange: str, underlying_con_id: int, trading_class: str, multiplier: str, expirations: set, strikes: set) → None
Return the option chain for an underlying on an exchange specified in reqSecDefOptParams There will be multiple callbacks to securityDefinitionOptionParameter if multiple exchanges are specified in reqSecDefOptParams.
async process_security_definition_option_parameter_end(, req_id: int) → None
Call when all callbacks to securityDefinitionOptionParameter are complete.
async process_symbol_samples(, req_id: int, contract_descriptions: list) → None
Return an array of sample contract descriptions.
async process_tick_by_tick_all_last(, req_id: int, tick_type: int, time: int, price: float, size: Decimal, tick_attrib_last: TickAttribLast, exchange: str, special_conditions: str) → None
Return “Last” or “AllLast” (trades) tick-by-tick real-time tick.
async process_tick_by_tick_bid_ask(, req_id: int, time: int, bid_price: float, ask_price: float, bid_size: Decimal, ask_size: Decimal, tick_attrib_bid_ask: TickAttribBidAsk) → None
Return “BidAsk” tick-by-tick real-time tick data.
async process_tick_price(, req_id: int, tick_type: int, price: float, attrib: Any) → None
Process tick price data from reqMktData for spread instruments.
async process_tick_size(, req_id: int, tick_type: int, size: Decimal) → None
Process tick size data from reqMktData for spread instruments.
async process_update_mkt_depth_l2(, req_id: int, position: int, market_maker: str, operation: int, side: int, price: float, size: Decimal, is_smart_depth: bool) → None
Return Market Depth (L2) real-time data.
NOTE
IBKR’s L2 depth data is updated based on position, so we need to maintain a local order book indexed by position, and then aggregate this order book by price.
- Parameters:
- req_id (TickerId) – The request’s identifier.
- position (int) – The order book’s row being updated.
- market_maker (str) – The exchange holding the order if is_smart_depth is True, otherwise the MPID of the market maker.
- operation (int) – How to refresh the row:
- 0: insert (insert this new order into the row identified by ‘position’)
- 1: update (update the existing order in the row identified by ‘position’)
- 2: delete (delete the existing order at the row identified by ‘position’)
- side (int) – 0 for ask, 1 for bid.
- price (float) – The order’s price.
- size (Decimal) – The order’s size.
- is_smart_depth (bool) – Is SMART Depth request.
reset(self) → void
Reset the component.
All stateful fields are reset to their initial value.
While executing on_reset() any exception will be logged and reraised, then the component
will remain in a RESETTING
state.
WARNING
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
resume(self) → void
Resume the component.
While executing on_resume() any exception will be logged and reraised, then the component
will remain in a RESUMING
state.
WARNING
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
async set_market_data_type(market_data_type: <ibapi.enum_implem.Enum object at 0x7f4db872d1d0>) → None
Set the market data type for data subscriptions. This method configures the type of market data (live, delayed, etc.) to be used for subsequent data requests.
- Parameters: market_data_type (MarketDataTypeEnum) – The market data type to be set
shutdown_system(self, str reason=None) → void
Initiate a system-wide shutdown by generating and publishing a ShutdownSystem command.
The command is handled by the system’s NautilusKernel, which will invoke either stop (synchronously) or stop_async (asynchronously) depending on the execution context and the presence of an active event loop.
- Parameters: reason (str , optional) – The reason for issuing the shutdown command.
start(self) → void
Start the component.
While executing on_start() any exception will be logged and reraised, then the component
will remain in a STARTING
state.
WARNING
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
state
ComponentState
Return the components current state.
- Return type: ComponentState
- Type: Component.state
stop(self) → void
Stop the component.
While executing on_stop() any exception will be logged and reraised, then the component
will remain in a STOPPING
state.
WARNING
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
subscribe_account_summary() → None
Subscribe to the account summary for all accounts.
It sends a request to Interactive Brokers to retrieve account summary information.
async subscribe_historical_bars(bar_type: BarType, contract: IBContract, use_rth: bool, handle_revised_bars: bool, params: dict) → None
Subscribe to historical bar data for a specified bar type and contract. It allows configuration for regular trading hours and handling of revised bars.
- Parameters:
- bar_type (BarType) – The type of bar to subscribe to.
- contract (IBContract) – The Interactive Brokers contract details for the instrument.
- use_rth (bool) – Whether to use regular trading hours (RTH) only.
- handle_revised_bars (bool) – Whether to handle revised bars or not.
- params (dict) – A dictionary of optional parameters.
async subscribe_market_data(instrument_id: InstrumentId, contract: IBContract, generic_tick_list: str = '') → None
Subscribe to market data for a specified instrument using reqMktData. This method is used for BAG (spread) contracts that don’t support reqTickByTickData.
- Parameters:
- instrument_id (InstrumentId) – The identifier of the instrument for which to subscribe.
- contract (IBContract) – The contract details for the instrument.
- generic_tick_list (str) – A comma-separated list of generic tick types to request. Empty string for basic bid/ask data.
async subscribe_order_book(instrument_id: InstrumentId, contract: IBContract, depth: int, is_smart_depth: bool = True) → None
Subscribe to order book data for a specified instrument.
- Parameters:
- instrument_id (InstrumentId) – The identifier of the instrument for which to subscribe.
- contract (IBContract) – The contract details for the instrument.
- depth (int) – The number of rows on each side of the order book.
- is_smart_depth (bool) – Flag indicates that this is smart depth request. If the isSmartDepth boolean (available with API v974+) is True, the marketMaker field will indicate the exchange from which the quote originates. Otherwise it indicates the MPID of a market maker.
subscribe_positions() → None
Subscribe to real-time position updates for all accounts.
This enables automatic detection of position changes from option exercises and other external events.
async subscribe_realtime_bars(bar_type: BarType, contract: IBContract, use_rth: bool) → None
Subscribe to real-time bar data for a specified bar type.
- Parameters:
- bar_type (BarType) – The type of bar to subscribe to.
- contract (IBContract) – The Interactive Brokers contract details for the instrument.
- use_rth (bool) – Whether to use regular trading hours (RTH) only.
async subscribe_ticks(instrument_id: InstrumentId, contract: IBContract, tick_type: str, ignore_size: bool) → None
Subscribe to tick data for a specified instrument.
- Parameters:
- instrument_id (InstrumentId) – The identifier of the instrument for which to subscribe.
- contract (IBContract) – The contract details for the instrument.
- tick_type (str) – The type of tick data to subscribe to.
- ignore_size (bool) – Omit updates that reflect only changes in size, and not price. Applicable to Bid_Ask data requests.
trader_id
The trader ID associated with the component.
- Returns: TraderId
type
The components type.
- Returns: type
unsubscribe_account_summary(account_id: str) → None
Unsubscribe from the account summary for the specified account. This method is not implemented.
- Parameters: account_id (str) – The identifier of the account to unsubscribe from.
async unsubscribe_historical_bars(bar_type: BarType) → None
Unsubscribe from historical bar data for a specified bar type.
- Parameters: bar_type (BarType) – The type of bar to unsubscribe from.
async unsubscribe_market_data(instrument_id: InstrumentId) → None
Unsubscribes from market data for a specified instrument.
- Parameters: instrument_id (InstrumentId) – The identifier of the instrument for which to unsubscribe.
async unsubscribe_order_book(instrument_id: InstrumentId, is_smart_depth: bool = True) → None
Unsubscribes from order book data for a specified instrument.
- Parameters:
- instrument_id (InstrumentId) – The identifier of the instrument for which to unsubscribe.
- depth (int) – The number of rows on each side of the order book.
- is_smart_depth (bool) – Flag indicates that this is smart depth request. If the isSmartDepth boolean (available with API v974+) is True, the marketMaker field will indicate the exchange from which the quote originates. Otherwise it indicates the MPID of a market maker.
unsubscribe_positions() → None
Unsubscribe from real-time position updates.
async unsubscribe_realtime_bars(bar_type: BarType) → None
Unsubscribes from real-time bar data for a specified bar type.
- Parameters: bar_type (BarType) – The type of bar to unsubscribe from.
async unsubscribe_ticks(instrument_id: InstrumentId, tick_type: str) → None
Unsubscribes from tick data for a specified instrument.
- Parameters:
- instrument_id (InstrumentId) – The identifier of the instrument for which to unsubscribe.
- tick_type (str) – The type of tick data to unsubscribe from.
logAnswer : Callable
Common
class ContractId
Bases: int
ContractId type.
as_integer_ratio()
Return a pair of integers, whose ratio is equal to the original int.
The ratio is in lowest terms and has a positive denominator.
>>> (10).as_integer_ratio()
(10, 1)
>>> (-10).as_integer_ratio()
(-10, 1)
>>> (0).as_integer_ratio()
(0, 1)
bit_count()
Number of ones in the binary representation of the absolute value of self.
Also known as the population count.
>>> bin(13)
'0b1101'
>>> (13).bit_count()
3
bit_length()
Number of bits necessary to represent self in binary.
>>> bin(37)
'0b100101'
>>> (37).bit_length()
6
conjugate()
Returns self, the complex conjugate of any int.
denominator
the denominator of a rational number in lowest terms
classmethod from_bytes(bytes, byteorder='big', , signed=False)
Return the integer represented by the given array of bytes.
bytes : Holds the array of bytes to convert. The argument must either support the buffer protocol or be an iterable object producing bytes. Bytes and bytearray are examples of built-in objects that support the buffer protocol.
byteorder : The byte order used to represent the integer. If byteorder is ‘big’, the most significant byte is at the beginning of the byte array. If byteorder is ‘little’, the most significant byte is at the end of the byte array. To request the native byte order of the host system, use sys.byteorder as the byte order value. Default is to use ‘big’.
signed : Indicates whether two’s complement is used to represent the integer.
imag
the imaginary part of a complex number
is_integer()
Returns True. Exists for duck type compatibility with float.is_integer.
numerator
the numerator of a rational number in lowest terms
real
the real part of a complex number
to_bytes(length=1, byteorder='big', , signed=False)
Return an array of bytes representing an integer.
length : Length of bytes object to use. An OverflowError is raised if the integer is not representable with the given number of bytes. Default is length 1.
byteorder : The byte order used to represent the integer. If byteorder is ‘big’, the most significant byte is at the beginning of the byte array. If byteorder is ‘little’, the most significant byte is at the end of the byte array. To request the native byte order of the host system, use sys.byteorder as the byte order value. Default is to use ‘big’.
signed : Determines whether two’s complement is used to represent the integer. If signed is False and a negative integer is given, an OverflowError is raised.
class ComboLeg
Bases: NautilusConfig
Class representing a leg within combo orders.
conId : int
ratio : int
action : str
exchange : str
openClose : int
shortSaleSlot : int
designatedLocation : str
exemptCode : int
dict() → dict[str, Any]
Return a dictionary representation of the configuration.
- Return type: dict[str, Any]
classmethod fully_qualified_name() → str
Return the fully qualified name for the NautilusConfig class.
- Return type: str
property id : str
Return the hashed identifier for the configuration.
- Return type: str
json() → bytes
Return serialized JSON encoded bytes.
- Return type: bytes
json_primitives() → dict[str, Any]
Return a dictionary representation of the configuration with JSON primitive types as values.
- Return type: dict[str, Any]
classmethod json_schema() → dict[str, Any]
Generate a JSON schema for this configuration class.
- Return type: dict[str, Any]
classmethod parse(raw: bytes | str) → Any
Return a decoded object of the given cls.
- Parameters:
- cls (type) – The type to decode to.
- raw (bytes or str) – The raw bytes or JSON string to decode.
- Return type: Any
validate() → bool
Return whether the configuration can be represented as valid JSON.
- Return type: bool
class DeltaNeutralContract
Bases: NautilusConfig
Delta-Neutral Contract.
conId : int
delta : float
price : float
dict() → dict[str, Any]
Return a dictionary representation of the configuration.
- Return type: dict[str, Any]
classmethod fully_qualified_name() → str
Return the fully qualified name for the NautilusConfig class.
- Return type: str
property id : str
Return the hashed identifier for the configuration.
- Return type: str
json() → bytes
Return serialized JSON encoded bytes.
- Return type: bytes
json_primitives() → dict[str, Any]
Return a dictionary representation of the configuration with JSON primitive types as values.
- Return type: dict[str, Any]
classmethod json_schema() → dict[str, Any]
Generate a JSON schema for this configuration class.
- Return type: dict[str, Any]
classmethod parse(raw: bytes | str) → Any
Return a decoded object of the given cls.
- Parameters:
- cls (type) – The type to decode to.
- raw (bytes or str) – The raw bytes or JSON string to decode.
- Return type: Any
validate() → bool
Return whether the configuration can be represented as valid JSON.
- Return type: bool
class IBContract
Bases: NautilusConfig
Class describing an instrument’s definition with additional fields for options/futures.
- Parameters:
- secType (str) – Security Type of the contract i.e STK, OPT, FUT, CONTFUT
- exchange (str) – Exchange where security is traded. Will be SMART for Stocks.
- primaryExchange (str) – Exchange where security is registered. Applies to Stocks.
- symbol (str) – Unique Symbol registered in Exchange.
- build_options_chain (bool *(*default: None )) – Search for full option chain
- build_futures_chain (bool *(*default: None )) – Search for full futures chain
- options_chain_exchange (str *(*default : None )) – optional exchange for options chain, in place of underlying exchange
- min_expiry_days (int *(*default: None )) – Filters the options_chain and futures_chain which are expiring after number of days specified.
- max_expiry_days (int *(*default: None )) – Filters the options_chain and futures_chain which are expiring before number of days specified.
- lastTradeDateOrContractMonth (str ( %Y%m%d or %Y%m ) *(*default: '' )) – Filters the options_chain and futures_chain specific for this expiry date
- lastTradeDate (str *(*default: '' )) – The contract last trading day.
secType : Literal['CASH', 'STK', 'OPT', 'FUT', 'FOP', 'CONTFUT', 'CRYPTO', 'CFD', 'CMDTY', 'IND', 'BAG', '']
conId : int
exchange : str
primaryExchange : str
symbol : str
localSymbol : str
currency : str
tradingClass : str
lastTradeDateOrContractMonth : str
lastTradeDate : str
multiplier : str
strike : float
right : str
includeExpired : bool
secIdType : str
secId : str
description : str
issuerId : str
comboLegsDescrip : str
comboLegs : list[ComboLeg] | None
deltaNeutralContract : DeltaNeutralContract | None
build_futures_chain : bool | None
build_options_chain : bool | None
options_chain_exchange : str | None
min_expiry_days : int | None
max_expiry_days : int | None
dict() → dict[str, Any]
Return a dictionary representation of the configuration.
- Return type: dict[str, Any]
classmethod fully_qualified_name() → str
Return the fully qualified name for the NautilusConfig class.
- Return type: str
property id : str
Return the hashed identifier for the configuration.
- Return type: str
json() → bytes
Return serialized JSON encoded bytes.
- Return type: bytes
json_primitives() → dict[str, Any]
Return a dictionary representation of the configuration with JSON primitive types as values.
- Return type: dict[str, Any]
classmethod json_schema() → dict[str, Any]
Generate a JSON schema for this configuration class.
- Return type: dict[str, Any]
classmethod parse(raw: bytes | str) → Any
Return a decoded object of the given cls.
- Parameters:
- cls (type) – The type to decode to.
- raw (bytes or str) – The raw bytes or JSON string to decode.
- Return type: Any
validate() → bool
Return whether the configuration can be represented as valid JSON.
- Return type: bool
class IBOrderTags
Bases: NautilusConfig
Used to attach to Nautilus Order Tags for IB specific order parameters.
whatIf : bool
ocaGroup : str
ocaType : int
allOrNone : bool
activeStartTime : str
activeStopTime : str
goodAfterTime : str
blockOrder = False
sweepToFill = False
outsideRth : bool
hidden : bool
property value
dict() → dict[str, Any]
Return a dictionary representation of the configuration.
- Return type: dict[str, Any]
classmethod fully_qualified_name() → str
Return the fully qualified name for the NautilusConfig class.
- Return type: str
property id : str
Return the hashed identifier for the configuration.
- Return type: str
json() → bytes
Return serialized JSON encoded bytes.
- Return type: bytes
json_primitives() → dict[str, Any]
Return a dictionary representation of the configuration with JSON primitive types as values.
- Return type: dict[str, Any]
classmethod json_schema() → dict[str, Any]
Generate a JSON schema for this configuration class.
- Return type: dict[str, Any]
classmethod parse(raw: bytes | str) → Any
Return a decoded object of the given cls.
- Parameters:
- cls (type) – The type to decode to.
- raw (bytes or str) – The raw bytes or JSON string to decode.
- Return type: Any
validate() → bool
Return whether the configuration can be represented as valid JSON.
- Return type: bool
class IBContractDetails
Bases: NautilusConfig
ContractDetails class to be used internally in Nautilus for ease of encoding/decoding.
Reference: https://ibkrcampus.com/campus/ibkr-api-page/twsapi-ref/#contract-pub-func