Interactive Brokers

Provides an API integration for Interactive Brokers.

Common

class ContractId

Bases: int

ContractId type.

as_integer_ratio ( )

Return integer ratio.

Return a pair of integers, whose ratio is exactly equal to the original int and with 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

from_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

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 ( conId : int = 0 , ratio : int = 0 , action : str = '' , exchange : str = '' , openClose : int = 0 , shortSaleSlot : int = 0 , designatedLocation : str = '' , exemptCode : int = -1 )

Bases: NautilusConfig

Class representing a leg within combo orders.

dict ( ) dict [ str , Any ]

Return a dictionary representation of the configuration.

Returns :

dict[str, Any]

classmethod fully_qualified_name ( ) str

Return the fully qualified name for the NautilusConfig class.

Returns :

str

References

https://www.python.org/dev/peps/pep-3155/

property id : str

Return the hashed identifier for the configuration.

Returns :

str

json ( ) bytes

Return serialized JSON encoded bytes.

Returns :

bytes

json_primitives ( ) dict [ str , Any ]

Return a dictionary representation of the configuration with JSON primitive types as values.

Returns :

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.

Returns :

Any

validate ( ) bool

Return whether the configuration can be represented as valid JSON.

Returns :

bool

class DeltaNeutralContract ( conId : int = 0 , delta : float = 0.0 , price : float = 0.0 )

Bases: NautilusConfig

Delta-Neutral Contract.

dict ( ) dict [ str , Any ]

Return a dictionary representation of the configuration.

Returns :

dict[str, Any]

classmethod fully_qualified_name ( ) str

Return the fully qualified name for the NautilusConfig class.

Returns :

str

References

https://www.python.org/dev/peps/pep-3155/

property id : str

Return the hashed identifier for the configuration.

Returns :

str

json ( ) bytes

Return serialized JSON encoded bytes.

Returns :

bytes

json_primitives ( ) dict [ str , Any ]

Return a dictionary representation of the configuration with JSON primitive types as values.

Returns :

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.

Returns :

Any

validate ( ) bool

Return whether the configuration can be represented as valid JSON.

Returns :

bool

class IBContract ( secType : Literal [ 'CASH' , 'STK' , 'OPT' , 'FUT' , 'FOP' , 'CONTFUT' , 'CRYPTO' , '' ] = '' , conId : int = 0 , exchange : str = '' , primaryExchange : str = '' , symbol : str = '' , localSymbol : str = '' , currency : str = '' , tradingClass : str = '' , lastTradeDateOrContractMonth : str = '' , multiplier : str = '' , strike : float = 0.0 , right : str = '' , includeExpired : bool = False , secIdType : str = '' , secId : str = '' , description : str = '' , issuerId : str = '' , comboLegsDescrip : str = '' , comboLegs : list [ nautilus_trader.adapters.interactive_brokers.common.ComboLeg ] | None = None , deltaNeutralContract : nautilus_trader.adapters.interactive_brokers.common.DeltaNeutralContract | None = None , build_futures_chain : bool | None = None , build_options_chain : bool | None = None , min_expiry_days : int | None = None , max_expiry_days : int | None = None )

Bases: NautilusConfig

Class describing an instrument’s definition with additional fields for options/futures.

Parameters :
  • secType ( str ) – Security Type of the contract i.e STK, OPT, FUT, CONTFUT

  • exchange ( str ) – Exchange where security is traded. Will be SMART for Stocks.

  • primaryExchange ( str ) – Exchange where security is registered. Applies to Stocks.

  • symbol ( str ) – Unique Symbol registered in Exchange.

  • build_options_chain ( bool ( default: None ) ) – Search for full option chain

  • build_futures_chain ( bool ( default: None ) ) – Search for full futures chain

  • 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

dict ( ) dict [ str , Any ]

Return a dictionary representation of the configuration.

Returns :

dict[str, Any]

classmethod fully_qualified_name ( ) str

Return the fully qualified name for the NautilusConfig class.

Returns :

str

References

https://www.python.org/dev/peps/pep-3155/

property id : str

Return the hashed identifier for the configuration.

Returns :

str

json ( ) bytes

Return serialized JSON encoded bytes.

Returns :

bytes

json_primitives ( ) dict [ str , Any ]

Return a dictionary representation of the configuration with JSON primitive types as values.

Returns :

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.

Returns :

Any

validate ( ) bool

Return whether the configuration can be represented as valid JSON.

