Live ¶
The live subpackage groups all engine and client implementations for live trading.
Generally a common event loop is passed into each live engine to support the overarching design of a single efficient event loop, by default uvloop .
Data Client ¶
The LiveDataClient class is responsible for interfacing with a particular API which may be presented directly by an exchange, or broker intermediary. It could also be possible to write clients for specialized data publishers.
- class LiveDataClient ( loop: asyncio.AbstractEventLoop, ClientId client_id, Venue venue: Optional[Venue], MessageBus msgbus, Cache cache, LiveClock clock, Logger logger, dict config=None ) ¶
-
Bases:
nautilus_trader.data.client.DataClient
The abstract base class for all live data clients.
- Parameters
-
-
loop ( asyncio.AbstractEventLoop ) – The event loop for the client.
-
client_id ( ClientId ) – The client ID.
-
venue ( Venue , optional ) – The client venue. If multi-venue then can be
None
. -
msgbus ( MessageBus ) – The message bus for the client.
-
cache ( Cache ) – The cache for the client.
-
clock ( LiveClock ) – The clock for the client.
-
logger ( Logger ) – The logger for the client.
-
config ( dict [ str , object ] , optional ) – The configuration for the instance.
-
Warning
This class should not be used directly, but through a concrete subclass.
- connect ( self ) None ¶
-
Connect the client.
- degrade ( self ) void ¶
-
Degrade the component.
While executing on_degrade() , any exception will be logged and reraised. 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 ( self ) None ¶
-
Disconnect the client.
- dispose ( self ) void ¶
-
Dispose of the component.
While executing on_dispose() , any exception will be logged and reraised. 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.
This method is idempotent and irreversible. No other methods should be called after faulting.
While executing on_fault() , any exception will be logged and reraised. 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 ( type cls ) str ¶
-
Return the fully qualified name for the components class.
- Returns
-
str
References
- id ¶
-
The components ID.
- Returns
-
ComponentId
- is_connected ¶
-
If the client is connected.
- Returns
-
bool
- is_degraded ¶
-
Return whether the current component state is
DEGRADED
.- Returns
-
bool
- is_disposed ¶
-
Return whether the current component state is
DISPOSED
.- Returns
-
bool
- is_faulted ¶
-
Return whether the current component state is
FAULTED
.- Returns
-
bool
- is_initialized ¶
-
Return whether the component has been initialized (component.state >=
INITIALIZED
).- Returns
-
bool
- is_running ¶
-
Return whether the current component state is
RUNNING
.- Returns
-
bool
- is_stopped ¶
-
Return whether the current component state is
STOPPED
.- Returns
-
bool
- request ( self , DataType data_type , UUID4 correlation_id ) void ¶
-
Request data for the given data type.
- 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. 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. 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.
- run_after_delay ( self , double delay: float , coro ) None ¶
- sleep0 ( self ) None ¶
- start ( self ) void ¶
-
Start the component.
While executing on_start() , any exception will be logged and reraised. 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 ¶
-
Return the components current state.
- Returns
-
ComponentState
- stop ( self ) void ¶
-
Stop the component.
While executing on_stop() , any exception will be logged and reraised. 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.
- subscribed_generic_data ( self ) list ¶
-
Return the generic data types subscribed to.
- Returns
-
list[DataType]
- 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.
- venue ¶
-
The clients venue ID (if not a routing client).
- Returns
-
Venue or
None
- class LiveMarketDataClient ( loop: asyncio.AbstractEventLoop, ClientId client_id, Venue venue: Optional[Venue], instrument_provider: InstrumentProvider, MessageBus msgbus, Cache cache, LiveClock clock, Logger logger, dict config=None ) ¶
-
Bases:
nautilus_trader.data.client.MarketDataClient
The abstract base class for all live data clients.
- Parameters
-
-
loop ( asyncio.AbstractEventLoop ) – The event loop for the client.
-
client_id ( ClientId ) – The client ID.
-
venue ( Venue , optional ) – The client venue. If multi-venue then can be
None
. -
instrument_provider ( InstrumentProvider ) – The instrument provider 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.
-
logger ( Logger ) – The logger for the client.
-
config ( dict [ str , object ] , optional ) – The configuration for the instance.
-
Warning
This class should not be used directly, but through a concrete subclass.
- connect ( self ) None ¶
-
Connect the client.
- degrade ( self ) void ¶
-
Degrade the component.
While executing on_degrade() , any exception will be logged and reraised. 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 ( self ) None ¶
-
Disconnect the client.
- dispose ( self ) void ¶
-
Dispose of the component.
While executing on_dispose() , any exception will be logged and reraised. 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.
This method is idempotent and irreversible. No other methods should be called after faulting.
While executing on_fault() , any exception will be logged and reraised. 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 ( type cls ) str ¶
-
Return the fully qualified name for the components class.
- Returns
-
str
References
- id ¶
-
The components ID.
- Returns
-
ComponentId
- is_connected ¶
-
If the client is connected.
- Returns
-
bool
- is_degraded ¶
-
Return whether the current component state is
DEGRADED
.- Returns
-
bool
- is_disposed ¶
-
Return whether the current component state is
DISPOSED
.- Returns
-
bool
- is_faulted ¶
-
Return whether the current component state is
FAULTED
.- Returns
-
bool
- is_initialized ¶
-
Return whether the component has been initialized (component.state >=
INITIALIZED
).- Returns
-
bool
- is_running ¶
-
Return whether the current component state is
RUNNING
.- Returns
-
bool
- is_stopped ¶
-
Return whether the current component state is
STOPPED
.- Returns
-
bool
- request ( self , DataType data_type , UUID4 correlation_id ) void ¶
-
Request data for the given data type.
- request_bars ( self , BarType bar_type , datetime from_datetime , datetime to_datetime , int limit , UUID4 correlation_id ) void ¶
-
Request historical Bar data.
- Parameters
-
-
bar_type ( BarType ) – The bar type for the request.
-
from_datetime ( datetime , optional ) – The specified from datetime for the data.
-
to_datetime ( datetime , optional ) – The specified to datetime for the data. If
None
then will default to the current datetime. -
limit ( int ) – The limit for the number of returned bars.
-
correlation_id ( UUID4 ) – The correlation ID for the request.
-
- request_instrument ( self , InstrumentId instrument_id , UUID4 correlation_id ) 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.
-
- request_quote_ticks ( self , InstrumentId instrument_id , datetime from_datetime , datetime to_datetime , int limit , UUID4 correlation_id ) void ¶
-
Request historical QuoteTick data.
- Parameters
-
-
instrument_id ( InstrumentId ) – The tick instrument ID for the request.
-
from_datetime ( datetime , optional ) – The specified from datetime for the data.
-
to_datetime ( datetime , optional ) – The specified to datetime for the data. If
None
then will default to the current datetime. -
limit ( int ) – The limit for the number of returned ticks.
-
correlation_id ( UUID4 ) – The correlation ID for the request.
-
- request_trade_ticks ( self , InstrumentId instrument_id , datetime from_datetime , datetime to_datetime , int limit , UUID4 correlation_id ) void ¶
-
Request historical TradeTick data.
- Parameters
-
-
instrument_id ( InstrumentId ) – The tick instrument ID for the request.
-
from_datetime ( datetime , optional ) – The specified from datetime for the data.
-
to_datetime ( datetime , optional ) – The specified to datetime for the data. If
None
then will default to the current datetime. -
limit ( int ) – The limit for the number of returned ticks.
-
correlation_id ( UUID4 ) – The correlation ID for the 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. 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. 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.
- run_after_delay ( self , delay , coro ) None ¶
- sleep0 ( self ) None ¶
- start ( self ) void ¶
-
Start the component.
While executing on_start() , any exception will be logged and reraised. 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 ¶
-
Return the components current state.
- Returns
-
ComponentState
- stop ( self ) void ¶
-
Stop the component.
While executing on_stop() , any exception will be logged and reraised. 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_prices ( self , InstrumentId instrument_id ) void ¶
-
Subscribe to InstrumentClosePrice data for the given instrument ID.
- Parameters
-
instrument_id ( InstrumentId ) – The tick instrument to subscribe to.
- subscribe_instrument_status_updates ( self , InstrumentId instrument_id ) void ¶
-
Subscribe to InstrumentStatusUpdates 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_TBBO
,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 OrderBookSnapshot data for the given instrument ID.
- Parameters
-
-
instrument_id ( InstrumentId ) – The order book instrument to subscribe to.
-
book_type (BookType {
L1_TBBO
,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_ticker ( self , InstrumentId instrument_id ) void ¶
-
Subscribe to Ticker data for the given instrument ID.
- Parameters
-
instrument_id ( InstrumentId ) – The ticker 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.
- subscribed_bars ( self ) list ¶
-
Return the bar types subscribed to.
- Returns
-
list[BarType]
- subscribed_generic_data ( self ) list ¶
-
Return the generic data types subscribed to.
- Returns
-
list[DataType]
- subscribed_instrument_close_prices ( self ) list ¶
-
Return the close price instruments subscribed to.
- Returns
-
list[InstrumentId]
- subscribed_instrument_status_updates ( 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_tickers ( self ) list ¶
-
Return the ticker instruments subscribed to.
- Returns
-
list[InstrumentId]
- subscribed_trade_ticks ( self ) list ¶
-
Return the trade tick 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_prices ( self , InstrumentId instrument_id ) void ¶
-
Unsubscribe from InstrumentClosePrice data for the given instrument ID.
- Parameters
-
instrument_id ( InstrumentId ) – The tick instrument to unsubscribe from.
- unsubscribe_instrument_status_updates ( self , InstrumentId instrument_id ) void ¶
-
Unsubscribe from InstrumentStatusUpdates data for the given instrument ID.
- Parameters
-
instrument_id ( InstrumentId ) – The tick instrument 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 OrderBookSnapshot 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_ticker ( self , InstrumentId instrument_id ) void ¶
-
Unsubscribe from Ticker data for the given instrument ID.
- Parameters
-
instrument_id ( InstrumentId ) – The ticker 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.
- venue ¶
-
The clients venue ID (if not a routing client).
- Returns
-
Venue or
None
Data Engine ¶
- class LiveDataEngine ( loop: asyncio.AbstractEventLoop , MessageBus msgbus , Cache cache , LiveClock clock , Logger logger , config: Optional[LiveDataEngineConfig] = None ) ¶
-
Bases:
nautilus_trader.data.engine.DataEngine
Provides a high-performance asynchronous live data engine.
- Parameters
-
-
loop ( asyncio.AbstractEventLoop ) – The event loop for the engine.
-
msgbus ( MessageBus ) – The message bus for the engine.
-
cache ( Cache ) – The cache for the engine.
-
clock ( Clock ) – The clock for the engine.
-
logger ( Logger ) – The logger for the engine.
-
config ( LiveDataEngineConfig , optional ) – The configuration for the instance.
-
- Raises
-
TypeError – If config is not of type LiveDataEngineConfig .
- check_connected ( self ) bool ¶
-
Check all of the engines clients are connected.
- Returns
-
bool – True if all clients connected, else False.
- check_disconnected ( self ) bool ¶
-
Check all of the engines clients are disconnected.
- Returns
-
bool – True if all clients disconnected, else False.
- command_count ¶
-
The total count of data commands received by the engine.
- Returns
-
int
- connect ( self ) ¶
-
Connect the engine by calling connect on all registered clients.
- data_count ¶
-
The total count of data stream objects received by the engine.
- Returns
-
int
- data_qsize ( self ) int ¶
-
Return the number of objects buffered on the internal data queue.
- Returns
-
int
- debug ¶
-
If debug mode is active (will provide extra debug logging).
- Returns
-
bool
- default_client ¶
-
Return the default data client registered with the engine.
- Returns
-
Optional[ClientId]
- degrade ( self ) void ¶
-
Degrade the component.
While executing on_degrade() , any exception will be logged and reraised. 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.
- deregister_client ( self , DataClient client ) void ¶
-
Deregister the given data client from the data engine.
- Parameters
-
client ( DataClient ) – The data client to deregister.
- disconnect ( self ) ¶
-
Disconnect the engine by calling disconnect on all registered clients.
- dispose ( self ) void ¶
-
Dispose of the component.
While executing on_dispose() , any exception will be logged and reraised. 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.
- execute ( self , DataCommand command ) void ¶
-
Execute the given data command.
If the internal queue is already full then will log a warning and block until queue size reduces.
- Parameters
-
command ( DataCommand ) – The command to execute.
Warning
This method should only be called from the same thread the event loop is running on.
- fault ( self ) void ¶
-
Fault the component.
This method is idempotent and irreversible. No other methods should be called after faulting.
While executing on_fault() , any exception will be logged and reraised. 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 ( type cls ) str ¶
-
Return the fully qualified name for the components class.
- Returns
-
str
References
- get_event_loop ( self ) asyncio.AbstractEventLoop ¶
-
Return the internal event loop for the engine.
- Returns
-
asyncio.AbstractEventLoop
- get_run_queue_task ( self ) asyncio.Task ¶
-
Return the internal run queue task for the engine.
- Returns
-
asyncio.Task
- id ¶
-
The components ID.
- Returns
-
ComponentId
- is_degraded ¶
-
Return whether the current component state is
DEGRADED
.- Returns
-
bool
- is_disposed ¶
-
Return whether the current component state is
DISPOSED
.- Returns
-
bool
- is_faulted ¶
-
Return whether the current component state is
FAULTED
.- Returns
-
bool
- is_initialized ¶
-
Return whether the component has been initialized (component.state >=
INITIALIZED
).- Returns
-
bool
- is_running ¶
-
If the data engine is running.
- Returns
-
bool
- is_stopped ¶
-
Return whether the current component state is
STOPPED
.- Returns
-
bool
- kill ( self ) void ¶
-
Kill the engine by abruptly cancelling the queue tasks and calling stop.
- message_qsize ( self ) int ¶
-
Return the number of objects buffered on the internal message queue.
- Returns
-
int
- process ( self , Data data ) void ¶
-
Process the given data.
If the internal queue is already full then will log a warning and block until queue size reduces.
- Parameters
-
data ( Data ) – The data to process.
Warning
This method should only be called from the same thread the event loop is running on.
- register_client ( self , DataClient client ) void ¶
-
Register the given data client with the data engine.
- Parameters
-
client ( DataClient ) – The client to register.
- Raises
-
ValueError – If client is already registered.
- register_default_client ( self , DataClient client ) void ¶
-
Register the given client as the default routing client (when a specific venue routing cannot be found).
Any existing default routing client will be overwritten.
- Parameters
-
client ( DataClient ) – The client to register.
- register_venue_routing ( self , DataClient client , Venue venue ) void ¶
-
Register the given client to route orders to the given venue.
Any existing client in the routing map for the given venue will be overwritten.
- Parameters
-
-
venue ( Venue ) – The venue to route orders to.
-
client ( ExecutionClient ) – The client for the venue routing.
-
- registered_clients ¶
-
Return the execution clients registered with the engine.
- Returns
-
list[ClientId]
- request ( self , DataRequest request ) void ¶
-
Handle the given request.
If the internal queue is already full then will log a warning and block until queue size reduces.
- Parameters
-
request ( DataRequest ) – The request to handle.
Warning
This method should only be called from the same thread the event loop is running on.
- request_count ¶
-
The total count of data requests received by the engine.
- Returns
-
int
- 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. 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.
- response ( self , DataResponse response ) void ¶
-
Handle the given response.
If the internal queue is already full then will log a warning and block until queue size reduces.
- Parameters
-
response ( DataResponse ) – The response to handle.
Warning
This method should only be called from the same thread the event loop is running on.
- response_count ¶
-
The total count of data responses received by the engine.
- Returns
-
int
- resume ( self ) void ¶
-
Resume the component.
While executing on_resume() , any exception will be logged and reraised. 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.
- start ( self ) void ¶
-
Start the component.
While executing on_start() , any exception will be logged and reraised. 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 ¶
-
Return the components current state.
- Returns
-
ComponentState
- stop ( self ) void ¶
-
Stop the component.
While executing on_stop() , any exception will be logged and reraised. 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.
- subscribed_bars ( self ) list ¶
-
Return the bar types subscribed to.
- Returns
-
list[BarType]
- subscribed_generic_data ( self ) list ¶
-
Return the generic data types subscribed to.
- Returns
-
list[DataType]
- subscribed_instrument_close_prices ( self ) list ¶
-
Return the close price instruments subscribed to.
- Returns
-
list[InstrumentId]
- subscribed_instrument_status_updates ( 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_tickers ( self ) list ¶
-
Return the ticker instruments subscribed to.
- Returns
-
list[InstrumentId]
- subscribed_trade_ticks ( self ) list ¶
-
Return the trade tick instruments subscribed to.
- Returns
-
list[InstrumentId]
- trader_id ¶
-
The trader ID associated with the component.
- Returns
-
TraderId
- type ¶
-
The components type.
- Returns
-
type
Execution Client ¶
The LiveExecutionClient class is responsible for interfacing with a particular API which may be presented directly by an exchange, or broker intermediary.
- class LiveExecutionClient ( loop: asyncio.AbstractEventLoop, ClientId client_id, Venue venue: Optional[Venue], OMSType oms_type, AccountType account_type, Currency base_currency: Optional[Currency], instrument_provider: InstrumentProvider, MessageBus msgbus, Cache cache, LiveClock clock, Logger logger, dict config=None ) ¶
-
Bases:
nautilus_trader.execution.client.ExecutionClient
The abstract base class for all live execution clients.
- Parameters
-
-
loop ( asyncio.AbstractEventLoop ) – The event loop for the client.
-
client_id ( ClientId ) – The client ID.
-
venue ( Venue , optional ) – The client venue. If multi-venue then can be
None
. -
instrument_provider ( InstrumentProvider ) – The instrument provider for the client.
-
account_type ( AccountType ) – The account type for the client.
-
base_currency ( Currency , optional ) – The account base currency for the client. Use
None
for multi-currency accounts. -
msgbus ( MessageBus ) – The message bus for the client.
-
cache ( Cache ) – The cache for the client.
-
clock ( LiveClock ) – The clock for the client.
-
logger ( Logger ) – The logger for the client.
-
config ( dict [ str , object ] , optional ) – The configuration for the instance.
-
- Raises
-
ValueError – If oms_type is
NONE
value (must be defined).
Warning
This class should not be used directly, but through a concrete subclass.
- 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
- 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 ( self ) None ¶
-
Abstract method (implement in subclass).
- degrade ( self ) void ¶
-
Degrade the component.
While executing on_degrade() , any exception will be logged and reraised. 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 ( self ) None ¶
-
Abstract method (implement in subclass).
- dispose ( self ) void ¶
-
Dispose of the component.
While executing on_dispose() , any exception will be logged and reraised. 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.
This method is idempotent and irreversible. No other methods should be called after faulting.
While executing on_fault() , any exception will be logged and reraised. 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 ( type cls ) str ¶
-
Return the fully qualified name for the components class.
- Returns
-
str
References
- 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.
-
- generate_mass_status ( self , lookback_mins : Optional [ int ] ) ¶
-
Generate an execution mass status report.
- Parameters
-
lookback_mins ( int , optional ) – The maximum lookback for querying closed orders, trades and positions.
- Returns
-
ExecutionMassStatus
- 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: Optional[PositionId], 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 ) – 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 {
NONE
,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_pending_cancel ( self , StrategyId strategy_id , InstrumentId instrument_id , ClientOrderId client_order_id , VenueOrderId venue_order_id , uint64_t ts_event ) void ¶
-
Generate an OrderPendingCancel 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 pending cancel event occurred.
-
- generate_order_pending_update ( self , StrategyId strategy_id , InstrumentId instrument_id , ClientOrderId client_order_id , VenueOrderId venue_order_id , uint64_t ts_event ) void ¶
-
Generate an OrderPendingUpdate 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 pending update 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_status_report ( self , InstrumentId instrument_id: InstrumentId , client_order_id: Optional[ClientOrderId] = None , venue_order_id: Optional[VenueOrderId] = None ) ¶
-
Generate an order status report 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
.
- generate_order_status_reports ( self , InstrumentId instrument_id=None , datetime start=None , datetime end=None , bool open_only=False ) ¶
-
Generate a list of order status reports 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 ( datetime , optional ) – The start datetime query filter.
-
end ( datetime , optional ) – The end datetime query filter.
-
open_only ( bool , default False ) – If the query is for open orders only.
-
- Returns
-
list[OrderStatusReport]
- 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 ) – 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.
-
- generate_position_status_reports ( self , InstrumentId instrument_id=None , datetime start=None , datetime end=None ) ¶
-
Generate a list of position status reports 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 ( datetime , optional ) – The start datetime query filter.
-
end ( datetime , optional ) – The end datetime query filter.
-
- Returns
-
list[PositionStatusReport]
- generate_trade_reports ( self , InstrumentId instrument_id=None , VenueOrderId venue_order_id=None , datetime start=None , datetime end=None ) ¶
-
Generate a list of trade reports 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 ( datetime , optional ) – The start datetime query filter.
-
end ( datetime , optional ) – The end datetime query filter.
-
- Returns
-
list[TradeReport]
- 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 ¶
-
Return whether the current component state is
DEGRADED
.- Returns
-
bool
- is_disposed ¶
-
Return whether the current component state is
DISPOSED
.- Returns
-
bool
- is_faulted ¶
-
Return whether the current component state is
FAULTED
.- Returns
-
bool
- is_initialized ¶
-
Return whether the component has been initialized (component.state >=
INITIALIZED
).- Returns
-
bool
- is_running ¶
-
Return whether the current component state is
RUNNING
.- Returns
-
bool
- is_stopped ¶
-
Return whether the current component state is
STOPPED
.- Returns
-
bool
- 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
- 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. 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. 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.
- run_after_delay ( self , double delay: float , coro ) None ¶
- sleep0 ( self ) None ¶
- start ( self ) void ¶
-
Start the component.
While executing on_start() , any exception will be logged and reraised. 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 ¶
-
Return the components current state.
- Returns
-
ComponentState
- stop ( self ) void ¶
-
Stop the component.
While executing on_stop() , any exception will be logged and reraised. 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.
- sync_order_status ( self , QueryOrder command ) void ¶
-
Request a reconciliation for the queried order which will generate an OrderStatusReport
- 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
Execution Engine ¶
- class LiveExecutionEngine ( loop: asyncio.AbstractEventLoop , MessageBus msgbus , Cache cache , LiveClock clock , Logger logger , config: Optional[LiveExecEngineConfig] = None ) ¶
-
Bases:
nautilus_trader.execution.engine.ExecutionEngine
Provides a high-performance asynchronous live execution engine.
- Parameters
-
-
loop ( asyncio.AbstractEventLoop ) – The event loop for the engine.
-
msgbus ( MessageBus ) – The message bus for the engine.
-
cache ( Cache ) – The cache for the engine.
-
clock ( Clock ) – The clock for the engine.
-
logger ( Logger ) – The logger for the engine.
-
config ( LiveExecEngineConfig , optional ) – The configuration for the instance.
-
- Raises
-
TypeError – If config is not of type LiveExecEngineConfig .
- allow_cash_positions ¶
-
If unleveraged spot cash assets should track positions.
- Returns
-
bool
- check_connected ( self ) bool ¶
-
Check all of the engines clients are connected.
- Returns
-
bool – True if all clients connected, else False.
- check_disconnected ( self ) bool ¶
-
Check all of the engines clients are disconnected.
- Returns
-
bool – True if all clients disconnected, else False.
- check_integrity ( self ) bool ¶
-
Check integrity of data within the cache and clients.
- Returns
-
bool – True if checks pass, else False.
- check_residuals ( self ) bool ¶
-
Check for any residual open state and log warnings if found.
‘Open state’ is considered to be open orders and open positions.
- Returns
-
bool – True if residuals exist, else False.
- command_count ¶
-
The total count of commands received by the engine.
- Returns
-
int
- connect ( self ) ¶
-
Connect the engine by calling connect on all registered clients.
- debug ¶
-
If debug mode is active (will provide extra debug logging).
- Returns
-
bool
- default_client ¶
-
Return the default execution client registered with the engine.
- Returns
-
Optional[ClientId]
- degrade ( self ) void ¶
-
Degrade the component.
While executing on_degrade() , any exception will be logged and reraised. 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.
- deregister_client ( self , ExecutionClient client ) void ¶
-
Deregister the given execution client from the execution engine.
- Parameters
-
client ( ExecutionClient ) – The execution client to deregister.
- Raises
-
ValueError – If client is not registered with the execution engine.
- disconnect ( self ) ¶
-
Disconnect the engine by calling disconnect on all registered clients.
- dispose ( self ) void ¶
-
Dispose of the component.
While executing on_dispose() , any exception will be logged and reraised. 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.
- event_count ¶
-
The total count of events received by the engine.
- Returns
-
int
- execute ( self , TradingCommand command ) void ¶
-
Execute the given command.
If the internal queue is already full then will log a warning and block until queue size reduces.
- Parameters
-
command ( TradingCommand ) – The command to execute.
Warning
This method should only be called from the same thread the event loop is running on.
- fault ( self ) void ¶
-
Fault the component.
This method is idempotent and irreversible. No other methods should be called after faulting.
While executing on_fault() , any exception will be logged and reraised. 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.
- flush_db ( self ) void ¶
-
Flush the execution database which permanently removes all persisted data.
Warning
Permanent data loss.
- classmethod fully_qualified_name ( type cls ) str ¶
-
Return the fully qualified name for the components class.
- Returns
-
str
References
- get_run_queue_task ( self ) asyncio.Task ¶
-
Return the internal run queue task for the engine.
- Returns
-
asyncio.Task
- id ¶
-
The components ID.
- Returns
-
ComponentId
- is_degraded ¶
-
Return whether the current component state is
DEGRADED
.- Returns
-
bool
- is_disposed ¶
-
Return whether the current component state is
DISPOSED
.- Returns
-
bool
- is_faulted ¶
-
Return whether the current component state is
FAULTED
.- Returns
-
bool
- is_initialized ¶
-
Return whether the component has been initialized (component.state >=
INITIALIZED
).- Returns
-
bool
- is_running ¶
-
If the execution engine is running.
- Returns
-
bool
- is_stopped ¶
-
Return whether the current component state is
STOPPED
.- Returns
-
bool
- kill ( self ) void ¶
-
Kill the engine by abruptly cancelling the queue task and calling stop.
- load_cache ( self ) void ¶
-
Load the cache up from the execution database.
- position_id_count ( self , StrategyId strategy_id ) int ¶
-
The position ID count for the given strategy ID.
- Parameters
-
strategy_id ( StrategyId ) – The strategy ID for the position count.
- Returns
-
int
- process ( self , OrderEvent event ) void ¶
-
Process the given event.
If the internal queue is already full then will log a warning and block until queue size reduces.
- Parameters
-
event ( OrderEvent ) – The event to process.
Warning
This method should only be called from the same thread the event loop is running on.
- qsize ( self ) int ¶
-
Return the number of messages buffered on the internal queue.
- Returns
-
int
- reconcile_mass_status ( self , ExecutionMassStatus report ) void ¶
-
Reconcile the given execution mass status report.
- Parameters
-
report ( Document ) – The execution mass status report to reconcile.
- reconcile_report ( self , ExecutionReport report ) void ¶
-
Check the given execution report.
- Parameters
-
report ( Document ) – The execution report to check.
- reconcile_state ( self , double timeout_secs=10.0 ) bool ¶
-
Reconcile the execution engines state with all execution clients.
- Parameters
-
timeout_secs ( double , default 10.0 ) – The seconds to allow for reconciliation before timing out.
- Returns
-
bool – True if states reconcile within timeout, else False.
- Raises
-
ValueError – If timeout_secs is not positive (> 0).
- reconciliation_auto ¶
-
If the execution engine will generate reconciliation events to align state.
- Returns
-
bool
- reconciliation_lookback_mins ¶
-
The lookback window for reconciliation on start-up (zero for max lookback).
- Returns
-
int
- register_client ( self , ExecutionClient client ) void ¶
-
Register the given execution client with the execution engine.
If the client.venue is
None
and a default routing client has not been previously registered then will be registered as such.- Parameters
-
client ( ExecutionClient ) – The execution client to register.
- Raises
-
ValueError – If client is already registered with the execution engine.
- register_default_client ( self , ExecutionClient client ) void ¶
-
Register the given client as the default routing client (when a specific venue routing cannot be found).
Any existing default routing client will be overwritten.
- Parameters
-
client ( ExecutionClient ) – The client to register.
- register_oms_type ( self , Strategy strategy ) void ¶
-
Register the given trading strategies OMS (Order Management System) type.
- Parameters
-
strategy ( Strategy ) – The strategy for the registration.
- register_venue_routing ( self , ExecutionClient client , Venue venue ) void ¶
-
Register the given client to route orders to the given venue.
Any existing client in the routing map for the given venue will be overwritten.
- Parameters
-
-
venue ( Venue ) – The venue to route orders to.
-
client ( ExecutionClient ) – The client for the venue routing.
-
- registered_clients ¶
-
Return the execution clients registered with the engine.
- Returns
-
list[ClientId]
- report_count ¶
-
The total count of reports received by the engine.
- Returns
-
int
- 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. 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. 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.
- start ( self ) void ¶
-
Start the component.
While executing on_start() , any exception will be logged and reraised. 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 ¶
-
Return the components current state.
- Returns
-
ComponentState
- stop ( self ) void ¶
-
Stop the component.
While executing on_stop() , any exception will be logged and reraised. 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.
- trader_id ¶
-
The trader ID associated with the component.
- Returns
-
TraderId
- type ¶
-
The components type.
- Returns
-
type
Risk Engine ¶
- class LiveRiskEngine ( loop: asyncio.AbstractEventLoop , PortfolioFacade portfolio , MessageBus msgbus , CacheFacade cache , LiveClock clock , Logger logger , config: Optional[LiveRiskEngineConfig] = None ) ¶
-
Bases:
nautilus_trader.risk.engine.RiskEngine
Provides a high-performance asynchronous live risk engine.
- Parameters
-
-
loop ( asyncio.AbstractEventLoop ) – The event loop for the engine.
-
portfolio ( PortfolioFacade ) – The portfolio for the engine.
-
msgbus ( MessageBus ) – The message bus for the engine.
-
cache ( CacheFacade ) – The read-only cache for the engine.
-
clock ( Clock ) – The clock for the engine.
-
logger ( Logger ) – The logger for the engine.
-
config ( LiveRiskEngineConfig ) – The configuration for the instance.
-
- Raises
-
TypeError – If config is not of type LiveRiskEngineConfig .
- command_count ¶
-
The total count of commands received by the engine.
- Returns
-
int
- debug ¶
-
If debug mode is active (will provide extra debug logging).
- Returns
-
bool
- degrade ( self ) void ¶
-
Degrade the component.
While executing on_degrade() , any exception will be logged and reraised. 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. 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.
- event_count ¶
-
The total count of events received by the engine.
- Returns
-
int
- execute ( self , Command command ) void ¶
-
Execute the given command.
If the internal queue is already full then will log a warning and block until queue size reduces.
- Parameters
-
command ( Command ) – The command to execute.
Warning
This method should only be called from the same thread the event loop is running on.
- fault ( self ) void ¶
-
Fault the component.
This method is idempotent and irreversible. No other methods should be called after faulting.
While executing on_fault() , any exception will be logged and reraised. 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 ( type cls ) str ¶
-
Return the fully qualified name for the components class.
- Returns
-
str
References
- get_event_loop ( self ) ¶
-
Return the internal event loop for the engine.
- Returns
-
asyncio.AbstractEventLoop
- get_run_queue_task ( self ) ¶
-
Return the internal run queue task for the engine.
- Returns
-
asyncio.Task
- id ¶
-
The components ID.
- Returns
-
ComponentId
- is_bypassed ¶
-
If the risk engine is completely bypassed..
- Returns
-
bool
- is_degraded ¶
-
Return whether the current component state is
DEGRADED
.- Returns
-
bool
- is_disposed ¶
-
Return whether the current component state is
DISPOSED
.- Returns
-
bool
- is_faulted ¶
-
Return whether the current component state is
FAULTED
.- Returns
-
bool
- is_initialized ¶
-
Return whether the component has been initialized (component.state >=
INITIALIZED
).- Returns
-
bool
- is_running ¶
-
If the risk engine is running.
- Returns
-
bool
- is_stopped ¶
-
Return whether the current component state is
STOPPED
.- Returns
-
bool
- kill ( self ) void ¶
-
Kill the engine by abruptly cancelling the queue task and calling stop.
- max_notional_per_order ( self , InstrumentId instrument_id ) ¶
-
Return the current maximum notional per order for the given instrument ID.
- Returns
-
Decimal or
None
- max_notionals_per_order ( self ) dict ¶
-
Return the current maximum notionals per order settings.
- Returns
-
dict[InstrumentId, Decimal]
- max_order_rate ( self ) tuple ¶
-
Return the current maximum order rate limit setting.
- Returns
-
(int, timedelta) – The limit per timedelta interval.
- process ( self , Event event ) void ¶
-
Process the given event.
If the internal queue is already full then will log a warning and block until queue size reduces.
- Parameters
-
event ( Event ) – The event to process.
Warning
This method should only be called from the same thread the event loop is running on.
- qsize ( self ) int ¶
-
Return the number of messages buffered on the internal queue.
- Returns
-
int
- 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. 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. 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.
- set_max_notional_per_order ( self , InstrumentId instrument_id , new_value ) void ¶
-
Set the maximum notional value per order for the given instrument ID.
Passing a new_value of
None
will disable the pre-trade risk max notional check.- Parameters
-
-
instrument_id ( InstrumentId ) – The instrument ID for the max notional.
-
new_value ( integer , float , string or Decimal ) – The max notional value to set.
-
- Raises
-
-
decimal.InvalidOperation – If new_value not a valid input for decimal.Decimal .
-
ValueError – If new_value is not
None
and not positive.
-
- set_trading_state ( self , TradingState state ) void ¶
-
Set the trading state for the engine.
- Parameters
-
state ( TradingState ) – The state to set.
- start ( self ) void ¶
-
Start the component.
While executing on_start() , any exception will be logged and reraised. 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 ¶
-
Return the components current state.
- Returns
-
ComponentState
- stop ( self ) void ¶
-
Stop the component.
While executing on_stop() , any exception will be logged and reraised. 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.
- trader_id ¶
-
The trader ID associated with the component.
- Returns
-
TraderId
- trading_state ¶
-
The current trading state for the engine.
- Returns
-
TradingState
- type ¶
-
The components type.
- Returns
-
type
Node ¶
- class TradingNode ( config : Optional [ nautilus_trader.config.live.TradingNodeConfig ] = None ) ¶
-
Bases:
object
Provides an asynchronous network node for live trading.
- Parameters
-
config ( TradingNodeConfig , optional ) – The configuration for the instance.
- Raises
-
TypeError – If config is not of type TradingNodeConfig .
- property trader_id : nautilus_trader.model.identifiers.TraderId ¶
-
Return the nodes trader ID.
- Returns
-
TraderId
- property machine_id : str ¶
-
Return the nodes machine ID.
- Returns
-
str
- property instance_id : nautilus_trader.core.uuid.UUID4 ¶
-
Return the nodes instance ID.
- Returns
-
UUID4
- property trader : nautilus_trader.trading.trader.Trader ¶
-
Return the nodes internal trader.
- Returns
-
Trader
- property cache : nautilus_trader.cache.base.CacheFacade ¶
-
Return the nodes internal read-only cache.
- Returns
-
CacheFacade
- property portfolio : nautilus_trader.portfolio.base.PortfolioFacade ¶
-
Return the nodes internal read-only portfolio.
- Returns
-
PortfolioFacade
- property is_running : bool ¶
-
Return whether the trading node is running.
- Returns
-
bool
- property is_built : bool ¶
-
Return whether the trading node clients are built.
- Returns
-
bool
- get_event_loop ( ) asyncio.events.AbstractEventLoop ¶
-
Return the event loop of the trading node.
- Returns
-
asyncio.AbstractEventLoop
- get_logger ( ) nautilus_trader.common.logging.LiveLogger ¶
-
Return the logger for the trading node.
- Returns
-
LiveLogger
- add_data_client_factory ( name : str , factory ) ¶
-
Add the given data client factory to the node.
- Parameters
-
-
name ( str ) – The name of the client factory.
-
factory ( LiveDataClientFactory or LiveExecutionClientFactory ) – The factory to add.
-
- Raises
-
-
ValueError – If name is not a valid string.
-
KeyError – If name has already been added.
-
- add_exec_client_factory ( name : str , factory ) ¶
-
Add the given execution client factory to the node.
- Parameters
-
-
name ( str ) – The name of the client factory.
-
factory ( LiveDataClientFactory or LiveExecutionClientFactory ) – The factory to add.
-
- Raises
-
-
ValueError – If name is not a valid string.
-
KeyError – If name has already been added.
-
- build ( ) None ¶
-
Build the nodes clients.
- start ( ) None ¶
-
Start the trading node.
- stop ( ) None ¶
-
Stop the trading node gracefully.
After a specified delay the internal Trader residuals will be checked.
If save strategy is specified then strategy states will then be saved.
- dispose ( ) None ¶
-
Dispose of the trading node.
Gracefully shuts down the executor and event loop.
Node Builder ¶
- class TradingNodeBuilder ( loop : asyncio.events.AbstractEventLoop , data_engine : nautilus_trader.live.data_engine.LiveDataEngine , exec_engine : nautilus_trader.live.execution_engine.LiveExecutionEngine , msgbus : nautilus_trader.msgbus.bus.MessageBus , cache : nautilus_trader.cache.cache.Cache , clock : nautilus_trader.common.clock.LiveClock , logger : nautilus_trader.common.logging.LiveLogger , log : nautilus_trader.common.logging.LoggerAdapter ) ¶
-
Bases:
object
Provides building services for a trading node.
- Parameters
-
-
loop ( asyncio.AbstractEventLoop ) – The event loop for the clients.
-
data_engine ( LiveDataEngine ) – The data engine for the trading node.
-
exec_engine ( LiveExecutionEngine ) – The execution engine for the trading node.
-
msgbus ( MessageBus ) – The message bus for the trading node.
-
cache ( Cache ) – The cache for building clients.
-
clock ( LiveClock ) – The clock for building clients.
-
logger ( LiveLogger ) – The logger for building clients.
-
log ( LoggerAdapter ) – The trading nodes logger.
-
- add_data_client_factory ( name : str , factory ) ¶
-
Add the given data client factory to the builder.
- Parameters
-
-
name ( str ) – The name of the client.
-
factory ( LiveDataClientFactory or LiveExecClientFactory ) – The factory to add.
-
- Raises
-
-
ValueError – If name is not a valid string.
-
KeyError – If name has already been added.
-
- add_exec_client_factory ( name : str , factory ) ¶
-
Add the given client factory to the builder.
- Parameters
-
-
name ( str ) – The name of the client.
-
factory ( LiveDataClientFactory or LiveExecClientFactory ) – The factory to add.
-
- Raises
-
-
ValueError – If name is not a valid string.
-
KeyError – If name has already been added.
-
- build_data_clients ( config : Dict ) ¶
-
Build the data clients with the given configuration.
- Parameters
-
config ( dict [ str , object ] ) – The data clients configuration.
- build_exec_clients ( config : Dict ) ¶
-
Build the execution clients with the given configuration.
- Parameters
-
config ( dict [ str , object ] ) – The execution clients configuration.