Execution¶
The execution subpackage groups components relating to the execution stack for the platform.
The layered architecture of the execution stack somewhat mirrors the data stack with a central engine, cache layer beneath, database layer beneath, with alternative implementations able to be written on top.
Due to the high-performance, the core components are reusable between both backtest and live implementations - helping to ensure consistent logic for trading operations.
Components¶
- class ExecAlgorithm¶
Bases:
ActorExecAlgorithm(config: ExecAlgorithmConfig | None = None)
The base class for all execution algorithms.
This class allows traders to implement their own customized execution algorithms.
- Parameters:
config (ExecAlgorithmConfig, optional) – The execution algorithm configuration.
- Raises:
TypeError – If config is not of type ExecAlgorithmConfig.
Warning
This class should not be used directly, but through a concrete subclass.
- add_synthetic(self, SyntheticInstrument synthetic) void¶
Add the created synthetic instrument to the cache.
- Parameters:
synthetic (SyntheticInstrument) – The synthetic instrument to add to the cache.
- Raises:
KeyError – If synthetic is already in the cache.
Notes
If you are updating the synthetic instrument then you should use the update_synthetic method.
- cache¶
The read-only cache for the actor.
- Returns:
CacheFacade
- cancel_all_tasks(self) void¶
Cancel all queued and active tasks.
- cancel_order(self, Order order, ClientId client_id=None) void¶
Cancel the given order with optional routing instructions.
A CancelOrder command will be created and then sent to either the OrderEmulator or the ExecutionEngine (depending on whether the order is emulated).
Logs an error if no VenueOrderId has been assigned to the order.
- cancel_task(self, task_id: TaskId) void¶
Cancel the task with the given task_id (if queued or active).
If the task is not found then a warning is logged.
- Parameters:
task_id (TaskId) – The task identifier.
- clock¶
The actors clock.
- Returns:
Clock
- config¶
The actors configuration.
- Returns:
NautilusConfig
- degrade(self) void¶
Degrade the component.
While executing on_degrade() any exception will be logged and reraised, then the component will remain in a
DEGRADINGstate.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_warning_event(self, type event) void¶
Deregister the given event type from warning log levels.
- Parameters:
event (type) – The event class to deregister.
- 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
DISPOSINGstate.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, TradingCommand command) void¶
Handle the given trading command by processing it with the execution algorithm.
- Parameters:
command (SubmitOrder) – The command to handle.
- Raises:
ValueError – If command.exec_algorithm_id is not equal to self.id.
- 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
FAULTINGstate.Warning
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
- classmethod fully_qualified_name(cls) str¶
Return the fully qualified name for the components class.
- Return type:
str
References
- greeks¶
The read-only greeks calculator for the actor.
- Returns:
GreeksCalculator
- handle_bar(self, Bar bar, bool historical=False) void¶
Handle the given bar data.
If state is
RUNNINGthen passes to on_bar.- Parameters:
bar (Bar) – The bar received.
Warning
System method (not intended to be called by user code).
- handle_data(self, Data data) void¶
Handle the given data.
If state is
RUNNINGthen passes to on_data.- Parameters:
data (Data) – The data received.
Warning
System method (not intended to be called by user code).
- handle_event(self, Event event) void¶
Handle the given event.
If state is
RUNNINGthen passes to on_event.- Parameters:
event (Event) – The event received.
Warning
System method (not intended to be called by user code).
- handle_funding_rate(self, FundingRateUpdate funding_rate, bool historical=False) void¶
Handle the given funding rate update.
If state is
RUNNINGthen passes to on_funding_rate.- Parameters:
funding_rate (FundingRateUpdate) – The funding rate update received.
Warning
System method (not intended to be called by user code).
- handle_historical_bar(self, Bar bar) void¶
- handle_historical_data(self, data) void¶
Handle the given historical data.
- Parameters:
data (Data) – The historical data received.
Warning
System method (not intended to be called by user code).
- handle_historical_funding_rate(self, FundingRateUpdate funding_rate) void¶
- handle_historical_order_book_deltas(self, OrderBookDeltas deltas) void¶
- handle_historical_order_book_depth(self, OrderBookDepth10 depth) void¶
- handle_historical_quote_tick(self, QuoteTick tick) void¶
- handle_historical_trade_tick(self, TradeTick tick) void¶
- handle_index_price(self, IndexPriceUpdate index_price) void¶
Handle the given index price update.
If state is
RUNNINGthen passes to on_index_price.- Parameters:
index_price (IndexPriceUpdate) – The index price update received.
Warning
System method (not intended to be called by user code).
- handle_instrument(self, Instrument instrument) void¶
Handle the given instrument.
Passes to on_instrument if state is
RUNNING.- Parameters:
instrument (Instrument) – The instrument received.
Warning
System method (not intended to be called by user code).
- handle_instrument_close(self, InstrumentClose update) void¶
Handle the given instrument close update.
If state is
RUNNINGthen passes to on_instrument_close.- Parameters:
update (InstrumentClose) – The update received.
Warning
System method (not intended to be called by user code).
- handle_instrument_status(self, InstrumentStatus data) void¶
Handle the given instrument status update.
If state is
RUNNINGthen passes to on_instrument_status.- Parameters:
data (InstrumentStatus) – The status update received.
Warning
System method (not intended to be called by user code).
- handle_mark_price(self, MarkPriceUpdate mark_price) void¶
Handle the given mark price update.
If state is
RUNNINGthen passes to on_mark_price.- Parameters:
mark_price (MarkPriceUpdate) – The mark price update received.
Warning
System method (not intended to be called by user code).
- handle_order_book(self, OrderBook order_book) void¶
Handle the given order book.
Passes to on_order_book if state is
RUNNING.- Parameters:
order_book (OrderBook) – The order book received.
Warning
System method (not intended to be called by user code).
- handle_order_book_deltas(self, deltas, bool historical=False) void¶
Handle the given order book deltas.
Passes to on_order_book_deltas if state is
RUNNING. The deltas will be nautilus_pyo3.OrderBookDeltas if the pyo3_conversion flag was set for the subscription.- Parameters:
deltas (OrderBookDeltas or nautilus_pyo3.OrderBookDeltas) – The order book deltas received.
historical (bool, default False) – If True, treats the data as historical.
Warning
System method (not intended to be called by user code).
- handle_order_book_depth(self, OrderBookDepth10 depth, bool historical=False) void¶
Handle the given order book depth
Passes to on_order_book_depth if state is
RUNNING.- Parameters:
depth (OrderBookDepth10) – The order book depth received.
Warning
System method (not intended to be called by user code).
- handle_quote_tick(self, QuoteTick tick, bool historical=False) void¶
Handle the given quote tick.
If state is
RUNNINGthen passes to on_quote_tick.- Parameters:
tick (QuoteTick) – The tick received.
Warning
System method (not intended to be called by user code).
- handle_signal(self, Data signal) void¶
Handle the given signal.
If state is
RUNNINGthen passes to on_signal.- Parameters:
signal (Data) – The signal received.
Warning
System method (not intended to be called by user code).
- handle_trade_tick(self, TradeTick tick, bool historical=False) void¶
Handle the given trade tick.
If state is
RUNNINGthen passes to on_trade_tick.- Parameters:
tick (TradeTick) – The tick received.
Warning
System method (not intended to be called by user code).
- has_active_tasks(self) bool¶
Return a value indicating whether there are any active tasks.
- Return type:
bool
- has_any_tasks(self) bool¶
Return a value indicating whether there are any queued OR active tasks.
- Return type:
bool
- has_pending_requests(self) bool¶
Return whether the actor is pending processing for any requests.
- Returns:
True if any requests are pending, else False.
- Return type:
bool
- has_queued_tasks(self) bool¶
Return a value indicating whether there are any queued tasks.
- Return type:
bool
- id¶
The components ID.
- Returns:
ComponentId
- indicators_initialized(self) bool¶
Return a value indicating whether all indicators are initialized.
- Returns:
True if all initialized, else False
- Return type:
bool
- is_degraded¶
bool
Return whether the current component state is
DEGRADED.- Return type:
bool
- Type:
- is_disposed¶
bool
Return whether the current component state is
DISPOSED.- Return type:
bool
- Type:
- is_faulted¶
bool
Return whether the current component state is
FAULTED.- Return type:
bool
- Type:
- is_initialized¶
bool
Return whether the component has been initialized (component.state >=
INITIALIZED).- Return type:
bool
- Type:
- is_pending_request(self, UUID4 request_id) bool¶
Return whether the request for the given identifier is pending processing.
- Parameters:
request_id (UUID4) – The request ID to check.
- Returns:
True if request is pending, else False.
- Return type:
bool
- is_running¶
bool
Return whether the current component state is
RUNNING.- Return type:
bool
- Type:
- is_stopped¶
bool
Return whether the current component state is
STOPPED.- Return type:
bool
- Type:
- load(self, dict state) void¶
Load the actor/strategy state from the give state dictionary.
Calls on_load and passes the state.
- Parameters:
state (dict[str, bytes]) – The strategy state to load.
Warning
Exceptions raised will be caught, logged, and reraised.
- log¶
The actors logger.
- Returns:
Logger
- modify_order(self, Order order, Quantity quantity=None, Price price=None, Price trigger_price=None, ClientId client_id=None) void¶
Modify the given order with optional parameters and routing instructions.
An ModifyOrder command will be created and then sent to the RiskEngine.
At least one value must differ from the original order for the command to be valid.
Will use an Order Cancel/Replace Request (a.k.a Order Modification) for FIX protocols, otherwise if order update is not available for the API, then will cancel and replace with a new order using the original ClientOrderId.
- Parameters:
order (Order) – The order to update.
quantity (Quantity, optional) – The updated quantity for the given order.
price (Price, optional) – The updated price for the given order (if applicable).
trigger_price (Price, optional) – The updated trigger price for the given order (if applicable).
client_id (ClientId, optional) – The specific client ID for the command. If
Nonethen will be inferred from the venue in the instrument ID.
- Raises:
ValueError – If price is not
Noneand order does not have a price.ValueError – If trigger is not
Noneand order does not have a trigger_price.
Warning
If the order is already closed or at PENDING_CANCEL status then the command will not be generated, and a warning will be logged.
- modify_order_in_place(self, Order order, Quantity quantity=None, Price price=None, Price trigger_price=None) void¶
Modify the given
INITIALIZEDorder in place (immediately) with optional parameters.At least one value must differ from the original order for the command to be valid.
- Parameters:
- Raises:
ValueError – If order.status is not
INITIALIZEDorRELEASED.ValueError – If price is not
Noneand order does not have a price.ValueError – If trigger is not
Noneand order does not have a trigger_price.
Warning
If the order is already closed or at PENDING_CANCEL status then the command will not be generated, and a warning will be logged.
- msgbus¶
The message bus for the actor (if registered).
- Returns:
MessageBus or
None
- on_bar(self, Bar bar) void¶
Actions to be performed when running and receives a bar.
- Parameters:
bar (Bar) – The bar received.
Warning
System method (not intended to be called by user code).
- on_data(self, data) void¶
Actions to be performed when running and receives data.
- Parameters:
data (Data) – The data received.
Warning
System method (not intended to be called by user code).
- on_degrade(self) void¶
Actions to be performed on degrade.
Warning
System method (not intended to be called by user code).
Should be overridden in the actor implementation.
- on_dispose(self) void¶
Actions to be performed on dispose.
Cleanup/release any resources used here.
Warning
System method (not intended to be called by user code).
- on_event(self, Event event) void¶
Actions to be performed running and receives an event.
- Parameters:
event (Event) – The event received.
Warning
System method (not intended to be called by user code).
- on_fault(self) void¶
Actions to be performed on fault.
Cleanup any resources used by the actor here.
Warning
System method (not intended to be called by user code).
Should be overridden in the actor implementation.
- on_funding_rate(self, FundingRateUpdate funding_rate) void¶
Actions to be performed when running and receives a funding rate update.
- Parameters:
funding_rate (FundingRateUpdate) – The funding rate update received.
Warning
System method (not intended to be called by user code).
- on_historical_data(self, data) void¶
Actions to be performed when running and receives historical data.
- Parameters:
data (Data) – The historical data received.
Warning
System method (not intended to be called by user code).
- on_index_price(self, IndexPriceUpdate index_price) void¶
Actions to be performed when running and receives an index price update.
- Parameters:
index_price (IndexPriceUpdate) – The index price update received.
Warning
System method (not intended to be called by user code).
- on_instrument(self, Instrument instrument) void¶
Actions to be performed when running and receives an instrument.
- Parameters:
instrument (Instrument) – The instrument received.
Warning
System method (not intended to be called by user code).
- on_instrument_close(self, InstrumentClose update) void¶
Actions to be performed when running and receives an instrument close update.
- Parameters:
update (InstrumentClose) – The instrument close received.
Warning
System method (not intended to be called by user code).
- on_instrument_status(self, InstrumentStatus data) void¶
Actions to be performed when running and receives an instrument status update.
- Parameters:
data (InstrumentStatus) – The instrument status update received.
Warning
System method (not intended to be called by user code).
- on_load(self, dict state) void¶
Actions to be performed when the actor state is loaded.
Saved state values will be contained in the give state dictionary.
- Parameters:
state (dict[str, bytes]) – The strategy state to load.
Warning
System method (not intended to be called by user code).
- on_mark_price(self, MarkPriceUpdate mark_price) void¶
Actions to be performed when running and receives a mark price update.
- Parameters:
mark_price (MarkPriceUpdate) – The mark price update received.
Warning
System method (not intended to be called by user code).
- on_order(self, Order order) void¶
Actions to be performed when running and receives an order.
- Parameters:
order (Order) – The order to be handled.
Warning
System method (not intended to be called by user code).
- on_order_accepted(self, OrderAccepted event) void¶
Actions to be performed when running and receives an order accepted event.
- Parameters:
event (OrderAccepted) – The event received.
Warning
System method (not intended to be called by user code).
- on_order_book(self, OrderBook order_book) void¶
Actions to be performed when running and receives an order book.
- Parameters:
order_book (OrderBook) – The order book received.
Warning
System method (not intended to be called by user code).
- on_order_book_deltas(self, deltas) void¶
Actions to be performed when running and receives order book deltas.
- Parameters:
deltas (OrderBookDeltas or nautilus_pyo3.OrderBookDeltas) – The order book deltas received.
Warning
System method (not intended to be called by user code).
- on_order_book_depth(self, depth) void¶
Actions to be performed when running and receives an order book depth.
- Parameters:
depth (OrderBookDepth10) – The order book depth received.
Warning
System method (not intended to be called by user code).
- on_order_cancel_rejected(self, OrderCancelRejected event) void¶
Actions to be performed when running and receives an order cancel rejected event.
- Parameters:
event (OrderCancelRejected) – The event received.
Warning
System method (not intended to be called by user code).
- on_order_canceled(self, OrderCanceled event) void¶
Actions to be performed when running and receives an order canceled event.
- Parameters:
event (OrderCanceled) – The event received.
Warning
System method (not intended to be called by user code).
- on_order_denied(self, OrderDenied event) void¶
Actions to be performed when running and receives an order denied event.
- Parameters:
event (OrderDenied) – The event received.
Warning
System method (not intended to be called by user code).
- on_order_emulated(self, OrderEmulated event) void¶
Actions to be performed when running and receives an order initialized event.
- Parameters:
event (OrderEmulated) – The event received.
Warning
System method (not intended to be called by user code).
- on_order_event(self, OrderEvent event) void¶
Actions to be performed when running and receives an order event.
- Parameters:
event (OrderEvent) – The event received.
Warning
System method (not intended to be called by user code).
- on_order_expired(self, OrderExpired event) void¶
Actions to be performed when running and receives an order expired event.
- Parameters:
event (OrderExpired) – The event received.
Warning
System method (not intended to be called by user code).
- on_order_filled(self, OrderFilled event) void¶
Actions to be performed when running and receives an order filled event.
- Parameters:
event (OrderFilled) – The event received.
Warning
System method (not intended to be called by user code).
- on_order_initialized(self, OrderInitialized event) void¶
Actions to be performed when running and receives an order initialized event.
- Parameters:
event (OrderInitialized) – The event received.
Warning
System method (not intended to be called by user code).
- on_order_list(self, OrderList order_list) void¶
Actions to be performed when running and receives an order list.
- Parameters:
order_list (OrderList) – The order list to be handled.
Warning
System method (not intended to be called by user code).
- on_order_modify_rejected(self, OrderModifyRejected event) void¶
Actions to be performed when running and receives an order modify rejected event.
- Parameters:
event (OrderModifyRejected) – The event received.
Warning
System method (not intended to be called by user code).
- on_order_pending_cancel(self, OrderPendingCancel event) void¶
Actions to be performed when running and receives an order pending cancel event.
- Parameters:
event (OrderPendingCancel) – The event received.
Warning
System method (not intended to be called by user code).
- on_order_pending_update(self, OrderPendingUpdate event) void¶
Actions to be performed when running and receives an order pending update event.
- Parameters:
event (OrderPendingUpdate) – The event received.
Warning
System method (not intended to be called by user code).
- on_order_rejected(self, OrderRejected event) void¶
Actions to be performed when running and receives an order rejected event.
- Parameters:
event (OrderRejected) – The event received.
Warning
System method (not intended to be called by user code).
- on_order_released(self, OrderReleased event) void¶
Actions to be performed when running and receives an order released event.
- Parameters:
event (OrderReleased) – The event received.
Warning
System method (not intended to be called by user code).
- on_order_submitted(self, OrderSubmitted event) void¶
Actions to be performed when running and receives an order submitted event.
- Parameters:
event (OrderSubmitted) – The event received.
Warning
System method (not intended to be called by user code).
- on_order_triggered(self, OrderTriggered event) void¶
Actions to be performed when running and receives an order triggered event.
- Parameters:
event (OrderTriggered) – The event received.
Warning
System method (not intended to be called by user code).
- on_order_updated(self, OrderUpdated event) void¶
Actions to be performed when running and receives an order updated event.
- Parameters:
event (OrderUpdated) – The event received.
Warning
System method (not intended to be called by user code).
- on_position_changed(self, PositionChanged event) void¶
Actions to be performed when running and receives a position changed event.
- Parameters:
event (PositionChanged) – The event received.
Warning
System method (not intended to be called by user code).
- on_position_closed(self, PositionClosed event) void¶
Actions to be performed when running and receives a position closed event.
- Parameters:
event (PositionClosed) – The event received.
Warning
System method (not intended to be called by user code).
- on_position_event(self, PositionEvent event) void¶
Actions to be performed when running and receives a position event.
- Parameters:
event (PositionEvent) – The event received.
Warning
System method (not intended to be called by user code).
- on_position_opened(self, PositionOpened event) void¶
Actions to be performed when running and receives a position opened event.
- Parameters:
event (PositionOpened) – The event received.
Warning
System method (not intended to be called by user code).
- on_quote_tick(self, QuoteTick tick) void¶
Actions to be performed when running and receives a quote tick.
- Parameters:
tick (QuoteTick) – The tick received.
Warning
System method (not intended to be called by user code).
- on_reset(self) void¶
Actions to be performed on reset.
Warning
System method (not intended to be called by user code).
Should be overridden in a user implementation.
- on_resume(self) void¶
Actions to be performed on resume.
Warning
System method (not intended to be called by user code).
- on_save(self) dict¶
Actions to be performed when the actor state is saved.
Create and return a state dictionary of values to be saved.
- Returns:
The strategy state to save.
- Return type:
dict[str, bytes]
Warning
System method (not intended to be called by user code).
- on_signal(self, signal) void¶
Actions to be performed when running and receives signal data.
- Parameters:
signal (Data) – The signal received.
Warning
System method (not intended to be called by user code).
Notes
This refers to a data signal, not an operating system signal (such as SIGTERM, SIGKILL, etc.).
- on_start(self) void¶
Actions to be performed on start.
The intent is that this method is called once per trading ‘run’, when initially starting.
It is recommended to subscribe/request for data here.
Warning
System method (not intended to be called by user code).
Should be overridden in a user implementation.
- on_stop(self) void¶
Actions to be performed on stop.
The intent is that this method is called to pause, or when done for day.
Warning
System method (not intended to be called by user code).
Should be overridden in a user implementation.
- on_trade_tick(self, TradeTick tick) void¶
Actions to be performed when running and receives a trade tick.
- Parameters:
tick (TradeTick) – The tick received.
Warning
System method (not intended to be called by user code).
- pending_requests(self) set¶
Return the request IDs which are currently pending processing.
- Return type:
set[UUID4]
- portfolio¶
The read-only portfolio for the actor.
- Returns:
PortfolioFacade
- publish_data(self, DataType data_type, Data data) void¶
Publish the given data to the message bus.
- publish_signal(self, str name, value, uint64_t ts_event=0) void¶
Publish the given value as a signal to the message bus.
- Parameters:
name (str) – The name of the signal being published. The signal name will be converted to title case, with each word capitalized (e.g., ‘example’ becomes ‘SignalExample’).
value (object) – The signal data to publish.
ts_event (uint64_t, optional) – UNIX timestamp (nanoseconds) when the signal event occurred. If
Nonethen will timestamp current time.
- queue_for_executor(self, func: Callable[..., Any], tuple args=None, dict kwargs=None)¶
Queues the callable func to be executed as fn(*args, **kwargs) sequentially.
- Parameters:
func (Callable) – The function to be executed.
args (positional arguments) – The positional arguments for the call to func.
kwargs (arbitrary keyword arguments) – The keyword arguments for the call to func.
- Raises:
TypeError – If func is not of type Callable.
Notes
For backtesting the func is immediately executed, as there’s no need for a Future object that can be awaited. In a backtesting scenario, the execution is not in real time, and so the results of func are ‘immediately’ available after it’s called.
- register(self, TraderId trader_id, PortfolioFacade portfolio, MessageBus msgbus, CacheFacade cache, Clock clock) void¶
Register the execution algorithm with a trader.
- Parameters:
trader_id (TraderId) – The trader ID for the execution algorithm.
portfolio (PortfolioFacade) – The read-only portfolio for the execution algorithm.
msgbus (MessageBus) – The message bus for the execution algorithm.
cache (CacheFacade) – The read-only cache for the execution algorithm.
clock (Clock) – The clock for the execution algorithm.
Warning
System method (not intended to be called by user code).
- register_base(self, PortfolioFacade portfolio, MessageBus msgbus, CacheFacade cache, Clock clock) void¶
Register with a trader.
- Parameters:
portfolio (PortfolioFacade) – The read-only portfolio for the actor.
msgbus (MessageBus) – The message bus for the actor.
cache (CacheFacade) – The read-only cache for the actor.
clock (Clock) – The clock for the actor.
Warning
System method (not intended to be called by user code).
- register_executor(self, loop: asyncio.AbstractEventLoop, executor: Executor) void¶
Register the given Executor for the actor.
- Parameters:
loop (asyncio.AbstractEventLoop) – The event loop of the application.
executor (concurrent.futures.Executor) – The executor to register.
- Raises:
TypeError – If executor is not of type concurrent.futures.Executor
- register_indicator_for_bars(self, BarType bar_type, Indicator indicator) void¶
Register the given indicator with the actor/strategy to receive bar data for the given bar type.
- register_indicator_for_quote_ticks(self, InstrumentId instrument_id, Indicator indicator) void¶
Register the given indicator with the actor/strategy to receive quote tick data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The instrument ID for tick updates.
indicator (Indicator) – The indicator to register.
- register_indicator_for_trade_ticks(self, InstrumentId instrument_id, Indicator indicator) void¶
Register the given indicator with the actor/strategy to receive trade tick data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The instrument ID for tick updates.
indicator (indicator) – The indicator to register.
- register_warning_event(self, type event) void¶
Register the given event type for warning log levels.
- Parameters:
event (type) – The event class to register.
- registered_indicators¶
Return the registered indicators for the strategy.
- Return type:
list[Indicator]
- request_aggregated_bars(self, list bar_types, datetime start, datetime end=None, int limit=0, ClientId client_id=None, callback: Callable[[UUID4], None] | None = None, bool include_external_data=False, bool update_subscriptions=False, bool update_catalog=False, bool aggregate_spread_quotes=False, UUID4 request_id=None, dict params=None) UUID4¶
Request historical aggregated Bar data for multiple bar types. The first bar is used to determine which market data type will be queried. This can either be quotes, trades or bars. If bars are queried, the first bar type needs to have a composite bar that is external (i.e. not internal/aggregated). This external bar type will be queried.
If end is
Nonethen will request up to the most recent data.Once the response is received, the bar data is forwarded from the message bus to the on_historical_data handler. Any tick data used for aggregation is also forwarded to the on_historical_data handler.
If the request fails, then an error is logged.
- Parameters:
bar_types (list[BarType]) – The list of bar types for the request. Composite bars can also be used and need to figure in the list after a BarType on which it depends.
start (datetime) – The start datetime (UTC) of request time range. Should be left-inclusive (start <= value), but inclusiveness is not currently guaranteed.
end (datetime, optional) – The end datetime (UTC) of request time range. If None then will be replaced with the current UTC time. Should be right-inclusive (value <= end), but inclusiveness is not currently guaranteed.
limit (int, optional) – The limit on the amount of data received (quote ticks, trade ticks or bars).
client_id (ClientId, optional) – The specific client ID for the command. If
Nonethen will be inferred from the venue in the instrument ID.callback (Callable[[UUID4], None], optional) – The registered callback, to be called with the request ID when the response has completed processing.
include_external_data (bool, default False) – If True, includes the queried external data in the response.
update_subscriptions (bool, default False) – If True, persists the aggregator of each bar_type so it’s up to date for a subsequent market data subscription.
update_catalog (bool, default False) – Whether to update a catalog with the received data.
aggregate_spread_quotes (bool, default False) – Whether to activate a spread quote aggregator from leg quotes. Only applicable when requesting quote ticks for spread instruments.
request_id (UUID4, optional) – The UUID to use for the request ID. If None, a new UUID will be generated.
params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- Returns:
The request_id for the request.
- Return type:
- Raises:
TypeError – If start is None.
ValueError – If start is > current timestamp (now).
ValueError – If end is > current timestamp (now).
ValueError – If start is > end.
ValueError – If bar_types is empty.
TypeError – If callback is not None and not of type Callable.
TypeError – If bar_types is empty or contains elements not of type BarType.
Notes
Make sure no subscription is active for the same underlying market data as the requested bar types.
A subscription can follow request_aggregated_bars and use an up to date aggregator when using the update_subscriptions parameter.
Subscribe to market data as a callback to request_aggregated_bars.
- request_bars(self, BarType bar_type, datetime start, datetime end=None, int limit=0, ClientId client_id=None, callback: Callable[[UUID4], None] | None = None, bool update_catalog=False, bool join_request=False, UUID4 request_id=None, dict params=None) UUID4¶
Request historical Bar data.
If end is
Nonethen will request up to the most recent data.Once the response is received, the bar data is forwarded from the message bus to the on_historical_data handler.
If the request fails, then an error is logged.
- Parameters:
bar_type (BarType) – The bar type for the request.
start (datetime) – The start datetime (UTC) of request time range. Should be left-inclusive (start <= value), but inclusiveness is not currently guaranteed.
end (datetime, optional) – The end datetime (UTC) of request time range. If None then will be replaced with the current UTC time. Should be right-inclusive (value <= end), but inclusiveness is not currently guaranteed.
limit (int, optional) – The limit on the amount of bars received.
client_id (ClientId, optional) – The specific client ID for the command. If
Nonethen will be inferred from the venue in the instrument ID.callback (Callable[[UUID4], None], optional) – The registered callback, to be called with the request ID when the response has completed processing.
update_catalog (bool, default False) – Whether to update a catalog with the received data.
join_request (bool, optional, default to False) – If a request should be joined and sorted with another one by using request_join.
request_id (UUID4, optional) – The UUID to use for the request ID. If None, a new UUID will be generated.
params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- Returns:
The request_id for the request.
- Return type:
- Raises:
TypeError – If start is None.
ValueError – If start is > current timestamp (now).
ValueError – If end is > current timestamp (now).
ValueError – If start is > end.
TypeError – If callback is not None and not of type Callable.
- request_data(self, DataType data_type, ClientId client_id, InstrumentId instrument_id=None, datetime start=None, datetime end=None, int limit=0, callback: Callable[[UUID4], None] | None = None, bool update_catalog=False, bool join_request=False, UUID4 request_id=None, dict params=None) UUID4¶
Request custom data for the given data type from the given data client.
Once the response is received, the data is forwarded from the message bus to the on_historical_data handler.
If the request fails, then an error is logged.
- Parameters:
data_type (DataType) – The data type for the request.
client_id (ClientId) – The data client ID.
start (datetime) – The start datetime (UTC) of request time range. Cannot be None. Should be left-inclusive (start <= value), but inclusiveness is not currently guaranteed.
end (datetime, optional) – The end datetime (UTC) of request time range. If None then will be replaced with the current UTC time. Should be right-inclusive (value <= end), but inclusiveness is not currently guaranteed.
limit (int, optional) – The limit on the amount of data points received.
callback (Callable[[UUID4], None], optional) – The registered callback, to be called with the request ID when the response has completed processing.
update_catalog (bool, default False) – Whether to update a catalog with the received data.
join_request (bool, optional, default to False) – If a request should be joined and sorted with another one by using request_join.
request_id (UUID4, optional) – The UUID to use for the request ID. If None, a new UUID will be generated.
params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- Returns:
The request_id for the request.
- Return type:
- Raises:
TypeError – If start is None.
ValueError – If start is > current timestamp (now).
ValueError – If end is > current timestamp (now).
ValueError – If start is > end.
TypeError – If callback is not None and not of type Callable.
- request_funding_rates(self, InstrumentId instrument_id, datetime start, datetime end=None, int limit=0, ClientId client_id=None, callback: Callable[[UUID4], None] | None = None, bool update_catalog=False, bool join_request=False, UUID4 request_id=None, dict params=None) UUID4¶
Request historical FundingRateUpdate data.
If end is
Nonethen will request up to the most recent data.Once the response is received, the funding rate data is forwarded from the message bus to the on_historical_data handler.
If the request fails, then an error is logged.
- Parameters:
instrument_id (InstrumentId) – The instrument ID for the request.
start (datetime) – The start datetime (UTC) of request time range. Should be left-inclusive (start <= value), but inclusiveness is not currently guaranteed.
end (datetime, optional) – The end datetime (UTC) of request time range. If None then will be replaced with the current UTC time. Should be right-inclusive (value <= end), but inclusiveness is not currently guaranteed.
limit (int, optional) – The limit on the amount of funding rates received.
client_id (ClientId, optional) – The specific client ID for the command. If
Nonethen will be inferred from the venue in the instrument ID.callback (Callable[[UUID4], None], optional) – The registered callback, to be called with the request ID when the response has completed processing.
update_catalog (bool, default False) – Whether to update a catalog with the received data.
join_request (bool, optional, default to False) – If a request should be joined and sorted with another one by using request_join.
request_id (UUID4, optional) – The UUID to use for the request ID. If None, a new UUID will be generated.
params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- Returns:
The request_id for the request.
- Return type:
- Raises:
TypeError – If start is None.
ValueError – If start is > current timestamp (now).
ValueError – If end is > current timestamp (now).
ValueError – If start is > end.
TypeError – If callback is not None and not of type Callable.
- request_instrument(self, InstrumentId instrument_id, datetime start=None, datetime end=None, ClientId client_id=None, callback: Callable[[UUID4], None] | None = None, bool update_catalog=False, bool join_request=False, UUID4 request_id=None, dict params=None) UUID4¶
Request Instrument data for the given instrument ID.
If end is
Nonethen will request up to the most recent data.Once the response is received, the instrument data is forwarded from the message bus to the on_instrument handler.
If the request fails, then an error is logged.
- Parameters:
instrument_id (InstrumentId) – The instrument ID for the request.
start (datetime, optional) – The start datetime (UTC) of request time range. The inclusiveness depends on individual data client implementation.
end (datetime, optional) – The end datetime (UTC) of request time range. The inclusiveness depends on individual data client implementation.
client_id (ClientId, optional) – The specific client ID for the command. If
Nonethen will be inferred from the venue in the instrument ID.callback (Callable[[UUID4], None], optional) – The registered callback, to be called with the request ID when the response has completed processing.
update_catalog (bool, default False) – Whether to update a catalog with the received data.
join_request (bool, optional, default to False) – If a request should be joined and sorted with another one by using request_join.
request_id (UUID4, optional) – The UUID to use for the request ID. If None, a new UUID will be generated.
params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- Returns:
The request_id for the request.
- Return type:
- Raises:
ValueError – If start is not None and > current timestamp (now).
ValueError – If end is not None and > current timestamp (now).
ValueError – If start and end are not None and start is >= end.
TypeError – If callback is not None and not of type Callable.
- request_instruments(self, Venue venue, datetime start=None, datetime end=None, ClientId client_id=None, callback: Callable[[UUID4], None] | None = None, bool update_catalog=False, bool join_request=False, UUID4 request_id=None, dict params=None) UUID4¶
Request all Instrument data for the given venue.
If end is
Nonethen will request up to the most recent data.Once the response is received, the instrument data is forwarded from the message bus to the on_instrument handler.
If the request fails, then an error is logged.
- Parameters:
venue (Venue) – The venue for the request.
start (datetime, optional) – The start datetime (UTC) of request time range. The inclusiveness depends on individual data client implementation.
end (datetime, optional) – The end datetime (UTC) of request time range. The inclusiveness depends on individual data client implementation.
client_id (ClientId, optional) – The specific client ID for the command. If
Nonethen will be inferred from the venue in the instrument ID.callback (Callable[[UUID4], None], optional) – The registered callback, to be called with the request ID when the response has completed processing.
update_catalog (bool, default False) – Whether to update a catalog with the received data.
join_request (bool, optional, default to False) – If a request should be joined and sorted with another one by using request_join.
request_id (UUID4, optional) – The UUID to use for the request ID. If None, a new UUID will be generated.
params (dict[str, Any], optional) – Additional parameters potentially used by a specific client: - only_last (default True) retains only the latest instrument record per instrument_id, based on the most recent ts_init.
- Returns:
The request_id for the request.
- Return type:
- Raises:
ValueError – If start is not None and > current timestamp (now).
ValueError – If end is not None and > current timestamp (now).
ValueError – If start and end are not None and start is >= end.
TypeError – If callback is not None and not of type Callable.
- request_join(self, tuple request_ids, datetime start, datetime end=None, ClientId client_id=None, Venue venue=None, callback: Callable[[UUID4], None] | None = None, UUID4 request_id=None, dict params=None) UUID4¶
Request a join of multiple data requests.
This method creates a RequestJoin message that will coordinate multiple sub-requests and combine their results.
- Parameters:
request_ids (tuple[UUID4]) – The tuple of request IDs to join.
start (datetime) – The start datetime (UTC) of request time range (inclusive).
end (datetime, optional) – The end datetime (UTC) of request time range. If None then will be replaced with the current UTC time.
client_id (ClientId, optional) – The data client ID for the request.
venue (Venue, optional) – The venue for the request.
callback (Callable[[UUID4], None], optional) – The registered callback, to be called with the request ID when the response has completed processing.
request_id (UUID4, optional) – The UUID to use for the request ID. If None, a new UUID will be generated.
params (dict[str, Any], optional) – Additional parameters for the request.
- Returns:
The request_id for the request.
- Return type:
- Raises:
ValueError – If both client_id and venue are both
None(not enough routing info).TypeError – If callback is not None and not of type Callable.
- request_order_book_deltas(self, InstrumentId instrument_id, datetime start, datetime end=None, int limit=0, ClientId client_id=None, callback: Callable[[UUID4], None] | None = None, bool update_catalog=False, bool join_request=False, UUID4 request_id=None, dict params=None) UUID4¶
Request historical OrderBookDeltas data.
Once the response is received, the order book deltas data is forwarded from the message bus to the on_historical_data handler.
If the request fails, then an error is logged.
- Parameters:
instrument_id (InstrumentId) – The instrument ID for the order book deltas request.
start (datetime) – 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.
limit (int, optional) – The limit on the amount of deltas received.
client_id (ClientId, optional) – The specific client ID for the command. If None, it will be inferred from the venue in the instrument ID.
callback (Callable[[UUID4], None], optional) – The registered callback, to be called with the request ID when the response has completed processing.
update_catalog (bool, default False) – If the data catalog should be updated with the received data.
join_request (bool, optional, default to False) – If a request should be joined and sorted with another one by using request_join.
request_id (UUID4, optional) – The UUID to use for the request ID. If None, a new UUID will be generated.
params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- Returns:
The request_id for the request.
- Return type:
- Raises:
ValueError – If the instrument_id is None.
TypeError – If callback is not None and not of type Callable.
- request_order_book_depth(self, InstrumentId instrument_id, datetime start, datetime end=None, int limit=0, int depth=10, ClientId client_id=None, callback: Callable[[UUID4], None] | None = None, bool update_catalog=False, bool join_request=False, UUID4 request_id=None, dict params=None) UUID4¶
Request historical OrderBookDepth10 snapshots.
Once the response is received, the order book depth data is forwarded from the message bus to the on_historical_data handler.
If the request fails, then an error is logged.
- Parameters:
instrument_id (InstrumentId) – The instrument ID for the order book depths request.
start (datetime) – 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.
limit (int, optional) – The limit on the amount of depth snapshots received.
depth (int, optional) – The maximum depth for the returned order book data (default is 10).
client_id (ClientId, optional) – The specific client ID for the command. If None, it will be inferred from the venue in the instrument ID.
callback (Callable[[UUID4], None], optional) – The registered callback, to be called with the request ID when the response has completed processing.
update_catalog (bool, default False) – If the data catalog should be updated with the received data.
join_request (bool, optional, default to False) – If a request should be joined and sorted with another one by using request_join.
request_id (UUID4, optional) – The UUID to use for the request ID. If None, a new UUID will be generated.
params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- Returns:
The request_id for the request.
- Return type:
- Raises:
ValueError – If the instrument_id is None.
TypeError – If callback is not None and not of type Callable.
- request_order_book_snapshot(self, InstrumentId instrument_id, int limit=0, ClientId client_id=None, callback: Callable[[UUID4], None] | None = None, bool join_request=False, UUID4 request_id=None, dict params=None) UUID4¶
Request an order book snapshot.
Once the response is received, the order book data is forwarded from the message bus to the on_historical_data handler.
If the request fails, then an error is logged.
- Parameters:
instrument_id (InstrumentId) – The instrument ID for the order book snapshot request.
limit (int, optional) – The limit on the depth of the order book snapshot.
client_id (ClientId, optional) – The specific client ID for the command. If None, it will be inferred from the venue in the instrument ID.
callback (Callable[[UUID4], None], optional) – The registered callback, to be called with the request ID when the response has completed processing.
join_request (bool, optional, default to False) – If a request should be joined and sorted with another one by using request_join.
request_id (UUID4, optional) – The UUID to use for the request ID. If None, a new UUID will be generated.
params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- Returns:
The request_id for the request.
- Return type:
- Raises:
ValueError – If the instrument_id is None.
TypeError – If callback is not None and not of type Callable.
- request_quote_ticks(self, InstrumentId instrument_id, datetime start, datetime end=None, int limit=0, ClientId client_id=None, callback: Callable[[UUID4], None] | None = None, bool update_catalog=False, bool aggregate_spread_quotes=False, bool join_request=False, UUID4 request_id=None, dict params=None) UUID4¶
Request historical QuoteTick data.
If end is
Nonethen will request up to the most recent data.Once the response is received, the quote tick data is forwarded from the message bus to the on_historical_data handler.
If the request fails, then an error is logged.
- Parameters:
instrument_id (InstrumentId) – The tick instrument ID for the request.
start (datetime) – The start datetime (UTC) of request time range. Should be left-inclusive (start <= value), but inclusiveness is not currently guaranteed.
end (datetime, optional) – The end datetime (UTC) of request time range. If None then will be replaced with the current UTC time. Should be right-inclusive (value <= end), but inclusiveness is not currently guaranteed.
limit (int, optional) – The limit on the amount of quote ticks received.
client_id (ClientId, optional) – The specific client ID for the command. If
Nonethen will be inferred from the venue in the instrument ID.callback (Callable[[UUID4], None], optional) – The registered callback, to be called with the request ID when the response has completed processing.
update_catalog (bool, default False) – Whether to update a catalog with the received data.
aggregate_spread_quotes (bool, default False) – Whether to activate a spread quote aggregator from leg quotes. Only applicable when the instrument_id is a spread instrument.
join_request (bool, optional, default to False) – If a request should be joined and sorted with another one by using request_join.
request_id (UUID4, optional) – The UUID to use for the request ID. If None, a new UUID will be generated.
params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- Returns:
The request_id for the request.
- Return type:
- Raises:
TypeError – If start is None.
ValueError – If start is > current timestamp (now).
ValueError – If end is > current timestamp (now).
ValueError – If start is > end.
TypeError – If callback is not None and not of type Callable.
- request_trade_ticks(self, InstrumentId instrument_id, datetime start, datetime end=None, int limit=0, ClientId client_id=None, callback: Callable[[UUID4], None] | None = None, bool update_catalog=False, bool join_request=False, UUID4 request_id=None, dict params=None) UUID4¶
Request historical TradeTick data.
If end is
Nonethen will request up to the most recent data.Once the response is received, the trade tick data is forwarded from the message bus to the on_historical_data handler.
If the request fails, then an error is logged.
- Parameters:
instrument_id (InstrumentId) – The tick instrument ID for the request.
start (datetime) – The start datetime (UTC) of request time range. Should be left-inclusive (start <= value), but inclusiveness is not currently guaranteed.
end (datetime, optional) – The end datetime (UTC) of request time range. If None then will be replaced with the current UTC time. Should be right-inclusive (value <= end), but inclusiveness is not currently guaranteed.
limit (int, optional) – The limit on the amount of trade ticks received.
client_id (ClientId, optional) – The specific client ID for the command. If
Nonethen will be inferred from the venue in the instrument ID.callback (Callable[[UUID4], None], optional) – The registered callback, to be called with the request ID when the response has completed processing.
update_catalog (bool, default False) – Whether to update a catalog with the received data.
join_request (bool, optional, default to False) – If a request should be joined and sorted with another one by using request_join.
request_id (UUID4, optional) – The UUID to use for the request ID. If None, a new UUID will be generated.
params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- Returns:
The request_id for the request.
- Return type:
- Raises:
TypeError – If start is None.
ValueError – If start is > current timestamp (now).
ValueError – If end is > current timestamp (now).
ValueError – If start is > end.
TypeError – If callback is not None and not of type Callable.
- 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
RESETTINGstate.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
RESUMINGstate.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_in_executor(self, func: Callable[..., Any], tuple args=None, dict kwargs=None)¶
Schedules the callable func to be executed as fn(*args, **kwargs).
- Parameters:
func (Callable) – The function to be executed.
args (positional arguments) – The positional arguments for the call to func.
kwargs (arbitrary keyword arguments) – The keyword arguments for the call to func.
- Returns:
The unique task identifier for the execution. This also corresponds to any future objects memory address.
- Return type:
- Raises:
TypeError – If func is not of type Callable.
Notes
For backtesting the func is immediately executed, as there’s no need for a Future object that can be awaited. In a backtesting scenario, the execution is not in real time, and so the results of func are ‘immediately’ available after it’s called.
- save(self) dict¶
Return the actor/strategy state dictionary to be saved.
Calls on_save.
- Returns:
The strategy state to save.
- Return type:
dict[str, bytes]
Warning
Exceptions raised will be caught, logged, and reraised.
- shutdown_system(self, str reason=None) void¶
Initiate a system-wide shutdown by generating and publishing a ShutdownSystem command.
The command is handled by the system’s NautilusKernel, which will invoke either stop (synchronously) or stop_async (asynchronously) depending on the execution context and the presence of an active event loop.
- Parameters:
reason (str, optional) – The reason for issuing the shutdown command.
- spawn_limit(self, Order primary, Quantity quantity, Price price, TimeInForce time_in_force=TimeInForce.GTC, datetime expire_time=None, bool post_only=False, bool reduce_only=False, Quantity display_qty=None, TriggerType emulation_trigger=TriggerType.NO_TRIGGER, list tags=None, bool reduce_primary=True) LimitOrder¶
Spawn a new
LIMITorder from the given primary order.- Parameters:
primary (Order) – The primary order from which this order will spawn.
quantity (Quantity) – The spawned orders quantity (> 0). Must not exceed primary.leaves_qty.
price (Price) – The spawned orders price.
time_in_force (TimeInForce {
GTC,IOC,FOK,GTD,DAY,AT_THE_OPEN,AT_THE_CLOSE}, defaultGTC) – The spawned orders time in force.expire_time (datetime, optional) – The spawned order expiration (for
GTDorders).post_only (bool, default False) – If the spawned order will only provide liquidity (make a market).
reduce_only (bool, default False) – If the spawned order carries the ‘reduce-only’ execution instruction.
display_qty (Quantity, optional) – The quantity of the spawned order to display on the public book (iceberg).
emulation_trigger (TriggerType, default
NO_TRIGGER) – The type of market price trigger to use for local order emulation. -NO_TRIGGER(default): Disables local emulation; orders are sent directly to the venue. -DEFAULT(the same asBID_ASK): Enables local order emulation by triggering orders based on bid/ask prices. Additional trigger types are available. See the “Emulated Orders” section in the documentation for more details.tags (list[str], optional) – The custom user tags for the order.
reduce_primary (bool, default True) – If the primary order quantity should be reduced by the given quantity.
- Return type:
- Raises:
ValueError – If primary.exec_algorithm_id is not equal to self.id.
ValueError – If quantity is not positive (> 0).
ValueError – If quantity exceeds primary.leaves_qty (when reduce_primary is True).
ValueError – If time_in_force is
GTDand expire_time <= UNIX epoch.ValueError – If display_qty is negative (< 0) or greater than quantity.
Notes
If reduce_primary is True and the spawned order is subsequently denied or rejected (before acceptance), the deducted quantity is automatically restored to the primary order. Once accepted, the reduction is considered committed.
- spawn_market(self, Order primary, Quantity quantity, TimeInForce time_in_force=TimeInForce.GTC, bool reduce_only=False, list tags=None, bool reduce_primary=True) MarketOrder¶
Spawn a new
MARKETorder from the given primary order.- Parameters:
primary (Order) – The primary order from which this order will spawn.
quantity (Quantity) – The spawned orders quantity (> 0). Must not exceed primary.leaves_qty.
time_in_force (TimeInForce {
GTC,IOC,FOK,DAY,AT_THE_OPEN,AT_THE_CLOSE}, defaultGTC) – The spawned orders time in force. Often not applicable for market orders.reduce_only (bool, default False) – If the spawned order carries the ‘reduce-only’ execution instruction.
tags (list[str], optional) – The custom user tags for the order.
reduce_primary (bool, default True) – If the primary order quantity should be reduced by the given quantity.
- Return type:
- Raises:
ValueError – If primary.exec_algorithm_id is not equal to self.id.
ValueError – If quantity is not positive (> 0).
ValueError – If quantity exceeds primary.leaves_qty (when reduce_primary is True).
ValueError – If time_in_force is
GTD.
Notes
If reduce_primary is True and the spawned order is subsequently denied or rejected (before acceptance), the deducted quantity is automatically restored to the primary order. Once accepted, the reduction is considered committed.
- spawn_market_to_limit(self, Order primary, Quantity quantity, TimeInForce time_in_force=TimeInForce.GTC, datetime expire_time=None, bool reduce_only=False, Quantity display_qty=None, TriggerType emulation_trigger=TriggerType.NO_TRIGGER, list tags=None, bool reduce_primary=True) MarketToLimitOrder¶
Spawn a new
MARKET_TO_LIMITorder from the given primary order.- Parameters:
primary (Order) – The primary order from which this order will spawn.
quantity (Quantity) – The spawned orders quantity (> 0). Must not exceed primary.leaves_qty.
time_in_force (TimeInForce {
GTC,IOC,FOK,GTD,DAY,AT_THE_OPEN,AT_THE_CLOSE}, defaultGTC) – The spawned orders time in force.expire_time (datetime, optional) – The spawned order expiration (for
GTDorders).reduce_only (bool, default False) – If the spawned order carries the ‘reduce-only’ execution instruction.
display_qty (Quantity, optional) – The quantity of the spawned order to display on the public book (iceberg).
emulation_trigger (TriggerType, default
NO_TRIGGER) – The type of market price trigger to use for local order emulation. -NO_TRIGGER(default): Disables local emulation; orders are sent directly to the venue. -DEFAULT(the same asBID_ASK): Enables local order emulation by triggering orders based on bid/ask prices. Additional trigger types are available. See the “Emulated Orders” section in the documentation for more details.tags (list[str], optional) – The custom user tags for the order.
reduce_primary (bool, default True) – If the primary order quantity should be reduced by the given quantity.
- Return type:
- Raises:
ValueError – If primary.exec_algorithm_id is not equal to self.id.
ValueError – If quantity is not positive (> 0).
ValueError – If quantity exceeds primary.leaves_qty (when reduce_primary is True).
ValueError – If time_in_force is
GTDand expire_time <= UNIX epoch.ValueError – If display_qty is negative (< 0) or greater than quantity.
Notes
If reduce_primary is True and the spawned order is subsequently denied or rejected (before acceptance), the deducted quantity is automatically restored to the primary order. Once accepted, the reduction is considered committed.
- start(self) void¶
Start the component.
While executing on_start() any exception will be logged and reraised, then the component will remain in a
STARTINGstate.Warning
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
- state¶
ComponentState
Return the components current state.
- Return type:
ComponentState
- Type:
- stop(self) void¶
Stop the component.
While executing on_stop() any exception will be logged and reraised, then the component will remain in a
STOPPINGstate.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, Order order) void¶
Submit the given order (may be the primary or spawned order).
A SubmitOrder command will be created and sent to the RiskEngine.
If the client order ID is duplicate, then the order will be denied.
- Parameters:
order (Order) – The order to submit.
parent_order_id (ClientOrderId, optional) – The parent client order identifier. If provided then will be considered a child order of the parent.
- Raises:
ValueError – If order.status is not
INITIALIZEDorRELEASED.ValueError – If order.emulation_trigger is not
NO_TRIGGER.
Warning
If a position_id is passed and a position does not yet exist, then any position opened by the order will have this position ID assigned. This may not be what you intended.
Emulated orders cannot be sent from execution algorithms (intentionally constraining complexity).
- subscribe_bars(self, BarType bar_type, ClientId client_id=None, bool update_catalog=False, dict params=None) void¶
Subscribe to streaming Bar data for the given bar type.
Once subscribed, any matching bar data published on the message bus is forwarded to the on_bar handler.
- Parameters:
bar_type (BarType) – The bar type to subscribe to.
client_id (ClientId, optional) – The specific client ID for the command. If
Nonethen will be inferred from the venue in the instrument ID.update_catalog (bool, default False) – Whether to update a catalog with the received data. Only useful when downloading data during a backtest.
params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- subscribe_data(self, DataType data_type, ClientId client_id=None, InstrumentId instrument_id=None, bool update_catalog=False, dict params=None) void¶
Subscribe to data of the given data type.
Once subscribed, any matching data published on the message bus is forwarded to the on_data handler.
- Parameters:
data_type (DataType) – The data type to subscribe to.
client_id (ClientId, optional) – The data client ID. If supplied then a Subscribe command will be sent to the corresponding data client.
update_catalog (bool, default False) – Whether to update a catalog with the received data. Only useful when downloading data during a backtest.
params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- subscribe_funding_rates(self, InstrumentId instrument_id, ClientId client_id=None, dict params=None) void¶
Subscribe to streaming FundingRateUpdate data for the given instrument ID.
Once subscribed, any matching funding rate updates published on the message bus are forwarded to the on_funding_rate handler.
- Parameters:
instrument_id (InstrumentId) – The instrument to subscribe to.
client_id (ClientId, optional) – The specific client ID for the command. If
Nonethen will be inferred from the venue in the instrument ID.params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- subscribe_index_prices(self, InstrumentId instrument_id, ClientId client_id=None, dict params=None) void¶
Subscribe to streaming IndexPriceUpdate data for the given instrument ID.
Once subscribed, any matching index price updates published on the message bus are forwarded to the on_index_price handler.
- Parameters:
instrument_id (InstrumentId) – The instrument to subscribe to.
client_id (ClientId, optional) – The specific client ID for the command. If
Nonethen will be inferred from the venue in the instrument ID.params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- subscribe_instrument(self, InstrumentId instrument_id, ClientId client_id=None, bool update_catalog=False, dict params=None) void¶
Subscribe to update Instrument data for the given instrument ID.
Once subscribed, any matching instrument data published on the message bus is forwarded to the on_instrument handler.
- Parameters:
instrument_id (InstrumentId) – The instrument ID for the subscription.
client_id (ClientId, optional) – The specific client ID for the command. If
Nonethen will be inferred from the venue in the instrument ID.update_catalog (bool, default False) – Whether to update a catalog with the received data. Only useful when downloading data during a backtest.
params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- subscribe_instrument_close(self, InstrumentId instrument_id, ClientId client_id=None, dict params=None) void¶
Subscribe to close updates for the given instrument ID.
Once subscribed, any matching instrument close data published on the message bus is forwarded to the on_instrument_close handler.
- Parameters:
instrument_id (InstrumentId) – The instrument to subscribe to status updates for.
client_id (ClientId, optional) – The specific client ID for the command. If
Nonethen will be inferred from the venue in the instrument ID.params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- subscribe_instrument_status(self, InstrumentId instrument_id, ClientId client_id=None, dict params=None) void¶
Subscribe to status updates for the given instrument ID.
Once subscribed, any matching instrument status data published on the message bus is forwarded to the on_instrument_status handler.
- Parameters:
instrument_id (InstrumentId) – The instrument to subscribe to status updates for.
client_id (ClientId, optional) – The specific client ID for the command. If
Nonethen will be inferred from the venue in the instrument ID.params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- subscribe_instruments(self, Venue venue, ClientId client_id=None, bool update_catalog=False, dict params=None) void¶
Subscribe to update Instrument data for the given venue.
Once subscribed, any matching instrument data published on the message bus is forwarded the on_instrument handler.
- Parameters:
venue (Venue) – The venue for the subscription.
client_id (ClientId, optional) – The specific client ID for the command. If
Nonethen will be inferred from the venue.update_catalog (bool, default False) – Whether to update a catalog with the received data. Only useful when downloading data during a backtest.
params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- subscribe_mark_prices(self, InstrumentId instrument_id, ClientId client_id=None, dict params=None) void¶
Subscribe to streaming MarkPriceUpdate data for the given instrument ID.
Once subscribed, any matching mark price updates published on the message bus are forwarded to the on_mark_price handler.
- Parameters:
instrument_id (InstrumentId) – The instrument to subscribe to.
client_id (ClientId, optional) – The specific client ID for the command. If
Nonethen will be inferred from the venue in the instrument ID.params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- subscribe_order_book_at_interval(self, InstrumentId instrument_id, BookType book_type=BookType.L2_MBP, int depth=0, int interval_ms=1000, ClientId client_id=None, dict params=None) void¶
Subscribe to an OrderBook at a specified interval for the given instrument ID.
Once subscribed, any matching order book updates published on the message bus are forwarded to the on_order_book handler.
The DataEngine will only maintain one order book for each instrument. Because of this - the level, depth and params for the stream will be set as per the last subscription request (this will also affect all subscribers).
- Parameters:
instrument_id (InstrumentId) – The order book instrument ID to subscribe to.
book_type (BookType {
L1_MBP,L2_MBP,L3_MBO}) – The order book type.depth (int, optional) – The maximum depth for the order book. A depth of 0 is maximum depth.
interval_ms (int, default 1000) – The order book snapshot interval (milliseconds).
client_id (ClientId, optional) – The specific client ID for the command. If
Nonethen will be inferred from the venue in the instrument ID.params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- Raises:
ValueError – If depth is negative (< 0).
ValueError – If interval_ms is not positive (> 0).
Warning
Consider subscribing to order book deltas if you need intervals less than 100 milliseconds.
- subscribe_order_book_deltas(self, InstrumentId instrument_id, BookType book_type=BookType.L2_MBP, int depth=0, ClientId client_id=None, bool managed=True, bool pyo3_conversion=False, dict params=None) void¶
Subscribe to the order book data stream, being a snapshot then deltas for the given instrument ID.
Once subscribed, any matching order book data published on the message bus is forwarded to the on_order_book_deltas handler.
- Parameters:
instrument_id (InstrumentId) – The order book instrument ID to subscribe to.
book_type (BookType {
L1_MBP,L2_MBP,L3_MBO}) – The order book type.depth (int, optional) – The maximum depth for the order book. A depth of 0 is maximum depth.
client_id (ClientId, optional) – The specific client ID for the command. If
Nonethen will be inferred from the venue in the instrument ID.managed (bool, default True) – If an order book should be managed by the data engine based on the subscribed feed.
pyo3_conversion (bool, default False) – If received deltas should be converted to nautilus_pyo3.OrderBookDeltas prior to being passed to the on_order_book_deltas handler.
params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- subscribe_order_book_depth(self, InstrumentId instrument_id, BookType book_type=BookType.L2_MBP, int depth=0, ClientId client_id=None, bool managed=True, bool pyo3_conversion=False, bool update_catalog=False, dict params=None) void¶
Subscribe to the order book depth stream for the given instrument ID.
Once subscribed, any matching order book data published on the message bus is forwarded to the on_order_book_depth handler.
- Parameters:
instrument_id (InstrumentId) – The order book instrument ID to subscribe to.
book_type (BookType {
L1_MBP,L2_MBP,L3_MBO}) – The order book type.client_id (ClientId, optional) – The specific client ID for the command. If
Nonethen will be inferred from the venue in the instrument ID.managed (bool, default True) – If an order book should be managed by the data engine based on the subscribed feed.
pyo3_conversion (bool, default False) – If received deltas should be converted to nautilus_pyo3.OrderBookDepth prior to being passed to the on_order_book_depth handler.
update_catalog (bool, default False) – Whether to update a catalog with the received data. Only useful when downloading data during a backtest.
params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- subscribe_order_cancels(self, InstrumentId instrument_id) void¶
Subscribe to all order cancels for the given instrument ID.
Once subscribed, any matching order cancels published on the message bus are forwarded to the on_order_canceled handler.
- Parameters:
instrument_id (InstrumentId) – The instrument to subscribe to cancels for.
- subscribe_order_fills(self, InstrumentId instrument_id) void¶
Subscribe to all order fills for the given instrument ID.
Once subscribed, any matching order fills published on the message bus are forwarded to the on_order_filled handler.
- Parameters:
instrument_id (InstrumentId) – The instrument to subscribe to fills for.
- subscribe_quote_ticks(self, InstrumentId instrument_id, ClientId client_id=None, bool update_catalog=False, bool aggregate_spread_quotes=False, dict params=None) void¶
Subscribe to streaming QuoteTick data for the given instrument ID.
Once subscribed, any matching quote tick data published on the message bus is forwarded to the on_quote_tick handler.
- Parameters:
instrument_id (InstrumentId) – The tick instrument to subscribe to.
client_id (ClientId, optional) – The specific client ID for the command. If
Nonethen will be inferred from the venue in the instrument ID.update_catalog (bool, default False) – Whether to update a catalog with the received data. Only useful when downloading data during a backtest.
aggregate_spread_quotes (bool, default False) – Whether to activate a spread quote aggregator from leg quotes. Only applicable when the instrument_id is a spread instrument.
params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- subscribe_signal(self, str name='') void¶
Subscribe to a specific signal by name, or to all signals if no name is provided.
Once subscribed, any matching signal data published on the message bus is forwarded to the on_signal handler.
- Parameters:
name (str, optional) – The name of the signal to subscribe to. If not provided or an empty string is passed, the subscription will include all signals. The signal name is case-insensitive and will be capitalized (e.g., ‘example’ becomes ‘SignalExample*’).
- subscribe_trade_ticks(self, InstrumentId instrument_id, ClientId client_id=None, bool update_catalog=False, dict params=None) void¶
Subscribe to streaming TradeTick data for the given instrument ID.
Once subscribed, any matching trade tick data published on the message bus is forwarded to the on_trade_tick handler.
- Parameters:
instrument_id (InstrumentId) – The tick instrument to subscribe to.
client_id (ClientId, optional) – The specific client ID for the command. If
Nonethen will be inferred from the venue in the instrument ID.update_catalog (bool, default False) – Whether to update a catalog with the received data. Only useful when downloading data during a backtest.
params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- to_importable_config(self) ImportableExecAlgorithmConfig¶
Returns an importable configuration for this execution algorithm.
- Return type:
- trader_id¶
The trader ID associated with the component.
- Returns:
TraderId
- type¶
The components type.
- Returns:
type
- unsubscribe_bars(self, BarType bar_type, ClientId client_id=None, dict params=None) void¶
Unsubscribe from streaming Bar data for the given bar type.
- Parameters:
- unsubscribe_data(self, DataType data_type, ClientId client_id=None, InstrumentId instrument_id=None, dict params=None) void¶
Unsubscribe from data of the given data type.
- unsubscribe_funding_rates(self, InstrumentId instrument_id, ClientId client_id=None, dict params=None) void¶
Unsubscribe from streaming FundingRateUpdate data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The instrument to unsubscribe from.
client_id (ClientId, optional) – The specific client ID for the command. If
Nonethen will be inferred from the venue in the instrument ID.params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- unsubscribe_index_prices(self, InstrumentId instrument_id, ClientId client_id=None, dict params=None) void¶
Unsubscribe from streaming IndexPriceUpdate data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The instrument to subscribe to.
client_id (ClientId, optional) – The specific client ID for the command. If
Nonethen will be inferred from the venue in the instrument ID.params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- unsubscribe_instrument(self, InstrumentId instrument_id, ClientId client_id=None, dict params=None) void¶
Unsubscribe from update Instrument data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The instrument to unsubscribe from.
client_id (ClientId, optional) – The specific client ID for the command. If
Nonethen will be inferred from the venue in the instrument ID.params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- unsubscribe_instrument_close(self, InstrumentId instrument_id, ClientId client_id=None, dict params=None) void¶
Unsubscribe from close updates for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The instrument to unsubscribe from close updates for.
client_id (ClientId, optional) – The specific client ID for the command. If
Nonethen will be inferred from the venue in the instrument ID.params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- unsubscribe_instrument_status(self, InstrumentId instrument_id, ClientId client_id=None, dict params=None) void¶
Unsubscribe from status updates for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The instrument to unsubscribe from status updates for.
client_id (ClientId, optional) – The specific client ID for the command. If
Nonethen will be inferred from the venue.params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- unsubscribe_instruments(self, Venue venue, ClientId client_id=None, dict params=None) void¶
Unsubscribe from update Instrument data for the given venue.
- unsubscribe_mark_prices(self, InstrumentId instrument_id, ClientId client_id=None, dict params=None) void¶
Unsubscribe from streaming MarkPriceUpdate data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The instrument to subscribe to.
client_id (ClientId, optional) – The specific client ID for the command. If
Nonethen will be inferred from the venue in the instrument ID.params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- unsubscribe_order_book_at_interval(self, InstrumentId instrument_id, int interval_ms=1000, ClientId client_id=None, dict params=None) void¶
Unsubscribe from an OrderBook at a specified interval for the given instrument ID.
The interval must match the previously subscribed interval.
- Parameters:
instrument_id (InstrumentId) – The order book instrument to subscribe to.
interval_ms (int, default 1000) – The order book snapshot interval (milliseconds).
client_id (ClientId, optional) – The specific client ID for the command. If
Nonethen will be inferred from the venue in the instrument ID.params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- unsubscribe_order_book_deltas(self, InstrumentId instrument_id, ClientId client_id=None, dict params=None) void¶
Unsubscribe the order book deltas stream for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The order book instrument to subscribe to.
client_id (ClientId, optional) – The specific client ID for the command. If
Nonethen will be inferred from the venue in the instrument ID.params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- unsubscribe_order_book_depth(self, InstrumentId instrument_id, ClientId client_id=None, dict params=None) void¶
Unsubscribe the order book depth stream for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The order book instrument to subscribe to.
client_id (ClientId, optional) – The specific client ID for the command. If
Nonethen will be inferred from the venue in the instrument ID.params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- unsubscribe_order_cancels(self, InstrumentId instrument_id) void¶
Unsubscribe from all order cancels for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The instrument to unsubscribe from cancels for.
- unsubscribe_order_fills(self, InstrumentId instrument_id) void¶
Unsubscribe from all order fills for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The instrument to unsubscribe from fills for.
- unsubscribe_quote_ticks(self, InstrumentId instrument_id, ClientId client_id=None, bool aggregate_spread_quotes=False, dict params=None) void¶
Unsubscribe from streaming QuoteTick data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The tick instrument to unsubscribe from.
client_id (ClientId, optional) – The specific client ID for the command. If
Nonethen will be inferred from the venue in the instrument ID.aggregate_spread_quotes (bool, default False) – Whether to unsubscribe from a spread quote aggregator. Only applicable when the instrument_id is a spread instrument.
params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- unsubscribe_trade_ticks(self, InstrumentId instrument_id, ClientId client_id=None, dict params=None) void¶
Unsubscribe from streaming TradeTick data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The tick instrument ID to unsubscribe from.
client_id (ClientId, optional) – The specific client ID for the command. If
Nonethen will be inferred from the venue in the instrument ID.params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- update_synthetic(self, SyntheticInstrument synthetic) void¶
Update the synthetic instrument in the cache.
- Parameters:
synthetic (SyntheticInstrument) – The synthetic instrument to update in the cache.
- Raises:
KeyError – If synthetic does not already exist in the cache.
Notes
If you are adding a new synthetic instrument then you should use the add_synthetic method.
- class ExecutionClient¶
Bases:
ComponentExecutionClient(ClientId client_id, Venue venue: Venue | None, OmsType oms_type, AccountType account_type, Currency base_currency: Currency | None, MessageBus msgbus, Cache cache, Clock clock, config: NautilusConfig | None = None)
The base class for all execution clients.
- Parameters:
client_id (ClientId) – The client ID.
venue (Venue or
None) – The client venue. If multi-venue then can beNone.oms_type (OmsType) – The venues order management system type.
account_type (AccountType) – The account type for the client.
base_currency (Currency or
None) – The account base currency. UseNonefor multi-currency accounts.msgbus (MessageBus) – The message bus for the client.
cache (Cache) – The cache for the client.
clock (Clock) – The clock for the client.
config (NautilusConfig, optional) – The configuration for the instance.
- Raises:
ValueError – If client_id is not equal to account_id.get_issuer().
ValueError – If oms_type is
UNSPECIFIED(must be specified).
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
- 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.
- degrade(self) void¶
Degrade the component.
While executing on_degrade() any exception will be logged and reraised, then the component will remain in a
DEGRADINGstate.Warning
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
- dispose(self) void¶
Dispose of the component.
While executing on_dispose() any exception will be logged and reraised, then the component will remain in a
DISPOSINGstate.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
FAULTINGstate.Warning
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
- classmethod fully_qualified_name(cls) str¶
Return the fully qualified name for the components class.
- Return type:
str
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) – UNIX timestamp (nanoseconds) when the account state event occurred.
info (dict [str, object]) – The additional implementation specific account information.
- generate_order_accepted(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, VenueOrderId venue_order_id, uint64_t ts_event) void¶
Generate an OrderAccepted event and send it to the ExecutionEngine.
- Parameters:
strategy_id (StrategyId) – The strategy ID associated with the event.
instrument_id (InstrumentId) – The instrument ID.
client_order_id (ClientOrderId) – The client order ID.
venue_order_id (VenueOrderId) – The venue order ID (assigned by the venue).
ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the order accepted event occurred.
- generate_order_cancel_rejected(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, VenueOrderId venue_order_id, str reason, uint64_t ts_event) void¶
Generate an OrderCancelRejected event and send it to the ExecutionEngine.
- Parameters:
strategy_id (StrategyId) – The strategy ID associated with the event.
instrument_id (InstrumentId) – The instrument ID.
client_order_id (ClientOrderId) – The client order ID.
venue_order_id (VenueOrderId) – The venue order ID (assigned by the venue).
reason (str) – The order cancel rejected reason.
ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the order cancel rejected event occurred.
- generate_order_canceled(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, VenueOrderId venue_order_id, uint64_t ts_event) void¶
Generate an OrderCanceled event and send it to the ExecutionEngine.
- Parameters:
strategy_id (StrategyId) – The strategy ID associated with the event.
instrument_id (InstrumentId) – The instrument ID.
client_order_id (ClientOrderId) – The client order ID.
venue_order_id (VenueOrderId) – The venue order ID (assigned by the venue).
ts_event (uint64_t) – UNIX timestamp (nanoseconds) when order canceled event occurred.
- generate_order_denied(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, str reason, uint64_t ts_event) void¶
Generate an OrderDenied 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 (str) – The order denied reason.
ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the order denied event occurred.
- generate_order_expired(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, VenueOrderId venue_order_id, uint64_t ts_event) void¶
Generate an OrderExpired event and send it to the ExecutionEngine.
- Parameters:
strategy_id (StrategyId) – The strategy ID associated with the event.
instrument_id (InstrumentId) – The instrument ID.
client_order_id (ClientOrderId) – The client order ID.
venue_order_id (VenueOrderId) – The venue order ID (assigned by the venue).
ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the order expired event occurred.
- generate_order_filled(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, VenueOrderId venue_order_id, PositionId venue_position_id: PositionId | None, TradeId trade_id, OrderSide order_side, OrderType order_type, Quantity last_qty, Price last_px, Currency quote_currency, Money commission, LiquiditySide liquidity_side, uint64_t ts_event, dict info=None) void¶
Generate an OrderFilled event and send it to the ExecutionEngine.
- Parameters:
strategy_id (StrategyId) – The strategy ID associated with the event.
instrument_id (InstrumentId) – The instrument ID.
client_order_id (ClientOrderId) – The client order ID.
venue_order_id (VenueOrderId) – The venue order ID (assigned by the venue).
trade_id (TradeId) – The trade ID.
venue_position_id (PositionId or
None) – The venue position ID associated with the order. If the trading venue has assigned a position ID / ticket then pass that here, otherwise passNoneand the execution engine OMS will handle position ID resolution.order_side (OrderSide {
BUY,SELL}) – The execution order side.order_type (OrderType) – The execution order type.
last_qty (Quantity) – The fill quantity for this execution.
last_px (Price) – The fill price for this execution (not average price).
quote_currency (Currency) – The currency of the price.
commission (Money) – The fill commission.
liquidity_side (LiquiditySide {
NO_LIQUIDITY_SIDE,MAKER,TAKER}) – The execution liquidity side.ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the order filled event occurred.
info (dict[str, object], optional) – The additional fill information.
- generate_order_modify_rejected(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, VenueOrderId venue_order_id, str reason, uint64_t ts_event) void¶
Generate an OrderModifyRejected event and send it to the ExecutionEngine.
- Parameters:
strategy_id (StrategyId) – The strategy ID associated with the event.
instrument_id (InstrumentId) – The instrument ID.
client_order_id (ClientOrderId) – The client order ID.
venue_order_id (VenueOrderId) – The venue order ID (assigned by the venue).
reason (str) – The order update rejected reason.
ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the order update rejection event occurred.
- generate_order_rejected(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, str reason, uint64_t ts_event, bool due_post_only=False) void¶
Generate an OrderRejected event and send it to the ExecutionEngine.
- Parameters:
strategy_id (StrategyId) – The strategy ID associated with the event.
instrument_id (InstrumentId) – The instrument ID.
client_order_id (ClientOrderId) – The client order ID.
reason (datetime) – The order rejected reason.
ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the order rejected event occurred.
due_post_only (bool, default False) – If the order was rejected because it was post-only and would execute immediately as a taker.
- generate_order_submitted(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, uint64_t ts_event) void¶
Generate an OrderSubmitted event and send it to the ExecutionEngine.
- Parameters:
strategy_id (StrategyId) – The strategy ID associated with the event.
instrument_id (InstrumentId) – The instrument ID.
client_order_id (ClientOrderId) – The client order ID.
ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the order submitted event occurred.
- generate_order_triggered(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, VenueOrderId venue_order_id, uint64_t ts_event) void¶
Generate an OrderTriggered event and send it to the ExecutionEngine.
- Parameters:
strategy_id (StrategyId) – The strategy ID associated with the event.
instrument_id (InstrumentId) – The instrument ID.
client_order_id (ClientOrderId) – The client order ID.
venue_order_id (VenueOrderId) – The venue order ID (assigned by the venue).
ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the order triggered event occurred.
- generate_order_updated(self, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, VenueOrderId venue_order_id, Quantity quantity, Price price, Price trigger_price, uint64_t ts_event, bool venue_order_id_modified=False) void¶
Generate an OrderUpdated event and send it to the ExecutionEngine.
- Parameters:
strategy_id (StrategyId) – The strategy ID associated with the event.
instrument_id (InstrumentId) – The instrument ID.
client_order_id (ClientOrderId) – The client order ID.
venue_order_id (VenueOrderId) – The venue order ID (assigned by the venue).
quantity (Quantity) – The orders current quantity.
price (Price) – The orders current price.
trigger_price (Price or
None) – The orders current trigger price.ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the order update event occurred.
venue_order_id_modified (bool) – If the ID was modified for this event.
- get_account(self) Account¶
Return the account for the client (if registered).
- Return type:
Account or
None
- id¶
The components ID.
- Returns:
ComponentId
- is_connected¶
If the client is connected.
- Returns:
bool
- is_degraded¶
bool
Return whether the current component state is
DEGRADED.- Return type:
bool
- Type:
- is_disposed¶
bool
Return whether the current component state is
DISPOSED.- Return type:
bool
- Type:
- is_faulted¶
bool
Return whether the current component state is
FAULTED.- Return type:
bool
- Type:
- is_initialized¶
bool
Return whether the component has been initialized (component.state >=
INITIALIZED).- Return type:
bool
- Type:
- is_running¶
bool
Return whether the current component state is
RUNNING.- Return type:
bool
- Type:
- is_stopped¶
bool
Return whether the current component state is
STOPPED.- Return type:
bool
- Type:
- 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_account(self, QueryAccount command) void¶
Query the account specified by the command which will generate an AccountState event.
- Parameters:
command (QueryAccount) – The command to execute.
- 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
RESETTINGstate.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
RESUMINGstate.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.
- shutdown_system(self, str reason=None) void¶
Initiate a system-wide shutdown by generating and publishing a ShutdownSystem command.
The command is handled by the system’s NautilusKernel, which will invoke either stop (synchronously) or stop_async (asynchronously) depending on the execution context and the presence of an active event loop.
- Parameters:
reason (str, optional) – The reason for issuing the shutdown command.
- start(self) void¶
Start the component.
While executing on_start() any exception will be logged and reraised, then the component will remain in a
STARTINGstate.Warning
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
- state¶
ComponentState
Return the components current state.
- Return type:
ComponentState
- Type:
- stop(self) void¶
Stop the component.
While executing on_stop() any exception will be logged and reraised, then the component will remain in a
STOPPINGstate.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
- class OrderEmulator¶
Bases:
ActorOrderEmulator(PortfolioFacade portfolio, MessageBus msgbus, Cache cache, Clock clock, config: OrderEmulatorConfig | None = None)
Provides order emulation for specified trigger types.
- Parameters:
portfolio (PortfolioFacade) – The read-only portfolio for the order emulator.
msgbus (MessageBus) – The message bus for the order emulator.
cache (Cache) – The cache for the order emulator.
clock (Clock) – The clock for the order emulator.
config (OrderEmulatorConfig, optional) – The configuration for the order emulator.
- add_synthetic(self, SyntheticInstrument synthetic) void¶
Add the created synthetic instrument to the cache.
- Parameters:
synthetic (SyntheticInstrument) – The synthetic instrument to add to the cache.
- Raises:
KeyError – If synthetic is already in the cache.
Notes
If you are updating the synthetic instrument then you should use the update_synthetic method.
- cache¶
The read-only cache for the actor.
- Returns:
CacheFacade
- cancel_all_tasks(self) void¶
Cancel all queued and active tasks.
- cancel_task(self, task_id: TaskId) void¶
Cancel the task with the given task_id (if queued or active).
If the task is not found then a warning is logged.
- Parameters:
task_id (TaskId) – The task identifier.
- clock¶
The actors clock.
- Returns:
Clock
- command_count¶
The total count of commands received by the emulator.
- Returns:
int
- config¶
The actors configuration.
- Returns:
NautilusConfig
- create_matching_core(self, InstrumentId instrument_id, Price price_increment) MatchingCore¶
Create an internal matching core for the given instrument.
- Parameters:
instrument_id (InstrumentId) – The instrument ID for the matching core.
price_increment (Price) – The minimum price increment (tick size) for the matching core.
- Return type:
- Raises:
KeyError – If a matching core for the given instrument_id already exists.
- 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, then the component will remain in a
DEGRADINGstate.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_warning_event(self, type event) void¶
Deregister the given event type from warning log levels.
- Parameters:
event (type) – The event class to deregister.
- 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
DISPOSINGstate.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 emulator.
- Returns:
int
- execute(self, TradingCommand command) void¶
Execute the given command.
- Parameters:
command (TradingCommand) – The command to execute.
- 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
FAULTINGstate.Warning
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
- classmethod fully_qualified_name(cls) str¶
Return the fully qualified name for the components class.
- Return type:
str
References
- get_matching_core(self, InstrumentId instrument_id) MatchingCore | None¶
Return the emulators matching core for the given instrument ID.
- Return type:
MatchingCore or
None
- get_submit_order_commands(self) dict[ClientOrderId, SubmitOrder]¶
Return the emulators cached submit order commands.
- Return type:
dict[ClientOrderId, SubmitOrder]
- greeks¶
The read-only greeks calculator for the actor.
- Returns:
GreeksCalculator
- handle_bar(self, Bar bar, bool historical=False) void¶
Handle the given bar data.
If state is
RUNNINGthen passes to on_bar.- Parameters:
bar (Bar) – The bar received.
Warning
System method (not intended to be called by user code).
- handle_data(self, Data data) void¶
Handle the given data.
If state is
RUNNINGthen passes to on_data.- Parameters:
data (Data) – The data received.
Warning
System method (not intended to be called by user code).
- handle_event(self, Event event) void¶
Handle the given event.
If state is
RUNNINGthen passes to on_event.- Parameters:
event (Event) – The event received.
Warning
System method (not intended to be called by user code).
- handle_funding_rate(self, FundingRateUpdate funding_rate, bool historical=False) void¶
Handle the given funding rate update.
If state is
RUNNINGthen passes to on_funding_rate.- Parameters:
funding_rate (FundingRateUpdate) – The funding rate update received.
Warning
System method (not intended to be called by user code).
- handle_historical_bar(self, Bar bar) void¶
- handle_historical_data(self, data) void¶
Handle the given historical data.
- Parameters:
data (Data) – The historical data received.
Warning
System method (not intended to be called by user code).
- handle_historical_funding_rate(self, FundingRateUpdate funding_rate) void¶
- handle_historical_order_book_deltas(self, OrderBookDeltas deltas) void¶
- handle_historical_order_book_depth(self, OrderBookDepth10 depth) void¶
- handle_historical_quote_tick(self, QuoteTick tick) void¶
- handle_historical_trade_tick(self, TradeTick tick) void¶
- handle_index_price(self, IndexPriceUpdate index_price) void¶
Handle the given index price update.
If state is
RUNNINGthen passes to on_index_price.- Parameters:
index_price (IndexPriceUpdate) – The index price update received.
Warning
System method (not intended to be called by user code).
- handle_instrument(self, Instrument instrument) void¶
Handle the given instrument.
Passes to on_instrument if state is
RUNNING.- Parameters:
instrument (Instrument) – The instrument received.
Warning
System method (not intended to be called by user code).
- handle_instrument_close(self, InstrumentClose update) void¶
Handle the given instrument close update.
If state is
RUNNINGthen passes to on_instrument_close.- Parameters:
update (InstrumentClose) – The update received.
Warning
System method (not intended to be called by user code).
- handle_instrument_status(self, InstrumentStatus data) void¶
Handle the given instrument status update.
If state is
RUNNINGthen passes to on_instrument_status.- Parameters:
data (InstrumentStatus) – The status update received.
Warning
System method (not intended to be called by user code).
- handle_mark_price(self, MarkPriceUpdate mark_price) void¶
Handle the given mark price update.
If state is
RUNNINGthen passes to on_mark_price.- Parameters:
mark_price (MarkPriceUpdate) – The mark price update received.
Warning
System method (not intended to be called by user code).
- handle_order_book(self, OrderBook order_book) void¶
Handle the given order book.
Passes to on_order_book if state is
RUNNING.- Parameters:
order_book (OrderBook) – The order book received.
Warning
System method (not intended to be called by user code).
- handle_order_book_deltas(self, deltas, bool historical=False) void¶
Handle the given order book deltas.
Passes to on_order_book_deltas if state is
RUNNING. The deltas will be nautilus_pyo3.OrderBookDeltas if the pyo3_conversion flag was set for the subscription.- Parameters:
deltas (OrderBookDeltas or nautilus_pyo3.OrderBookDeltas) – The order book deltas received.
historical (bool, default False) – If True, treats the data as historical.
Warning
System method (not intended to be called by user code).
- handle_order_book_depth(self, OrderBookDepth10 depth, bool historical=False) void¶
Handle the given order book depth
Passes to on_order_book_depth if state is
RUNNING.- Parameters:
depth (OrderBookDepth10) – The order book depth received.
Warning
System method (not intended to be called by user code).
- handle_quote_tick(self, QuoteTick tick, bool historical=False) void¶
Handle the given quote tick.
If state is
RUNNINGthen passes to on_quote_tick.- Parameters:
tick (QuoteTick) – The tick received.
Warning
System method (not intended to be called by user code).
- handle_signal(self, Data signal) void¶
Handle the given signal.
If state is
RUNNINGthen passes to on_signal.- Parameters:
signal (Data) – The signal received.
Warning
System method (not intended to be called by user code).
- handle_trade_tick(self, TradeTick tick, bool historical=False) void¶
Handle the given trade tick.
If state is
RUNNINGthen passes to on_trade_tick.- Parameters:
tick (TradeTick) – The tick received.
Warning
System method (not intended to be called by user code).
- has_active_tasks(self) bool¶
Return a value indicating whether there are any active tasks.
- Return type:
bool
- has_any_tasks(self) bool¶
Return a value indicating whether there are any queued OR active tasks.
- Return type:
bool
- has_pending_requests(self) bool¶
Return whether the actor is pending processing for any requests.
- Returns:
True if any requests are pending, else False.
- Return type:
bool
- has_queued_tasks(self) bool¶
Return a value indicating whether there are any queued tasks.
- Return type:
bool
- id¶
The components ID.
- Returns:
ComponentId
- indicators_initialized(self) bool¶
Return a value indicating whether all indicators are initialized.
- Returns:
True if all initialized, else False
- Return type:
bool
- is_degraded¶
bool
Return whether the current component state is
DEGRADED.- Return type:
bool
- Type:
- is_disposed¶
bool
Return whether the current component state is
DISPOSED.- Return type:
bool
- Type:
- is_faulted¶
bool
Return whether the current component state is
FAULTED.- Return type:
bool
- Type:
- is_initialized¶
bool
Return whether the component has been initialized (component.state >=
INITIALIZED).- Return type:
bool
- Type:
- is_pending_request(self, UUID4 request_id) bool¶
Return whether the request for the given identifier is pending processing.
- Parameters:
request_id (UUID4) – The request ID to check.
- Returns:
True if request is pending, else False.
- Return type:
bool
- is_running¶
bool
Return whether the current component state is
RUNNING.- Return type:
bool
- Type:
- is_stopped¶
bool
Return whether the current component state is
STOPPED.- Return type:
bool
- Type:
- load(self, dict state) void¶
Load the actor/strategy state from the give state dictionary.
Calls on_load and passes the state.
- Parameters:
state (dict[str, bytes]) – The strategy state to load.
Warning
Exceptions raised will be caught, logged, and reraised.
- log¶
The actors logger.
- Returns:
Logger
- msgbus¶
The message bus for the actor (if registered).
- Returns:
MessageBus or
None
- on_bar(self, Bar bar) void¶
Actions to be performed when running and receives a bar.
- Parameters:
bar (Bar) – The bar received.
Warning
System method (not intended to be called by user code).
- on_data(self, data) void¶
Actions to be performed when running and receives data.
- Parameters:
data (Data) – The data received.
Warning
System method (not intended to be called by user code).
- on_degrade(self) void¶
Actions to be performed on degrade.
Warning
System method (not intended to be called by user code).
Should be overridden in the actor implementation.
- on_dispose(self) void¶
- on_event(self, Event event) void¶
Handle the given event.
- Parameters:
event (Event) – The received event to handle.
- on_fault(self) void¶
Actions to be performed on fault.
Cleanup any resources used by the actor here.
Warning
System method (not intended to be called by user code).
Should be overridden in the actor implementation.
- on_funding_rate(self, FundingRateUpdate funding_rate) void¶
Actions to be performed when running and receives a funding rate update.
- Parameters:
funding_rate (FundingRateUpdate) – The funding rate update received.
Warning
System method (not intended to be called by user code).
- on_historical_data(self, data) void¶
Actions to be performed when running and receives historical data.
- Parameters:
data (Data) – The historical data received.
Warning
System method (not intended to be called by user code).
- on_index_price(self, IndexPriceUpdate index_price) void¶
Actions to be performed when running and receives an index price update.
- Parameters:
index_price (IndexPriceUpdate) – The index price update received.
Warning
System method (not intended to be called by user code).
- on_instrument(self, Instrument instrument) void¶
Actions to be performed when running and receives an instrument.
- Parameters:
instrument (Instrument) – The instrument received.
Warning
System method (not intended to be called by user code).
- on_instrument_close(self, InstrumentClose update) void¶
Actions to be performed when running and receives an instrument close update.
- Parameters:
update (InstrumentClose) – The instrument close received.
Warning
System method (not intended to be called by user code).
- on_instrument_status(self, InstrumentStatus data) void¶
Actions to be performed when running and receives an instrument status update.
- Parameters:
data (InstrumentStatus) – The instrument status update received.
Warning
System method (not intended to be called by user code).
- on_load(self, dict state) void¶
Actions to be performed when the actor state is loaded.
Saved state values will be contained in the give state dictionary.
- Parameters:
state (dict[str, bytes]) – The strategy state to load.
Warning
System method (not intended to be called by user code).
- on_mark_price(self, MarkPriceUpdate mark_price) void¶
Actions to be performed when running and receives a mark price update.
- Parameters:
mark_price (MarkPriceUpdate) – The mark price update received.
Warning
System method (not intended to be called by user code).
- on_order_book(self, OrderBook order_book) void¶
Actions to be performed when running and receives an order book.
- Parameters:
order_book (OrderBook) – The order book received.
Warning
System method (not intended to be called by user code).
- on_order_book_deltas(self, deltas) void¶
- on_order_book_depth(self, depth) void¶
Actions to be performed when running and receives an order book depth.
- Parameters:
depth (OrderBookDepth10) – The order book depth received.
Warning
System method (not intended to be called by user code).
- on_order_canceled(self, OrderCanceled event) void¶
Actions to be performed when running and receives an order canceled event.
- Parameters:
event (OrderCanceled) – The event received.
Warning
System method (not intended to be called by user code).
- on_order_filled(self, OrderFilled event) void¶
Actions to be performed when running and receives an order filled event.
- Parameters:
event (OrderFilled) – The event received.
Warning
System method (not intended to be called by user code).
- on_quote_tick(self, QuoteTick tick) void¶
- on_reset(self) void¶
- on_resume(self) void¶
Actions to be performed on resume.
Warning
System method (not intended to be called by user code).
- on_save(self) dict¶
Actions to be performed when the actor state is saved.
Create and return a state dictionary of values to be saved.
- Returns:
The strategy state to save.
- Return type:
dict[str, bytes]
Warning
System method (not intended to be called by user code).
- on_signal(self, signal) void¶
Actions to be performed when running and receives signal data.
- Parameters:
signal (Data) – The signal received.
Warning
System method (not intended to be called by user code).
Notes
This refers to a data signal, not an operating system signal (such as SIGTERM, SIGKILL, etc.).
- on_start(self) void¶
- on_stop(self) void¶
- on_trade_tick(self, TradeTick tick) void¶
- pending_requests(self) set¶
Return the request IDs which are currently pending processing.
- Return type:
set[UUID4]
- portfolio¶
The read-only portfolio for the actor.
- Returns:
PortfolioFacade
- publish_data(self, DataType data_type, Data data) void¶
Publish the given data to the message bus.
- publish_signal(self, str name, value, uint64_t ts_event=0) void¶
Publish the given value as a signal to the message bus.
- Parameters:
name (str) – The name of the signal being published. The signal name will be converted to title case, with each word capitalized (e.g., ‘example’ becomes ‘SignalExample’).
value (object) – The signal data to publish.
ts_event (uint64_t, optional) – UNIX timestamp (nanoseconds) when the signal event occurred. If
Nonethen will timestamp current time.
- queue_for_executor(self, func: Callable[..., Any], tuple args=None, dict kwargs=None)¶
Queues the callable func to be executed as fn(*args, **kwargs) sequentially.
- Parameters:
func (Callable) – The function to be executed.
args (positional arguments) – The positional arguments for the call to func.
kwargs (arbitrary keyword arguments) – The keyword arguments for the call to func.
- Raises:
TypeError – If func is not of type Callable.
Notes
For backtesting the func is immediately executed, as there’s no need for a Future object that can be awaited. In a backtesting scenario, the execution is not in real time, and so the results of func are ‘immediately’ available after it’s called.
- register_base(self, PortfolioFacade portfolio, MessageBus msgbus, CacheFacade cache, Clock clock) void¶
Register with a trader.
- Parameters:
portfolio (PortfolioFacade) – The read-only portfolio for the actor.
msgbus (MessageBus) – The message bus for the actor.
cache (CacheFacade) – The read-only cache for the actor.
clock (Clock) – The clock for the actor.
Warning
System method (not intended to be called by user code).
- register_executor(self, loop: asyncio.AbstractEventLoop, executor: Executor) void¶
Register the given Executor for the actor.
- Parameters:
loop (asyncio.AbstractEventLoop) – The event loop of the application.
executor (concurrent.futures.Executor) – The executor to register.
- Raises:
TypeError – If executor is not of type concurrent.futures.Executor
- register_indicator_for_bars(self, BarType bar_type, Indicator indicator) void¶
Register the given indicator with the actor/strategy to receive bar data for the given bar type.
- register_indicator_for_quote_ticks(self, InstrumentId instrument_id, Indicator indicator) void¶
Register the given indicator with the actor/strategy to receive quote tick data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The instrument ID for tick updates.
indicator (Indicator) – The indicator to register.
- register_indicator_for_trade_ticks(self, InstrumentId instrument_id, Indicator indicator) void¶
Register the given indicator with the actor/strategy to receive trade tick data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The instrument ID for tick updates.
indicator (indicator) – The indicator to register.
- register_warning_event(self, type event) void¶
Register the given event type for warning log levels.
- Parameters:
event (type) – The event class to register.
- registered_indicators¶
Return the registered indicators for the strategy.
- Return type:
list[Indicator]
- request_aggregated_bars(self, list bar_types, datetime start, datetime end=None, int limit=0, ClientId client_id=None, callback: Callable[[UUID4], None] | None = None, bool include_external_data=False, bool update_subscriptions=False, bool update_catalog=False, bool aggregate_spread_quotes=False, UUID4 request_id=None, dict params=None) UUID4¶
Request historical aggregated Bar data for multiple bar types. The first bar is used to determine which market data type will be queried. This can either be quotes, trades or bars. If bars are queried, the first bar type needs to have a composite bar that is external (i.e. not internal/aggregated). This external bar type will be queried.
If end is
Nonethen will request up to the most recent data.Once the response is received, the bar data is forwarded from the message bus to the on_historical_data handler. Any tick data used for aggregation is also forwarded to the on_historical_data handler.
If the request fails, then an error is logged.
- Parameters:
bar_types (list[BarType]) – The list of bar types for the request. Composite bars can also be used and need to figure in the list after a BarType on which it depends.
start (datetime) – The start datetime (UTC) of request time range. Should be left-inclusive (start <= value), but inclusiveness is not currently guaranteed.
end (datetime, optional) – The end datetime (UTC) of request time range. If None then will be replaced with the current UTC time. Should be right-inclusive (value <= end), but inclusiveness is not currently guaranteed.
limit (int, optional) – The limit on the amount of data received (quote ticks, trade ticks or bars).
client_id (ClientId, optional) – The specific client ID for the command. If
Nonethen will be inferred from the venue in the instrument ID.callback (Callable[[UUID4], None], optional) – The registered callback, to be called with the request ID when the response has completed processing.
include_external_data (bool, default False) – If True, includes the queried external data in the response.
update_subscriptions (bool, default False) – If True, persists the aggregator of each bar_type so it’s up to date for a subsequent market data subscription.
update_catalog (bool, default False) – Whether to update a catalog with the received data.
aggregate_spread_quotes (bool, default False) – Whether to activate a spread quote aggregator from leg quotes. Only applicable when requesting quote ticks for spread instruments.
request_id (UUID4, optional) – The UUID to use for the request ID. If None, a new UUID will be generated.
params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- Returns:
The request_id for the request.
- Return type:
- Raises:
TypeError – If start is None.
ValueError – If start is > current timestamp (now).
ValueError – If end is > current timestamp (now).
ValueError – If start is > end.
ValueError – If bar_types is empty.
TypeError – If callback is not None and not of type Callable.
TypeError – If bar_types is empty or contains elements not of type BarType.
Notes
Make sure no subscription is active for the same underlying market data as the requested bar types.
A subscription can follow request_aggregated_bars and use an up to date aggregator when using the update_subscriptions parameter.
Subscribe to market data as a callback to request_aggregated_bars.
- request_bars(self, BarType bar_type, datetime start, datetime end=None, int limit=0, ClientId client_id=None, callback: Callable[[UUID4], None] | None = None, bool update_catalog=False, bool join_request=False, UUID4 request_id=None, dict params=None) UUID4¶
Request historical Bar data.
If end is
Nonethen will request up to the most recent data.Once the response is received, the bar data is forwarded from the message bus to the on_historical_data handler.
If the request fails, then an error is logged.
- Parameters:
bar_type (BarType) – The bar type for the request.
start (datetime) – The start datetime (UTC) of request time range. Should be left-inclusive (start <= value), but inclusiveness is not currently guaranteed.
end (datetime, optional) – The end datetime (UTC) of request time range. If None then will be replaced with the current UTC time. Should be right-inclusive (value <= end), but inclusiveness is not currently guaranteed.
limit (int, optional) – The limit on the amount of bars received.
client_id (ClientId, optional) – The specific client ID for the command. If
Nonethen will be inferred from the venue in the instrument ID.callback (Callable[[UUID4], None], optional) – The registered callback, to be called with the request ID when the response has completed processing.
update_catalog (bool, default False) – Whether to update a catalog with the received data.
join_request (bool, optional, default to False) – If a request should be joined and sorted with another one by using request_join.
request_id (UUID4, optional) – The UUID to use for the request ID. If None, a new UUID will be generated.
params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- Returns:
The request_id for the request.
- Return type:
- Raises:
TypeError – If start is None.
ValueError – If start is > current timestamp (now).
ValueError – If end is > current timestamp (now).
ValueError – If start is > end.
TypeError – If callback is not None and not of type Callable.
- request_data(self, DataType data_type, ClientId client_id, InstrumentId instrument_id=None, datetime start=None, datetime end=None, int limit=0, callback: Callable[[UUID4], None] | None = None, bool update_catalog=False, bool join_request=False, UUID4 request_id=None, dict params=None) UUID4¶
Request custom data for the given data type from the given data client.
Once the response is received, the data is forwarded from the message bus to the on_historical_data handler.
If the request fails, then an error is logged.
- Parameters:
data_type (DataType) – The data type for the request.
client_id (ClientId) – The data client ID.
start (datetime) – The start datetime (UTC) of request time range. Cannot be None. Should be left-inclusive (start <= value), but inclusiveness is not currently guaranteed.
end (datetime, optional) – The end datetime (UTC) of request time range. If None then will be replaced with the current UTC time. Should be right-inclusive (value <= end), but inclusiveness is not currently guaranteed.
limit (int, optional) – The limit on the amount of data points received.
callback (Callable[[UUID4], None], optional) – The registered callback, to be called with the request ID when the response has completed processing.
update_catalog (bool, default False) – Whether to update a catalog with the received data.
join_request (bool, optional, default to False) – If a request should be joined and sorted with another one by using request_join.
request_id (UUID4, optional) – The UUID to use for the request ID. If None, a new UUID will be generated.
params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- Returns:
The request_id for the request.
- Return type:
- Raises:
TypeError – If start is None.
ValueError – If start is > current timestamp (now).
ValueError – If end is > current timestamp (now).
ValueError – If start is > end.
TypeError – If callback is not None and not of type Callable.
- request_funding_rates(self, InstrumentId instrument_id, datetime start, datetime end=None, int limit=0, ClientId client_id=None, callback: Callable[[UUID4], None] | None = None, bool update_catalog=False, bool join_request=False, UUID4 request_id=None, dict params=None) UUID4¶
Request historical FundingRateUpdate data.
If end is
Nonethen will request up to the most recent data.Once the response is received, the funding rate data is forwarded from the message bus to the on_historical_data handler.
If the request fails, then an error is logged.
- Parameters:
instrument_id (InstrumentId) – The instrument ID for the request.
start (datetime) – The start datetime (UTC) of request time range. Should be left-inclusive (start <= value), but inclusiveness is not currently guaranteed.
end (datetime, optional) – The end datetime (UTC) of request time range. If None then will be replaced with the current UTC time. Should be right-inclusive (value <= end), but inclusiveness is not currently guaranteed.
limit (int, optional) – The limit on the amount of funding rates received.
client_id (ClientId, optional) – The specific client ID for the command. If
Nonethen will be inferred from the venue in the instrument ID.callback (Callable[[UUID4], None], optional) – The registered callback, to be called with the request ID when the response has completed processing.
update_catalog (bool, default False) – Whether to update a catalog with the received data.
join_request (bool, optional, default to False) – If a request should be joined and sorted with another one by using request_join.
request_id (UUID4, optional) – The UUID to use for the request ID. If None, a new UUID will be generated.
params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- Returns:
The request_id for the request.
- Return type:
- Raises:
TypeError – If start is None.
ValueError – If start is > current timestamp (now).
ValueError – If end is > current timestamp (now).
ValueError – If start is > end.
TypeError – If callback is not None and not of type Callable.
- request_instrument(self, InstrumentId instrument_id, datetime start=None, datetime end=None, ClientId client_id=None, callback: Callable[[UUID4], None] | None = None, bool update_catalog=False, bool join_request=False, UUID4 request_id=None, dict params=None) UUID4¶
Request Instrument data for the given instrument ID.
If end is
Nonethen will request up to the most recent data.Once the response is received, the instrument data is forwarded from the message bus to the on_instrument handler.
If the request fails, then an error is logged.
- Parameters:
instrument_id (InstrumentId) – The instrument ID for the request.
start (datetime, optional) – The start datetime (UTC) of request time range. The inclusiveness depends on individual data client implementation.
end (datetime, optional) – The end datetime (UTC) of request time range. The inclusiveness depends on individual data client implementation.
client_id (ClientId, optional) – The specific client ID for the command. If
Nonethen will be inferred from the venue in the instrument ID.callback (Callable[[UUID4], None], optional) – The registered callback, to be called with the request ID when the response has completed processing.
update_catalog (bool, default False) – Whether to update a catalog with the received data.
join_request (bool, optional, default to False) – If a request should be joined and sorted with another one by using request_join.
request_id (UUID4, optional) – The UUID to use for the request ID. If None, a new UUID will be generated.
params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- Returns:
The request_id for the request.
- Return type:
- Raises:
ValueError – If start is not None and > current timestamp (now).
ValueError – If end is not None and > current timestamp (now).
ValueError – If start and end are not None and start is >= end.
TypeError – If callback is not None and not of type Callable.
- request_instruments(self, Venue venue, datetime start=None, datetime end=None, ClientId client_id=None, callback: Callable[[UUID4], None] | None = None, bool update_catalog=False, bool join_request=False, UUID4 request_id=None, dict params=None) UUID4¶
Request all Instrument data for the given venue.
If end is
Nonethen will request up to the most recent data.Once the response is received, the instrument data is forwarded from the message bus to the on_instrument handler.
If the request fails, then an error is logged.
- Parameters:
venue (Venue) – The venue for the request.
start (datetime, optional) – The start datetime (UTC) of request time range. The inclusiveness depends on individual data client implementation.
end (datetime, optional) – The end datetime (UTC) of request time range. The inclusiveness depends on individual data client implementation.
client_id (ClientId, optional) – The specific client ID for the command. If
Nonethen will be inferred from the venue in the instrument ID.callback (Callable[[UUID4], None], optional) – The registered callback, to be called with the request ID when the response has completed processing.
update_catalog (bool, default False) – Whether to update a catalog with the received data.
join_request (bool, optional, default to False) – If a request should be joined and sorted with another one by using request_join.
request_id (UUID4, optional) – The UUID to use for the request ID. If None, a new UUID will be generated.
params (dict[str, Any], optional) – Additional parameters potentially used by a specific client: - only_last (default True) retains only the latest instrument record per instrument_id, based on the most recent ts_init.
- Returns:
The request_id for the request.
- Return type:
- Raises:
ValueError – If start is not None and > current timestamp (now).
ValueError – If end is not None and > current timestamp (now).
ValueError – If start and end are not None and start is >= end.
TypeError – If callback is not None and not of type Callable.
- request_join(self, tuple request_ids, datetime start, datetime end=None, ClientId client_id=None, Venue venue=None, callback: Callable[[UUID4], None] | None = None, UUID4 request_id=None, dict params=None) UUID4¶
Request a join of multiple data requests.
This method creates a RequestJoin message that will coordinate multiple sub-requests and combine their results.
- Parameters:
request_ids (tuple[UUID4]) – The tuple of request IDs to join.
start (datetime) – The start datetime (UTC) of request time range (inclusive).
end (datetime, optional) – The end datetime (UTC) of request time range. If None then will be replaced with the current UTC time.
client_id (ClientId, optional) – The data client ID for the request.
venue (Venue, optional) – The venue for the request.
callback (Callable[[UUID4], None], optional) – The registered callback, to be called with the request ID when the response has completed processing.
request_id (UUID4, optional) – The UUID to use for the request ID. If None, a new UUID will be generated.
params (dict[str, Any], optional) – Additional parameters for the request.
- Returns:
The request_id for the request.
- Return type:
- Raises:
ValueError – If both client_id and venue are both
None(not enough routing info).TypeError – If callback is not None and not of type Callable.
- request_order_book_deltas(self, InstrumentId instrument_id, datetime start, datetime end=None, int limit=0, ClientId client_id=None, callback: Callable[[UUID4], None] | None = None, bool update_catalog=False, bool join_request=False, UUID4 request_id=None, dict params=None) UUID4¶
Request historical OrderBookDeltas data.
Once the response is received, the order book deltas data is forwarded from the message bus to the on_historical_data handler.
If the request fails, then an error is logged.
- Parameters:
instrument_id (InstrumentId) – The instrument ID for the order book deltas request.
start (datetime) – 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.
limit (int, optional) – The limit on the amount of deltas received.
client_id (ClientId, optional) – The specific client ID for the command. If None, it will be inferred from the venue in the instrument ID.
callback (Callable[[UUID4], None], optional) – The registered callback, to be called with the request ID when the response has completed processing.
update_catalog (bool, default False) – If the data catalog should be updated with the received data.
join_request (bool, optional, default to False) – If a request should be joined and sorted with another one by using request_join.
request_id (UUID4, optional) – The UUID to use for the request ID. If None, a new UUID will be generated.
params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- Returns:
The request_id for the request.
- Return type:
- Raises:
ValueError – If the instrument_id is None.
TypeError – If callback is not None and not of type Callable.
- request_order_book_depth(self, InstrumentId instrument_id, datetime start, datetime end=None, int limit=0, int depth=10, ClientId client_id=None, callback: Callable[[UUID4], None] | None = None, bool update_catalog=False, bool join_request=False, UUID4 request_id=None, dict params=None) UUID4¶
Request historical OrderBookDepth10 snapshots.
Once the response is received, the order book depth data is forwarded from the message bus to the on_historical_data handler.
If the request fails, then an error is logged.
- Parameters:
instrument_id (InstrumentId) – The instrument ID for the order book depths request.
start (datetime) – 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.
limit (int, optional) – The limit on the amount of depth snapshots received.
depth (int, optional) – The maximum depth for the returned order book data (default is 10).
client_id (ClientId, optional) – The specific client ID for the command. If None, it will be inferred from the venue in the instrument ID.
callback (Callable[[UUID4], None], optional) – The registered callback, to be called with the request ID when the response has completed processing.
update_catalog (bool, default False) – If the data catalog should be updated with the received data.
join_request (bool, optional, default to False) – If a request should be joined and sorted with another one by using request_join.
request_id (UUID4, optional) – The UUID to use for the request ID. If None, a new UUID will be generated.
params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- Returns:
The request_id for the request.
- Return type:
- Raises:
ValueError – If the instrument_id is None.
TypeError – If callback is not None and not of type Callable.
- request_order_book_snapshot(self, InstrumentId instrument_id, int limit=0, ClientId client_id=None, callback: Callable[[UUID4], None] | None = None, bool join_request=False, UUID4 request_id=None, dict params=None) UUID4¶
Request an order book snapshot.
Once the response is received, the order book data is forwarded from the message bus to the on_historical_data handler.
If the request fails, then an error is logged.
- Parameters:
instrument_id (InstrumentId) – The instrument ID for the order book snapshot request.
limit (int, optional) – The limit on the depth of the order book snapshot.
client_id (ClientId, optional) – The specific client ID for the command. If None, it will be inferred from the venue in the instrument ID.
callback (Callable[[UUID4], None], optional) – The registered callback, to be called with the request ID when the response has completed processing.
join_request (bool, optional, default to False) – If a request should be joined and sorted with another one by using request_join.
request_id (UUID4, optional) – The UUID to use for the request ID. If None, a new UUID will be generated.
params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- Returns:
The request_id for the request.
- Return type:
- Raises:
ValueError – If the instrument_id is None.
TypeError – If callback is not None and not of type Callable.
- request_quote_ticks(self, InstrumentId instrument_id, datetime start, datetime end=None, int limit=0, ClientId client_id=None, callback: Callable[[UUID4], None] | None = None, bool update_catalog=False, bool aggregate_spread_quotes=False, bool join_request=False, UUID4 request_id=None, dict params=None) UUID4¶
Request historical QuoteTick data.
If end is
Nonethen will request up to the most recent data.Once the response is received, the quote tick data is forwarded from the message bus to the on_historical_data handler.
If the request fails, then an error is logged.
- Parameters:
instrument_id (InstrumentId) – The tick instrument ID for the request.
start (datetime) – The start datetime (UTC) of request time range. Should be left-inclusive (start <= value), but inclusiveness is not currently guaranteed.
end (datetime, optional) – The end datetime (UTC) of request time range. If None then will be replaced with the current UTC time. Should be right-inclusive (value <= end), but inclusiveness is not currently guaranteed.
limit (int, optional) – The limit on the amount of quote ticks received.
client_id (ClientId, optional) – The specific client ID for the command. If
Nonethen will be inferred from the venue in the instrument ID.callback (Callable[[UUID4], None], optional) – The registered callback, to be called with the request ID when the response has completed processing.
update_catalog (bool, default False) – Whether to update a catalog with the received data.
aggregate_spread_quotes (bool, default False) – Whether to activate a spread quote aggregator from leg quotes. Only applicable when the instrument_id is a spread instrument.
join_request (bool, optional, default to False) – If a request should be joined and sorted with another one by using request_join.
request_id (UUID4, optional) – The UUID to use for the request ID. If None, a new UUID will be generated.
params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- Returns:
The request_id for the request.
- Return type:
- Raises:
TypeError – If start is None.
ValueError – If start is > current timestamp (now).
ValueError – If end is > current timestamp (now).
ValueError – If start is > end.
TypeError – If callback is not None and not of type Callable.
- request_trade_ticks(self, InstrumentId instrument_id, datetime start, datetime end=None, int limit=0, ClientId client_id=None, callback: Callable[[UUID4], None] | None = None, bool update_catalog=False, bool join_request=False, UUID4 request_id=None, dict params=None) UUID4¶
Request historical TradeTick data.
If end is
Nonethen will request up to the most recent data.Once the response is received, the trade tick data is forwarded from the message bus to the on_historical_data handler.
If the request fails, then an error is logged.
- Parameters:
instrument_id (InstrumentId) – The tick instrument ID for the request.
start (datetime) – The start datetime (UTC) of request time range. Should be left-inclusive (start <= value), but inclusiveness is not currently guaranteed.
end (datetime, optional) – The end datetime (UTC) of request time range. If None then will be replaced with the current UTC time. Should be right-inclusive (value <= end), but inclusiveness is not currently guaranteed.
limit (int, optional) – The limit on the amount of trade ticks received.
client_id (ClientId, optional) – The specific client ID for the command. If
Nonethen will be inferred from the venue in the instrument ID.callback (Callable[[UUID4], None], optional) – The registered callback, to be called with the request ID when the response has completed processing.
update_catalog (bool, default False) – Whether to update a catalog with the received data.
join_request (bool, optional, default to False) – If a request should be joined and sorted with another one by using request_join.
request_id (UUID4, optional) – The UUID to use for the request ID. If None, a new UUID will be generated.
params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- Returns:
The request_id for the request.
- Return type:
- Raises:
TypeError – If start is None.
ValueError – If start is > current timestamp (now).
ValueError – If end is > current timestamp (now).
ValueError – If start is > end.
TypeError – If callback is not None and not of type Callable.
- 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
RESETTINGstate.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
RESUMINGstate.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_in_executor(self, func: Callable[..., Any], tuple args=None, dict kwargs=None)¶
Schedules the callable func to be executed as fn(*args, **kwargs).
- Parameters:
func (Callable) – The function to be executed.
args (positional arguments) – The positional arguments for the call to func.
kwargs (arbitrary keyword arguments) – The keyword arguments for the call to func.
- Returns:
The unique task identifier for the execution. This also corresponds to any future objects memory address.
- Return type:
- Raises:
TypeError – If func is not of type Callable.
Notes
For backtesting the func is immediately executed, as there’s no need for a Future object that can be awaited. In a backtesting scenario, the execution is not in real time, and so the results of func are ‘immediately’ available after it’s called.
- save(self) dict¶
Return the actor/strategy state dictionary to be saved.
Calls on_save.
- Returns:
The strategy state to save.
- Return type:
dict[str, bytes]
Warning
Exceptions raised will be caught, logged, and reraised.
- shutdown_system(self, str reason=None) void¶
Initiate a system-wide shutdown by generating and publishing a ShutdownSystem command.
The command is handled by the system’s NautilusKernel, which will invoke either stop (synchronously) or stop_async (asynchronously) depending on the execution context and the presence of an active event loop.
- Parameters:
reason (str, optional) – The reason for issuing the shutdown command.
- start(self) void¶
Start the component.
While executing on_start() any exception will be logged and reraised, then the component will remain in a
STARTINGstate.Warning
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
- state¶
ComponentState
Return the components current state.
- Return type:
ComponentState
- Type:
- stop(self) void¶
Stop the component.
While executing on_stop() any exception will be logged and reraised, then the component will remain in a
STOPPINGstate.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_bars(self, BarType bar_type, ClientId client_id=None, bool update_catalog=False, dict params=None) void¶
Subscribe to streaming Bar data for the given bar type.
Once subscribed, any matching bar data published on the message bus is forwarded to the on_bar handler.
- Parameters:
bar_type (BarType) – The bar type to subscribe to.
client_id (ClientId, optional) – The specific client ID for the command. If
Nonethen will be inferred from the venue in the instrument ID.update_catalog (bool, default False) – Whether to update a catalog with the received data. Only useful when downloading data during a backtest.
params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- subscribe_data(self, DataType data_type, ClientId client_id=None, InstrumentId instrument_id=None, bool update_catalog=False, dict params=None) void¶
Subscribe to data of the given data type.
Once subscribed, any matching data published on the message bus is forwarded to the on_data handler.
- Parameters:
data_type (DataType) – The data type to subscribe to.
client_id (ClientId, optional) – The data client ID. If supplied then a Subscribe command will be sent to the corresponding data client.
update_catalog (bool, default False) – Whether to update a catalog with the received data. Only useful when downloading data during a backtest.
params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- subscribe_funding_rates(self, InstrumentId instrument_id, ClientId client_id=None, dict params=None) void¶
Subscribe to streaming FundingRateUpdate data for the given instrument ID.
Once subscribed, any matching funding rate updates published on the message bus are forwarded to the on_funding_rate handler.
- Parameters:
instrument_id (InstrumentId) – The instrument to subscribe to.
client_id (ClientId, optional) – The specific client ID for the command. If
Nonethen will be inferred from the venue in the instrument ID.params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- subscribe_index_prices(self, InstrumentId instrument_id, ClientId client_id=None, dict params=None) void¶
Subscribe to streaming IndexPriceUpdate data for the given instrument ID.
Once subscribed, any matching index price updates published on the message bus are forwarded to the on_index_price handler.
- Parameters:
instrument_id (InstrumentId) – The instrument to subscribe to.
client_id (ClientId, optional) – The specific client ID for the command. If
Nonethen will be inferred from the venue in the instrument ID.params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- subscribe_instrument(self, InstrumentId instrument_id, ClientId client_id=None, bool update_catalog=False, dict params=None) void¶
Subscribe to update Instrument data for the given instrument ID.
Once subscribed, any matching instrument data published on the message bus is forwarded to the on_instrument handler.
- Parameters:
instrument_id (InstrumentId) – The instrument ID for the subscription.
client_id (ClientId, optional) – The specific client ID for the command. If
Nonethen will be inferred from the venue in the instrument ID.update_catalog (bool, default False) – Whether to update a catalog with the received data. Only useful when downloading data during a backtest.
params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- subscribe_instrument_close(self, InstrumentId instrument_id, ClientId client_id=None, dict params=None) void¶
Subscribe to close updates for the given instrument ID.
Once subscribed, any matching instrument close data published on the message bus is forwarded to the on_instrument_close handler.
- Parameters:
instrument_id (InstrumentId) – The instrument to subscribe to status updates for.
client_id (ClientId, optional) – The specific client ID for the command. If
Nonethen will be inferred from the venue in the instrument ID.params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- subscribe_instrument_status(self, InstrumentId instrument_id, ClientId client_id=None, dict params=None) void¶
Subscribe to status updates for the given instrument ID.
Once subscribed, any matching instrument status data published on the message bus is forwarded to the on_instrument_status handler.
- Parameters:
instrument_id (InstrumentId) – The instrument to subscribe to status updates for.
client_id (ClientId, optional) – The specific client ID for the command. If
Nonethen will be inferred from the venue in the instrument ID.params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- subscribe_instruments(self, Venue venue, ClientId client_id=None, bool update_catalog=False, dict params=None) void¶
Subscribe to update Instrument data for the given venue.
Once subscribed, any matching instrument data published on the message bus is forwarded the on_instrument handler.
- Parameters:
venue (Venue) – The venue for the subscription.
client_id (ClientId, optional) – The specific client ID for the command. If
Nonethen will be inferred from the venue.update_catalog (bool, default False) – Whether to update a catalog with the received data. Only useful when downloading data during a backtest.
params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- subscribe_mark_prices(self, InstrumentId instrument_id, ClientId client_id=None, dict params=None) void¶
Subscribe to streaming MarkPriceUpdate data for the given instrument ID.
Once subscribed, any matching mark price updates published on the message bus are forwarded to the on_mark_price handler.
- Parameters:
instrument_id (InstrumentId) – The instrument to subscribe to.
client_id (ClientId, optional) – The specific client ID for the command. If
Nonethen will be inferred from the venue in the instrument ID.params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- subscribe_order_book_at_interval(self, InstrumentId instrument_id, BookType book_type=BookType.L2_MBP, int depth=0, int interval_ms=1000, ClientId client_id=None, dict params=None) void¶
Subscribe to an OrderBook at a specified interval for the given instrument ID.
Once subscribed, any matching order book updates published on the message bus are forwarded to the on_order_book handler.
The DataEngine will only maintain one order book for each instrument. Because of this - the level, depth and params for the stream will be set as per the last subscription request (this will also affect all subscribers).
- Parameters:
instrument_id (InstrumentId) – The order book instrument ID to subscribe to.
book_type (BookType {
L1_MBP,L2_MBP,L3_MBO}) – The order book type.depth (int, optional) – The maximum depth for the order book. A depth of 0 is maximum depth.
interval_ms (int, default 1000) – The order book snapshot interval (milliseconds).
client_id (ClientId, optional) – The specific client ID for the command. If
Nonethen will be inferred from the venue in the instrument ID.params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- Raises:
ValueError – If depth is negative (< 0).
ValueError – If interval_ms is not positive (> 0).
Warning
Consider subscribing to order book deltas if you need intervals less than 100 milliseconds.
- subscribe_order_book_deltas(self, InstrumentId instrument_id, BookType book_type=BookType.L2_MBP, int depth=0, ClientId client_id=None, bool managed=True, bool pyo3_conversion=False, dict params=None) void¶
Subscribe to the order book data stream, being a snapshot then deltas for the given instrument ID.
Once subscribed, any matching order book data published on the message bus is forwarded to the on_order_book_deltas handler.
- Parameters:
instrument_id (InstrumentId) – The order book instrument ID to subscribe to.
book_type (BookType {
L1_MBP,L2_MBP,L3_MBO}) – The order book type.depth (int, optional) – The maximum depth for the order book. A depth of 0 is maximum depth.
client_id (ClientId, optional) – The specific client ID for the command. If
Nonethen will be inferred from the venue in the instrument ID.managed (bool, default True) – If an order book should be managed by the data engine based on the subscribed feed.
pyo3_conversion (bool, default False) – If received deltas should be converted to nautilus_pyo3.OrderBookDeltas prior to being passed to the on_order_book_deltas handler.
params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- subscribe_order_book_depth(self, InstrumentId instrument_id, BookType book_type=BookType.L2_MBP, int depth=0, ClientId client_id=None, bool managed=True, bool pyo3_conversion=False, bool update_catalog=False, dict params=None) void¶
Subscribe to the order book depth stream for the given instrument ID.
Once subscribed, any matching order book data published on the message bus is forwarded to the on_order_book_depth handler.
- Parameters:
instrument_id (InstrumentId) – The order book instrument ID to subscribe to.
book_type (BookType {
L1_MBP,L2_MBP,L3_MBO}) – The order book type.client_id (ClientId, optional) – The specific client ID for the command. If
Nonethen will be inferred from the venue in the instrument ID.managed (bool, default True) – If an order book should be managed by the data engine based on the subscribed feed.
pyo3_conversion (bool, default False) – If received deltas should be converted to nautilus_pyo3.OrderBookDepth prior to being passed to the on_order_book_depth handler.
update_catalog (bool, default False) – Whether to update a catalog with the received data. Only useful when downloading data during a backtest.
params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- subscribe_order_cancels(self, InstrumentId instrument_id) void¶
Subscribe to all order cancels for the given instrument ID.
Once subscribed, any matching order cancels published on the message bus are forwarded to the on_order_canceled handler.
- Parameters:
instrument_id (InstrumentId) – The instrument to subscribe to cancels for.
- subscribe_order_fills(self, InstrumentId instrument_id) void¶
Subscribe to all order fills for the given instrument ID.
Once subscribed, any matching order fills published on the message bus are forwarded to the on_order_filled handler.
- Parameters:
instrument_id (InstrumentId) – The instrument to subscribe to fills for.
- subscribe_quote_ticks(self, InstrumentId instrument_id, ClientId client_id=None, bool update_catalog=False, bool aggregate_spread_quotes=False, dict params=None) void¶
Subscribe to streaming QuoteTick data for the given instrument ID.
Once subscribed, any matching quote tick data published on the message bus is forwarded to the on_quote_tick handler.
- Parameters:
instrument_id (InstrumentId) – The tick instrument to subscribe to.
client_id (ClientId, optional) – The specific client ID for the command. If
Nonethen will be inferred from the venue in the instrument ID.update_catalog (bool, default False) – Whether to update a catalog with the received data. Only useful when downloading data during a backtest.
aggregate_spread_quotes (bool, default False) – Whether to activate a spread quote aggregator from leg quotes. Only applicable when the instrument_id is a spread instrument.
params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- subscribe_signal(self, str name='') void¶
Subscribe to a specific signal by name, or to all signals if no name is provided.
Once subscribed, any matching signal data published on the message bus is forwarded to the on_signal handler.
- Parameters:
name (str, optional) – The name of the signal to subscribe to. If not provided or an empty string is passed, the subscription will include all signals. The signal name is case-insensitive and will be capitalized (e.g., ‘example’ becomes ‘SignalExample*’).
- subscribe_trade_ticks(self, InstrumentId instrument_id, ClientId client_id=None, bool update_catalog=False, dict params=None) void¶
Subscribe to streaming TradeTick data for the given instrument ID.
Once subscribed, any matching trade tick data published on the message bus is forwarded to the on_trade_tick handler.
- Parameters:
instrument_id (InstrumentId) – The tick instrument to subscribe to.
client_id (ClientId, optional) – The specific client ID for the command. If
Nonethen will be inferred from the venue in the instrument ID.update_catalog (bool, default False) – Whether to update a catalog with the received data. Only useful when downloading data during a backtest.
params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- subscribed_quotes¶
list[InstrumentId]
Return the subscribed quote feeds for the emulator.
- Return type:
list[InstrumentId]
- Type:
- subscribed_trades¶
list[InstrumentId]
Return the subscribed trade feeds for the emulator.
- Return type:
list[InstrumentId]
- Type:
- to_importable_config(self) ImportableActorConfig¶
Returns an importable configuration for this actor.
- Return type:
- trader_id¶
The trader ID associated with the component.
- Returns:
TraderId
- type¶
The components type.
- Returns:
type
- unsubscribe_bars(self, BarType bar_type, ClientId client_id=None, dict params=None) void¶
Unsubscribe from streaming Bar data for the given bar type.
- Parameters:
- unsubscribe_data(self, DataType data_type, ClientId client_id=None, InstrumentId instrument_id=None, dict params=None) void¶
Unsubscribe from data of the given data type.
- unsubscribe_funding_rates(self, InstrumentId instrument_id, ClientId client_id=None, dict params=None) void¶
Unsubscribe from streaming FundingRateUpdate data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The instrument to unsubscribe from.
client_id (ClientId, optional) – The specific client ID for the command. If
Nonethen will be inferred from the venue in the instrument ID.params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- unsubscribe_index_prices(self, InstrumentId instrument_id, ClientId client_id=None, dict params=None) void¶
Unsubscribe from streaming IndexPriceUpdate data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The instrument to subscribe to.
client_id (ClientId, optional) – The specific client ID for the command. If
Nonethen will be inferred from the venue in the instrument ID.params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- unsubscribe_instrument(self, InstrumentId instrument_id, ClientId client_id=None, dict params=None) void¶
Unsubscribe from update Instrument data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The instrument to unsubscribe from.
client_id (ClientId, optional) – The specific client ID for the command. If
Nonethen will be inferred from the venue in the instrument ID.params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- unsubscribe_instrument_close(self, InstrumentId instrument_id, ClientId client_id=None, dict params=None) void¶
Unsubscribe from close updates for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The instrument to unsubscribe from close updates for.
client_id (ClientId, optional) – The specific client ID for the command. If
Nonethen will be inferred from the venue in the instrument ID.params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- unsubscribe_instrument_status(self, InstrumentId instrument_id, ClientId client_id=None, dict params=None) void¶
Unsubscribe from status updates for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The instrument to unsubscribe from status updates for.
client_id (ClientId, optional) – The specific client ID for the command. If
Nonethen will be inferred from the venue.params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- unsubscribe_instruments(self, Venue venue, ClientId client_id=None, dict params=None) void¶
Unsubscribe from update Instrument data for the given venue.
- unsubscribe_mark_prices(self, InstrumentId instrument_id, ClientId client_id=None, dict params=None) void¶
Unsubscribe from streaming MarkPriceUpdate data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The instrument to subscribe to.
client_id (ClientId, optional) – The specific client ID for the command. If
Nonethen will be inferred from the venue in the instrument ID.params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- unsubscribe_order_book_at_interval(self, InstrumentId instrument_id, int interval_ms=1000, ClientId client_id=None, dict params=None) void¶
Unsubscribe from an OrderBook at a specified interval for the given instrument ID.
The interval must match the previously subscribed interval.
- Parameters:
instrument_id (InstrumentId) – The order book instrument to subscribe to.
interval_ms (int, default 1000) – The order book snapshot interval (milliseconds).
client_id (ClientId, optional) – The specific client ID for the command. If
Nonethen will be inferred from the venue in the instrument ID.params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- unsubscribe_order_book_deltas(self, InstrumentId instrument_id, ClientId client_id=None, dict params=None) void¶
Unsubscribe the order book deltas stream for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The order book instrument to subscribe to.
client_id (ClientId, optional) – The specific client ID for the command. If
Nonethen will be inferred from the venue in the instrument ID.params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- unsubscribe_order_book_depth(self, InstrumentId instrument_id, ClientId client_id=None, dict params=None) void¶
Unsubscribe the order book depth stream for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The order book instrument to subscribe to.
client_id (ClientId, optional) – The specific client ID for the command. If
Nonethen will be inferred from the venue in the instrument ID.params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- unsubscribe_order_cancels(self, InstrumentId instrument_id) void¶
Unsubscribe from all order cancels for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The instrument to unsubscribe from cancels for.
- unsubscribe_order_fills(self, InstrumentId instrument_id) void¶
Unsubscribe from all order fills for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The instrument to unsubscribe from fills for.
- unsubscribe_quote_ticks(self, InstrumentId instrument_id, ClientId client_id=None, bool aggregate_spread_quotes=False, dict params=None) void¶
Unsubscribe from streaming QuoteTick data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The tick instrument to unsubscribe from.
client_id (ClientId, optional) – The specific client ID for the command. If
Nonethen will be inferred from the venue in the instrument ID.aggregate_spread_quotes (bool, default False) – Whether to unsubscribe from a spread quote aggregator. Only applicable when the instrument_id is a spread instrument.
params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- unsubscribe_trade_ticks(self, InstrumentId instrument_id, ClientId client_id=None, dict params=None) void¶
Unsubscribe from streaming TradeTick data for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The tick instrument ID to unsubscribe from.
client_id (ClientId, optional) – The specific client ID for the command. If
Nonethen will be inferred from the venue in the instrument ID.params (dict[str, Any], optional) – Additional parameters potentially used by a specific client.
- update_synthetic(self, SyntheticInstrument synthetic) void¶
Update the synthetic instrument in the cache.
- Parameters:
synthetic (SyntheticInstrument) – The synthetic instrument to update in the cache.
- Raises:
KeyError – If synthetic does not already exist in the cache.
Notes
If you are adding a new synthetic instrument then you should use the add_synthetic method.
The ExecutionEngine is the central component of the entire execution stack.
The execution engines primary responsibility is to orchestrate interactions between the ExecutionClient instances, and the rest of the platform. This includes sending commands to, and receiving events from, the trading venue endpoints via its registered execution clients.
The engine employs a simple fan-in fan-out messaging pattern to execute TradingCommand messages and OrderEvent messages.
Alternative implementations can be written on top of the generic engine - which just need to override the execute and process methods.
- class ExecutionEngine¶
Bases:
ComponentExecutionEngine(MessageBus msgbus, Cache cache, Clock clock, config: ExecEngineConfig | None = None) -> None
Provides a high-performance execution engine for the management of many ExecutionClient instances, and the asynchronous ingest and distribution of trading commands and events.
- Parameters:
msgbus (MessageBus) – The message bus for the engine.
cache (Cache) – The cache for the engine.
clock (Clock) – The clock for the engine.
config (ExecEngineConfig, optional) – The configuration for the instance.
- Raises:
TypeError – If config is not of type ExecEngineConfig.
- allow_overfills¶
If order fills exceeding order quantity are allowed (logs warning instead of raising).
- Returns:
bool
- check_connected(self) bool¶
Check all of the engines clients are connected.
- Returns:
True if all clients connected, else False.
- Return type:
bool
- check_disconnected(self) bool¶
Check all of the engines clients are disconnected.
- Returns:
True if all clients disconnected, else False.
- Return type:
bool
- check_integrity(self) bool¶
Check integrity of data within the cache and clients.
- Returns:
True if checks pass, else False.
- Return type:
bool
- 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:
True if residuals exist, else False.
- Return type:
bool
- command_count¶
The total count of commands received by the engine.
- Returns:
int
- connect(self) None¶
Connect the engine by calling connect on all registered clients.
- convert_quote_qty_to_base¶
If quote-denominated order quantities should be converted to base units before submission.
- Returns:
bool
- debug¶
If debug mode is active (will provide extra debug logging).
- Returns:
bool
- default_client¶
ClientId | None
Return the default execution client registered with the engine.
- Return type:
ClientId or
None- Type:
- degrade(self) void¶
Degrade the component.
While executing on_degrade() any exception will be logged and reraised, then the component will remain in a
DEGRADINGstate.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) None¶
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, then the component will remain in a
DISPOSINGstate.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.
- Parameters:
command (Command) – The command to execute.
- 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
FAULTINGstate.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(cls) str¶
Return the fully qualified name for the components class.
- Return type:
str
References
- get_clients_for_orders(self, list orders) set¶
Get all execution clients corresponding to the given orders.
- Parameters:
orders (list[Order]) – The orders to locate associated execution clients for.
- Return type:
set[ExecutionClient]
- get_external_client_ids(self) set¶
Returns the configured external client order IDs.
- Return type:
set[ClientId]
- get_external_order_claim(self, InstrumentId instrument_id) StrategyId¶
Get any external order claim for the given instrument ID.
- Parameters:
instrument_id (InstrumentId) – The instrument ID for the claim.
- Return type:
StrategyId or
None
- get_external_order_claims_instruments(self) set¶
Get all instrument IDs registered for external order claims.
- Return type:
set[InstrumentId]
- id¶
The components ID.
- Returns:
ComponentId
- is_degraded¶
bool
Return whether the current component state is
DEGRADED.- Return type:
bool
- Type:
- is_disposed¶
bool
Return whether the current component state is
DISPOSED.- Return type:
bool
- Type:
- is_faulted¶
bool
Return whether the current component state is
FAULTED.- Return type:
bool
- Type:
- is_initialized¶
bool
Return whether the component has been initialized (component.state >=
INITIALIZED).- Return type:
bool
- Type:
- is_running¶
bool
Return whether the current component state is
RUNNING.- Return type:
bool
- Type:
- is_stopped¶
bool
Return whether the current component state is
STOPPED.- Return type:
bool
- Type:
- load_cache(self) void¶
Load the cache up from the execution database.
- manage_own_order_books¶
If the execution engine should maintain own order books based on commands and events.
- Returns:
bool
- 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.
- Return type:
int
- process(self, OrderEvent event) void¶
Process the given order event.
- Parameters:
event (OrderEvent) – The order event to process.
- reconcile_execution_mass_status(self, report: ExecutionMassStatus) None¶
Reconcile the given execution mass status report.
- Parameters:
report (ExecutionMassStatus) – The execution mass status report to reconcile.
- reconcile_execution_report(self, report: ExecutionReport) bool¶
Check the given execution report.
- Parameters:
report (ExecutionReport) – The execution report to check.
- Returns:
True if reconciliation successful, else False.
- Return type:
bool
- async reconcile_execution_state(self, double timeout_secs: float = 10.0) bool¶
Reconcile the internal execution state with all execution clients (external state).
- Parameters:
timeout_secs (double, default 10.0) – The timeout (seconds) for reconciliation to complete.
- Returns:
True if states reconcile within timeout, else False.
- Return type:
bool
- Raises:
ValueError – If timeout_secs is not positive (> 0).
- reconciliation¶
bool
Return whether the reconciliation process will be run on start.
- Return type:
bool
- Type:
- register_client(self, ExecutionClient client) void¶
Register the given execution client with the execution engine.
If the client.venue is
Noneand 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_external_order_claims(self, Strategy strategy) void¶
Register the given strategies external order claim instrument IDs (if any)
- Parameters:
strategy (Strategy) – The strategy for the registration.
- Raises:
InvalidConfiguration – If a strategy is already registered to claim external orders for an instrument ID.
- 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¶
list[ClientId]
Return the execution clients registered with the engine.
- Return type:
list[ClientId]
- Type:
- report_count¶
‘int’
The total count of reports received by the engine.
- Returns:
int
- 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, then the component will remain in a
RESETTINGstate.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
RESUMINGstate.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_convert_quote_qty_to_base(self, bool value) void¶
Set the convert_quote_qty_to_base flag with the given value.
- Parameters:
value (bool) – The value to set.
- set_manage_own_order_books(self, bool value) void¶
Set the manage_own_order_books setting with the given value.
- Parameters:
value (bool) – The value to set.
- shutdown_system(self, str reason=None) void¶
Initiate a system-wide shutdown by generating and publishing a ShutdownSystem command.
The command is handled by the system’s NautilusKernel, which will invoke either stop (synchronously) or stop_async (asynchronously) depending on the execution context and the presence of an active event loop.
- Parameters:
reason (str, optional) – The reason for issuing the shutdown command.
- snapshot_orders¶
If order state snapshots should be persisted.
- Returns:
bool
- snapshot_positions¶
If position state snapshots should be persisted.
- Returns:
bool
- snapshot_positions_interval_secs¶
The interval (seconds) at which additional position state snapshots are persisted.
- Returns:
double
- snapshot_positions_timer_name¶
- start(self) void¶
Start the component.
While executing on_start() any exception will be logged and reraised, then the component will remain in a
STARTINGstate.Warning
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
- state¶
ComponentState
Return the components current state.
- Return type:
ComponentState
- Type:
- stop(self) void¶
Stop the component.
While executing on_stop() any exception will be logged and reraised, then the component will remain in a
STOPPINGstate.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.
- stop_clients(self) void¶
Stop the registered clients.
- trader_id¶
The trader ID associated with the component.
- Returns:
TraderId
- type¶
The components type.
- Returns:
type
- class OrderManager¶
Bases:
objectOrderManager(Clock clock, MessageBus msgbus, Cache cache, str component_name, bool active_local, submit_order_handler: Callable[[SubmitOrder], None] = None, cancel_order_handler: Callable[[Order], None] = None, modify_order_handler: Callable[[Order, Quantity], None] = None, bool debug=False, bool log_events=True, bool log_commands=True)
Provides a generic order execution manager.
- Parameters:
clock (Clock) – The clock for the order manager.
msgbus (MessageBus) – The message bus for the order manager.
cache (Cache) – The cache for the order manager.
component_name (str) – The component name for the order manager.
active_local (str) – If the manager is for active local orders.
submit_order_handler (Callable[[SubmitOrder], None], optional) – The handler to call when submitting orders.
cancel_order_handler (Callable[[Order], None], optional) – The handler to call when canceling orders.
modify_order_handler (Callable[[Order, Quantity], None], optional) – The handler to call when modifying orders (limited to modifying quantity).
debug (bool, default False) – If debug mode is active (will provide extra debug logging).
- Raises:
TypeError – If submit_order_handler is not
Noneand not of type Callable.TypeError – If cancel_order_handler is not
Noneand not of type Callable.TypeError – If modify_order_handler is not
Noneand not of type Callable.
- active_local¶
- cache_submit_order_command(self, SubmitOrder command) void¶
Cache the given submit order command with the manager.
- Parameters:
command (SubmitOrder) – The submit order command to cache.
- cancel_order(self, Order order) void¶
Cancel the given order with the manager.
- Parameters:
order (Order) – The order to cancel.
- create_new_submit_order(self, Order order, PositionId position_id=None, ClientId client_id=None) void¶
Create a new submit order command for the given order.
- Parameters:
order (Order) – The order for the command.
position_id (PositionId, optional) – The position ID for the command.
client_id (ClientId, optional) – The client ID for the command.
- debug¶
- get_submit_order_commands(self) dict¶
Return the managers cached submit order commands.
- Return type:
dict[ClientOrderId, SubmitOrder]
- handle_contingencies(self, Order order) void¶
- handle_contingencies_update(self, Order order) void¶
- handle_event(self, Event event) void¶
Handle the given event.
If a handler for the given event is not implemented then this will simply be a no-op.
- Parameters:
event (Event) – The event to handle
- handle_order_canceled(self, OrderCanceled canceled) void¶
- handle_order_expired(self, OrderExpired expired) void¶
- handle_order_filled(self, OrderFilled filled) void¶
- handle_order_rejected(self, OrderRejected rejected) void¶
- handle_order_updated(self, OrderUpdated updated) void¶
- handle_position_event(self, PositionEvent event) void¶
- log_commands¶
- log_events¶
- modify_order_quantity(self, Order order, Quantity new_quantity) void¶
Modify the given order with the manager.
- Parameters:
order (Order) – The order to modify.
- pop_submit_order_command(self, ClientOrderId client_order_id) SubmitOrder¶
Pop the submit order command for the given client_order_id out of the managers cache (if found).
- Parameters:
client_order_id (ClientOrderId) – The client order ID for the command to pop.
- Return type:
SubmitOrder or
None
- reset(self) void¶
Reset the manager, clearing all stateful values.
- send_algo_command(self, TradingCommand command, ExecAlgorithmId exec_algorithm_id) void¶
- send_emulator_command(self, TradingCommand command) void¶
- send_exec_command(self, Command command) void¶
- send_exec_event(self, OrderEvent event) void¶
- send_risk_command(self, TradingCommand command) void¶
- send_risk_event(self, OrderEvent event) void¶
- class MatchingCore¶
Bases:
objectMatchingCore(InstrumentId instrument_id, Price price_increment, trigger_stop_order: Callable, fill_market_order: Callable, fill_limit_order: Callable)
Provides a generic order matching core.
- Parameters:
instrument_id (InstrumentId) – The instrument ID for the matching core.
price_increment (Price) – The minimum price increment (tick size) for the matching core.
trigger_stop_order (Callable[[Order], None]) – The callable when a stop order is triggered.
fill_market_order (Callable[[Order], None]) – The callable when a market order is filled.
fill_limit_order (Callable[[Order], None]) – The callable when a limit order is filled.
- add_order(self, Order order) void¶
- ask¶
Price | None
Return the current ask price for the matching core.
- Return type:
Price or
None- Type:
- ask_raw¶
- bid¶
Price | None
Return the current bid price for the matching core.
- Return type:
Price or
None- Type:
- bid_raw¶
- delete_order(self, Order order) void¶
- get_orders(self) list¶
- get_orders_ask(self) list¶
- get_orders_bid(self) list¶
- instrument_id¶
InstrumentId
Return the instrument ID for the matching core.
- Return type:
- Type:
- is_ask_initialized¶
- is_bid_initialized¶
- is_last_initialized¶
- is_limit_fillable(self, OrderSide side, Price price) bool¶
- is_limit_marketable(self, OrderSide side, Price price) bool¶
- is_stop_triggered(self, OrderSide side, Price trigger_price) bool¶
- is_touch_triggered(self, OrderSide side, Price trigger_price) bool¶
- iterate(self, uint64_t timestamp_ns) void¶
- last¶
Price | None
Return the current last price for the matching core.
- Return type:
Price or
None- Type:
- last_raw¶
- match_limit_if_touched_order(self, Order order, bool initial) void¶
- match_limit_order(self, Order order) void¶
- match_market_if_touched_order(self, Order order) void¶
- match_order(self, Order order, bool initial=False) void¶
Match the given order.
- Parameters:
order (Order) – The order to match.
initial (bool, default False) – If this is an initial match.
- Raises:
TypeError – If the order.order_type is an invalid type for the core (e.g. MARKET).
- match_stop_limit_order(self, Order order, bool initial) void¶
- match_stop_market_order(self, Order order) void¶
- match_trailing_stop_limit_order(self, Order order, bool initial) void¶
- match_trailing_stop_market_order(self, Order order) void¶
- order_exists(self, ClientOrderId client_order_id) bool¶
- price_increment¶
Price
Return the instruments minimum price increment (tick size) for the matching core.
- Return type:
- Type:
- price_precision¶
int
Return the instruments price precision for the matching core.
- Return type:
int
- Type:
- reset(self) void¶
- set_fill_limit_inside_spread(self, bool value) void¶
Messages¶
- class BatchCancelOrders¶
Bases:
TradingCommandBatchCancelOrders(TraderId trader_id, StrategyId strategy_id, InstrumentId instrument_id, list cancels, UUID4 command_id, uint64_t ts_init, ClientId client_id=None, dict params: dict | None = None, UUID4 correlation_id=None) -> None
Represents a command to batch cancel orders working on a venue for an instrument.
- Parameters:
trader_id (TraderId) – The trader ID for the command.
strategy_id (StrategyId) – The strategy ID for the command.
instrument_id (InstrumentId) – The instrument ID for the command.
cancels (list[CancelOrder]) – The inner list of cancel order commands.
command_id (UUID4) – The command ID.
ts_init (uint64_t) – UNIX timestamp (nanoseconds) when the object was initialized.
client_id (ClientId, optional) – The execution client ID for the command.
params (dict[str, object], optional) – Additional parameters for the command.
- Raises:
ValueError – If cancels is empty.
ValueError – If cancels contains a type other than CancelOrder.
- cancels¶
- client_id¶
The execution client ID for the command.
- Returns:
ClientId or
None
- correlation_id¶
The command correlation ID.
- Returns:
UUID4 or
None
- static from_dict(dict values) BatchCancelOrders¶
Return a batch cancel order command from the given dict values.
- Parameters:
values (dict[str, object]) – The values for initialization.
- Return type:
- id¶
The command message ID.
- Returns:
UUID4
- instrument_id¶
The instrument ID associated with the command.
- Returns:
InstrumentId
- params¶
Additional specific parameters for the command.
- Returns:
dict[str, object] or
None
- strategy_id¶
The strategy ID associated with the command.
- Returns:
StrategyId
- static to_dict(BatchCancelOrders obj)¶
Return a dictionary representation of this object.
- Return type:
dict[str, object]
- trader_id¶
The trader ID associated with the command.
- Returns:
TraderId
- ts_init¶
UNIX timestamp (nanoseconds) when the object was initialized.
- Returns:
uint64_t
- class CancelAllOrders¶
Bases:
TradingCommandCancelAllOrders(TraderId trader_id, StrategyId strategy_id, InstrumentId instrument_id, OrderSide order_side, UUID4 command_id, uint64_t ts_init, ClientId client_id=None, dict params: dict | None = None, UUID4 correlation_id=None) -> None
Represents a command to cancel all orders for an instrument.
- Parameters:
trader_id (TraderId) – The trader ID for the command.
strategy_id (StrategyId) – The strategy ID for the command.
instrument_id (InstrumentId) – The instrument ID for the command.
order_side (OrderSide) – The order side for the command.
command_id (UUID4) – The command ID.
ts_init (uint64_t) – UNIX timestamp (nanoseconds) when the object was initialized.
client_id (ClientId, optional) – The execution client ID for the command.
params (dict[str, object], optional) – Additional parameters for the command.
- client_id¶
The execution client ID for the command.
- Returns:
ClientId or
None
- correlation_id¶
The command correlation ID.
- Returns:
UUID4 or
None
- static from_dict(dict values) CancelAllOrders¶
Return a cancel order command from the given dict values.
- Parameters:
values (dict[str, object]) – The values for initialization.
- Return type:
- id¶
The command message ID.
- Returns:
UUID4
- instrument_id¶
The instrument ID associated with the command.
- Returns:
InstrumentId
- order_side¶
The order side for the command.
- Returns:
OrderSide
- params¶
Additional specific parameters for the command.
- Returns:
dict[str, object] or
None
- strategy_id¶
The strategy ID associated with the command.
- Returns:
StrategyId
- static to_dict(CancelAllOrders obj)¶
Return a dictionary representation of this object.
- Return type:
dict[str, object]
- trader_id¶
The trader ID associated with the command.
- Returns:
TraderId
- ts_init¶
UNIX timestamp (nanoseconds) when the object was initialized.
- Returns:
uint64_t
- class CancelOrder¶
Bases:
TradingCommandCancelOrder(TraderId trader_id, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, VenueOrderId venue_order_id: VenueOrderId | None, UUID4 command_id, uint64_t ts_init, ClientId client_id=None, dict params: dict | None = None, UUID4 correlation_id=None) -> None
Represents a command to cancel an order.
- Parameters:
trader_id (TraderId) – The trader ID for the command.
strategy_id (StrategyId) – The strategy ID for the command.
instrument_id (InstrumentId) – The instrument ID for the command.
client_order_id (ClientOrderId) – The client order ID to cancel.
venue_order_id (VenueOrderId or
None) – The venue order ID (assigned by the venue) to cancel.command_id (UUID4) – The command ID.
ts_init (uint64_t) – UNIX timestamp (nanoseconds) when the object was initialized.
client_id (ClientId, optional) – The execution client ID for the command.
params (dict[str, object], optional) – Additional parameters for the command.
- client_id¶
The execution client ID for the command.
- Returns:
ClientId or
None
- client_order_id¶
The client order ID associated with the command.
- Returns:
ClientOrderId
- correlation_id¶
The command correlation ID.
- Returns:
UUID4 or
None
- static from_dict(dict values) CancelOrder¶
Return a cancel order command from the given dict values.
- Parameters:
values (dict[str, object]) – The values for initialization.
- Return type:
- id¶
The command message ID.
- Returns:
UUID4
- instrument_id¶
The instrument ID associated with the command.
- Returns:
InstrumentId
- params¶
Additional specific parameters for the command.
- Returns:
dict[str, object] or
None
- strategy_id¶
The strategy ID associated with the command.
- Returns:
StrategyId
- static to_dict(CancelOrder obj)¶
Return a dictionary representation of this object.
- Return type:
dict[str, object]
- trader_id¶
The trader ID associated with the command.
- Returns:
TraderId
- ts_init¶
UNIX timestamp (nanoseconds) when the object was initialized.
- Returns:
uint64_t
- venue_order_id¶
The venue order ID associated with the command.
- Returns:
VenueOrderId or
None
- class ExecutionReportCommand¶
Bases:
CommandExecutionReportCommand(InstrumentId instrument_id: InstrumentId | None, datetime start: datetime | None, datetime end: datetime | None, UUID4 command_id, uint64_t ts_init, dict params: dict | None = None, UUID4 correlation_id=None) -> None
The base class for all execution report commands.
- Parameters:
instrument_id (InstrumentId) – The instrument ID for the command.
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.
command_id (UUID4) – The commands ID.
ts_init (uint64_t) – UNIX timestamp (nanoseconds) when the object was initialized.
params (dict[str, object], optional) – Additional parameters for the command.
Warning
This class should not be used directly, but through a concrete subclass.
- correlation_id¶
The command correlation ID.
- Returns:
UUID4 or
None
- end¶
The end datetime (UTC) of request time range.
:returns datetime or
None
- id¶
The command message ID.
- Returns:
UUID4
- instrument_id¶
The instrument ID associated with the command.
- Returns:
InstrumentId
- params¶
Additional specific parameters for the command.
- Returns:
dict[str, object] or
None
- start¶
The start datetime (UTC) of request time range (inclusive).
:returns datetime or
None
- ts_init¶
UNIX timestamp (nanoseconds) when the object was initialized.
- Returns:
uint64_t
- class GenerateExecutionMassStatus¶
Bases:
ExecutionReportCommandGenerateExecutionMassStatus(TraderId trader_id, ClientId client_id, UUID4 command_id, uint64_t ts_init, Venue venue: Venue | None = None, dict params: dict | None = None, UUID4 correlation_id=None) -> None
Command to generate an execution mass status report.
- Parameters:
trader_id (TraderId) – The trader ID for the command.
client_id (ClientId) – The client ID for the command.
command_id (UUID4) – The command ID.
ts_init (uint64_t) – UNIX timestamp (nanoseconds) when the object was initialized.
venue (Venue, optional) – The venue for the command.
params (dict[str, object], optional) – Additional parameters for the command.
- client_id¶
The client ID associated with the command.
- Returns:
ClientId
- correlation_id¶
The command correlation ID.
- Returns:
UUID4 or
None
- end¶
The end datetime (UTC) of request time range.
:returns datetime or
None
- static from_dict(dict values) GenerateExecutionMassStatus¶
Return a generate execution mass status command from the given dict values.
- Parameters:
values (dict[str, object]) – The values for initialization.
- Return type:
- id¶
The command message ID.
- Returns:
UUID4
- instrument_id¶
The instrument ID associated with the command.
- Returns:
InstrumentId
- params¶
Additional specific parameters for the command.
- Returns:
dict[str, object] or
None
- start¶
The start datetime (UTC) of request time range (inclusive).
:returns datetime or
None
- static to_dict(GenerateExecutionMassStatus obj)¶
Return a dictionary representation of this object.
- Return type:
dict[str, object]
- trader_id¶
The trader ID associated with the command.
- Returns:
TraderId
- ts_init¶
UNIX timestamp (nanoseconds) when the object was initialized.
- Returns:
uint64_t
- venue¶
The venue associated with the command.
- Returns:
Venue or
None
- class GenerateFillReports¶
Bases:
ExecutionReportCommandGenerateFillReports(InstrumentId instrument_id: InstrumentId | None, VenueOrderId venue_order_id: VenueOrderId | None, datetime start: datetime | None, datetime end: datetime | None, UUID4 command_id, uint64_t ts_init, dict params: dict | None = None, UUID4 correlation_id=None) -> None
Command to generate fill reports.
- Parameters:
instrument_id (InstrumentId) – The instrument ID for the command.
venue_order_id (VenueOrderId or
None) – The venue order ID (assigned by the venue) to query.start (datetime) – The start datetime (UTC) of request time range (inclusive).
end (datetime) – The end datetime (UTC) of request time range. The inclusiveness depends on individual data client implementation.
command_id (UUID4) – The commands ID.
ts_init (uint64_t) – UNIX timestamp (nanoseconds) when the object was initialized.
params (dict[str, object], optional) – Additional parameters for the command.
- correlation_id¶
The command correlation ID.
- Returns:
UUID4 or
None
- end¶
The end datetime (UTC) of request time range.
:returns datetime or
None
- static from_dict(dict values) GenerateFillReports¶
Return a generate fill reports command from the given dict values.
- Parameters:
values (dict[str, object]) – The values for initialization.
- Return type:
- id¶
The command message ID.
- Returns:
UUID4
- instrument_id¶
The instrument ID associated with the command.
- Returns:
InstrumentId
- params¶
Additional specific parameters for the command.
- Returns:
dict[str, object] or
None
- start¶
The start datetime (UTC) of request time range (inclusive).
:returns datetime or
None
- static to_dict(GenerateFillReports obj)¶
Return a dictionary representation of this object.
- Return type:
dict[str, object]
- ts_init¶
UNIX timestamp (nanoseconds) when the object was initialized.
- Returns:
uint64_t
- venue_order_id¶
The venue order ID associated with the command.
- Returns:
VenueOrderId or
None
- class GenerateOrderStatusReport¶
Bases:
ExecutionReportCommandGenerateOrderStatusReport(InstrumentId instrument_id: InstrumentId | None, ClientOrderId client_order_id: ClientOrderId | None, VenueOrderId venue_order_id: VenueOrderId | None, UUID4 command_id, uint64_t ts_init, dict params: dict | None = None, UUID4 correlation_id=None) -> None
Command to generate an order status report.
- Parameters:
instrument_id (InstrumentId) – The instrument ID for the command.
client_order_id (ClientOrderId) – The client order ID to update.
venue_order_id (VenueOrderId or
None) – The venue order ID (assigned by the venue) to query.command_id (UUID4) – The commands ID.
ts_init (uint64_t) – UNIX timestamp (nanoseconds) when the object was initialized.
params (dict[str, object], optional) – Additional parameters for the command.
- client_order_id¶
The client order ID associated with the command.
- Returns:
ClientOrderId
- correlation_id¶
The command correlation ID.
- Returns:
UUID4 or
None
- end¶
The end datetime (UTC) of request time range.
:returns datetime or
None
- static from_dict(dict values) GenerateOrderStatusReport¶
Return a generate order status report command from the given dict values.
- Parameters:
values (dict[str, object]) – The values for initialization.
- Return type:
- id¶
The command message ID.
- Returns:
UUID4
- instrument_id¶
The instrument ID associated with the command.
- Returns:
InstrumentId
- params¶
Additional specific parameters for the command.
- Returns:
dict[str, object] or
None
- start¶
The start datetime (UTC) of request time range (inclusive).
:returns datetime or
None
- static to_dict(GenerateOrderStatusReport obj)¶
Return a dictionary representation of this object.
- Return type:
dict[str, object]
- ts_init¶
UNIX timestamp (nanoseconds) when the object was initialized.
- Returns:
uint64_t
- venue_order_id¶
The venue order ID associated with the command.
- Returns:
VenueOrderId or
None
- class GenerateOrderStatusReports¶
Bases:
ExecutionReportCommandGenerateOrderStatusReports(InstrumentId instrument_id: InstrumentId | None, datetime start: datetime | None, datetime end: datetime | None, bool open_only, UUID4 command_id, uint64_t ts_init, dict params: dict | None = None, LogLevel log_receipt_level=LogLevel.INFO, UUID4 correlation_id=None) -> None
Command to generate order status reports.
- Parameters:
instrument_id (InstrumentId) – The instrument ID for the command.
start (datetime) – The start datetime (UTC) of request time range (inclusive).
end (datetime) – The end datetime (UTC) of request time range. The inclusiveness depends on individual data client implementation.
open_only (bool) – If True then only open orders will be requested.
command_id (UUID4) – The commands ID.
ts_init (uint64_t) – UNIX timestamp (nanoseconds) when the object was initialized.
params (dict[str, object], optional) – Additional parameters for the command.
log_receipt_level (LogLevel, default 'INFO') – The log level for logging received reports. Must be either LogLevel.DEBUG or LogLevel.INFO.
- correlation_id¶
The command correlation ID.
- Returns:
UUID4 or
None
- end¶
The end datetime (UTC) of request time range.
:returns datetime or
None
- static from_dict(dict values) GenerateOrderStatusReports¶
Return a generate order status reports command from the given dict values.
- Parameters:
values (dict[str, object]) – The values for initialization.
- Return type:
- id¶
The command message ID.
- Returns:
UUID4
- instrument_id¶
The instrument ID associated with the command.
- Returns:
InstrumentId
- log_receipt_level¶
The log level for logging received reports.
- Returns:
LogLevel
- open_only¶
If the request is only for open orders.
- Returns:
bool
- params¶
Additional specific parameters for the command.
- Returns:
dict[str, object] or
None
- start¶
The start datetime (UTC) of request time range (inclusive).
:returns datetime or
None
- static to_dict(GenerateOrderStatusReports obj)¶
Return a dictionary representation of this object.
- Return type:
dict[str, object]
- ts_init¶
UNIX timestamp (nanoseconds) when the object was initialized.
- Returns:
uint64_t
- class GeneratePositionStatusReports¶
Bases:
ExecutionReportCommandGeneratePositionStatusReports(InstrumentId instrument_id: InstrumentId | None, datetime start: datetime | None, datetime end: datetime | None, UUID4 command_id, uint64_t ts_init, dict params: dict | None = None, LogLevel log_receipt_level=LogLevel.INFO, UUID4 correlation_id=None) -> None
Command to generate position status reports.
- Parameters:
instrument_id (InstrumentId) – The instrument ID for the command.
start (datetime) – The start datetime (UTC) of request time range (inclusive).
end (datetime) – The end datetime (UTC) of request time range. The inclusiveness depends on individual data client implementation.
command_id (UUID4) – The commands ID.
ts_init (uint64_t) – UNIX timestamp (nanoseconds) when the object was initialized.
params (dict[str, object], optional) – Additional parameters for the command.
log_receipt_level (LogLevel, default 'INFO') – The log level for logging received reports. Must be either LogLevel.DEBUG or LogLevel.INFO.
- correlation_id¶
The command correlation ID.
- Returns:
UUID4 or
None
- end¶
The end datetime (UTC) of request time range.
:returns datetime or
None
- static from_dict(dict values) GeneratePositionStatusReports¶
Return a generate position status reports command from the given dict values.
- Parameters:
values (dict[str, object]) – The values for initialization.
- Return type:
- id¶
The command message ID.
- Returns:
UUID4
- instrument_id¶
The instrument ID associated with the command.
- Returns:
InstrumentId
- log_receipt_level¶
The log level for logging received reports.
- Returns:
LogLevel
- params¶
Additional specific parameters for the command.
- Returns:
dict[str, object] or
None
- start¶
The start datetime (UTC) of request time range (inclusive).
:returns datetime or
None
- static to_dict(GeneratePositionStatusReports obj)¶
Return a dictionary representation of this object.
- Return type:
dict[str, object]
- ts_init¶
UNIX timestamp (nanoseconds) when the object was initialized.
- Returns:
uint64_t
- class ModifyOrder¶
Bases:
TradingCommandModifyOrder(TraderId trader_id, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, VenueOrderId venue_order_id: VenueOrderId | None, Quantity quantity: Quantity | None, Price price: Price | None, Price trigger_price: Price | None, UUID4 command_id, uint64_t ts_init, ClientId client_id=None, dict params: dict | None = None, UUID4 correlation_id=None) -> None
Represents a command to modify the properties of an existing order.
- Parameters:
trader_id (TraderId) – The trader ID for the command.
strategy_id (StrategyId) – The strategy ID for the command.
instrument_id (InstrumentId) – The instrument ID for the command.
client_order_id (ClientOrderId) – The client order ID to update.
venue_order_id (VenueOrderId or
None) – The venue order ID (assigned by the venue) to update.quantity (Quantity or
None) – The quantity for the order update.price (Price or
None) – The price for the order update.trigger_price (Price or
None) – The trigger price for the order update.command_id (UUID4) – The command ID.
ts_init (uint64_t) – UNIX timestamp (nanoseconds) when the object was initialized.
client_id (ClientId, optional) – The execution client ID for the command.
params (dict[str, object], optional) – Additional parameters for the command.
- client_id¶
The execution client ID for the command.
- Returns:
ClientId or
None
- client_order_id¶
The client order ID associated with the command.
- Returns:
ClientOrderId
- correlation_id¶
The command correlation ID.
- Returns:
UUID4 or
None
- static from_dict(dict values) ModifyOrder¶
Return a modify order command from the given dict values.
- Parameters:
values (dict[str, object]) – The values for initialization.
- Return type:
- id¶
The command message ID.
- Returns:
UUID4
- instrument_id¶
The instrument ID associated with the command.
- Returns:
InstrumentId
- params¶
Additional specific parameters for the command.
- Returns:
dict[str, object] or
None
- price¶
The updated price for the command.
- Returns:
Price or
None
- quantity¶
The updated quantity for the command.
- Returns:
Quantity or
None
- strategy_id¶
The strategy ID associated with the command.
- Returns:
StrategyId
- static to_dict(ModifyOrder obj)¶
Return a dictionary representation of this object.
- Return type:
dict[str, object]
- trader_id¶
The trader ID associated with the command.
- Returns:
TraderId
- trigger_price¶
The updated trigger price for the command.
- Returns:
Price or
None
- ts_init¶
UNIX timestamp (nanoseconds) when the object was initialized.
- Returns:
uint64_t
- venue_order_id¶
The venue order ID associated with the command.
- Returns:
VenueOrderId or
None
- class QueryAccount¶
Bases:
CommandQueryAccount(TraderId trader_id, AccountId account_id, UUID4 command_id, uint64_t ts_init, ClientId client_id=None, dict params: dict | None = None, UUID4 correlation_id=None) -> None
Represents a command to query an account.
- Parameters:
trader_id (TraderId) – The trader ID for the command.
account_id (AccountId) – The account ID to query.
command_id (UUID4) – The command ID.
ts_init (uint64_t) – UNIX timestamp (nanoseconds) when the object was initialized.
client_id (ClientId, optional) – The execution client ID for the command.
params (dict[str, object], optional) – Additional parameters for the command.
- account_id¶
The account ID to query.
- Returns:
AccountId
- client_id¶
The execution client ID for the command.
- Returns:
ClientId or
None
- correlation_id¶
The command correlation ID.
- Returns:
UUID4 or
None
- static from_dict(dict values) QueryAccount¶
Return a query account command from the given dict values.
- Parameters:
values (dict[str, object]) – The values for initialization.
- Return type:
- id¶
The command message ID.
- Returns:
UUID4
- params¶
Additional parameters for the command.
- Returns:
dict[str, object]
- static to_dict(QueryAccount obj)¶
Return a dictionary representation of this object.
- Return type:
dict[str, object]
- trader_id¶
The trader ID associated with the command.
- Returns:
TraderId
- ts_init¶
UNIX timestamp (nanoseconds) when the object was initialized.
- Returns:
uint64_t
- class QueryOrder¶
Bases:
TradingCommandQueryOrder(TraderId trader_id, StrategyId strategy_id, InstrumentId instrument_id, ClientOrderId client_order_id, VenueOrderId venue_order_id: VenueOrderId | None, UUID4 command_id, uint64_t ts_init, ClientId client_id=None, dict params: dict | None = None, UUID4 correlation_id=None) -> None
Represents a command to query an order.
- Parameters:
trader_id (TraderId) – The trader ID for the command.
strategy_id (StrategyId) – The strategy ID for the command.
instrument_id (InstrumentId) – The instrument ID for the command.
client_order_id (ClientOrderId) – The client order ID for the order to query.
venue_order_id (VenueOrderId or
None) – The venue order ID (assigned by the venue) to query.command_id (UUID4) – The command ID.
ts_init (uint64_t) – UNIX timestamp (nanoseconds) when the object was initialized.
client_id (ClientId, optional) – The execution client ID for the command.
params (dict[str, object], optional) – Additional parameters for the command.
- client_id¶
The execution client ID for the command.
- Returns:
ClientId or
None
- client_order_id¶
The client order ID for the order to query.
- Returns:
ClientOrderId
- correlation_id¶
The command correlation ID.
- Returns:
UUID4 or
None
- static from_dict(dict values) QueryOrder¶
Return a query order command from the given dict values.
- Parameters:
values (dict[str, object]) – The values for initialization.
- Return type:
- id¶
The command message ID.
- Returns:
UUID4
- instrument_id¶
The instrument ID associated with the command.
- Returns:
InstrumentId
- params¶
Additional specific parameters for the command.
- Returns:
dict[str, object] or
None
- strategy_id¶
The strategy ID associated with the command.
- Returns:
StrategyId
- static to_dict(QueryOrder obj)¶
Return a dictionary representation of this object.
- Return type:
dict[str, object]
- trader_id¶
The trader ID associated with the command.
- Returns:
TraderId
- ts_init¶
UNIX timestamp (nanoseconds) when the object was initialized.
- Returns:
uint64_t
- venue_order_id¶
The venue order ID for the order to query.
- Returns:
VenueOrderId or
None
- class SubmitOrder¶
Bases:
TradingCommandSubmitOrder(TraderId trader_id, StrategyId strategy_id, Order order, UUID4 command_id, uint64_t ts_init, PositionId position_id: PositionId | None = None, ClientId client_id=None, dict params: dict | None = None, UUID4 correlation_id=None) -> None
Represents a command to submit the given order.
- Parameters:
trader_id (TraderId) – The trader ID for the command.
strategy_id (StrategyId) – The strategy ID for the command.
order (Order) – The order to submit.
command_id (UUID4) – The commands ID.
ts_init (uint64_t) – UNIX timestamp (nanoseconds) when the object was initialized.
position_id (PositionId, optional) – The position ID for the command.
client_id (ClientId, optional) – The execution client ID for the command.
params (dict[str, object], optional) – Additional parameters for the command.
- client_id¶
The execution client ID for the command.
- Returns:
ClientId or
None
- correlation_id¶
The command correlation ID.
- Returns:
UUID4 or
None
- exec_algorithm_id¶
The execution algorithm ID for the order.
- Returns:
ExecAlgorithmId or
None
- static from_dict(dict values) SubmitOrder¶
Return a submit order command from the given dict values.
- Parameters:
values (dict[str, object]) – The values for initialization.
- Return type:
- id¶
The command message ID.
- Returns:
UUID4
- instrument_id¶
The instrument ID associated with the command.
- Returns:
InstrumentId
- order¶
The order to submit.
- Returns:
Order
- params¶
Additional specific parameters for the command.
- Returns:
dict[str, object] or
None
- position_id¶
The position ID to associate with the order.
- Returns:
PositionId or
None
- strategy_id¶
The strategy ID associated with the command.
- Returns:
StrategyId
- static to_dict(SubmitOrder obj)¶
Return a dictionary representation of this object.
- Return type:
dict[str, object]
- trader_id¶
The trader ID associated with the command.
- Returns:
TraderId
- ts_init¶
UNIX timestamp (nanoseconds) when the object was initialized.
- Returns:
uint64_t
- class SubmitOrderList¶
Bases:
TradingCommandSubmitOrderList(TraderId trader_id, StrategyId strategy_id, OrderList order_list, UUID4 command_id, uint64_t ts_init, PositionId position_id: PositionId | None = None, ClientId client_id=None, dict params: dict | None = None, UUID4 correlation_id=None) -> None
Represents a command to submit an order list consisting of an order batch/bulk of related parent-child contingent orders.
This command can correspond to a NewOrderList <E> message for the FIX protocol.
- Parameters:
trader_id (TraderId) – The trader ID for the command.
strategy_id (StrategyId) – The strategy ID for the command.
order_list (OrderList) – The order list to submit.
command_id (UUID4) – The command ID.
ts_init (uint64_t) – UNIX timestamp (nanoseconds) when the object was initialized.
position_id (PositionId, optional) – The position ID for the command.
client_id (ClientId, optional) – The execution client ID for the command.
params (dict[str, object], optional) – Additional parameters for the command.
- client_id¶
The execution client ID for the command.
- Returns:
ClientId or
None
- correlation_id¶
The command correlation ID.
- Returns:
UUID4 or
None
- exec_algorithm_id¶
The execution algorithm ID for the order list.
- Returns:
ExecAlgorithmId or
None
- static from_dict(dict values) SubmitOrderList¶
Return a submit order list command from the given dict values.
- Parameters:
values (dict[str, object]) – The values for initialization.
- Return type:
- has_emulated_order¶
If the contained order_list holds at least one emulated order.
- Returns:
bool
- id¶
The command message ID.
- Returns:
UUID4
- instrument_id¶
The instrument ID associated with the command.
- Returns:
InstrumentId
- order_list¶
The order list to submit.
- Returns:
OrderList
- params¶
Additional specific parameters for the command.
- Returns:
dict[str, object] or
None
- position_id¶
The position ID to associate with the orders.
- Returns:
PositionId or
None
- strategy_id¶
The strategy ID associated with the command.
- Returns:
StrategyId
- static to_dict(SubmitOrderList obj)¶
Return a dictionary representation of this object.
- Return type:
dict[str, object]
- trader_id¶
The trader ID associated with the command.
- Returns:
TraderId
- ts_init¶
UNIX timestamp (nanoseconds) when the object was initialized.
- Returns:
uint64_t
- class TradingCommand¶
Bases:
CommandTradingCommand(ClientId client_id: ClientId | None, TraderId trader_id, StrategyId strategy_id, InstrumentId instrument_id, UUID4 command_id, uint64_t ts_init, dict params: dict | None = None, UUID4 correlation_id=None) -> None
The base class for all trading related commands.
- Parameters:
client_id (ClientId or
None) – The execution client ID for the command.trader_id (TraderId) – The trader ID for the command.
strategy_id (StrategyId) – The strategy ID for the command.
instrument_id (InstrumentId) – The instrument ID for the command.
command_id (UUID4) – The commands ID.
ts_init (uint64_t) – UNIX timestamp (nanoseconds) when the object was initialized.
params (dict[str, object], optional) – Additional parameters for the command.
Warning
This class should not be used directly, but through a concrete subclass.
- client_id¶
The execution client ID for the command.
- Returns:
ClientId or
None
- correlation_id¶
The command correlation ID.
- Returns:
UUID4 or
None
- id¶
The command message ID.
- Returns:
UUID4
- instrument_id¶
The instrument ID associated with the command.
- Returns:
InstrumentId
- params¶
Additional specific parameters for the command.
- Returns:
dict[str, object] or
None
- strategy_id¶
The strategy ID associated with the command.
- Returns:
StrategyId
- trader_id¶
The trader ID associated with the command.
- Returns:
TraderId
- ts_init¶
UNIX timestamp (nanoseconds) when the object was initialized.
- Returns:
uint64_t
Reports¶
- class ExecutionReport¶
Bases:
DocumentThe base class for all execution reports.
- id¶
The document message ID.
- Returns:
UUID4
- ts_init¶
UNIX timestamp (nanoseconds) when the object was initialized.
- Returns:
uint64_t
- class OrderStatusReport¶
Bases:
ExecutionReportRepresents an order status at a point in time.
Reporting is best-effort; if filled exceeds quantity due to venue anomalies, avoid negative leaves_qty by clamping to zero.
- Parameters:
account_id (AccountId) – The account ID for the report.
instrument_id (InstrumentId) – The instrument ID for the report.
venue_order_id (VenueOrderId) – The reported order ID (assigned by the venue).
order_side (OrderSide {
BUY,SELL}) – The reported order side.order_type (OrderType) – The reported order type.
time_in_force (TimeInForce {
GTC,IOC,FOK,GTD,DAY,AT_THE_OPEN,AT_THE_CLOSE}) – The reported order time in force.order_status (OrderStatus) – The reported order status at the exchange.
quantity (Quantity) – The reported order original quantity.
filled_qty (Quantity) – The reported filled quantity at the exchange.
report_id (UUID4) – The report ID.
ts_accepted (int) – UNIX timestamp (nanoseconds) when the reported order was accepted.
ts_last (int) – UNIX timestamp (nanoseconds) of the last order status change.
ts_init (int) – UNIX timestamp (nanoseconds) when the object was initialized.
client_order_id (ClientOrderId, optional) – The reported client order ID.
order_list_id (OrderListId, optional) – The reported order list ID associated with the order.
venue_position_id (PositionId, optional) – The reported venue position ID for the order. If the trading venue has associated a position ID / ticket with the order then pass that here, otherwise pass
Noneand the execution engine OMS will handle position ID resolution.contingency_type (ContingencyType, default
NO_CONTINGENCY) – The reported order contingency type.expire_time (datetime, optional) – The order expiration.
price (Price, optional) – The reported order price (LIMIT).
trigger_price (Price, optional) – The reported order trigger price (STOP).
trigger_type (TriggerType, default
NO_TRIGGER) – The reported order trigger type.limit_offset (Decimal, optional) – The trailing offset for the order price (LIMIT).
trailing_offset (Decimal, optional) – The trailing offset for the trigger price (STOP).
trailing_offset_type (TrailingOffsetType, default
NO_TRAILING_OFFSET) – The order trailing offset type.avg_px (Decimal, optional) – The reported order average fill price.
display_qty (Quantity, optional) – The reported order quantity displayed on the public book (iceberg).
post_only (bool, default False) – If the reported order will only provide liquidity (make a market).
reduce_only (bool, default False) – If the reported order carries the ‘reduce-only’ execution instruction.
cancel_reason (str, optional) – The reported reason for order cancellation.
ts_triggered (int, optional) – UNIX timestamp (nanoseconds) when the object was initialized.
- Raises:
ValueError – If quantity is not positive (> 0).
ValueError – If filled_qty is negative (< 0).
ValueError – If trigger_price is not
Noneand trigger_price is equal toNO_TRIGGER.ValueError – If limit_offset or trailing_offset is not
Noneand trailing_offset_type is equal toNO_TRAILING_OFFSET.
- property is_open: bool¶
Return whether the reported order status is ‘open’.
- Return type:
bool
- is_order_updated(order: Order) bool¶
Return whether the order has been updated based on this report.
- Parameters:
order (Order) – The order to compare against.
- Return type:
bool
- to_dict() dict[str, Any]¶
Return a dictionary representation of this object.
- Return type:
dict[str, Any]
- classmethod from_dict(values: dict[str, Any]) OrderStatusReport¶
Return an order status report from the given dict values.
- Parameters:
values (dict[str, Any]) – The values for initialization.
- Return type:
- to_pyo3() OrderStatusReport¶
- static from_pyo3(pyo3_report: OrderStatusReport) OrderStatusReport¶
- id¶
The document message ID.
- Returns:
UUID4
- ts_init¶
UNIX timestamp (nanoseconds) when the object was initialized.
- Returns:
uint64_t
- class FillReport¶
Bases:
ExecutionReportRepresents a report of a single order fill.
- Parameters:
account_id (AccountId) – The account ID for the report.
instrument_id (InstrumentId) – The reported instrument ID for the trade.
venue_order_id (VenueOrderId) – The reported venue order ID (assigned by the venue) for the trade.
trade_id (TradeId) – The reported trade match ID (assigned by the venue).
order_side (OrderSide {
BUY,SELL}) – The reported order side for the trade.last_qty (Quantity) – The reported quantity of the trade.
last_px (Price) – The reported price of the trade.
commission (Money) – The reported commission for the trade. If no commission then use a zero Money amount of the commission currency.
liquidity_side (LiquiditySide {
NO_LIQUIDITY_SIDE,MAKER,TAKER}) – The reported liquidity side for the trade.report_id (UUID4) – The report ID.
ts_event (int) – UNIX timestamp (nanoseconds) when the trade occurred.
ts_init (int) – UNIX timestamp (nanoseconds) when the object was initialized.
client_order_id (ClientOrderId, optional) – The reported client order ID for the trade.
venue_position_id (PositionId, optional) – The reported venue position ID for the trade. If the trading venue has assigned a position ID / ticket for the trade then pass that here, otherwise pass
Noneand the execution engine OMS will handle position ID resolution.
- Raises:
ValueError – If last_qty is not positive (> 0).
- to_dict() dict[str, Any]¶
Return a dictionary representation of this object.
- Return type:
dict[str, Any]
- classmethod from_dict(values: dict[str, Any]) FillReport¶
Return a fill report from the given dict values.
- Parameters:
values (dict[str, Any]) – The values for initialization.
- Return type:
- to_pyo3() FillReport¶
- static from_pyo3(pyo3_report: FillReport) FillReport¶
- id¶
The document message ID.
- Returns:
UUID4
- ts_init¶
UNIX timestamp (nanoseconds) when the object was initialized.
- Returns:
uint64_t
- class PositionStatusReport¶
Bases:
ExecutionReportRepresents a position status at a point in time.
- Parameters:
account_id (AccountId) – The account ID for the report.
instrument_id (InstrumentId) – The reported instrument ID for the position.
position_side (PositionSide {
FLAT,LONG,SHORT}) – The reported position side at the exchange.quantity (Quantity) – The reported position quantity at the exchange.
report_id (UUID4) – The report ID.
ts_last (int) – UNIX timestamp (nanoseconds) of the last position change.
ts_init (int) – UNIX timestamp (nanoseconds) when the object was initialized.
venue_position_id (PositionId, optional) – The reported venue position ID (assigned by the venue). If the trading venue has assigned a position ID / ticket for the trade then pass that here, otherwise pass
Noneand the execution engine OMS will handle position ID resolution.avg_px_open (Decimal, optional) – The reported position average open price.
- static create_flat(account_id: AccountId, instrument_id: InstrumentId, size_precision: int, ts_init: int, report_id: UUID4 | None = None) PositionStatusReport¶
- to_dict() dict[str, Any]¶
Return a dictionary representation of this object.
- Return type:
dict[str, Any]
- classmethod from_dict(values: dict[str, Any]) PositionStatusReport¶
Return a position status report from the given dict values.
- Parameters:
values (dict[str, Any]) – The values for initialization.
- Return type:
- to_pyo3() PositionStatusReport¶
- static from_pyo3(pyo3_report: PositionStatusReport) PositionStatusReport¶
- id¶
The document message ID.
- Returns:
UUID4
- ts_init¶
UNIX timestamp (nanoseconds) when the object was initialized.
- Returns:
uint64_t
- class ExecutionMassStatus¶
Bases:
DocumentRepresents an execution mass status report for an execution client - including status of all orders, trades for those orders and open positions.
- Parameters:
- property order_reports: dict[VenueOrderId, OrderStatusReport]¶
The order status reports.
- Return type:
dict[VenueOrderId, OrderStatusReport]
- property fill_reports: dict[VenueOrderId, list[FillReport]]¶
The fill reports.
- Return type:
dict[VenueOrderId, list[FillReport]
- property position_reports: dict[InstrumentId, list[PositionStatusReport]]¶
The position status reports.
- Return type:
dict[InstrumentId, list[PositionStatusReport]]
- add_order_reports(reports: list[OrderStatusReport]) None¶
Add the order reports to the mass status.
- Parameters:
reports (list[OrderStatusReport]) – The list of reports to add.
- Raises:
TypeError – If reports contains a type other than OrderStatusReport.
- add_fill_reports(reports: list[FillReport]) None¶
Add the fill reports to the mass status.
- Parameters:
reports (list[FillReport]) – The list of reports to add.
- Raises:
TypeError – If reports contains a type other than FillReport.
- add_position_reports(reports: list[PositionStatusReport]) None¶
Add the position status reports to the mass status.
- Parameters:
reports (list[PositionStatusReport]) – The reports to add.
- to_dict() dict[str, Any]¶
Return a dictionary representation of this object.
- Return type:
dict[str, Any]
- to_pyo3() ExecutionMassStatus¶
- classmethod from_dict(values: dict[str, Any]) ExecutionMassStatus¶
Return an execution mass status from the given dict values.
- Parameters:
values (dict[str, Any]) – The values for initialization.
- Return type:
- id¶
The document message ID.
- Returns:
UUID4
- ts_init¶
UNIX timestamp (nanoseconds) when the object was initialized.
- Returns:
uint64_t