Returns :

bool

class IBOrderTags ( whatIf : bool = False , ocaGroup : str = '' , ocaType : int = 0 , allOrNone : bool = False , activeStartTime : str = '' , activeStopTime : str = '' , goodAfterTime : str = '' , outsideRth : bool = False )

Bases: NautilusConfig

Used to attach to Nautilus Order Tags for IB specific order parameters.

dict ( ) dict [ str , Any ]

Return a dictionary representation of the configuration.

Returns :

dict[str, Any]

classmethod fully_qualified_name ( ) str

Return the fully qualified name for the NautilusConfig class.

Returns :

str

References

https://www.python.org/dev/peps/pep-3155/

property id : str

Return the hashed identifier for the configuration.

Returns :

str

json ( ) bytes

Return serialized JSON encoded bytes.

Returns :

bytes

json_primitives ( ) dict [ str , Any ]

Return a dictionary representation of the configuration with JSON primitive types as values.

Returns :

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.

Returns :

Any

validate ( ) bool

Return whether the configuration can be represented as valid JSON.

Returns :

bool

class IBContractDetails ( contract : nautilus_trader.adapters.interactive_brokers.common.IBContract | None = None , marketName : str = '' , minTick : float = 0 , orderTypes : str = '' , validExchanges : str = '' , priceMagnifier : float = 0 , underConId : int = 0 , longName : str = '' , contractMonth : str = '' , industry : str = '' , category : str = '' , subcategory : str = '' , timeZoneId : str = '' , tradingHours : str = '' , liquidHours : str = '' , evRule : str = '' , evMultiplier : int = 0 , mdSizeMultiplier : int = 1 , aggGroup : int = 0 , underSymbol : str = '' , underSecType : str = '' , marketRuleIds : str = '' , secIdList : list [ ibapi.tag_value.TagValue ] | None = None , realExpirationDate : str = '' , lastTradeTime : str = '' , stockType : str = '' , minSize : Decimal = Decimal('170141183460469231731687303715884105727') , sizeIncrement : Decimal = Decimal('170141183460469231731687303715884105727') , suggestedSizeIncrement : Decimal = Decimal('170141183460469231731687303715884105727') , cusip : str = '' , ratings : str = '' , descAppend : str = '' , bondType : str = '' , couponType : str = '' , callable : bool = False , putable : bool = False , coupon : int = 0 , convertible : bool = False , maturity : str = '' , issueDate : str = '' , nextOptionDate : str = '' , nextOptionType : str = '' , nextOptionPartial : bool = False , notes : str = '' )

Bases: NautilusConfig

ContractDetails class to be used internally in Nautilus for ease of encoding/decoding.

dict ( ) dict [ str , Any ]

Return a dictionary representation of the configuration.

Returns :

dict[str, Any]

classmethod fully_qualified_name ( ) str

Return the fully qualified name for the NautilusConfig class.

Returns :

str

References

https://www.python.org/dev/peps/pep-3155/

property id : str

Return the hashed identifier for the configuration.

Returns :

str

json ( ) bytes

Return serialized JSON encoded bytes.

Returns :

bytes

json_primitives ( ) dict [ str , Any ]

Return a dictionary representation of the configuration with JSON primitive types as values.

Returns :

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.

Returns :

Any

validate ( ) bool

Return whether the configuration can be represented as valid JSON.

Returns :

bool

Config

class InteractiveBrokersGatewayConfig ( username : str | None = None , password : str | None = None , host : str | None = '127.0.0.1' , port : Optional [ Literal [ 4001 , 4002 ] ] = None , trading_mode : Literal [ 'paper' , 'live' ] = 'paper' , start : bool = False , read_only_api : bool = True , timeout : int = 300 )

Bases: NautilusConfig

Configuration for InteractiveBrokersGateway setup.

Parameters :
  • username ( str , optional ) – The Interactive Brokers account username. If None then will source the TWS_USERNAME .

  • password ( str , optional ) – The Interactive Brokers account password. If None then will source the TWS_PASSWORD .

  • host ( str , optional ) – The hostname or ip address for the IB Gateway or TWS.

  • port ( int , optional ) – The port for the gateway server (“paper” 4002, or “live” 4001).

  • trading_mode ( str ) – paper or live.

  • start ( bool , optional ) – Start or not internal tws docker container.

  • read_only_api ( bool , optional , default True ) – Read only; no execution. Set read_only_api=False to allow executing live orders.

  • timeout ( int , optional ) – The timeout for trying to start gateway

