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 cancelling 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 (str) – The end time for the historical data request, formatted “%Y%m%d-%H:%M:%S”.
- 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: IBContract, 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.
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 0x7ff76ae3d460>) → 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 PoseiKernel, 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) → 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.
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_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: PoseiConfig
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 PoseiConfig 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: PoseiConfig
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 PoseiConfig 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: PoseiConfig
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', '']
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 PoseiConfig 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: PoseiConfig
Used to attach to Posei 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
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 PoseiConfig 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: PoseiConfig
ContractDetails class to be used internally in Posei for ease of encoding/decoding.
Reference: https://ibkrcampus.com/campus/ibkr-api-page/twsapi-ref/#contract-pub-func
contract : IBContract | None
marketName : str
minTick : float
orderTypes : str
validExchanges : str
priceMagnifier : int
underConId : int
longName : str
contractMonth : str
industry : str
category : str
subcategory : str
timeZoneId : str
tradingHours : str
liquidHours : str
evRule : str
evMultiplier : float
mdSizeMultiplier : int
aggGroup : int
underSymbol : str
underSecType : str
marketRuleIds : str
secIdList : list[TagValue] | None
realExpirationDate : str
lastTradeTime : str
stockType : str
minSize : Decimal
sizeIncrement : Decimal
suggestedSizeIncrement : Decimal
cusip : str
ratings : str
descAppend : str
bondType : str
couponType : str
callable : bool
putable : bool
coupon : float
convertible : bool
maturity : str
issueDate : str
nextOptionDate : str
nextOptionType : str
nextOptionPartial : bool
notes : str
fundName : str
fundFamily : str
fundType : str
fundFrontLoad : str
fundBackLoad : str
fundBackLoadTimeInterval : str
fundManagementFee : str
fundClosed : bool
fundClosedForNewInvestors : bool
fundClosedForNewMoney : bool
fundNotifyAmount : str
fundMinimumInitialPurchase : str
fundSubsequentMinimumPurchase : str
fundBlueSkyStates : str
fundBlueSkyTerritories : str
fundDistributionPolicyIndicator : FundDistributionPolicyIndicator
fundAssetType : FundAssetType
ineligibilityReasonList : list
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 PoseiConfig 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
dict_to_contract_details(dict_details: dict) → IBContractDetails
Config
class SymbologyMethod
Bases: Enum
IB_SIMPLIFIED = 'simplified'
IB_RAW = 'raw'
class DockerizedIBGatewayConfig
Bases: PoseiConfig
Configuration for DockerizedIBGateway setup when working with containerized installations.
- Parameters:
- username (str , optional) – The Interactive Brokers account username.
If
None
then will source the TWS_USERNAME environment variable. - password (str , optional) – The Interactive Brokers account password.
If
None
then will source the TWS_PASSWORD environment variable. - trading_mode (str) –
paper
orlive
. - read_only_api (bool , optional , default True) – If True, no order execution is allowed. Set read_only_api=False to allow executing live orders.
- timeout (int , optional) – The timeout (seconds) for trying to launch IBG docker container when start=True.
- container_image (str , optional) – The reference to the container image used by the IB Gateway.
- username (str , optional) – The Interactive Brokers account username.
If
username : str | None
password : str | None
trading_mode : Literal['paper', 'live']
read_only_api : bool
timeout : int
container_image : str
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 PoseiConfig 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 InteractiveBrokersInstrumentProviderConfig
Bases: InstrumentProviderConfig
Configuration for instances of InteractiveBrokersInstrumentProvider.
Specify either load_ids, load_contracts, or both to dictate which instruments the system loads upon start. It should be noted that the InteractiveBrokersInstrumentProviderConfig isn’t limited to the instruments initially loaded. Instruments can be dynamically requested and loaded at runtime as needed.
- Parameters:
- load_all (bool , default False) – Note: Loading all instruments isn’t supported by the InteractiveBrokersInstrumentProvider. As such, this parameter is not applicable.
- load_ids (FrozenSet [InstrumentId ] , optional) – A frozenset of InstrumentId instances that should be loaded during startup. These represent the specific instruments that the provider should initially load.
- load_contracts (FrozenSet [IBContract ] , optional) – A frozenset of IBContract objects that are loaded during the initial startup.These specific contracts correspond to the instruments that the provider preloads. It’s important to note that while the load_ids option can be used for loading individual instruments, using load_contracts allows for a more versatile loading of several related instruments like Futures and Options that share the same underlying asset.
- symbology_method (SymbologyMethod , optional) – Specifies the symbology format used for identifying financial instruments. The available options are:
- IB_RAW: Uses the raw symbology format provided by Interactive Brokers. Instrument symbols follow a detailed format such as localSymbol=secType.exchange (e.g., EUR.USD=CASH.IDEALPRO). While this format may lack visual clarity, it is robust and supports instruments from any region, especially those with non-standard symbology where simplified parsing may fail.
- IB_SIMPLIFIED: Adopts a simplified symbology format specific to Interactive Brokers which uses Venue acronym. Instrument symbols use a cleaner notation, such as ESZ28.CME or EUR/USD.IDEALPRO. This format prioritizes ease of readability and usability and is default.
- build_options_chain (bool *(*default: None )) – Search for full option chain. Global setting for all applicable instruments.
- build_futures_chain (bool *(*default: None )) – Search for full futures chain. Global setting for all applicable instruments.
- min_expiry_days (int *(*default: None )) – Filters the options_chain and futures_chain which are expiring after specified number of days. Global setting for all applicable instruments.
- max_expiry_days (int *(*default: None )) – Filters the options_chain and futures_chain which are expiring before specified number of days. Global setting for all applicable instruments.
- convert_exchange_to_mic_venue (bool *(*default: False )) – Whether to convert IB exchanges to MIC venues when converting an IB contract to an instrument id.
- symbol_to_mic_venue (dict , optional) – A dictionary to override the default MIC venue conversion. A key is a symbol prefix (for example ES for all futures and options on it), the value is the MIC venue to use.
- cache_validity_days (int *(*default: None )) – Default None, will request fresh pull upon starting of TradingNode [only once]. Setting value will pull the instruments at specified interval, useful when TradingNode runs for many days. Example: value set to 1, InstrumentProvider will make fresh pull every day even if TradingNode is not restarted.
- pickle_path (str *(*default: None )) – If provided valid path, will store the ContractDetails as pickle, and use during cache_validity period.
symbology_method : SymbologyMethod
load_contracts : frozenset[IBContract] | None
build_options_chain : bool | None
build_futures_chain : bool | None
min_expiry_days : int | None
max_expiry_days : int | None
convert_exchange_to_mic_venue : bool
symbol_to_mic_venue : dict
cache_validity_days : int | None
pickle_path : str | None
dict() → dict[str, Any]
Return a dictionary representation of the configuration.
- Return type: dict[str, Any]
filter_callable : str | None
filters : dict[str, Any] | None
classmethod fully_qualified_name() → str
Return the fully qualified name for the PoseiConfig 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]
load_all : bool
load_ids : frozenset[InstrumentId] | None
log_warnings : bool
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 InteractiveBrokersDataClientConfig
Bases: LiveDataClientConfig
Configuration for InteractiveBrokersDataClient
instances.
- Parameters:
- ibg_host (str , default "127.0.0.1") – The hostname or ip address for the IB Gateway (IBG) or Trader Workstation (TWS).
- ibg_port (int , default None) – The port for the gateway server. (“paper”/”live” defaults: IBG 4002/4001; TWS 7497/7496)
- ibg_client_id (int , default 1) – The client_id to be passed into connect call.
- use_regular_trading_hours (bool) – If True, will request data for Regular Trading Hours only. Only applies to bar data - will have no effect on trade or tick data feeds. Usually used for ‘STK’ security type. Check with InteractiveBrokers for RTH Info.
- market_data_type (IBMarketDataTypeEnum , default REALTIME) – Set which IBMarketDataTypeEnum to be used by InteractiveBrokersClient. Configure IBMarketDataTypeEnum.DELAYED_FROZEN to use with account without data subscription.
- ignore_quote_tick_size_updates (bool) – If set to True, the QuoteTick subscription will exclude ticks where only the size has changed but not the price. This can help reduce the volume of tick data. When set to False (the default), QuoteTick updates will include all updates, including those where only the size has changed.
- dockerized_gateway (DockerizedIBGatewayConfig , Optional) – The client’s gateway container configuration.
- connection_timeout (int , default 300) – The timeout (seconds) to wait for the client connection to be established.
- request_timeout (int , default 60) – The timeout (seconds) to wait for a historical data response.
instrument_provider : InteractiveBrokersInstrumentProviderConfig
ibg_host : str
ibg_port : int | None
ibg_client_id : int
use_regular_trading_hours : bool
market_data_type : IBMarketDataTypeEnum
ignore_quote_tick_size_updates : bool
dockerized_gateway : DockerizedIBGatewayConfig | None
connection_timeout : int
request_timeout : 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 PoseiConfig class.
- Return type: str
handle_revised_bars : bool
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
routing : RoutingConfig
validate() → bool
Return whether the configuration can be represented as valid JSON.
- Return type: bool
class InteractiveBrokersExecClientConfig
Bases: LiveExecClientConfig
Configuration for InteractiveBrokersExecClient
instances.
- Parameters:
- ibg_host (str , default "127.0.0.1") – The hostname or ip address for the IB Gateway (IBG) or Trader Workstation (TWS).
- ibg_port (int) – The port for the gateway server. (“paper”/”live” defaults: IBG 4002/4001; TWS 7497/7496)
- ibg_client_id (int , default 1) – The client_id to be passed into connect call.
- account_id (str) – Represents the account_id for the Interactive Brokers to which the TWS/Gateway is logged in. It’s crucial that the account_id aligns with the account for which the TWS/Gateway is logged in. If the account_id is None, the system will fallback to use the TWS_ACCOUNT from environment variable.
- dockerized_gateway (DockerizedIBGatewayConfig , Optional) – The client’s gateway container configuration.
- connection_timeout (int , default 300) – The timeout (seconds) to wait for the client connection to be established.
instrument_provider : InteractiveBrokersInstrumentProviderConfig
ibg_host : str
ibg_port : int | None
ibg_client_id : int
account_id : str | None
dockerized_gateway : DockerizedIBGatewayConfig | None
connection_timeout : 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 PoseiConfig 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
routing : RoutingConfig
validate() → bool
Return whether the configuration can be represented as valid JSON.
- Return type: bool
Data
class InteractiveBrokersDataClient
Bases: LiveMarketDataClient
Provides a data client for the InteractiveBrokers exchange by using the Gateway to stream market data.
- Parameters:
- loop (asyncio.AbstractEventLoop) – The event loop for the client.
- client (InteractiveBrokersClient) – The nautilus InteractiveBrokersClient using ibapi.
- msgbus (MessageBus) – The message bus for the client.
- cache (Cache) – The cache for the client.
- clock (LiveClock) – The clock for the client.
- instrument_provider (InteractiveBrokersInstrumentProvider) – The instrument provider.
- ibg_client_id (int) – Client ID used to connect TWS/Gateway.
- config (InteractiveBrokersDataClientConfig) – Configuration for the client.
- name (str , optional) – The custom client ID.
property instrument_provider : InteractiveBrokersInstrumentProvider
connect() → None
Connect the client.
create_task(coro: ~collections.abc.Coroutine, log_msg: str | None = None, actions: ~collections.abc.Callable | None = None, success_msg: str | None = None, success_color: ~posei_trader.core.rust.common.LogColor = <LogColor.NORMAL: 0>) → Task | None
Run the given coroutine with error handling and optional callback actions when done.
- Parameters:
- coro (Coroutine) – The coroutine to run.
- log_msg (str , optional) – The log message for the task.
- actions (Callable , optional) – The actions callback to run when the coroutine is done.
- success_msg (str , optional) – The log message to write on actions success.
- success_color (LogColor, default
NORMAL
) – The log message color for actions success.
- Return type: asyncio.Task
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.
disconnect() → None
Disconnect the client.
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
id
The components ID.
- Returns: ComponentId
is_connected
If the client is connected.
- Returns: bool
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
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
request(self, RequestData request) → void
Request data for the given data type.
- Parameters: request (RequestData) – The message for the data request.
request_bars(self, RequestBars request) → void
Request historical Bar data. To load historical data from a catalog, you can pass a list[DataCatalogConfig] to the TradingNodeConfig or the BacktestEngineConfig.
- Parameters: request (RequestBars) – The message for the data request.
request_instrument(self, RequestInstrument request) → void
Request Instrument data for the given instrument ID.
- Parameters: request (RequestInstrument) – The message for the data request.
request_instruments(self, RequestInstruments request) → void
Request all Instrument data for the given venue.
- Parameters: request (RequestInstruments) – The message for the data request.
request_order_book_snapshot(self, RequestOrderBookSnapshot request) → void
Request order book snapshot data.
- Parameters: request (RequestOrderBookSnapshot) – The message for the data request.
request_quote_ticks(self, RequestQuoteTicks request) → void
Request historical QuoteTick data.
- Parameters: request (RequestQuoteTicks) – The message for the data request.
request_trade_ticks(self, RequestTradeTicks request) → void
Request historical TradeTick data.
- Parameters: request (RequestTradeTicks) – The message for the data 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 run_after_delay(delay: float, coro: Coroutine) → None
Run the given coroutine after a delay.
- Parameters:
- delay (float) – The delay (seconds) before running the coroutine.
- coro (Coroutine) – The coroutine to run after the initial delay.
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 PoseiKernel, 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(self, SubscribeData command) → void
Subscribe to data for the given data type.
- Parameters:
- data_type (DataType) – The data type for the subscription.
- params (dict *[*str , Any ] , optional) – Additional params for the subscription.
subscribe_bars(self, SubscribeBars command) → void
Subscribe to Bar data for the given bar type.
- Parameters:
- bar_type (BarType) – The bar type to subscribe to.
- params (dict *[*str , Any ] , optional) – Additional params for the subscription.
subscribe_index_prices(self, SubscribeIndexPrices command) → void
Subscribe to IndexPriceUpdate data for the given instrument ID.
- Parameters:
- instrument_id (InstrumentId) – The instrument to subscribe to.
- params (dict *[*str , Any ] , optional) – Additional params for the subscription.
subscribe_instrument(self, SubscribeInstrument command) → void
Subscribe to the Instrument with the given instrument ID.
- Parameters: params (dict *[*str , Any ] , optional) – Additional params for the subscription.
subscribe_instrument_close(self, SubscribeInstrumentClose command) → void
Subscribe to InstrumentClose updates for the given instrument ID.
- Parameters:
- instrument_id (InstrumentId) – The tick instrument to subscribe to.
- params (dict *[*str , Any ] , optional) – Additional params for the subscription.
subscribe_instrument_status(self, SubscribeInstrumentStatus command) → void
Subscribe to InstrumentStatus data for the given instrument ID.
- Parameters:
- instrument_id (InstrumentId) – The tick instrument to subscribe to.
- params (dict *[*str , Any ] , optional) – Additional params for the subscription.
subscribe_instruments(self, SubscribeInstruments command) → void
Subscribe to all Instrument data.
- Parameters: params (dict *[*str , Any ] , optional) – Additional params for the subscription.
subscribe_mark_prices(self, SubscribeMarkPrices command) → void
Subscribe to MarkPriceUpdate data for the given instrument ID.
- Parameters:
- instrument_id (InstrumentId) – The instrument to subscribe to.
- params (dict *[*str , Any ] , optional) – Additional params for the subscription.
subscribe_order_book_deltas(self, SubscribeOrderBook command) → void
Subscribe to OrderBookDeltas data for the given instrument ID.
- Parameters:
- instrument_id (InstrumentId) – The order book instrument to subscribe to.
- book_type (BookType {
L1_MBP
,L2_MBP
,L3_MBO
}) – The order book type. - depth (int , optional , default None) – The maximum depth for the subscription.
- params (dict *[*str , Any ] , optional) – Additional params for the subscription.
subscribe_order_book_snapshots(self, SubscribeOrderBook command) → void
Subscribe to OrderBook snapshots data for the given instrument ID.
- Parameters:
- instrument_id (InstrumentId) – The order book instrument to subscribe to.
- book_type (BookType {
L1_MBP
,L2_MBP
,L3_MBO
}) – The order book level. - depth (int , optional) – The maximum depth for the order book. A depth of 0 is maximum depth.
- params (dict *[*str , Any ] , optional) – Additional params for the subscription.
subscribe_quote_ticks(self, SubscribeQuoteTicks command) → void
Subscribe to QuoteTick data for the given instrument ID.
- Parameters:
- instrument_id (InstrumentId) – The tick instrument to subscribe to.
- params (dict *[*str , Any ] , optional) – Additional params for the subscription.
subscribe_trade_ticks(self, SubscribeTradeTicks command) → void
Subscribe to TradeTick data for the given instrument ID.
- Parameters:
- instrument_id (InstrumentId) – The tick instrument to subscribe to.
- params (dict *[*str , Any ] , optional) – Additional params for the subscription.
subscribed_bars(self) → list
Return the bar types subscribed to.
- Return type: list[BarType]
subscribed_custom_data(self) → list
Return the custom data types subscribed to.
- Return type: list[DataType]
subscribed_index_prices(self) → list
Return the index price update instruments subscribed to.
- Return type: list[InstrumentId]
subscribed_instrument_close(self) → list
Return the instrument closes subscribed to.
- Return type: list[InstrumentId]
subscribed_instrument_status(self) → list
Return the status update instruments subscribed to.
- Return type: list[InstrumentId]
subscribed_instruments(self) → list
Return the instruments subscribed to.
- Return type: list[InstrumentId]
subscribed_mark_prices(self) → list
Return the mark price update instruments subscribed to.
- Return type: list[InstrumentId]
subscribed_order_book_deltas(self) → list
Return the order book delta instruments subscribed to.
- Return type: list[InstrumentId]
subscribed_order_book_snapshots(self) → list
Return the order book snapshot instruments subscribed to.
- Return type: list[InstrumentId]
subscribed_quote_ticks(self) → list
Return the quote tick instruments subscribed to.
- Return type: list[InstrumentId]
subscribed_trade_ticks(self) → list
Return the trade tick instruments subscribed to.
- Return type: list[InstrumentId]
trader_id
The trader ID associated with the component.
- Returns: TraderId
type
The components type.
- Returns: type
unsubscribe(self, UnsubscribeData command) → void
Unsubscribe from data for the given data type.
- Parameters:
- data_type (DataType) – The data type for the subscription.
- params (dict *[*str , Any ] , optional) – Additional params for the subscription.
unsubscribe_bars(self, UnsubscribeBars command) → void
Unsubscribe from Bar data for the given bar type.
- Parameters:
- bar_type (BarType) – The bar type to unsubscribe from.
- params (dict *[*str , Any ] , optional) – Additional params for the subscription.
unsubscribe_index_prices(self, UnsubscribeIndexPrices command) → void
Unsubscribe from IndexPriceUpdate data for the given instrument ID.
- Parameters:
- instrument_id (InstrumentId) – The instrument to subscribe to.
- params (dict *[*str , Any ] , optional) – Additional params for the subscription.
unsubscribe_instrument(self, UnsubscribeInstrument command) → void
Unsubscribe from Instrument data for the given instrument ID.
- Parameters:
- instrument_id (InstrumentId) – The instrument to unsubscribe from.
- params (dict *[*str , Any ] , optional) – Additional params for the subscription.
unsubscribe_instrument_close(self, UnsubscribeInstrumentClose command) → void
Unsubscribe from InstrumentClose data for the given instrument ID.
- Parameters:
- instrument_id (InstrumentId) – The tick instrument to unsubscribe from.
- params (dict *[*str , Any ] , optional) – Additional params for the subscription.
unsubscribe_instrument_status(self, UnsubscribeInstrumentStatus command) → void
Unsubscribe from InstrumentStatus data for the given instrument ID.
- Parameters:
- instrument_id (InstrumentId) – The instrument status updates to unsubscribe from.
- params (dict *[*str , Any ] , optional) – Additional params for the subscription.
unsubscribe_instruments(self, UnsubscribeInstruments command) → void
Unsubscribe from all Instrument data.
- Parameters: params (dict *[*str , Any ] , optional) – Additional params for the subscription.
unsubscribe_mark_prices(self, UnsubscribeMarkPrices command) → void
Unsubscribe from MarkPriceUpdate data for the given instrument ID.
- Parameters:
- instrument_id (InstrumentId) – The instrument to subscribe to.
- params (dict *[*str , Any ] , optional) – Additional params for the subscription.
unsubscribe_order_book_deltas(self, UnsubscribeOrderBook command) → void
Unsubscribe from OrderBookDeltas data for the given instrument ID.
- Parameters:
- instrument_id (InstrumentId) – The order book instrument to unsubscribe from.
- params (dict *[*str , Any ] , optional) – Additional params for the subscription.
unsubscribe_order_book_snapshots(self, UnsubscribeOrderBook command) → void
Unsubscribe from OrderBook snapshots data for the given instrument ID.
- Parameters:
- instrument_id (InstrumentId) – The order book instrument to unsubscribe from.
- params (dict *[*str , Any ] , optional) – Additional params for the subscription.
unsubscribe_quote_ticks(self, UnsubscribeQuoteTicks command) → void
Unsubscribe from QuoteTick data for the given instrument ID.
- Parameters:
- instrument_id (InstrumentId) – The tick instrument to unsubscribe from.
- params (dict *[*str , Any ] , optional) – Additional params for the subscription.
unsubscribe_trade_ticks(self, UnsubscribeTradeTicks command) → void
Unsubscribe from TradeTick data for the given instrument ID.
- Parameters:
- instrument_id (InstrumentId) – The tick instrument to unsubscribe from.
- params (dict *[*str , Any ] , optional) – Additional params for the subscription.
venue
The clients venue ID (if applicable).
- Returns:
Venue or
None
Execution
class InteractiveBrokersExecutionClient
Bases: LiveExecutionClient
Provides an execution client for Interactive Brokers TWS API, allowing for the retrieval of account information and execution of orders.
- Parameters:
- loop (asyncio.AbstractEventLoop) – The event loop for the client.
- client (InteractiveBrokersClient) – The nautilus InteractiveBrokersClient using ibapi.
- account_id (AccountId) – Account ID associated with this client.
- msgbus (MessageBus) – The message bus for the client.
- cache (Cache) – The cache for the client.
- clock (LiveClock) – The clock for the client.
- instrument_provider (InteractiveBrokersInstrumentProvider) – The instrument provider.
- config (InteractiveBrokersExecClientConfig , optional) – The configuration for the instance.
- name (str , optional) – The custom client ID.
property instrument_provider : InteractiveBrokersInstrumentProvider
async generate_order_status_report(command: GenerateOrderStatusReport) → OrderStatusReport | None
Generate an OrderStatusReport for the given order identifier parameter(s).
If the order is not found, or an error occurs, then logs and returns None
.
- Parameters: command (GenerateOrderStatusReport) – The command to generate the report.
- Return type:
OrderStatusReport or
None
- Raises:
ValueError – If both the client_order_id and venue_order_id are
None
.
async generate_order_status_reports(command: GenerateOrderStatusReports) → list[OrderStatusReport]
Generate a list of
`
OrderStatusReport`s with optional query filters.
The returned list may be empty if no orders match the given parameters.
- Parameters: command (GenerateOrderStatusReports) – The command for generating the reports.
- Return type: list[OrderStatusReport]
async generate_fill_reports(command: GenerateFillReports) → list[FillReport]
Generate a list of
`
FillReport`s with optional query filters.
The returned list may be empty if no trades match the given parameters.
- Parameters: command (GenerateFillReports) – The command for generating the reports.
- Return type: list[FillReport]
async generate_position_status_reports(command: GeneratePositionStatusReports) → list[PositionStatusReport]
Generate a list of
`
PositionStatusReport`s with optional query filters.
The returned list may be empty if no positions match the given parameters.
- Parameters: command (GeneratePositionStatusReports) – The command for generating the position status reports.
- Return type: list[PositionStatusReport]
async handle_order_status_report(ib_order: Order) → None
account_id
The clients account ID.
- Returns:
AccountId or
None
account_type
The clients account type.
- Returns: AccountType
base_currency
The clients account base currency (None for multi-currency accounts).
- Returns:
Currency or
None
batch_cancel_orders(self, BatchCancelOrders command) → void
Batch cancel orders for the instrument ID contained in the given command.
- Parameters: command (BatchCancelOrders) – The command to execute.
cancel_all_orders(self, CancelAllOrders command) → void
Cancel all orders for the instrument ID contained in the given command.
- Parameters: command (CancelAllOrders) – The command to execute.
cancel_order(self, CancelOrder command) → void
Cancel the order with the client order ID contained in the given command.
- Parameters: command (CancelOrder) – The command to execute.
connect() → None
Connect the client.
create_task(coro: ~collections.abc.Coroutine, log_msg: str | None = None, actions: ~collections.abc.Callable | None = None, success_msg: str | None = None, success_color: ~posei_trader.core.rust.common.LogColor = <LogColor.NORMAL: 0>) → Task
Run the given coroutine with error handling and optional callback actions when done.
- Parameters:
- coro (Coroutine) – The coroutine to run.
- log_msg (str , optional) – The log message for the task.
- actions (Callable , optional) – The actions callback to run when the coroutine is done.
- success_msg (str , optional) – The log message to write on actions success.
- success_color (str, default
NORMAL
) – The log message color for actions success.
- Return type: asyncio.Task
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.
disconnect() → None
Disconnect the client.
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
generate_account_state(self, list balances, list margins, bool reported, uint64_t ts_event, dict info=None) → void
Generate an AccountState event and publish on the message bus.
- Parameters:
- balances (list [AccountBalance ]) – The account balances.
- margins (list [MarginBalance ]) – The margin balances.
- reported (bool) – If the balances are reported directly from the exchange.
- ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the account state event occurred.
- info (dict *[*str , object ]) – The additional implementation specific account information.
async generate_mass_status(lookback_mins: int | None = None) → ExecutionMassStatus | None
Generate an ExecutionMassStatus report.
- Parameters: lookback_mins (int , optional) – The maximum lookback for querying closed orders, trades and positions.
- Return type:
ExecutionMassStatus or
None
generate_order_accepted(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, VenueOrderId venue_order_id, uint64_t ts_event) → void
Generate an OrderAccepted event and send it to the ExecutionEngine.
- Parameters:
- strategy_id (StrategyId) – The strategy ID associated with the event.
- instrument_id (InstrumentId) – The instrument ID.
- client_order_id (ClientOrderId) – The client order ID.
- venue_order_id (VenueOrderId) – The venue order ID (assigned by the venue).
- ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the order accepted event occurred.
generate_order_cancel_rejected(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, VenueOrderId venue_order_id, str reason, uint64_t ts_event) → void
Generate an OrderCancelRejected event and send it to the ExecutionEngine.
- Parameters:
- strategy_id (StrategyId) – The strategy ID associated with the event.
- instrument_id (InstrumentId) – The instrument ID.
- client_order_id (ClientOrderId) – The client order ID.
- venue_order_id (VenueOrderId) – The venue order ID (assigned by the venue).
- reason (str) – The order cancel rejected reason.
- ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the order cancel rejected event occurred.
generate_order_canceled(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, VenueOrderId venue_order_id, uint64_t ts_event) → void
Generate an OrderCanceled event and send it to the ExecutionEngine.
- Parameters:
- strategy_id (StrategyId) – The strategy ID associated with the event.
- instrument_id (InstrumentId) – The instrument ID.
- client_order_id (ClientOrderId) – The client order ID.
- venue_order_id (VenueOrderId) – The venue order ID (assigned by the venue).
- ts_event (uint64_t) – UNIX timestamp (nanoseconds) when order canceled event occurred.
generate_order_expired(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, VenueOrderId venue_order_id, uint64_t ts_event) → void
Generate an OrderExpired event and send it to the ExecutionEngine.
- Parameters:
- strategy_id (StrategyId) – The strategy ID associated with the event.
- instrument_id (InstrumentId) – The instrument ID.
- client_order_id (ClientOrderId) – The client order ID.
- venue_order_id (VenueOrderId) – The venue order ID (assigned by the venue).
- ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the order expired event occurred.
generate_order_filled(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, VenueOrderId venue_order_id, PositionId venue_position_id: PositionId | None, TradeId trade_id, OrderSide order_side, OrderType order_type, Quantity last_qty, Price last_px, Currency quote_currency, Money commission, LiquiditySide liquidity_side, uint64_t ts_event, dict info=None) → void
Generate an OrderFilled event and send it to the ExecutionEngine.
- Parameters:
- strategy_id (StrategyId) – The strategy ID associated with the event.
- instrument_id (InstrumentId) – The instrument ID.
- client_order_id (ClientOrderId) – The client order ID.
- venue_order_id (VenueOrderId) – The venue order ID (assigned by the venue).
- trade_id (TradeId) – The trade ID.
- venue_position_id (PositionId or
None
) – The venue position ID associated with the order. If the trading venue has assigned a position ID / ticket then pass that here, otherwise passNone
and the execution engine OMS will handle position ID resolution. - order_side (OrderSide {
BUY
,SELL
}) – The execution order side. - order_type (OrderType) – The execution order type.
- last_qty (Quantity) – The fill quantity for this execution.
- last_px (Price) – The fill price for this execution (not average price).
- quote_currency (Currency) – The currency of the price.
- commission (Money) – The fill commission.
- liquidity_side (LiquiditySide {
NO_LIQUIDITY_SIDE
,MAKER
,TAKER
}) – The execution liquidity side. - ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the order filled event occurred.
- info (dict *[*str , object ] , optional) – The additional fill information.
generate_order_modify_rejected(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, VenueOrderId venue_order_id, str reason, uint64_t ts_event) → void
Generate an OrderModifyRejected event and send it to the ExecutionEngine.
- Parameters:
- strategy_id (StrategyId) – The strategy ID associated with the event.
- instrument_id (InstrumentId) – The instrument ID.
- client_order_id (ClientOrderId) – The client order ID.
- venue_order_id (VenueOrderId) – The venue order ID (assigned by the venue).
- reason (str) – The order update rejected reason.
- ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the order update rejection event occurred.
generate_order_rejected(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, str reason, uint64_t ts_event) → void
Generate an OrderRejected event and send it to the ExecutionEngine.
- Parameters:
- strategy_id (StrategyId) – The strategy ID associated with the event.
- instrument_id (InstrumentId) – The instrument ID.
- client_order_id (ClientOrderId) – The client order ID.
- reason (datetime) – The order rejected reason.
- ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the order rejected event occurred.
generate_order_submitted(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, uint64_t ts_event) → void
Generate an OrderSubmitted event and send it to the ExecutionEngine.
- Parameters:
- strategy_id (StrategyId) – The strategy ID associated with the event.
- instrument_id (InstrumentId) – The instrument ID.
- client_order_id (ClientOrderId) – The client order ID.
- ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the order submitted event occurred.
generate_order_triggered(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, VenueOrderId venue_order_id, uint64_t ts_event) → void
Generate an OrderTriggered event and send it to the ExecutionEngine.
- Parameters:
- strategy_id (StrategyId) – The strategy ID associated with the event.
- instrument_id (InstrumentId) – The instrument ID.
- client_order_id (ClientOrderId) – The client order ID.
- venue_order_id (VenueOrderId) – The venue order ID (assigned by the venue).
- ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the order triggered event occurred.
generate_order_updated(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, VenueOrderId venue_order_id, Quantity quantity, Price price, Price trigger_price, uint64_t ts_event, bool venue_order_id_modified=False) → void
Generate an OrderUpdated event and send it to the ExecutionEngine.
- Parameters:
- strategy_id (StrategyId) – The strategy ID associated with the event.
- instrument_id (InstrumentId) – The instrument ID.
- client_order_id (ClientOrderId) – The client order ID.
- venue_order_id (VenueOrderId) – The venue order ID (assigned by the venue).
- quantity (Quantity) – The orders current quantity.
- price (Price) – The orders current price.
- trigger_price (Price or
None
) – The orders current trigger price. - ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the order update event occurred.
- venue_order_id_modified (bool) – If the ID was modified for this event.
get_account(self) → Account
Return the account for the client (if registered).
- Return type:
Account or
None
id
The components ID.
- Returns: ComponentId
is_connected
If the client is connected.
- Returns: bool
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
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
modify_order(self, ModifyOrder command) → void
Modify the order with parameters contained in the command.
- Parameters: command (ModifyOrder) – The command to execute.
oms_type
The venues order management system type.
- Returns: OmsType
query_order(self, QueryOrder command) → void
Initiate a reconciliation for the queried order which will generate an OrderStatusReport.
- Parameters: command (QueryOrder) – The command to execute.
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 run_after_delay(delay: float, coro: Coroutine) → None
Run the given coroutine after a delay.
- Parameters:
- delay (float) – The delay (seconds) before running the coroutine.
- coro (Coroutine) – The coroutine to run after the initial delay.
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 PoseiKernel, 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.
submit_order(self, SubmitOrder command) → void
Submit the order contained in the given command for execution.
- Parameters: command (SubmitOrder) – The command to execute.
submit_order_list(self, SubmitOrderList command) → void
Submit the order list contained in the given command for execution.
- Parameters: command (SubmitOrderList) – The command to execute.
trader_id
The trader ID associated with the component.
- Returns: TraderId
type
The components type.
- Returns: type
venue
The clients venue ID (if not a routing client).
- Returns:
Venue or
None
Factories
get_cached_ib_client(loop: AbstractEventLoop, msgbus: MessageBus, cache: Cache, clock: LiveClock, host: str = '127.0.0.1', port: int | None = None, client_id: int = 1, dockerized_gateway: DockerizedIBGatewayConfig | None = None) → InteractiveBrokersClient
Retrieve or create a cached InteractiveBrokersClient using the provided key.
Should a keyed client already exist within the cache, the function will return this instance. It’s important to note that the key comprises a combination of the host, port, and client_id.
- Parameters:
- loop (asyncio.AbstractEventLoop ,) – loop
- msgbus (MessageBus ,) – msgbus
- cache (Cache ,) – cache
- clock (LiveClock ,) – clock
- host (str) – The IB host to connect to. This is optional if using DockerizedIBGatewayConfig, but is required otherwise.
- port (int) – The IB port to connect to. This is optional if using DockerizedIBGatewayConfig, but is required otherwise.
- client_id (int) – The unique session identifier for the TWS or Gateway.A single host can support multiple connections; however, each must use a different client_id.
- dockerized_gateway (DockerizedIBGatewayConfig , optional) – The configuration for the dockerized gateway.If this is provided, Posei will oversee the docker environment, facilitating the operation of the IB Gateway within.
- Return type: InteractiveBrokersClient
get_cached_interactive_brokers_instrument_provider(client: InteractiveBrokersClient, config: InteractiveBrokersInstrumentProviderConfig) → InteractiveBrokersInstrumentProvider
Cache and return a InteractiveBrokersInstrumentProvider.
If a cached provider already exists, then that cached provider will be returned.
- Parameters:
- client (InteractiveBrokersClient) – The client for the instrument provider.
- config (InteractiveBrokersInstrumentProviderConfig) – The instrument provider config
- Return type: InteractiveBrokersInstrumentProvider
class InteractiveBrokersLiveDataClientFactory
Bases: LiveDataClientFactory
Provides a InteractiveBrokers live data client factory.
static create(loop: AbstractEventLoop, name: str, config: InteractiveBrokersDataClientConfig, msgbus: MessageBus, cache: Cache, clock: LiveClock) → InteractiveBrokersDataClient
Create a new InteractiveBrokers data client.
- Parameters:
- loop (asyncio.AbstractEventLoop) – The event loop for the client.
- name (str) – The custom client ID.
- config (dict) – The configuration dictionary.
- msgbus (MessageBus) – The message bus for the client.
- cache (Cache) – The cache for the client.
- clock (LiveClock) – The clock for the client.
- Return type: InteractiveBrokersDataClient
class InteractiveBrokersLiveExecClientFactory
Bases: LiveExecClientFactory
Provides a InteractiveBrokers live execution client factory.
static create(loop: AbstractEventLoop, name: str, config: InteractiveBrokersExecClientConfig, msgbus: MessageBus, cache: Cache, clock: LiveClock) → InteractiveBrokersExecutionClient
Create a new InteractiveBrokers execution client.
- Parameters:
- loop (asyncio.AbstractEventLoop) – The event loop for the client.
- name (str) – The custom client ID.
- config (dict *[*str , object ]) – The configuration for the client.
- msgbus (MessageBus) – The message bus for the client.
- cache (Cache) – The cache for the client.
- clock (LiveClock) – The clock for the client.
- Return type: InteractiveBrokersSpotExecutionClient
Gateway
class DockerizedIBGateway
Bases: object
A class to manage starting an Interactive Brokers Gateway docker container.
CONTAINER_NAME : ClassVar[str] = 'nautilus-ib-gateway'
PORTS : ClassVar[dict[str, int]] = {'live': 4001, 'paper': 4002}
property container_status : ContainerStatus
property container
static is_logged_in(container) → bool
start(wait: int | None = None) → None
Start the gateway.
- Parameters: wait (int , optional) – The seconds to wait until container is ready.
safe_start(wait: int | None = None) → None
stop() → None
Historical
class HistoricInteractiveBrokersClient
Bases: object
Provides a means of requesting historical market data for backtesting.
async connect() → None
async request_instruments(instrument_ids: list[str] | None = None, contracts: list[IBContract] | None = None, instrument_provider_config: InteractiveBrokersInstrumentProviderConfig | None = None) → list[Instrument]
Return Instruments given either a InteractiveBrokersInstrumentProviderConfig or a list of IBContracts and/or InstrumentId strings.
- Parameters:
- instrument_ids (list *[*str ] , default 'None') – Instrument IDs (e.g. AAPL.NASDAQ) defining which instruments to retrieve.
- contracts (list [IBContract ] , default 'None') – IBContracts defining which instruments to retrieve.
- instrument_provider_config (InteractiveBrokersInstrumentProviderConfig) – An instrument provider config defining which instruments to retrieve.
- Return type: list[Instrument]
async request_bars(bar_specifications: list[str], end_date_time: datetime, tz_name: str, start_date_time: datetime | None = None, duration: str | None = None, contracts: list[IBContract] | None = None, instrument_ids: list[str] | None = None, instrument_provider_config: InteractiveBrokersInstrumentProviderConfig | None = None, use_rth: bool = True, timeout: int = 120) → list[Bar]
Return Bars for one or more bar specifications for a list of IBContracts and/or InstrumentId strings.
- Parameters:
- bar_specifications (list *[*str ]) – BarSpecifications represented as strings defining which bars to retrieve. (e.g. ‘1-HOUR-LAST’, ‘5-MINUTE-MID’)
- start_date_time (datetime.datetime) – The start date time for the bars. If provided, duration is derived.
- end_date_time (datetime.datetime) – The end date time for the bars. Note that for continuous futures (CONTFUT), the downloaded data is always up to now.
- tz_name (str) – The timezone to use. (e.g. ‘America/New_York’, ‘UTC’)
- duration (str) – The amount of time to go back from the end_date_time. Valid values follow the pattern of an integer followed by S|D|W|M|Y for seconds, days, weeks, months, or years respectively.
- contracts (list [IBContract ] , default 'None') – IBContracts defining which bars to retrieve.
- instrument_ids (list *[*str ] , default 'None') – Instrument IDs (e.g. AAPL.NASDAQ) defining which bars to retrieve.
- instrument_provider_config (InteractiveBrokersInstrumentProviderConfig , optional) – Configuration for the instrument provider to determine venues and handle symbology.
- use_rth (bool , default 'True') – Whether to use regular trading hours.
- timeout (int , default 120) – The timeout (seconds) for each request.
- Return type: list[Bar]
async request_ticks(tick_type: Literal['TRADES', 'BID_ASK'], start_date_time: datetime, end_date_time: datetime, tz_name: str, contracts: list[IBContract] | None = None, instrument_ids: list[str] | None = None, instrument_provider_config: InteractiveBrokersInstrumentProviderConfig | None = None, use_rth: bool = True, timeout: int = 60) → list[TradeTick | QuoteTick]
Return TradeTicks or QuoteTicks for one or more bar specifications for a list of IBContracts and/or InstrumentId strings.
- Parameters:
- tick_type (Literal [ "TRADES" , "BID_ASK" ]) – The type of ticks to retrieve.
- start_date_time (datetime.date) – The start date for the ticks.
- end_date_time (datetime.date) – The end date for the ticks.
- tz_name (str) – The timezone to use. (e.g. ‘America/New_York’, ‘UTC’)
- contracts (list [IBContract ] , default 'None') – IBContracts defining which ticks to retrieve.
- instrument_ids (list *[*str ] , default 'None') – Instrument IDs (e.g. AAPL.NASDAQ) defining which ticks to retrieve.
- instrument_provider_config (InteractiveBrokersInstrumentProviderConfig , optional) – Configuration for the instrument provider to determine venues and handle symbology.
- use_rth (bool , default 'True') – Whether to use regular trading hours.
- timeout (int , default 60) – The timeout (seconds) for each request.
- Return type: list[TradeTick | QuoteTick]
Parsing
timestring_to_timestamp(timestring: str) → Timestamp
sec_type_to_asset_class(sec_type: str) → AssetClass
contract_details_to_ib_contract_details(details: ContractDetails) → IBContractDetails
parse_instrument(contract_details: IBContractDetails, venue: str, symbology_method: SymbologyMethod = SymbologyMethod.IB_SIMPLIFIED) → Instrument
parse_equity_contract(details: IBContractDetails, instrument_id: InstrumentId) → Equity
parse_index_contract(details: IBContractDetails, instrument_id: InstrumentId) → IndexInstrument
parse_futures_contract(details: IBContractDetails, instrument_id: InstrumentId) → FuturesContract
parse_option_contract(details: IBContractDetails, instrument_id: InstrumentId) → OptionContract
expiry_timestring_to_datetime(expiry: str) → Timestamp
Most contract expirations are %Y%m%d format some exchanges have expirations in %Y%m%d %H:%M:%S %Z.
parse_forex_contract(details: IBContractDetails, instrument_id: InstrumentId) → CurrencyPair
parse_crypto_contract(details: IBContractDetails, instrument_id: InstrumentId) → CryptoPerpetual
parse_cfd_contract(details: IBContractDetails, instrument_id: InstrumentId) → Cfd
parse_commodity_contract(details: IBContractDetails, instrument_id: InstrumentId) → Commodity
contract_details_to_dict(details: IBContractDetails) → dict
decade_digit(last_digit: str, contract: IBContract) → int
ib_contract_to_instrument_id(contract: IBContract, venue: str, symbology_method: SymbologyMethod = SymbologyMethod.IB_SIMPLIFIED) → InstrumentId
ib_contract_to_instrument_id_simplified_symbology(contract: IBContract, venue: str) → InstrumentId
ib_contract_to_instrument_id_raw_symbology(contract: IBContract, venue: str) → InstrumentId
instrument_id_to_ib_contract(instrument_id: InstrumentId, exchange: str, symbology_method: SymbologyMethod = SymbologyMethod.IB_SIMPLIFIED) → IBContract
instrument_id_to_ib_contract_simplified_symbology(instrument_id: InstrumentId, exchange: str) → IBContract
instrument_id_to_ib_contract_raw_symbology(instrument_id: InstrumentId) → IBContract
Providers
class InteractiveBrokersInstrumentProvider
Bases: InstrumentProvider
Provides a means of loading Instrument objects through Interactive Brokers.
async initialize(reload: bool = False) → None
Initialize the instrument provider.
- Parameters: reload (bool , default False) – If True, then will always reload instruments. If False, then will immediately return if already loaded.
async get_instrument(contract_id: int) → Instrument
async instrument_id_to_ib_contract(instrument_id: InstrumentId) → IBContract | None
async instrument_id_to_ib_contract_details(instrument_id: InstrumentId) → IBContractDetails | None
get_price_magnifier(instrument_id: InstrumentId) → int
Get the price magnifier for an instrument from its contract details.
- Parameters: instrument_id (InstrumentId) – The instrument identifier.
- Returns: The price magnifier, defaults to 1 if not found.
- Return type: int
determine_venue_from_contract(contract: IBContract) → str
Determine the venue for a contract using the instrument provider configuration logic.
- Parameters: contract (IBContract) – The contract to determine the venue for.
- Returns: The determined venue.
- Return type: str
async load_all_async(filters: dict | None = None) → None
Load the latest instruments into the provider asynchronously, optionally applying the given filters.
async load_ids_async(instrument_ids: list[InstrumentId], filters: dict | None = None, force_instrument_update: bool = False) → None
Load the instruments for the given IDs into the provider, optionally applying the given filters.
- Parameters:
- instrument_ids (list [InstrumentId ]) – The instrument IDs to load.
- filters (frozendict *[*str , Any ] or dict *[*str , Any ] , optional) – The venue specific instrument loading filters to apply.
- Raises: ValueError – If any instrument_id.venue is not equal to self.venue.
async load_async(instrument_id: InstrumentId | IBContract, filters: dict | None = None, force_instrument_update: bool = False) → None
Search and load the instrument for the given IBContract. It is important that the Contract shall have enough parameters so only one match is returned.
- Parameters:
- instrument_id (IBContract) – InteractiveBroker’s Contract.
- filters (dict , optional) – Not applicable in this case.
- force_instrument_update (bool , optional) – Whether to reload instrument from IB if it’s already cached.
async fetch_instrument_id(instrument_id: InstrumentId, force_instrument_update: bool = False) → bool
async get_contract_details(contract: IBContract) → list[ContractDetails]
async get_future_chain_details(underlying: IBContract, min_expiry: Timestamp, max_expiry: Timestamp) → list[ContractDetails]
async get_option_chain_details_by_range(underlying: IBContract, min_expiry: Timestamp, max_expiry: Timestamp, exchange: str | None = None) → list[ContractDetails]
async get_option_chain_details_by_expiry(underlying: IBContract, last_trading_date: str, exchange: str) → list[ContractDetails]
add(instrument: Instrument) → None
Add the given instrument to the provider.
- Parameters: instrument (Instrument) – The instrument to add.
add_bulk(instruments: list[Instrument]) → None
Add the given instruments bulk to the provider.
- Parameters: instruments (list [Instrument ]) – The instruments to add.
add_currency(currency: Currency) → None
Add the given currency to the provider.
- Parameters: currency (Currency) – The currency to add.
property count : int
Return the count of instruments held by the provider.
- Return type: int
currencies() → dict[str, Currency]
Return all currencies held by the instrument provider.
- Return type: dict[str, Currency]
currency(code: str) → Currency | None
Return the currency with the given code (if found).
- Parameters: code (str) – The currency code.
- Return type:
Currency or
None
- Raises: ValueError – If code is not a valid string.
find(instrument_id: InstrumentId) → Instrument | None
Return the instrument for the given instrument ID (if found).
- Parameters: instrument_id (InstrumentId) – The ID for the instrument
- Return type:
Instrument or
None
get_all() → dict[InstrumentId, Instrument]
Return all loaded instruments as a map keyed by instrument ID.
If no instruments loaded, will return an empty dict.
- Return type: dict[InstrumentId, Instrument]
list_all() → list[Instrument]
Return all loaded instruments.
- Return type: list[Instrument]
load(instrument_id: InstrumentId, filters: dict | None = None) → None
Load the instrument for the given ID into the provider, optionally applying the given filters.
- Parameters:
- instrument_id (InstrumentId) – The instrument ID to load.
- filters (frozendict *[*str , Any ] or dict *[*str , Any ] , optional) – The venue specific instrument loading filters to apply.
load_all(filters: dict | None = None) → None
Load the latest instruments into the provider, optionally applying the given filters.
- Parameters: filters (frozendict *[*str , Any ] or dict *[*str , Any ] , optional) – The venue specific instrument loading filters to apply.
load_ids(instrument_ids: list[InstrumentId], filters: dict | None = None) → None
Load the instruments for the given IDs into the provider, optionally applying the given filters.
- Parameters:
- instrument_ids (list [InstrumentId ]) – The instrument IDs to load.
- filters (frozendict *[*str , Any ] or dict *[*str , Any ] , optional) – The venue specific instrument loading filters to apply.