dict ( ) dict [ str , Any ]

Return a dictionary representation of the configuration.

Returns :

dict[str, Any]

classmethod fully_qualified_name ( ) str

Return the fully qualified name for the NautilusConfig class.

Returns :

str

References

https://www.python.org/dev/peps/pep-3155/

property id : str

Return the hashed identifier for the configuration.

Returns :

str

json ( ) bytes

Return serialized JSON encoded bytes.

Returns :

bytes

json_primitives ( ) dict [ str , Any ]

Return a dictionary representation of the configuration with JSON primitive types as values.

Returns :

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.

Returns :

Any

validate ( ) bool

Return whether the configuration can be represented as valid JSON.

Returns :

bool

class InteractiveBrokersInstrumentProviderConfig ( load_all : bool = False , load_ids : frozenset [ nautilus_trader.model.identifiers.InstrumentId ] | None = None , filters : dict [ str , Any ] | None = None , filter_callable : str | None = None , log_warnings : bool = True , strict_symbology : bool = False , load_contracts : frozenset [ nautilus_trader.adapters.interactive_brokers.common.IBContract ] | None = None , build_options_chain : bool | None = None , build_futures_chain : bool | None = None , min_expiry_days : int | None = None , max_expiry_days : int | None = None , cache_validity_days : int | None = None , pickle_path : str | None = None )

Bases: InstrumentProviderConfig

Configuration for InteractiveBrokersInstrumentProvider instances.

Parameters :
  • strict_symbology ( bool , optional ) – Determines the symbology format used for identifying instruments. If set to True, a strict symbology format is used, as provided by InteractiveBrokers where instrument symbols are detailed in the format localSymbol=secType.exchange (e.g., EUR.USD=CASH.IDEALPRO ). If False, a simplified symbology format is applied, using a notation like EUR/USD.IDEALPRO . The default value is False, favoring simplified symbology unless specified otherwise.

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

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

dict ( ) dict [ str , Any ]

Return a dictionary representation of the configuration.

Returns :

dict[str, Any]

classmethod fully_qualified_name ( ) str

Return the fully qualified name for the NautilusConfig class.

Returns :

str

References

https://www.python.org/dev/peps/pep-3155/

property id : str

Return the hashed identifier for the configuration.

Returns :

str

json ( ) bytes

Return serialized JSON encoded bytes.

Returns :

bytes

json_primitives ( ) dict [ str , Any ]

Return a dictionary representation of the configuration with JSON primitive types as values.

Returns :

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.

Returns :

Any

validate ( ) bool

Return whether the configuration can be represented as valid JSON.

Returns :

bool

class InteractiveBrokersDataClientConfig ( handle_revised_bars: bool = False , instrument_provider: ~nautilus_trader.adapters.interactive_brokers.config.InteractiveBrokersInstrumentProviderConfig = InteractiveBrokersInstrumentProviderConfig(load_all=False , load_ids=None , filters=None , filter_callable=None , log_warnings=True , strict_symbology=False , load_contracts=None , build_options_chain=None , build_futures_chain=None , min_expiry_days=None , max_expiry_days=None , cache_validity_days=None , pickle_path=None) , routing: ~nautilus_trader.live.config.RoutingConfig = RoutingConfig(default=False , venues=None) , ibg_host: str = '127.0.0.1' , ibg_port: int | None = None , ibg_client_id: int = 1 , gateway: ~nautilus_trader.adapters.interactive_brokers.config.InteractiveBrokersGatewayConfig = InteractiveBrokersGatewayConfig(username=None , password=None , host='127.0.0.1' , port=None , trading_mode='paper' , start=False , read_only_api=True , timeout=300) , use_regular_trading_hours: bool = True , market_data_type: <ibapi.enum_implem.Enum object at 0x7f272e0ccad0> = 1 )

Bases: LiveDataClientConfig

Configuration for InteractiveBrokersDataClient instances.

Parameters :
  • ibg_host ( str , default "127.0.0.1" ) – The hostname or ip address for the IB Gateway or TWS.

  • ibg_port ( int , default for "paper" 4002 , or "live" 4001 ) – The port for the gateway server.

  • ibg_client_id ( int , default 1 ) – The client_id to be passed into connect call.

  • gateway ( InteractiveBrokersGatewayConfig ) – The clients gateway container configuration.

  • use_regular_trading_hours ( bool ) – If True will request data for Regular Trading Hours only. Mostly applies to ‘STK’ security type. Check with InteractiveBrokers for RTH Info.

  • market_data_type ( bool , default REALTIME ) – Set which IBMarketDataTypeEnum to be used by InteractiveBrokersClient. Configure IBMarketDataTypeEnum.DELAYED_FROZEN to use with account without data subscription.

dict ( ) dict [ str , Any ]

Return a dictionary representation of the configuration.

Returns :

dict[str, Any]

classmethod fully_qualified_name ( ) str

Return the fully qualified name for the NautilusConfig class.

Returns :

str

References

https://www.python.org/dev/peps/pep-3155/

property id : str

Return the hashed identifier for the configuration.

Returns :

str

json ( ) bytes

Return serialized JSON encoded bytes.

Returns :

bytes

json_primitives ( ) dict [ str , Any ]

Return a dictionary representation of the configuration with JSON primitive types as values.

Returns :

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.

Returns :

Any

validate ( ) bool

Return whether the configuration can be represented as valid JSON.

Returns :

bool

class InteractiveBrokersExecClientConfig ( instrument_provider : InteractiveBrokersInstrumentProviderConfig = InteractiveBrokersInstrumentProviderConfig(load_all=False, load_ids=None, filters=None, filter_callable=None, log_warnings=True, strict_symbology=False, load_contracts=None, build_options_chain=None, build_futures_chain=None, min_expiry_days=None, max_expiry_days=None, cache_validity_days=None, pickle_path=None) , routing : RoutingConfig = RoutingConfig(default=False, venues=None) , ibg_host : str = '127.0.0.1' , ibg_port : int | None = None , ibg_client_id : int = 1 , gateway : InteractiveBrokersGatewayConfig = InteractiveBrokersGatewayConfig(username=None, password=None, host='127.0.0.1', port=None, trading_mode='paper', start=False, read_only_api=True, timeout=300) , account_id : str | None = None )

Bases: LiveExecClientConfig

Configuration for InteractiveBrokersExecClient instances.

Parameters :
  • ibg_host ( str , default "127.0.0.1" ) – The hostname or ip address for the IB Gateway or TWS.

  • ibg_port ( int ) – The port for the gateway server (“paper” 4002, or “live” 4001).

  • ibg_client_id ( int , default 1 ) – The client_id to be passed into connect call.

  • ibg_account_id ( str ) – The Interactive Brokers account id to which TWS/Gateway is logged on. If None then will source the TWS_ACCOUNT .

dict ( ) dict [ str , Any ]

Return a dictionary representation of the configuration.

Returns :

dict[str, Any]

classmethod fully_qualified_name ( ) str

Return the fully qualified name for the NautilusConfig class.

Returns :

str

References

https://www.python.org/dev/peps/pep-3155/

property id : str

Return the hashed identifier for the configuration.

Returns :

str

json ( ) bytes

Return serialized JSON encoded bytes.

Returns :

bytes

json_primitives ( ) dict [ str , Any ]

Return a dictionary representation of the configuration with JSON primitive types as values.

Returns :

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.

Returns :

Any

validate ( ) bool

Return whether the configuration can be represented as valid JSON.

Returns :

bool

Data

class InteractiveBrokersDataClient ( loop : AbstractEventLoop , client : InteractiveBrokersClient , msgbus : MessageBus , cache : Cache , clock : LiveClock , instrument_provider : InteractiveBrokersInstrumentProvider , ibg_client_id : int , config : InteractiveBrokersDataClientConfig , name : str | None = None )

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.

connect ( ) None

Connect the client.

create_task ( coro : Coroutine , log_msg : str | None = None , actions : collections.abc.Callable | None = None , success_msg : str | None = None , success_color : LogColor = LogColor.NORMAL ) 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 (LogColor, default NORMAL ) – The log message color for actions success.

Returns :

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.

Returns :

str

References

https://www.python.org/dev/peps/pep-3155/

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 .

Returns :

bool

Type :

Component.is_degraded

is_disposed

bool

Return whether the current component state is DISPOSED .

Returns :

bool

Type :

Component.is_disposed

is_faulted

bool

Return whether the current component state is FAULTED .

Returns :

bool

Type :

Component.is_faulted

is_initialized

bool

Return whether the component has been initialized (component.state >= INITIALIZED ).

Returns :

bool

Type :

Component.is_initialized

is_running

bool

Return whether the current component state is RUNNING .

Returns :

bool

Type :

Component.is_running

is_stopped

bool

Return whether the current component state is STOPPED .

Returns :

bool

Type :

Component.is_stopped

request ( self , DataType data_type , UUID4 correlation_id ) void

Request data for the given data type.

Parameters :
  • data_type ( DataType ) – The data type for the subscription.

  • correlation_id ( UUID4 ) – The correlation ID for the response.

request_bars ( self , BarType bar_type , int limit , UUID4 correlation_id , datetime start=None , datetime end=None ) void

Request historical Bar data.

Parameters :
  • bar_type ( BarType ) – The bar type for the request.

  • limit ( int ) – The limit for the number of returned bars.

  • correlation_id ( UUID4 ) – The correlation ID for the request.

  • start ( datetime , optional ) – The start datetime (UTC) of request time range (inclusive).

  • end ( datetime , optional ) – The end datetime (UTC) of request time range. The inclusiveness depends on individual data client implementation.

request_instrument ( self , InstrumentId instrument_id , UUID4 correlation_id , datetime start=None , datetime end=None ) void

Request Instrument data for the given instrument ID.

Parameters :
  • instrument_id ( InstrumentId ) – The instrument ID for the request.

  • correlation_id ( UUID4 ) – The correlation ID for the request.

  • start ( datetime , optional ) – The start datetime (UTC) of request time range (inclusive).

  • end ( datetime , optional ) – The end datetime (UTC) of request time range. The inclusiveness depends on individual data client implementation.

request_instruments ( self , Venue venue , UUID4 correlation_id , datetime start=None , datetime end=None ) void

Request all Instrument data for the given venue.

Parameters :
  • venue ( Venue ) – The venue for the request.

  • correlation_id ( UUID4 ) – The correlation ID for the request.

  • start ( datetime , optional ) – The start datetime (UTC) of request time range (inclusive).

  • end ( datetime , optional ) – The end datetime (UTC) of request time range. The inclusiveness depends on individual data client implementation.

request_quote_ticks ( self , InstrumentId instrument_id , int limit , UUID4 correlation_id , datetime start=None , datetime end=None ) void

Request historical QuoteTick data.

Parameters :
  • instrument_id ( InstrumentId ) – The tick instrument ID for the request.

  • limit ( int ) – The limit for the number of returned ticks.

  • correlation_id ( UUID4 ) – The correlation ID for the request.

  • start ( datetime , optional ) – The start datetime (UTC) of request time range (inclusive).

  • end ( datetime , optional ) – The end datetime (UTC) of request time range. The inclusiveness depends on individual data client implementation.

request_trade_ticks ( self , InstrumentId instrument_id , int limit , UUID4 correlation_id , datetime start=None , datetime end=None ) void

Request historical TradeTick data.

Parameters :
  • instrument_id ( InstrumentId ) – The tick instrument ID for the request.

  • limit ( int ) – The limit for the number of returned ticks.

  • correlation_id ( UUID4 ) – The correlation ID for the request.

  • start ( datetime , optional ) – The start datetime (UTC) of request time range (inclusive).

  • end ( datetime , optional ) – The end datetime (UTC) of request time range. The inclusiveness depends on individual data client implementation.

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.

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.

Returns :

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 , DataType data_type ) void

Subscribe to data for the given data type.

Parameters :

data_type ( DataType ) – The data type for the subscription.

subscribe_bars ( self , BarType bar_type ) void

Subscribe to Bar data for the given bar type.

Parameters :

bar_type ( BarType ) – The bar type to subscribe to.

subscribe_instrument ( self , InstrumentId instrument_id ) void

Subscribe to the Instrument with the given instrument ID.

subscribe_instrument_close ( self , InstrumentId instrument_id ) void

Subscribe to InstrumentClose updates for the given instrument ID.

Parameters :

instrument_id ( InstrumentId ) – The tick instrument to subscribe to.

subscribe_instrument_status ( self , InstrumentId instrument_id ) void

Subscribe to InstrumentStatus data for the given instrument ID.

Parameters :

instrument_id ( InstrumentId ) – The tick instrument to subscribe to.

subscribe_instruments ( self ) void

Subscribe to all Instrument data.

subscribe_order_book_deltas ( self , InstrumentId instrument_id , BookType book_type , int depth=0 , dict kwargs=None ) 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.

  • kwargs ( dict , optional ) – The keyword arguments for exchange specific parameters.

subscribe_order_book_snapshots ( self , InstrumentId instrument_id , BookType book_type , int depth=0 , dict kwargs=None ) 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.

  • kwargs ( dict , optional ) – The keyword arguments for exchange specific parameters.

subscribe_quote_ticks ( self , InstrumentId instrument_id ) void

Subscribe to QuoteTick data for the given instrument ID.

Parameters :

instrument_id ( InstrumentId ) – The tick instrument to subscribe to.

subscribe_trade_ticks ( self , InstrumentId instrument_id ) void

Subscribe to TradeTick data for the given instrument ID.

Parameters :

instrument_id ( InstrumentId ) – The tick instrument to subscribe to.

subscribe_venue_status ( self , Venue venue ) void

Subscribe to InstrumentStatus data for the venue.

Parameters :

venue ( Venue ) – The venue to subscribe to.

subscribed_bars ( self ) list

Return the bar types subscribed to.

Returns :

list[BarType]

subscribed_custom_data ( self ) list

Return the custom data types subscribed to.

Returns :

list[DataType]

subscribed_instrument_close ( self ) list

Return the instrument closes subscribed to.

Returns :

list[InstrumentId]

subscribed_instrument_status ( self ) list

Return the status update instruments subscribed to.

Returns :

list[InstrumentId]

subscribed_instruments ( self ) list

Return the instruments subscribed to.

Returns :

list[InstrumentId]

subscribed_order_book_deltas ( self ) list

Return the order book delta instruments subscribed to.

Returns :

list[InstrumentId]

subscribed_order_book_snapshots ( self ) list

Return the order book snapshot instruments subscribed to.

Returns :

list[InstrumentId]

subscribed_quote_ticks ( self ) list

Return the quote tick instruments subscribed to.

Returns :

list[InstrumentId]

subscribed_trade_ticks ( self ) list

Return the trade tick instruments subscribed to.

Returns :

list[InstrumentId]

subscribed_venue_status ( self ) list

Return the status update instruments subscribed to.

Returns :

list[InstrumentId]

trader_id

The trader ID associated with the component.

Returns :

TraderId

type

The components type.

Returns :

type

unsubscribe ( self , DataType data_type ) void

Unsubscribe from data for the given data type.

Parameters :

data_type ( DataType ) – The data type for the subscription.

unsubscribe_bars ( self , BarType bar_type ) void

Unsubscribe from Bar data for the given bar type.

Parameters :

bar_type ( BarType ) – The bar type to unsubscribe from.

unsubscribe_instrument ( self , InstrumentId instrument_id ) void

Unsubscribe from Instrument data for the given instrument ID.

Parameters :

instrument_id ( InstrumentId ) – The instrument to unsubscribe from.

unsubscribe_instrument_close ( self , InstrumentId instrument_id ) void

Unsubscribe from InstrumentClose data for the given instrument ID.

Parameters :

instrument_id ( InstrumentId ) – The tick instrument to unsubscribe from.

unsubscribe_instrument_status ( self , InstrumentId instrument_id ) void

Unsubscribe from InstrumentStatus data for the given instrument ID.

Parameters :

instrument_id ( InstrumentId ) – The instrument status updates to unsubscribe from.

unsubscribe_instruments ( self ) void

Unsubscribe from all Instrument data.

unsubscribe_order_book_deltas ( self , InstrumentId instrument_id ) void

Unsubscribe from OrderBookDeltas data for the given instrument ID.

Parameters :

instrument_id ( InstrumentId ) – The order book instrument to unsubscribe from.

unsubscribe_order_book_snapshots ( self , InstrumentId instrument_id ) void

Unsubscribe from OrderBook snapshots data for the given instrument ID.

Parameters :

instrument_id ( InstrumentId ) – The order book instrument to unsubscribe from.

unsubscribe_quote_ticks ( self , InstrumentId instrument_id ) void

Unsubscribe from QuoteTick data for the given instrument ID.

Parameters :

instrument_id ( InstrumentId ) – The tick instrument to unsubscribe from.

unsubscribe_trade_ticks ( self , InstrumentId instrument_id ) void

Unsubscribe from TradeTick data for the given instrument ID.

Parameters :

instrument_id ( InstrumentId ) – The tick instrument to unsubscribe from.

unsubscribe_venue_status ( self , Venue venue ) void

Unsubscribe from InstrumentStatus data for the given venue.

Parameters :

venue ( Venue ) – The venue to unsubscribe from.

venue

The clients venue ID (if applicable).

Returns :

Venue or None

Execution

class InteractiveBrokersExecutionClient ( loop : AbstractEventLoop , client : InteractiveBrokersClient , account_id : AccountId , msgbus : MessageBus , cache : Cache , clock : LiveClock , instrument_provider : InteractiveBrokersInstrumentProvider , ibg_client_id : int , config : InteractiveBrokersExecClientConfig , name : str | None = None )

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.

  • ibg_client_id ( int ) – Client ID used to connect TWS/Gateway.

  • config ( InteractiveBrokersExecClientConfig , optional ) – The configuration for the instance.

  • name ( str , optional ) – The custom client ID.

async generate_order_status_report ( instrument_id : InstrumentId , client_order_id : nautilus_trader.model.identifiers.ClientOrderId | None = None , venue_order_id : nautilus_trader.model.identifiers.VenueOrderId | None = None ) nautilus_trader.execution.reports.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 :
  • instrument_id ( InstrumentId ) – The instrument ID for the report.

  • client_order_id ( ClientOrderId , optional ) – The client order ID for the report.

  • venue_order_id ( VenueOrderId , optional ) – The venue order ID for the report.

Returns :

OrderStatusReport or None

Raises :

ValueError – If both the client_order_id and venue_order_id are None .

async generate_order_status_reports ( instrument_id : nautilus_trader.model.identifiers.InstrumentId | None = None , start : pandas._libs.tslibs.timestamps.Timestamp | None = None , end : pandas._libs.tslibs.timestamps.Timestamp | None = None , open_only : bool = False ) list [ nautilus_trader.execution.reports.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 :
  • instrument_id ( InstrumentId , optional ) – The instrument ID query filter.

  • start ( pd.Timestamp , optional ) – The start datetime (UTC) query filter.

  • end ( pd.Timestamp , optional ) – The end datetime (UTC) query filter.

  • open_only ( bool , default False ) – If the query is for open orders only.

Returns :

list[OrderStatusReport]

async generate_fill_reports ( instrument_id : nautilus_trader.model.identifiers.InstrumentId | None = None , venue_order_id : nautilus_trader.model.identifiers.VenueOrderId | None = None , start : pandas._libs.tslibs.timestamps.Timestamp | None = None , end : pandas._libs.tslibs.timestamps.Timestamp | None = None ) list [ nautilus_trader.execution.reports.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 :
  • instrument_id ( InstrumentId , optional ) – The instrument ID query filter.

  • venue_order_id ( VenueOrderId , optional ) – The venue order ID (assigned by the venue) query filter.

  • start ( pd.Timestamp , optional ) – The start datetime (UTC) query filter.

  • end ( pd.Timestamp , optional ) – The end datetime (UTC) query filter.

Returns :

list[FillReport]

async generate_position_status_reports ( instrument_id : nautilus_trader.model.identifiers.InstrumentId | None = None , start : pandas._libs.tslibs.timestamps.Timestamp | None = None , end : pandas._libs.tslibs.timestamps.Timestamp | None = None ) list [ nautilus_trader.execution.reports.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 :
  • instrument_id ( InstrumentId , optional ) – The instrument ID query filter.

  • start ( pd.Timestamp , optional ) – The start datetime (UTC) query filter.

  • end ( pd.Timestamp , optional ) – The end datetime (UTC) query filter.

Returns :

list[PositionStatusReport]

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 : Coroutine , log_msg : str | None = None , actions : collections.abc.Callable | None = None , success_msg : str | None = None , success_color : LogColor = LogColor.NORMAL ) 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.

Returns :

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.

Returns :

str

References

https://www.python.org/dev/peps/pep-3155/

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 ) – The 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 ) nautilus_trader.execution.reports.ExecutionMassStatus | None

Generate an ExecutionMassStatus report.

Parameters :

lookback_mins ( int , optional ) – The maximum lookback for querying closed orders, trades and positions.

Returns :

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 ) – The 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 , unicode 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 ) – The 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 ) – The 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 ) – The 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 ) 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, optional with no default so None must be passed explicitly) – The venue position ID associated with the order. If the trading venue has assigned a position ID / ticket then pass that here, otherwise pass None 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 ) – The UNIX timestamp (nanoseconds) when the order filled event occurred.

generate_order_modify_rejected ( self , StrategyId strategy_id , InstrumentId instrument_id , ClientOrderId client_order_id , VenueOrderId venue_order_id , unicode 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 ) – The UNIX timestamp (nanoseconds) when the order update rejection event occurred.

generate_order_rejected ( self , StrategyId strategy_id , InstrumentId instrument_id , ClientOrderId client_order_id , unicode 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 ) – The 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 ) – The 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 ) – The 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, optional with no default so None must be passed explicitly) – The orders current trigger price.

  • ts_event ( uint64_t ) – The 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).

Returns :

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 .

Returns :

bool

Type :

Component.is_degraded

is_disposed

bool

Return whether the current component state is DISPOSED .

Returns :

bool

Type :

Component.is_disposed

is_faulted

bool

Return whether the current component state is FAULTED .

Returns :

bool

Type :

Component.is_faulted

is_initialized

bool

Return whether the component has been initialized (component.state >= INITIALIZED ).

Returns :

bool

Type :

Component.is_initialized

is_running

bool

Return whether the current component state is RUNNING .

Returns :

bool

Type :

Component.is_running

is_stopped

bool

Return whether the current component state is STOPPED .

Returns :

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.

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.

Returns :

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 , gateway : InteractiveBrokersGatewayConfig = InteractiveBrokersGatewayConfig(username=None, password=None, host='127.0.0.1', port=None, trading_mode='paper', start=False, read_only_api=True, timeout=300) ) InteractiveBrokersClient

Cache and return a InteractiveBrokers HTTP client with the given key and secret.

If a cached client with matching key and secret already exists, then that cached client will be returned.

Parameters :
  • loop ( asyncio.AbstractEventLoop , ) – loop

  • msgbus ( MessageBus , ) – msgbus

  • cache ( Cache , ) – cache

  • clock ( LiveClock , ) – clock

  • host ( str , optional ) – The IB host to connect to

  • port ( int , optional ) – The IB port to connect to

  • client_id ( int , optional ) – The client_id to connect with

  • gateway ( InteractiveBrokersGatewayConfig ) – Configuration for the gateway.

Returns :

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 :
Returns :

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.

Returns :

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.

Returns :

InteractiveBrokersSpotExecutionClient

Providers

class InteractiveBrokersInstrumentProvider ( client : InteractiveBrokersClient , config : InteractiveBrokersInstrumentProviderConfig )

Bases: InstrumentProvider

Provides a means of loading Instrument objects through Interactive Brokers.

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 [ nautilus_trader.model.identifiers.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 ( dict , 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 : nautilus_trader.model.identifiers.InstrumentId | nautilus_trader.adapters.interactive_brokers.common.IBContract , filters : dict | None = None ) 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.

add ( instrument : Instrument ) None

Add the given instrument to the provider.

Parameters :

instrument ( Instrument ) – The instrument to add.

add_bulk ( instruments : list [ nautilus_trader.model.instruments.base.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.

Returns :

int

currencies ( ) dict [ str , nautilus_trader.model.objects.Currency ]

Return all currencies held by the instrument provider.

Returns :

dict[str, Currency]

currency ( code : str ) nautilus_trader.model.objects.Currency | None

Return the currency with the given code (if found).

Parameters :

code ( str ) – The currency code.

Returns :

Currency or None

Raises :

ValueError – If code is not a valid string.

find ( instrument_id : InstrumentId ) nautilus_trader.model.instruments.base.Instrument | None

Return the instrument for the given instrument ID (if found).

Parameters :

instrument_id ( InstrumentId ) – The ID for the instrument

Returns :

Instrument or None

get_all ( ) dict [ nautilus_trader.model.identifiers.InstrumentId , nautilus_trader.model.instruments.base.Instrument ]

Return all loaded instruments as a map keyed by instrument ID.

If no instruments loaded, will return an empty dict.

Returns :

dict[InstrumentId, Instrument]

async initialize ( ) None

Initialize the instrument provider.

If initialize() then will immediately return.

list_all ( ) list [ nautilus_trader.model.instruments.base.Instrument ]

Return all loaded instruments.

Returns :

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 ( dict , 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 ( dict , optional ) – The venue specific instrument loading filters to apply.

load_ids ( instrument_ids : list [ nautilus_trader.model.identifiers.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 ( dict , optional ) – The venue specific instrument loading filters to apply.