Common
The common subpackage provides generic/common parts for assembling the frameworks various components.
More domain specific concepts are introduced above the core base layer. The ID cache is implemented, a base Clock with Test and Live implementations which can control many Timer instances.
Trading domain specific components for generating Order and Identifier objects, common logging components, a high performance Queue and UUID4 factory.
class Environment
Bases: Enum
Represents the environment context for a Nautilus system.
BACKTEST = 'backtest'
SANDBOX = 'sandbox'
LIVE = 'live'
The Actor class allows traders to implement their own customized components.
A user can inherit from Actor and optionally override any of the “on” named event handler methods. The class is not entirely initialized in a stand-alone way, the intended usage is to pass actors to a Trader so that they can be fully “wired” into the platform. Exceptions will be raised if an Actor attempts to operate without a managing Trader instance.
class Actor
Bases: Component
Actor(config: ActorConfig | None = None)
The base class for all actor components.
- Parameters: config (ActorConfig , optional) – The actor configuration.
- Raises: TypeError – If config is not of type ActorConfig.
WARNING
- This class should not be used directly, but through a concrete subclass.
- Do not call components such as clock and logger in the __init__ prior to registration.
active_task_ids(self) → list
Return the active task identifiers.
- Return type: list[TaskId]
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.
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
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 DEGRADING
state.
WARNING
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
deregister_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 DISPOSING
state.
WARNING
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
fault(self) → void
Fault the component.
Calling this method multiple times has the same effect as calling it once (it is idempotent). Once called, it cannot be reversed, and no other methods should be called on this instance.
While executing on_fault() any exception will be logged and reraised, then the component
will remain in a FAULTING
state.
WARNING
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
classmethod fully_qualified_name(cls) → str
Return the fully qualified name for the components class.
- Return type: str
handle_bar(self, Bar bar) → void
Handle the given bar data.
If state is RUNNING
then passes to on_bar.
- Parameters: bar (Bar) – The bar received.
WARNING
System method (not intended to be called by user code).
handle_bars(self, list bars) → void
Handle the given historical bar data by handling each bar individually.
- Parameters: bars (list [Bar ]) – The bars to handle.
WARNING
System method (not intended to be called by user code).
handle_data(self, Data data) → void
Handle the given data.
If state is RUNNING
then 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 RUNNING
then passes to on_event.
- Parameters: event (Event) – The event received.
WARNING
System method (not intended to be called by user code).
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_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 RUNNING
then 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 RUNNING
then passes to on_instrument_status.
- Parameters: data (InstrumentStatus) – The status update received.
WARNING
System method (not intended to be called by user code).
handle_instruments(self, list instruments) → void
Handle the given instruments data by handling each instrument individually.
- Parameters: instruments (list [Instrument ]) – The instruments 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) → 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.
WARNING
System method (not intended to be called by user code).
handle_quote_tick(self, QuoteTick tick) → void
Handle the given quote tick.
If state is RUNNING
then passes to on_quote_tick.
- Parameters: tick (QuoteTick) – The tick received.
WARNING
System method (not intended to be called by user code).
handle_quote_ticks(self, list ticks) → void
Handle the given historical quote tick data by handling each tick individually.
- Parameters: ticks (list [QuoteTick ]) – The ticks 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 RUNNING
then 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) → void
Handle the given trade tick.
If state is RUNNING
then passes to on_trade_tick.
- Parameters: tick (TradeTick) – The tick received.
WARNING
System method (not intended to be called by user code).
handle_trade_ticks(self, list ticks) → void
Handle the given historical trade tick data by handling each tick individually.
- Parameters: ticks (list [TradeTick ]) – The ticks 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
instrument_greeks_data(self, InstrumentId instrument_id) → GreeksData
Retrieve the Greeks data for a given instrument.
This method handles both options and futures instruments. For options, it retrieves the Greeks data from the cache. For futures, it creates a GreeksData object based on the instrument’s delta and multiplier.
- Parameters: instrument_id (InstrumentId) – The identifier of the instrument for which to retrieve Greeks data.
- Returns: The Greeks data for the specified instrument, including vol, price, delta, gamma, vega, theta.
- Return type: GreeksData
is_degraded
bool
Return whether the current component state is DEGRADED
.
- Return type: bool
- Type: Component.is_degraded
is_disposed
bool
Return whether the current component state is DISPOSED
.
- Return type: bool
- Type: Component.is_disposed
is_faulted
bool
Return whether the current component state is FAULTED
.
- Return type: bool
- Type: Component.is_faulted
is_initialized
bool
Return whether the component has been initialized (component.state >= INITIALIZED
).
- Return type: bool
- Type: Component.is_initialized
is_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: Component.is_running
is_stopped
bool
Return whether the current component state is STOPPED
.
- Return type: bool
- Type: Component.is_stopped
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 , object ]) – The state dictionary.
- Raises: RuntimeError – If actor/strategy is not registered with a trader.
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
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_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_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.
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_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 dictionary.
- 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).
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
portfolio_greeks(self, unicode underlying=u'', Venue venue=None, InstrumentId instrument_id=None, StrategyId strategy_id=None, PositionSide side=PositionSide.NO_POSITION_SIDE) → PortfolioGreeks
Calculate the portfolio Greeks for a given set of positions.
This method aggregates the Greeks data for all open positions that match the specified criteria.
- Parameters:
- underlying (str , optional) – The underlying asset symbol to filter positions. If provided, only positions with instruments starting with this symbol will be included. Default is an empty string (no filtering).
- venue (Venue , optional) – The venue to filter positions. If provided, only positions from this venue will be included.
- instrument_id (InstrumentId , optional) – The instrument ID to filter positions. If provided, only positions for this instrument will be included.
- strategy_id (StrategyId , optional) – The strategy ID to filter positions. If provided, only positions for this strategy will be included.
- side (PositionSide , optional) – The position side to filter. If provided, only positions with this side will be included. Default is PositionSide.NO_POSITION_SIDE (no filtering).
- Returns: The aggregated Greeks data for the portfolio, including delta, gamma, vega, theta.
- Return type: PortfolioGreeks
publish_data(self, DataType data_type, Data data) → void
Publish the given data to the message bus.
- Parameters:
- data_type (DataType) – The data type being published.
- data (Data) – The data to publish.
publish_signal(self, unicode 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
None
then 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.
queued_task_ids(self) → list
Return the queued task identifiers.
- Return type: list[TaskId]
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.AsbtractEventLoop) – 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.
- Parameters:
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=None, datetime end=None, ClientId client_id=None, callback: Callable[[UUID4], None] | None = None, bool include_external_data=False, bool update_existing_subscriptions=False, bool update_catalog=False) → 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 None
then will request up to the most recent data.
- 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 , 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.
- client_id (ClientId , optional) – The specific client ID for the command.
If
None
then 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_existing_subscriptions (bool , default False) – If True, updates the aggregators of any existing subscription with the queried external data.
- update_catalog (bool , default False) – If True then updates the catalog with new data received from a client.
- Returns: The request_id for the request.
- Return type: UUID4
- 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.
- 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.
request_bars(self, BarType bar_type, datetime start=None, datetime end=None, ClientId client_id=None, callback: Callable[[UUID4], None] | None = None, bool update_catalog=False) → UUID4
Request historical Bar data.
If end is None
then will request up to the most recent data.
- Parameters:
- bar_type (BarType) – The bar type for the request.
- start (datetime , optional) – The start datetime (UTC) of request time range (inclusive).
- end (datetime , optional) – The end datetime (UTC) of request time range. The inclusiveness depends on individual data client implementation.
- client_id (ClientId , optional) – The specific client ID for the command.
If
None
then 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 True then updates the catalog with new data received from a client.
- Returns: The request_id for the request.
- Return type: UUID4
- 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_data(self, DataType data_type, ClientId client_id, callback: Callable[[UUID4], None] | None = None) → UUID4
Request custom data for the given data type from the given data client.
- Parameters:
- Returns: The request_id for the request.
- Return type: UUID4
- Raises: 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) → UUID4
Request Instrument data for the given instrument ID.
If end is None
then will request up to the most recent data.
- Parameters:
- instrument_id (InstrumentId) – The instrument ID for the request.
- start (datetime , optional) – The start datetime (UTC) of request time range (inclusive).
- end (datetime , optional) – The end datetime (UTC) of request time range. The inclusiveness depends on individual data client implementation.
- client_id (ClientId , optional) – The specific client ID for the command.
If
None
then 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 True then updates the catalog with new data received from a client.
- Returns: The request_id for the request.
- Return type: UUID4
- 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) → UUID4
Request all Instrument data for the given venue.
If end is None
then will request up to the most recent data.
- Parameters:
- venue (Venue) – The venue for the request.
- start (datetime , optional) – The start datetime (UTC) of request time range (inclusive).
- end (datetime , optional) – The end datetime (UTC) of request time range. The inclusiveness depends on individual data client implementation.
- client_id (ClientId , optional) – The specific client ID for the command.
If
None
then 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 True then updates the catalog with new data received from a client.
- Returns: The request_id for the request.
- Return type: UUID4
- 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_order_book_snapshot(self, InstrumentId instrument_id, int limit, ClientId client_id=None, callback: Callable[[UUID4], None] | None = None) → UUID4
Request an order book snapshot.
- 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 (default is None).
- 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 True then updates the catalog with new data received from a client.
- Returns: The request_id for the request.
- Return type: UUID4
- 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=None, datetime end=None, ClientId client_id=None, callback: Callable[[UUID4], None] | None = None, unicode quote_type=u'', bool update_catalog=False) → UUID4
Request historical QuoteTick data.
If end is None
then will request up to the most recent data.
- Parameters:
- instrument_id (InstrumentId) – The tick instrument ID for the request.
- start (datetime , optional) – The start datetime (UTC) of request time range (inclusive).
- end (datetime , optional) – The end datetime (UTC) of request time range. The inclusiveness depends on individual data client implementation.
- client_id (ClientId , optional) – The specific client ID for the command.
If
None
then 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.
- quote_type (str , default '') – The specified quote type applicable to certain client implementations.
- update_catalog (bool , default False) – If True then updates the catalog with new data received from a client.
- Returns: The request_id for the request.
- Return type: UUID4
- 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_trade_ticks(self, InstrumentId instrument_id, datetime start=None, datetime end=None, ClientId client_id=None, callback: Callable[[UUID4], None] | None = None, bool update_catalog=False) → UUID4
Request historical TradeTick data.
If end is None
then will request up to the most recent data.
- Parameters:
- instrument_id (InstrumentId) – The tick instrument ID for the request.
- start (datetime , optional) – The start datetime (UTC) of request time range (inclusive).
- end (datetime , optional) – The end datetime (UTC) of request time range. The inclusiveness depends on individual data client implementation.
- client_id (ClientId , optional) – The specific client ID for the command.
If
None
then 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 True then updates the catalog with new data received from a client.
- Returns: The request_id for the request.
- Return type: UUID4
- 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.
reset(self) → void
Reset the component.
All stateful fields are reset to their initial value.
While executing on_reset() any exception will be logged and reraised, then the component
will remain in a RESETTING
state.
WARNING
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
resume(self) → void
Resume the component.
While executing on_resume() any exception will be logged and reraised, then the component
will remain in a RESUMING
state.
WARNING
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
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: TaskId
- Raises: TypeError – If func is not of type Callable.
save(self) → dict
Return the actor/strategy state dictionary to be saved.
Calls on_save.
- Raises: RuntimeError – If actor/strategy is not registered with a trader.
WARNING
Exceptions raised will be caught, logged, and reraised.
start(self) → void
Start the component.
While executing on_start() any exception will be logged and reraised, then the component
will remain in a STARTING
state.
WARNING
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
state
ComponentState
Return the components current state.
- Return type: ComponentState
- Type: Component.state
stop(self) → void
Stop the component.
While executing on_stop() any exception will be logged and reraised, then the component
will remain in a STOPPING
state.
WARNING
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
subscribe_bars(self, BarType bar_type, ClientId client_id=None, bool await_partial=False) → void
Subscribe to streaming Bar data for the given bar type.
- Parameters:
- bar_type (BarType) – The bar type to subscribe to.
- client_id (ClientId , optional) – The specific client ID for the command.
If
None
then will be inferred from the venue in the instrument ID. - await_partial (bool , default False) – If the bar aggregator should await the arrival of a historical partial bar prior to actively aggregating new bars.
subscribe_data(self, DataType data_type, ClientId client_id=None) → void
Subscribe to data of the given data type.
- Parameters:
subscribe_instrument(self, InstrumentId instrument_id, ClientId client_id=None) → void
Subscribe to update Instrument data for the given instrument ID.
- Parameters:
- instrument_id (InstrumentId) – The instrument ID for the subscription.
- client_id (ClientId , optional) – The specific client ID for the command.
If
None
then will be inferred from the venue in the instrument ID.
subscribe_instrument_close(self, InstrumentId instrument_id, ClientId client_id=None) → void
Subscribe to close updates for the given instrument ID.
- Parameters:
- instrument_id (InstrumentId) – The instrument to subscribe to status updates for.
- client_id (ClientId , optional) – The specific client ID for the command.
If
None
then will be inferred from the venue in the instrument ID.
subscribe_instrument_status(self, InstrumentId instrument_id, ClientId client_id=None) → void
Subscribe to status updates for the given instrument ID.
- Parameters:
- instrument_id (InstrumentId) – The instrument to subscribe to status updates for.
- client_id (ClientId , optional) – The specific client ID for the command.
If
None
then will be inferred from the venue in the instrument ID.
subscribe_instruments(self, Venue venue, ClientId client_id=None) → void
Subscribe to update Instrument data for the given venue.
- Parameters:
subscribe_order_book_at_interval(self, InstrumentId instrument_id, BookType book_type=BookType.L2_MBP, int depth=0, int interval_ms=1000, dict kwargs=None, ClientId client_id=None, bool managed=True) → void
Subscribe to an OrderBook at a specified interval for the given instrument ID.
The DataEngine will only maintain one order book for each instrument. Because of this - the level, depth and kwargs 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) – The order book snapshot interval in milliseconds (must be positive).
- kwargs (dict , optional) – The keyword arguments for exchange specific parameters.
- client_id (ClientId , optional) – The specific client ID for the command.
If
None
then 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.
- 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, dict kwargs=None, ClientId client_id=None, bool managed=True, bool pyo3_conversion=False) → void
Subscribe to the order book data stream, being a snapshot then deltas for the given instrument ID.
- 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.
- kwargs (dict , optional) – The keyword arguments for exchange specific parameters.
- client_id (ClientId , optional) – The specific client ID for the command.
If
None
then 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.
subscribe_quote_ticks(self, InstrumentId instrument_id, ClientId client_id=None) → void
Subscribe to streaming QuoteTick data for the given instrument ID.
- Parameters:
- instrument_id (InstrumentId) – The tick instrument to subscribe to.
- client_id (ClientId , optional) – The specific client ID for the command.
If
None
then will be inferred from the venue in the instrument ID.
subscribe_signal(self, unicode name=u'') → void
Subscribe to a specific signal by name, or to all signals if no name is provided.
- 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) → void
Subscribe to streaming TradeTick data for the given instrument ID.
- Parameters:
- instrument_id (InstrumentId) – The tick instrument to subscribe to.
- client_id (ClientId , optional) – The specific client ID for the command.
If
None
then will be inferred from the venue in the instrument ID.
to_importable_config(self) → ImportableActorConfig
Returns an importable configuration for this actor.
- Return type: ImportableActorConfig
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) → void
Unsubscribe from streaming Bar data for the given bar type.
- Parameters:
unsubscribe_data(self, DataType data_type, ClientId client_id=None) → void
Unsubscribe from data of the given data type.
- Parameters:
unsubscribe_instrument(self, InstrumentId instrument_id, ClientId client_id=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
None
then will be inferred from the venue in the instrument ID.
unsubscribe_instrument_status(self, InstrumentId instrument_id, ClientId client_id=None) → void
Unsubscribe to status updates of the given venue.
- Parameters:
- instrument_id (InstrumentId) – The instrument to unsubscribe to status updates for.
- client_id (ClientId , optional) – The specific client ID for the command.
If
None
then will be inferred from the venue.
unsubscribe_instruments(self, Venue venue, ClientId client_id=None) → void
Unsubscribe from update Instrument data for the given venue.
- Parameters:
unsubscribe_order_book_at_interval(self, InstrumentId instrument_id, int interval_ms=1000, ClientId client_id=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) – The order book snapshot interval in milliseconds.
- client_id (ClientId , optional) – The specific client ID for the command.
If
None
then will be inferred from the venue in the instrument ID.
unsubscribe_order_book_deltas(self, InstrumentId instrument_id, ClientId client_id=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
None
then will be inferred from the venue in the instrument ID.
unsubscribe_quote_ticks(self, InstrumentId instrument_id, ClientId client_id=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
None
then will be inferred from the venue in the instrument ID.
unsubscribe_trade_ticks(self, InstrumentId instrument_id, ClientId client_id=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
None
then will be inferred from the venue in the instrument ID.
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.
class OrderFactory
Bases: object
OrderFactory(TraderId trader_id, StrategyId strategy_id, Clock clock, CacheFacade cache: CacheFacade | None = None, int initial_order_id_count=0, int initial_order_list_id_count=0)
A factory class which provides different order types.
The TraderId tag and StrategyId tag will be inserted into all IDs generated.
- Parameters:
- trader_id (TraderId) – The trader ID (only numerical tag sent to venue).
- strategy_id (StrategyId) – The strategy ID (only numerical tag sent to venue).
- clock (Clock) – The clock for the factory.
- cache (CacheFacade , optional) – The cache facade for the order factory.
- initial_order_id_count (int , optional) – The initial order ID count for the factory.
- initial_order_list_id_count (int , optional) – The initial order list ID count for the factory.
- Raises:
- ValueError – If initial_order_id_count is negative (< 0).
- ValueError – If initial_order_list_id_count is negative (< 0).
bracket(self, InstrumentId instrument_id, OrderSide order_side, Quantity quantity, Price entry_trigger_price=None, Price entry_price=None, Price sl_trigger_price=None, Price tp_trigger_price=None, Price tp_price=None, OrderType entry_order_type=OrderType.MARKET, OrderType tp_order_type=OrderType.LIMIT, TimeInForce time_in_force=TimeInForce.GTC, TimeInForce sl_time_in_force=TimeInForce.GTC, TimeInForce tp_time_in_force=TimeInForce.GTC, datetime expire_time=None, bool entry_post_only=False, bool tp_post_only=True, bool quote_quantity=False, TriggerType emulation_trigger=TriggerType.NO_TRIGGER, InstrumentId trigger_instrument_id=None, ContingencyType contingency_type=ContingencyType.OUO, ExecAlgorithmId entry_exec_algorithm_id=None, ExecAlgorithmId sl_exec_algorithm_id=None, ExecAlgorithmId tp_exec_algorithm_id=None, dict entry_exec_algorithm_params=None, dict sl_exec_algorithm_params=None, dict tp_exec_algorithm_params=None, list entry_tags=None, list sl_tags=None, list tp_tags=None, ClientOrderId entry_client_order_id=None, ClientOrderId sl_client_order_id=None, ClientOrderId tp_client_order_id=None) → OrderList
Create a bracket order with optional entry of take-profit order types.
The stop-loss order will always be STOP_MARKET
.
- Parameters:
- instrument_id (InstrumentId) – The orders instrument ID.
- order_side (OrderSide {
BUY
,SELL
}) – The entry orders side. - quantity (Quantity) – The entry orders quantity (> 0).
- entry_trigger_price (Price , optional) – The entry order trigger price (STOP).
- entry_price (Price , optional) – The entry order price (LIMIT).
- sl_trigger_price (Price) – The stop-loss child order trigger price (STOP).
- tp_trigger_price (Price , optional) – The take-profit child order trigger price (STOP).
- tp_price (Price , optional) – The take-profit child order price (LIMIT).
- entry_order_type (OrderType {
MARKET
,LIMIT
,LIMIT_IF_TOUCHED
,MARKET_IF_TOUCHED
}, defaultMARKET
) – The entry order type. - tp_order_type (OrderType {
LIMIT
,LIMIT_IF_TOUCHED
,MARKET_IF_TOUCHED
}, defaultLIMIT
) – The take-profit order type. - time_in_force (TimeInForce, default
GTC
) – The entry orders time in force. - sl_time_in_force (TimeInForce, default
GTC
) – The stop-loss orders time in force. - tp_time_in_force (TimeInForce, default
GTC
) – The take-profit orders time in force. - expire_time (datetime , optional) – The order expiration (for
GTD
orders). - entry_post_only (bool , default False) – If the entry order will only provide liquidity (make a market).
- tp_post_only (bool , default False) – If the take-profit order will only provide liquidity (make a market).
- quote_quantity (bool) – If order quantity is denominated in the quote currency.
- emulation_trigger (TriggerType, default
NO_TRIGGER
) – The emulation trigger type for the entry, as well as the TP and SL bracket orders. - trigger_instrument_id (InstrumentId , optional) – The emulation trigger instrument ID for the order (if
None
then will be the instrument_id). - contingency_type (ContingencyType, default
OUO
) – The contingency type for the TP and SL bracket orders. - entry_exec_algorithm_id (ExecAlgorithmId , optional) – The entry order execution algorithm ID.
- sl_exec_algorithm_id (ExecAlgorithmId , optional) – The stop-loss order execution algorithm ID.
- tp_exec_algorithm_id (ExecAlgorithmId , optional) – The take-profit order execution algorithm ID.
- entry_exec_algorithm_params (dict *[*str , Any ] , optional) – The execution algorithm parameters for the order.
- sl_exec_algorithm_params (dict *[*str , Any ] , optional) – The execution algorithm parameters for the order.
- tp_exec_algorithm_params (dict *[*str , Any ] , optional) – The execution algorithm parameters for the order.
- entry_tags (list *[*str ] , default [ "ENTRY" ]) – The custom user tags for the entry order.
- sl_tags (list *[*str ] , default [ "STOP_LOSS" ]) – The custom user tags for the stop-loss order.
- tp_tags (list *[*str ] , default [ "TAKE_PROFIT" ]) – The custom user tags for the take-profit order.
- entry_client_order_id (ClientOrderId , optional) – The custom client order ID for the order. If a client order ID is not provided then one will be generated by the factory.
- sl_client_order_id (ClientOrderId , optional) – The custom client order ID for the order. If a client order ID is not provided then one will be generated by the factory.
- tp_client_order_id (ClientOrderId , optional) – The custom client order ID for the order. If a client order ID is not provided then one will be generated by the factory.
- Return type: OrderList
create_list(self, list orders) → OrderList
Return a new order list containing the given orders.
- Parameters: orders (list [Order ]) – The orders for the list.
- Return type: OrderList
- Raises: ValueError – If orders is empty.
generate_client_order_id(self) → ClientOrderId
Generate and return a new client order ID.
The identifier will be the next in the logical sequence.
- Return type: ClientOrderId
generate_order_list_id(self) → OrderListId
Generate and return a new order list ID.
The identifier will be the next in the logical sequence.
- Return type: OrderListId
limit(self, InstrumentId instrument_id, OrderSide order_side, Quantity quantity, Price price, TimeInForce time_in_force=TimeInForce.GTC, datetime expire_time=None, bool post_only=False, bool reduce_only=False, bool quote_quantity=False, Quantity display_qty=None, TriggerType emulation_trigger=TriggerType.NO_TRIGGER, InstrumentId trigger_instrument_id=None, ExecAlgorithmId exec_algorithm_id=None, dict exec_algorithm_params=None, list tags=None, ClientOrderId client_order_id=None) → LimitOrder
Create a new LIMIT
order.
- Parameters:
- instrument_id (InstrumentId) – The orders instrument ID.
- order_side (OrderSide {
BUY
,SELL
}) – The orders side. - quantity (Quantity) – The orders quantity (> 0).
- price (Price) – The orders price.
- time_in_force (TimeInForce {
GTC
,IOC
,FOK
,GTD
,DAY
,AT_THE_OPEN
,AT_THE_CLOSE
}, defaultGTC
) – The orders time in force. - expire_time (datetime , optional) – The order expiration (for
GTD
orders). - post_only (bool , default False) – If the order will only provide liquidity (make a market).
- reduce_only (bool , default False) – If the order carries the ‘reduce-only’ execution instruction.
- quote_quantity (bool) – If the order quantity is denominated in the quote currency.
- display_qty (Quantity , optional) – The quantity of the order to display on the public book (iceberg).
- emulation_trigger (TriggerType, default
NO_TRIGGER
) – The orders emulation trigger. - trigger_instrument_id (InstrumentId , optional) – The emulation trigger instrument ID for the order (if
None
then will be the instrument_id). - exec_algorithm_id (ExecAlgorithmId , optional) – The execution algorithm ID for the order.
- exec_algorithm_params (dict *[*str , Any ] , optional) – The execution algorithm parameters for the order.
- tags (list *[*str ] , optional) – The custom user tags for the order.
- client_order_id (ClientOrderId , optional) – The custom client order ID for the order. If a client order ID is not provided then one will be generated by the factory.
- Return type: LimitOrder
- Raises:
- ValueError – If quantity is not positive (> 0).
- ValueError – If time_in_force is
GTD
and expire_time <= UNIX epoch. - ValueError – If display_qty is negative (< 0) or greater than quantity.
limit_if_touched(self, InstrumentId instrument_id, OrderSide order_side, Quantity quantity, Price price, Price trigger_price, TriggerType trigger_type=TriggerType.DEFAULT, TimeInForce time_in_force=TimeInForce.GTC, datetime expire_time=None, bool post_only=False, bool reduce_only=False, bool quote_quantity=False, Quantity display_qty=None, TriggerType emulation_trigger=TriggerType.NO_TRIGGER, InstrumentId trigger_instrument_id=None, ExecAlgorithmId exec_algorithm_id=None, dict exec_algorithm_params=None, list tags=None, ClientOrderId client_order_id=None) → LimitIfTouchedOrder
Create a new LIMIT_IF_TOUCHED
(LIT) conditional order.
- Parameters:
- instrument_id (InstrumentId) – The orders instrument ID.
- order_side (OrderSide {
BUY
,SELL
}) – The orders side. - quantity (Quantity) – The orders quantity (> 0).
- price (Price) – The orders limit price.
- trigger_price (Price) – The orders trigger stop price.
- trigger_type (TriggerType, default
DEFAULT
) – The order trigger type. - time_in_force (TimeInForce {
GTC
,IOC
,FOK
,GTD
,DAY
}, defaultGTC
) – The orders time in force. - expire_time (datetime , optional) – The order expiration (for
GTD
orders). - post_only (bool , default False) – If the order will only provide liquidity (make a market).
- reduce_only (bool , default False) – If the order carries the ‘reduce-only’ execution instruction.
- quote_quantity (bool) – If the order quantity is denominated in the quote currency.
- display_qty (Quantity , optional) – The quantity of the order to display on the public book (iceberg).
- emulation_trigger (TriggerType, default
NO_TRIGGER
) – The orders emulation trigger. - trigger_instrument_id (InstrumentId , optional) – The emulation trigger instrument ID for the order (if
None
then will be the instrument_id). - exec_algorithm_id (ExecAlgorithmId , optional) – The execution algorithm ID for the order.
- exec_algorithm_params (dict *[*str , Any ] , optional) – The execution algorithm parameters for the order.
- tags (list *[*str ] , optional) – The custom user tags for the order.
- client_order_id (ClientOrderId , optional) – The custom client order ID for the order. If a client order ID is not provided then one will be generated by the factory.
- Return type: LimitIfTouchedOrder
- Raises:
- ValueError – If quantity is not positive (> 0).
- ValueError – If trigger_type is
NO_TRIGGER
. - ValueError – If time_in_force is
AT_THE_OPEN
orAT_THE_CLOSE
. - ValueError – If time_in_force is
GTD
and expire_time <= UNIX epoch. - ValueError – If display_qty is negative (< 0) or greater than quantity.
market(self, InstrumentId instrument_id, OrderSide order_side, Quantity quantity, TimeInForce time_in_force=TimeInForce.GTC, bool reduce_only=False, bool quote_quantity=False, ExecAlgorithmId exec_algorithm_id=None, dict exec_algorithm_params=None, list tags=None, ClientOrderId client_order_id=None) → MarketOrder
Create a new MARKET
order.
- Parameters:
- instrument_id (InstrumentId) – The orders instrument ID.
- order_side (OrderSide {
BUY
,SELL
}) – The orders side. - quantity (Quantity) – The orders quantity (> 0).
- time_in_force (TimeInForce {
GTC
,IOC
,FOK
,DAY
,AT_THE_OPEN
,AT_THE_CLOSE
}, defaultGTC
) – The orders time in force. Often not applicable for market orders. - reduce_only (bool , default False) – If the order carries the ‘reduce-only’ execution instruction.
- quote_quantity (bool) – If the order quantity is denominated in the quote currency.
- exec_algorithm_id (ExecAlgorithmId , optional) – The execution algorithm ID for the order.
- exec_algorithm_params (dict *[*str , Any ] , optional) – The execution algorithm parameters for the order.
- tags (list *[*str ] , optional) – The custom user tags for the order.
- client_order_id (ClientOrderId , optional) – The custom client order ID for the order. If a client order ID is not provided then one will be generated by the factory.
- Return type: MarketOrder
- Raises:
- ValueError – If quantity is not positive (> 0).
- ValueError – If time_in_force is
GTD
.
market_if_touched(self, InstrumentId instrument_id, OrderSide order_side, Quantity quantity, Price trigger_price, TriggerType trigger_type=TriggerType.DEFAULT, TimeInForce time_in_force=TimeInForce.GTC, datetime expire_time=None, bool reduce_only=False, bool quote_quantity=False, TriggerType emulation_trigger=TriggerType.NO_TRIGGER, InstrumentId trigger_instrument_id=None, ExecAlgorithmId exec_algorithm_id=None, dict exec_algorithm_params=None, list tags=None, ClientOrderId client_order_id=None) → MarketIfTouchedOrder
Create a new MARKET_IF_TOUCHED
(MIT) conditional order.
- Parameters:
- instrument_id (InstrumentId) – The orders instrument ID.
- order_side (OrderSide {
BUY
,SELL
}) – The orders side. - quantity (Quantity) – The orders quantity (> 0).
- trigger_price (Price) – The orders trigger price (STOP).
- trigger_type (TriggerType, default
DEFAULT
) – The order trigger type. - time_in_force (TimeInForce {
GTC
,IOC
,FOK
,GTD
,DAY
}, defaultGTC
) – The orders time in force. - expire_time (datetime , optional) – The order expiration (for
GTD
orders). - reduce_only (bool , default False) – If the order carries the ‘reduce-only’ execution instruction.
- quote_quantity (bool) – If the order quantity is denominated in the quote currency.
- emulation_trigger (TriggerType, default
NO_TRIGGER
) – The orders emulation trigger. - trigger_instrument_id (InstrumentId , optional) – The emulation trigger instrument ID for the order (if
None
then will be the instrument_id). - exec_algorithm_id (ExecAlgorithmId , optional) – The execution algorithm ID for the order.
- exec_algorithm_params (dict *[*str , Any ] , optional) – The execution algorithm parameters for the order.
- tags (list *[*str ] , optional) – The custom user tags for the order.
- client_order_id (ClientOrderId , optional) – The custom client order ID for the order. If a client order ID is not provided then one will be generated by the factory.
- Return type: MarketIfTouchedOrder
- Raises:
- ValueError – If quantity is not positive (> 0).
- ValueError – If trigger_type is
NO_TRIGGER
. - ValueError – If time_in_force is
AT_THE_OPEN
orAT_THE_CLOSE
. - ValueError – If time_in_force is
GTD
and expire_time <= UNIX epoch.
market_to_limit(self, InstrumentId instrument_id, OrderSide order_side, Quantity quantity, TimeInForce time_in_force=TimeInForce.GTC, datetime expire_time=None, bool reduce_only=False, bool quote_quantity=False, Quantity display_qty=None, ExecAlgorithmId exec_algorithm_id=None, dict exec_algorithm_params=None, list tags=None, ClientOrderId client_order_id=None) → MarketToLimitOrder
Create a new MARKET
order.
- Parameters:
- instrument_id (InstrumentId) – The orders instrument ID.
- order_side (OrderSide {
BUY
,SELL
}) – The orders side. - quantity (Quantity) – The orders quantity (> 0).
- time_in_force (TimeInForce {
GTC
,GTD
,IOC
,FOK
}, defaultGTC
) – The orders time in force. - expire_time (datetime , optional) – The order expiration (for
GTD
orders). - reduce_only (bool , default False) – If the order carries the ‘reduce-only’ execution instruction.
- quote_quantity (bool) – If the order quantity is denominated in the quote currency.
- display_qty (Quantity , optional) – The quantity of the limit order to display on the public book (iceberg).
- exec_algorithm_id (ExecAlgorithmId , optional) – The execution algorithm ID for the order.
- exec_algorithm_params (dict *[*str , Any ] , optional) – The execution algorithm parameters for the order.
- tags (list *[*str ] , optional) – The custom user tags for the order.
- client_order_id (ClientOrderId , optional) – The custom client order ID for the order. If a client order ID is not provided then one will be generated by the factory.
- Return type: MarketToLimitOrder
- Raises:
- ValueError – If quantity is not positive (> 0).
- ValueError – If time_in_force is
AT_THE_OPEN
orAT_THE_CLOSE
.
reset(self) → void
Reset the order factory.
All stateful fields are reset to their initial value.
set_client_order_id_count(self, int count) → void
Set the internal order ID generator count to the given count.
- Parameters: count (int) – The count to set.
WARNING
System method (not intended to be called by user code).
set_order_list_id_count(self, int count) → void
Set the internal order list ID generator count to the given count.
- Parameters: count (int) – The count to set.
WARNING
System method (not intended to be called by user code).
stop_limit(self, InstrumentId instrument_id, OrderSide order_side, Quantity quantity, Price price, Price trigger_price, TriggerType trigger_type=TriggerType.DEFAULT, TimeInForce time_in_force=TimeInForce.GTC, datetime expire_time=None, bool post_only=False, bool reduce_only=False, bool quote_quantity=False, Quantity display_qty=None, TriggerType emulation_trigger=TriggerType.NO_TRIGGER, InstrumentId trigger_instrument_id=None, ExecAlgorithmId exec_algorithm_id=None, dict exec_algorithm_params=None, list tags=None, ClientOrderId client_order_id=None) → StopLimitOrder
Create a new STOP_LIMIT
conditional order.
- Parameters:
- instrument_id (InstrumentId) – The orders instrument ID.
- order_side (OrderSide {
BUY
,SELL
}) – The orders side. - quantity (Quantity) – The orders quantity (> 0).
- price (Price) – The orders limit price.
- trigger_price (Price) – The orders trigger stop price.
- trigger_type (TriggerType, default
DEFAULT
) – The order trigger type. - time_in_force (TimeInForce {
GTC
,IOC
,FOK
,GTD
,DAY
}, defaultGTC
) – The orders time in force. - expire_time (datetime , optional) – The order expiration (for
GTD
orders). - post_only (bool , default False) – If the order will only provide liquidity (make a market).
- reduce_only (bool , default False) – If the order carries the ‘reduce-only’ execution instruction.
- quote_quantity (bool) – If the order quantity is denominated in the quote currency.
- display_qty (Quantity , optional) – The quantity of the order to display on the public book (iceberg).
- emulation_trigger (TriggerType, default
NO_TRIGGER
) – The orders emulation trigger. - trigger_instrument_id (InstrumentId , optional) – The emulation trigger instrument ID for the order (if
None
then will be the instrument_id). - exec_algorithm_id (ExecAlgorithmId , optional) – The execution algorithm ID for the order.
- exec_algorithm_params (dict *[*str , Any ] , optional) – The execution algorithm parameters for the order.
- tags (list *[*str ] , optional) – The custom user tags for the order.
- client_order_id (ClientOrderId , optional) – The custom client order ID for the order. If a client order ID is not provided then one will be generated by the factory.
- Return type: StopLimitOrder
- Raises:
- ValueError – If quantity is not positive (> 0).
- ValueError – If trigger_type is
NO_TRIGGER
. - ValueError – If time_in_force is
AT_THE_OPEN
orAT_THE_CLOSE
. - ValueError – If time_in_force is
GTD
and expire_time <= UNIX epoch. - ValueError – If display_qty is negative (< 0) or greater than quantity.
stop_market(self, InstrumentId instrument_id, OrderSide order_side, Quantity quantity, Price trigger_price, TriggerType trigger_type=TriggerType.DEFAULT, TimeInForce time_in_force=TimeInForce.GTC, datetime expire_time=None, bool reduce_only=False, bool quote_quantity=False, TriggerType emulation_trigger=TriggerType.NO_TRIGGER, InstrumentId trigger_instrument_id=None, ExecAlgorithmId exec_algorithm_id=None, dict exec_algorithm_params=None, list tags=None, ClientOrderId client_order_id=None) → StopMarketOrder
Create a new STOP_MARKET
conditional order.
- Parameters:
- instrument_id (InstrumentId) – The orders instrument ID.
- order_side (OrderSide {
BUY
,SELL
}) – The orders side. - quantity (Quantity) – The orders quantity (> 0).
- trigger_price (Price) – The orders trigger price (STOP).
- trigger_type (TriggerType, default
DEFAULT
) – The order trigger type. - time_in_force (TimeInForce {
GTC
,IOC
,FOK
,GTD
,DAY
}, defaultGTC
) – The orders time in force. - expire_time (datetime , optional) – The order expiration (for
GTD
orders). - reduce_only (bool , default False) – If the order carries the ‘reduce-only’ execution instruction.
- quote_quantity (bool) – If the order quantity is denominated in the quote currency.
- emulation_trigger (TriggerType, default
NO_TRIGGER
) – The orders emulation trigger. - trigger_instrument_id (InstrumentId , optional) – The emulation trigger instrument ID for the order (if
None
then will be the instrument_id). - exec_algorithm_id (ExecAlgorithmId , optional) – The execution algorithm ID for the order.
- exec_algorithm_params (dict *[*str , Any ] , optional) – The execution algorithm parameters for the order.
- tags (list *[*str ] , optional) – The custom user tags for the order.
- client_order_id (ClientOrderId , optional) – The custom client order ID for the order. If a client order ID is not provided then one will be generated by the factory.
- Return type: StopMarketOrder
- Raises:
- ValueError – If quantity is not positive (> 0).
- ValueError – If trigger_type is
NO_TRIGGER
. - ValueError – If time_in_force is
AT_THE_OPEN
orAT_THE_CLOSE
. - ValueError – If time_in_force is
GTD
and expire_time <= UNIX epoch.
strategy_id
The order factories trading strategy ID.
- Returns: StrategyId
trader_id
The order factories trader ID.
- Returns: TraderId
trailing_stop_limit(self, InstrumentId instrument_id, OrderSide order_side, Quantity quantity, limit_offset: Decimal, trailing_offset: Decimal, Price price=None, Price trigger_price=None, TriggerType trigger_type=TriggerType.DEFAULT, TrailingOffsetType trailing_offset_type=TrailingOffsetType.PRICE, TimeInForce time_in_force=TimeInForce.GTC, datetime expire_time=None, bool post_only=False, bool reduce_only=False, bool quote_quantity=False, Quantity display_qty=None, TriggerType emulation_trigger=TriggerType.NO_TRIGGER, InstrumentId trigger_instrument_id=None, ExecAlgorithmId exec_algorithm_id=None, dict exec_algorithm_params=None, list tags=None, ClientOrderId client_order_id=None) → TrailingStopLimitOrder
Create a new TRAILING_STOP_LIMIT
conditional order.
- Parameters:
- instrument_id (InstrumentId) – The orders instrument ID.
- order_side (OrderSide {
BUY
,SELL
}) – The orders side. - quantity (Quantity) – The orders quantity (> 0).
- trailing_offset (Decimal) – The trailing offset for the trigger price (STOP).
- limit_offset (Decimal) – The trailing offset for the order price (LIMIT).
- price (Price , optional) – The order price (LIMIT). If
None
then will typically default to the delta of market price and limit_offset. - trigger_price (Price , optional) – The order trigger price (STOP). If
None
then will typically default to the delta of market price and trailing_offset. - trigger_type (TriggerType, default
DEFAULT
) – The order trigger type. - trailing_offset_type (TrailingOffsetType, default
PRICE
) – The order trailing offset type. - time_in_force (TimeInForce {
GTC
,IOC
,FOK
,GTD
,DAY
}, defaultGTC
) – The orders time in force. - expire_time (datetime , optional) – The order expiration (for
GTD
orders). - post_only (bool , default False) – If the order will only provide liquidity (make a market).
- reduce_only (bool , default False) – If the order carries the ‘reduce-only’ execution instruction.
- quote_quantity (bool) – If the order quantity is denominated in the quote currency.
- display_qty (Quantity , optional) – The quantity of the order to display on the public book (iceberg).
- emulation_trigger (TriggerType, default
NO_TRIGGER
) – The orders emulation trigger. - trigger_instrument_id (InstrumentId , optional) – The emulation trigger instrument ID for the order (if
None
then will be the instrument_id). - exec_algorithm_id (ExecAlgorithmId , optional) – The execution algorithm ID for the order.
- exec_algorithm_params (dict *[*str , Any ] , optional) – The execution algorithm parameters for the order.
- tags (list *[*str ] , optional) – The custom user tags for the order.
- client_order_id (ClientOrderId , optional) – The custom client order ID for the order. If a client order ID is not provided then one will be generated by the factory.
- Return type: TrailingStopLimitOrder
- Raises:
- ValueError – If quantity is not positive (> 0).
- ValueError – If trigger_type is
NO_TRIGGER
. - ValueError – If trailing_offset_type is
NO_TRAILING_OFFSET
. - ValueError – If time_in_force is
AT_THE_OPEN
orAT_THE_CLOSE
. - ValueError – If time_in_force is
GTD
and expire_time <= UNIX epoch. - ValueError – If display_qty is negative (< 0) or greater than quantity.
trailing_stop_market(self, InstrumentId instrument_id, OrderSide order_side, Quantity quantity, trailing_offset: Decimal, Price trigger_price=None, TriggerType trigger_type=TriggerType.DEFAULT, TrailingOffsetType trailing_offset_type=TrailingOffsetType.PRICE, TimeInForce time_in_force=TimeInForce.GTC, datetime expire_time=None, bool reduce_only=False, bool quote_quantity=False, TriggerType emulation_trigger=TriggerType.NO_TRIGGER, InstrumentId trigger_instrument_id=None, ExecAlgorithmId exec_algorithm_id=None, dict exec_algorithm_params=None, list tags=None, ClientOrderId client_order_id=None) → TrailingStopMarketOrder
Create a new TRAILING_STOP_MARKET
conditional order.
- Parameters:
- instrument_id (InstrumentId) – The orders instrument ID.
- order_side (OrderSide {
BUY
,SELL
}) – The orders side. - quantity (Quantity) – The orders quantity (> 0).
- trailing_offset (Decimal) – The trailing offset for the trigger price (STOP).
- trigger_price (Price , optional) – The order trigger price (STOP). If
None
then will typically default to the delta of market price and trailing_offset. - trigger_type (TriggerType, default
DEFAULT
) – The order trigger type. - trailing_offset_type (TrailingOffsetType, default
PRICE
) – The order trailing offset type. - time_in_force (TimeInForce {
GTC
,IOC
,FOK
,GTD
,DAY
}, defaultGTC
) – The orders time in force. - expire_time (datetime , optional) – The order expiration (for
GTD
orders). - reduce_only (bool , default False) – If the order carries the ‘reduce-only’ execution instruction.
- quote_quantity (bool) – If the order quantity is denominated in the quote currency.
- emulation_trigger (TriggerType, default
NO_TRIGGER
) – The orders emulation trigger. - exec_algorithm_id (ExecAlgorithmId , optional) – The execution algorithm ID for the order.
- exec_algorithm_params (dict *[*str , Any ] , optional) – The execution algorithm parameters for the order.
- tags (list *[*str ] , optional) – The custom user tags for the order.
- client_order_id (ClientOrderId , optional) – The custom client order ID for the order. If a client order ID is not provided then one will be generated by the factory.
- Return type: TrailingStopMarketOrder
- Raises:
- ValueError – If quantity is not positive (> 0).
- ValueError – If trigger_type is
NO_TRIGGER
. - ValueError – If trailing_offset_type is
NO_TRAILING_OFFSET
. - ValueError – If time_in_force is
AT_THE_OPEN
orAT_THE_CLOSE
. - ValueError – If time_in_force is
GTD
and expire_time <= UNIX epoch.
Component
class Clock
Bases: object
The base class for all clocks.
WARNING
This class should not be used directly, but through a concrete subclass.
cancel_timer(self, unicode name) → void
Cancel the timer corresponding to the given label.
- Parameters: name (str) – The name for the timer to cancel.
- Raises:
- ValueError – If name is not a valid string.
- KeyError – If name is not an active timer name for this clock.
cancel_timers(self) → void
Cancel all timers.
local_now(self, tzinfo tz=None) → datetime
Return the current datetime of the clock in the given local timezone.
- Parameters: tz (tzinfo , optional) – The local timezone (if None the system local timezone is assumed for the target timezone).
- Returns: tz-aware in local timezone.
- Return type: datetime
next_time_ns(self, unicode name) → uint64_t
Find a particular timer.
- Parameters: name (str) – The name of the timer.
- Return type: uint64_t
- Raises: ValueError – If name is not a valid string.
register_default_handler(self, handler: Callable[[TimeEvent], None]) → void
Register the given handler as the clocks default handler.
- Parameters: handler (Callable [ [TimeEvent ] , None ]) – The handler to register.
- Raises: TypeError – If handler is not of type Callable.
set_time_alert(self, unicode name, datetime alert_time, callback: Callable[[TimeEvent], None] = None, bool override=False) → void
Set a time alert for the given time.
When the time is reached the handler will be passed the TimeEvent containing the timers unique name. If no handler is passed then the default handler (if registered) will receive the TimeEvent.
- Parameters:
- name (str) – The name for the alert (must be unique for this clock).
- alert_time (datetime) – The time for the alert.
- callback (Callable [ [TimeEvent ] , None ] , optional) – The callback to receive time events.
- override (bool) – If override is set to True an alert with a given name can be overwritten if it exists already.
- Raises:
- ValueError – If name is not a valid string.
- KeyError – If name is not unique for this clock.
- TypeError – If handler is not of type Callable or
None
. - ValueError – If handler is
None
and no default handler is registered.
WARNING
If alert_time is in the past or at current time, then an immediate time event will be generated (rather than being invalid and failing a condition check).
set_time_alert_ns(self, unicode name, uint64_t alert_time_ns, callback: Callable[[TimeEvent], None] = None) → void
Set a time alert for the given time.
When the time is reached the handler will be passed the TimeEvent containing the timers unique name. If no callback is passed then the default handler (if registered) will receive the TimeEvent.
- Parameters:
- name (str) – The name for the alert (must be unique for this clock).
- alert_time_ns (uint64_t) – The UNIX timestamp (nanoseconds) for the alert.
- callback (Callable [ [TimeEvent ] , None ] , optional) – The callback to receive time events.
- Raises:
- ValueError – If name is not a valid string.
- ValueError – If name is not unique for this clock.
- TypeError – If callback is not of type Callable or
None
. - ValueError – If callback is
None
and no default handler is registered.
WARNING
If alert_time_ns is in the past or at current time, then an immediate time event will be generated (rather than being invalid and failing a condition check).
set_timer(self, unicode name, timedelta interval, datetime start_time=None, datetime stop_time=None, callback: Callable[[TimeEvent], None] | None = None) → void
Set a timer to run.
The timer will run from the start time (optionally until the stop time). When the intervals are reached the handlers will be passed the TimeEvent containing the timers unique name. If no handler is passed then the default handler (if registered) will receive the TimeEvent.
- Parameters:
- name (str) – The name for the timer (must be unique for this clock).
- interval (timedelta) – The time interval for the timer.
- start_time (datetime , optional) – The start time for the timer (if None then starts immediately).
- stop_time (datetime , optional) – The stop time for the timer (if None then repeats indefinitely).
- callback (Callable [ [TimeEvent ] , None ] , optional) – The callback to receive time events.
- Raises:
- ValueError – If name is not a valid string.
- KeyError – If name is not unique for this clock.
- ValueError – If interval is not positive (> 0).
- ValueError – If stop_time is not
None
and stop_time < time now. - ValueError – If stop_time is not
None
and start_time + interval > stop_time. - TypeError – If handler is not of type Callable or
None
. - ValueError – If handler is
None
and no default handler is registered.
set_timer_ns(self, unicode name, uint64_t interval_ns, uint64_t start_time_ns, uint64_t stop_time_ns, callback: Callable[[TimeEvent], None] | None = None) → void
Set a timer to run.
The timer will run from the start time until the stop time. When the intervals are reached the handlers will be passed the TimeEvent containing the timers unique name. If no handler is passed then the default handler (if registered) will receive the TimeEvent.
- Parameters:
- name (str) – The name for the timer (must be unique for this clock).
- interval_ns (uint64_t) – The time interval (nanoseconds) for the timer.
- start_time_ns (uint64_t) – The start UNIX timestamp (nanoseconds) for the timer.
- stop_time_ns (uint64_t) – The stop UNIX timestamp (nanoseconds) for the timer.
- callback (Callable [ [TimeEvent ] , None ] , optional) – The callback to receive time events.
- Raises:
- ValueError – If name is not a valid string.
- KeyError – If name is not unique for this clock.
- ValueError – If interval is not positive (> 0).
- ValueError – If stop_time is not
None
and stop_time < time now. - ValueError – If stop_time is not
None
and start_time + interval > stop_time. - TypeError – If callback is not of type Callable or
None
. - ValueError – If callback is
None
and no default handler is registered.
timer_count
int
Return the count of active timers running in the clock.
- Return type: int
- Type: Clock.timer_count
timer_names
list[str]
Return the names of active timers running in the clock.
- Return type: list[str]
- Type: Clock.timer_names
timestamp(self) → double
Return the current UNIX timestamp in seconds.
- Return type: double
timestamp_ms(self) → uint64_t
Return the current UNIX timestamp in milliseconds (ms).
- Return type: uint64_t
timestamp_ns(self) → uint64_t
Return the current UNIX timestamp in nanoseconds (ns).
- Return type: uint64_t
timestamp_us(self) → uint64_t
Return the current UNIX timestamp in microseconds (μs).
- Return type: uint64_t
utc_now(self) → datetime
Return the current time (UTC).
- Returns: The current tz-aware UTC time of the clock.
- Return type: datetime
class Component
Bases: object
Component(Clock clock, TraderId trader_id=None, Identifier component_id=None, unicode component_name=None, MessageBus msgbus=None, config: NautilusConfig | None = None)
The base class for all system components.
A component is not considered initialized until a message bus is registered (this either happens when one is passed to the constructor, or when registered with a trader).
Thus, if the component does not receive a message bus through the constructor,
then it will be in a PRE_INITIALIZED
state, otherwise if one is passed
then it will be in an INITIALIZED
state.
- Parameters:
- clock (Clock) – The clock for the component.
- trader_id (TraderId , optional) – The trader ID associated with the component.
- component_id (Identifier , optional) – The component ID. If
None
is passed then the identifier will be taken from type(self)._name_. - component_name (str , optional) – The custom component name.
- msgbus (MessageBus , optional) – The message bus for the component (required before initialized).
- config (NautilusConfig , optional) – The configuration for the component.
- Raises:
- ValueError – If component_name is not a valid string.
- TypeError – If config is not of type NautilusConfig.
WARNING
This class should not be used directly, but through a concrete subclass.
degrade(self) → void
Degrade the component.
While executing on_degrade() any exception will be logged and reraised, then the component
will remain in a DEGRADING
state.
WARNING
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
dispose(self) → void
Dispose of the component.
While executing on_dispose() any exception will be logged and reraised, then the component
will remain in a DISPOSING
state.
WARNING
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
fault(self) → void
Fault the component.
Calling this method multiple times has the same effect as calling it once (it is idempotent). Once called, it cannot be reversed, and no other methods should be called on this instance.
While executing on_fault() any exception will be logged and reraised, then the component
will remain in a FAULTING
state.
WARNING
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
classmethod fully_qualified_name(cls) → str
Return the fully qualified name for the components class.
- Return type: str
id
The components ID.
- Returns: ComponentId
is_degraded
bool
Return whether the current component state is DEGRADED
.
- Return type: bool
- Type: Component.is_degraded
is_disposed
bool
Return whether the current component state is DISPOSED
.
- Return type: bool
- Type: Component.is_disposed
is_faulted
bool
Return whether the current component state is FAULTED
.
- Return type: bool
- Type: Component.is_faulted
is_initialized
bool
Return whether the component has been initialized (component.state >= INITIALIZED
).
- Return type: bool
- Type: Component.is_initialized
is_running
bool
Return whether the current component state is RUNNING
.
- Return type: bool
- Type: Component.is_running
is_stopped
bool
Return whether the current component state is STOPPED
.
- Return type: bool
- Type: Component.is_stopped
reset(self) → void
Reset the component.
All stateful fields are reset to their initial value.
While executing on_reset() any exception will be logged and reraised, then the component
will remain in a RESETTING
state.
WARNING
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
resume(self) → void
Resume the component.
While executing on_resume() any exception will be logged and reraised, then the component
will remain in a RESUMING
state.
WARNING
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
start(self) → void
Start the component.
While executing on_start() any exception will be logged and reraised, then the component
will remain in a STARTING
state.
WARNING
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
state
ComponentState
Return the components current state.
- Return type: ComponentState
- Type: Component.state
stop(self) → void
Stop the component.
While executing on_stop() any exception will be logged and reraised, then the component
will remain in a STOPPING
state.
WARNING
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
trader_id
The trader ID associated with the component.
- Returns: TraderId
type
The components type.
- Returns: type
class ComponentFSMFactory
Bases: object
Provides a generic component Finite-State Machine.
static get_state_transition_table() → dict
The default state transition table.
- Returns: C Enums.
- Return type: dict[int, int]
class LiveClock
Bases: Clock
LiveClock()
Provides a monotonic clock for live trading.
All times are tz-aware UTC.
- Parameters: loop (asyncio.AbstractEventLoop) – The event loop for the clocks timers.
cancel_timer(self, unicode name) → void
cancel_timers(self) → void
local_now(self, tzinfo tz=None) → datetime
Return the current datetime of the clock in the given local timezone.
- Parameters: tz (tzinfo , optional) – The local timezone (if None the system local timezone is assumed for the target timezone).
- Returns: tz-aware in local timezone.
- Return type: datetime
next_time_ns(self, unicode name) → uint64_t
register_default_handler(self, callback: Callable[[TimeEvent], None]) → void
set_time_alert(self, unicode name, datetime alert_time, callback: Callable[[TimeEvent], None] = None, bool override=False) → void
Set a time alert for the given time.
When the time is reached the handler will be passed the TimeEvent containing the timers unique name. If no handler is passed then the default handler (if registered) will receive the TimeEvent.
- Parameters:
- name (str) – The name for the alert (must be unique for this clock).
- alert_time (datetime) – The time for the alert.
- callback (Callable [ [TimeEvent ] , None ] , optional) – The callback to receive time events.
- override (bool) – If override is set to True an alert with a given name can be overwritten if it exists already.
- Raises:
- ValueError – If name is not a valid string.
- KeyError – If name is not unique for this clock.
- TypeError – If handler is not of type Callable or
None
. - ValueError – If handler is
None
and no default handler is registered.
WARNING
If alert_time is in the past or at current time, then an immediate time event will be generated (rather than being invalid and failing a condition check).
set_time_alert_ns(self, unicode name, uint64_t alert_time_ns, callback: Callable[[TimeEvent], None] | None = None) → void
set_timer(self, unicode name, timedelta interval, datetime start_time=None, datetime stop_time=None, callback: Callable[[TimeEvent], None] | None = None) → void
Set a timer to run.
The timer will run from the start time (optionally until the stop time). When the intervals are reached the handlers will be passed the TimeEvent containing the timers unique name. If no handler is passed then the default handler (if registered) will receive the TimeEvent.
- Parameters:
- name (str) – The name for the timer (must be unique for this clock).
- interval (timedelta) – The time interval for the timer.
- start_time (datetime , optional) – The start time for the timer (if None then starts immediately).
- stop_time (datetime , optional) – The stop time for the timer (if None then repeats indefinitely).
- callback (Callable [ [TimeEvent ] , None ] , optional) – The callback to receive time events.
- Raises:
- ValueError – If name is not a valid string.
- KeyError – If name is not unique for this clock.
- ValueError – If interval is not positive (> 0).
- ValueError – If stop_time is not
None
and stop_time < time now. - ValueError – If stop_time is not
None
and start_time + interval > stop_time. - TypeError – If handler is not of type Callable or
None
. - ValueError – If handler is
None
and no default handler is registered.
set_timer_ns(self, unicode name, uint64_t interval_ns, uint64_t start_time_ns, uint64_t stop_time_ns, callback: Callable[[TimeEvent], None] | None = None) → void
timer_count
int
- Type: LiveClock.timer_count
timer_names
list[str]
- Type: LiveClock.timer_names
timestamp(self) → double
timestamp_ms(self) → uint64_t
timestamp_ns(self) → uint64_t
timestamp_us(self) → uint64_t
utc_now(self) → datetime
Return the current time (UTC).
- Returns: The current tz-aware UTC time of the clock.
- Return type: datetime
class LogGuard
Bases: object
Provides a LogGuard which serves as a token to signal the initialization of the logging system. It also ensures that the global logger is flushed of any buffered records when the instance is destroyed.
class Logger
Bases: object
Logger(unicode name) -> None
Provides a logger adapter into the logging system.
- Parameters: name (str) – The name of the logger. This will appear within each log line.
debug(self, unicode message, LogColor color=LogColor.NORMAL) → void
Log the given DEBUG level message.
- Parameters:
- message (str) – The log message text (valid UTF-8).
- color (LogColor , optional) – The log message color.
error(self, unicode message, LogColor color=LogColor.RED) → void
Log the given ERROR level message.
- Parameters:
- message (str) – The log message text (valid UTF-8).
- color (LogColor , optional) – The log message color.
exception(self, unicode message, ex) → void
Log the given exception including stack trace information.
- Parameters:
- message (str) – The log message text (valid UTF-8).
- ex (Exception) – The exception to log.
info(self, unicode message, LogColor color=LogColor.NORMAL) → void
Log the given INFO level message.
- Parameters:
- message (str) – The log message text (valid UTF-8).
- color (LogColor , optional) – The log message color.
name
str
Return the name of the logger.
- Return type: str
- Type: Logger.name
warning(self, unicode message, LogColor color=LogColor.YELLOW) → void
Log the given WARNING level message.
- Parameters:
- message (str) – The log message text (valid UTF-8).
- color (LogColor , optional) – The log message color.
class MessageBus
Bases: object
MessageBus(TraderId trader_id, Clock clock, UUID4 instance_id=None, unicode name=None, Serializer serializer=None, database: nautilus_pyo3.RedisMessageBusDatabase | None = None, config: Any | None = None) -> None
Provides a generic message bus to facilitate various messaging patterns.
The bus provides both a producer and consumer API for Pub/Sub, Req/Rep, as well as direct point-to-point messaging to registered endpoints.
Pub/Sub wildcard patterns for hierarchical topics are possible: : - * asterisk represents one or more characters in a pattern.
- ? question mark represents a single character in a pattern.
Given a topic and pattern potentially containing wildcard characters, i.e. * and ?, where ? can match any single character in the topic, and * can match any number of characters including zero characters.
The asterisk in a wildcard matches any character zero or more times. For example, comp* matches anything beginning with comp which means comp, complete, and computer are all matched.
A question mark matches a single character once. For example, c?mp matches camp and comp. The question mark can also be used more than once. For example, c??p would match both of the above examples and coop.
- Parameters:
- trader_id (TraderId) – The trader ID associated with the message bus.
- clock (Clock) – The clock for the message bus.
- name (str , optional) – The custom name for the message bus.
- serializer (Serializer , optional) – The serializer for database operations.
- database (nautilus_pyo3.RedisMessageBusDatabase , optional) – The backing database for the message bus.
- config (MessageBusConfig , optional) – The configuration for the message bus.
- Raises:
ValueError – If name is not
None
and not a valid string.
WARNING
This message bus is not thread-safe and must be called from the same thread as the event loop.
add_streaming_type(self, type cls) → void
Register the given type for external->internal message bus streaming.
- Parameters: type (cls) – The type to add for streaming.
deregister(self, unicode endpoint, handler: Callable[[Any], None]) → void
Deregister the given handler from the endpoint address.
- Parameters:
- endpoint (str) – The endpoint address to deregister.
- handler (Callable [ *[*Any ] , None ]) – The handler to deregister.
- Raises:
- ValueError – If endpoint is not a valid string.
- ValueError – If handler is not of type Callable.
- KeyError – If endpoint is not registered.
- ValueError – If handler is not registered at the endpoint.
dispose(self) → void
Dispose of the message bus which will close the internal channel and thread.
endpoints(self) → list
Return all endpoint addresses registered with the message bus.
- Return type: list[str]
has_backing
If the message bus has a database backing.
- Returns: bool
has_subscribers(self, unicode pattern=None) → bool
If the message bus has subscribers for the give topic pattern.
- Parameters:
pattern (str , optional) – The topic filter. May include wildcard characters * and ?.
If
None
then query is for all topics. - Return type: bool
is_pending_request(self, UUID4 request_id) → bool
Return if the given request_id is still pending a response.
- Parameters: request_id (UUID4) – The request ID to check (to match the correlation_id).
- Return type: bool
is_streaming_type(self, type cls) → bool
Return whether the given type has been registered for external message streaming.
- Returns: True if registered, else False.
- Return type: bool
is_subscribed(self, unicode topic, handler: Callable[[Any], None]) → bool
Return if topic and handler is subscribed to the message bus.
Does not consider any previous priority.
- Parameters:
- topic (str) – The topic of the subscription.
- handler (Callable [ *[*Any ] , None ]) – The handler of the subscription.
- Return type: bool
pub_count
The count of messages published by the bus.
- Returns: uint64_t
publish(self, unicode topic, msg: Any, bool external_pub=True) → void
Publish the given message for the given topic.
Subscription handlers will receive the message in priority order (highest first).
- Parameters:
- topic (str) – The topic to publish on.
- msg (object) – The message to publish.
- external_pub (bool , default True) – If the message should also be published externally.
register(self, unicode endpoint, handler: Callable[[Any], None]) → void
Register the given handler to receive messages at the endpoint address.
- Parameters:
- endpoint (str) – The endpoint address to register.
- handler (Callable [ *[*Any ] , None ]) – The handler for the registration.
- Raises:
- ValueError – If endpoint is not a valid string.
- ValueError – If handler is not of type Callable.
- KeyError – If endpoint already registered.
req_count
The count of requests processed by the bus.
- Returns: uint64_t
request(self, unicode endpoint, Request request) → void
Handle the given request.
Will log an error if the correlation ID already exists.
- Parameters:
- endpoint (str) – The endpoint address to send the request to.
- request (Request) – The request to handle.
res_count
The count of responses processed by the bus.
- Returns: uint64_t
response(self, Response response) → void
Handle the given response.
Will log an error if the correlation ID is not found.
- Parameters: response (Response) – The response to handle
send(self, unicode endpoint, msg: Any) → void
Send the given message to the given endpoint address.
- Parameters:
- endpoint (str) – The endpoint address to send the message to.
- msg (object) – The message to send.
sent_count
The count of messages sent through the bus.
- Returns: uint64_t
serializer
The serializer for the bus.
- Returns: Serializer
subscribe(self, unicode topic, handler: Callable[[Any], None], int priority=0) → void
Subscribe to the given message topic with the given callback handler.
- Parameters:
- topic (str) – The topic for the subscription. May include wildcard characters * and ?.
- handler (Callable [ *[*Any ] , None ]) – The handler for the subscription.
- priority (int , optional) – The priority for the subscription. Determines the ordering of handlers receiving messages being processed, higher priority handlers will receive messages prior to lower priority handlers.
- Raises:
- ValueError – If topic is not a valid string.
- ValueError – If handler is not of type Callable.
WARNING
Assigning priority handling is an advanced feature which shouldn’t normally be needed by most users. Only assign a higher priority to the subscription if you are certain of what you’re doing. If an inappropriate priority is assigned then the handler may receive messages before core system components have been able to process necessary calculations and produce potential side effects for logically sound behavior.
subscriptions(self, unicode pattern=None) → list
Return all subscriptions matching the given topic pattern.
- Parameters:
pattern (str , optional) – The topic pattern filter. May include wildcard characters * and ?.
If
None
then query is for all topics. - Return type: list[Subscription]
topics(self) → list
Return all topics with active subscribers.
- Return type: list[str]
trader_id
The trader ID associated with the bus.
- Returns: TraderId
unsubscribe(self, unicode topic, handler: Callable[[Any], None]) → void
Unsubscribe the given callback handler from the given message topic.
- Parameters:
- topic (str , optional) – The topic to unsubscribe from. May include wildcard characters * and ?.
- handler (Callable [ *[*Any ] , None ]) – The handler for the subscription.
- Raises:
- ValueError – If topic is not a valid string.
- ValueError – If handler is not of type Callable.
class Subscription
Bases: object
Subscription(unicode topic, handler: Callable[[Any], None], int priority=0)
Represents a subscription to a particular topic.
This is an internal class intended to be used by the message bus to organize topics and their subscribers.
- Parameters:
- topic (str) – The topic for the subscription. May include wildcard characters * and ?.
- handler (Callable [ *[*Message ] , None ]) – The handler for the subscription.
- priority (int) – The priority for the subscription.
- Raises:
- ValueError – If topic is not a valid string.
- ValueError – If handler is not of type Callable.
- ValueError – If priority is negative (< 0).
handler
The handler for the subscription.
- Returns: Callable
priority
The priority for the subscription.
- Returns: int
topic
The topic for the subscription.
- Returns: str
class TestClock
Bases: Clock
TestClock()
Provides a monotonic clock for backtesting and unit testing.
advance_time(self, uint64_t to_time_ns, bool set_time=True) → list
Advance the clocks time to the given to_time_ns.
- Parameters:
- to_time_ns (uint64_t) – The UNIX timestamp (nanoseconds) to advance the clock to.
- set_time (bool) – If the clock should also be set to the given to_time_ns.
- Returns: Sorted chronologically.
- Return type: list[TimeEventHandler]
- Raises: ValueError – If to_time_ns is < the clocks current time.
cancel_timer(self, unicode name) → void
cancel_timers(self) → void
local_now(self, tzinfo tz=None) → datetime
Return the current datetime of the clock in the given local timezone.
- Parameters: tz (tzinfo , optional) – The local timezone (if None the system local timezone is assumed for the target timezone).
- Returns: tz-aware in local timezone.
- Return type: datetime
next_time_ns(self, unicode name) → uint64_t
register_default_handler(self, callback: Callable[[TimeEvent], None]) → void
set_time(self, uint64_t to_time_ns) → void
Set the clocks datetime to the given time (UTC).
- Parameters: to_time_ns (uint64_t) – The UNIX timestamp (nanoseconds) to set.
set_time_alert(self, unicode name, datetime alert_time, callback: Callable[[TimeEvent], None] = None, bool override=False) → void
Set a time alert for the given time.
When the time is reached the handler will be passed the TimeEvent containing the timers unique name. If no handler is passed then the default handler (if registered) will receive the TimeEvent.
- Parameters:
- name (str) – The name for the alert (must be unique for this clock).
- alert_time (datetime) – The time for the alert.
- callback (Callable [ [TimeEvent ] , None ] , optional) – The callback to receive time events.
- override (bool) – If override is set to True an alert with a given name can be overwritten if it exists already.
- Raises:
- ValueError – If name is not a valid string.
- KeyError – If name is not unique for this clock.
- TypeError – If handler is not of type Callable or
None
. - ValueError – If handler is
None
and no default handler is registered.
WARNING
If alert_time is in the past or at current time, then an immediate time event will be generated (rather than being invalid and failing a condition check).
set_time_alert_ns(self, unicode name, uint64_t alert_time_ns, callback: Callable[[TimeEvent], None] | None = None) → void
set_timer(self, unicode name, timedelta interval, datetime start_time=None, datetime stop_time=None, callback: Callable[[TimeEvent], None] | None = None) → void
Set a timer to run.
The timer will run from the start time (optionally until the stop time). When the intervals are reached the handlers will be passed the TimeEvent containing the timers unique name. If no handler is passed then the default handler (if registered) will receive the TimeEvent.
- Parameters:
- name (str) – The name for the timer (must be unique for this clock).
- interval (timedelta) – The time interval for the timer.
- start_time (datetime , optional) – The start time for the timer (if None then starts immediately).
- stop_time (datetime , optional) – The stop time for the timer (if None then repeats indefinitely).
- callback (Callable [ [TimeEvent ] , None ] , optional) – The callback to receive time events.
- Raises:
- ValueError – If name is not a valid string.
- KeyError – If name is not unique for this clock.
- ValueError – If interval is not positive (> 0).
- ValueError – If stop_time is not
None
and stop_time < time now. - ValueError – If stop_time is not
None
and start_time + interval > stop_time. - TypeError – If handler is not of type Callable or
None
. - ValueError – If handler is
None
and no default handler is registered.
set_timer_ns(self, unicode name, uint64_t interval_ns, uint64_t start_time_ns, uint64_t stop_time_ns, callback: Callable[[TimeEvent], None] | None = None) → void
timer_count
int
- Type: TestClock.timer_count
timer_names
list[str]
- Type: TestClock.timer_names
timestamp(self) → double
timestamp_ms(self) → uint64_t
timestamp_ns(self) → uint64_t
timestamp_us(self) → uint64_t
utc_now(self) → datetime
Return the current time (UTC).
- Returns: The current tz-aware UTC time of the clock.
- Return type: datetime
class Throttler
Bases: object
Throttler(unicode name, int limit, timedelta interval, Clock clock, output_send: Callable[[Any], None], output_drop: Callable[[Any], None] | None = None) -> None
Provides a generic throttler which can either buffer or drop messages.
Will throttle messages to the given maximum limit-interval rate. If an output_drop handler is provided, then will drop messages which would exceed the rate limit. Otherwise will buffer messages until within the rate limit, then send.
- Parameters:
- name (str) – The unique name of the throttler.
- limit (int) – The limit setting for the throttling.
- interval (timedelta) – The interval setting for the throttling.
- clock (Clock) – The clock for the throttler.
- output_send (Callable [ *[*Any ] , None ]) – The output handler to send messages from the throttler.
- output_drop (Callable [ *[*Any ] , None ] , optional) – The output handler to drop messages from the throttler.
If
None
then messages will be buffered.
- Raises:
- ValueError – If name is not a valid string.
- ValueError – If limit is not positive (> 0).
- ValueError – If interval is not positive (> 0).
- ValueError – If output_send is not of type Callable.
- ValueError – If output_drop is not of type Callable or
None
.
WARNING
This throttler is not thread-safe and must be called from the same thread as the event loop.
The internal buffer queue is unbounded and so a bounded queue should be upstream.
interval
The interval for the throttler rate.
- Returns: timedelta
is_limiting
If the throttler is currently limiting messages (buffering or dropping).
- Returns: bool
limit
The limit for the throttler rate.
- Returns: int
name
The name of the throttler.
- Returns: str
qsize
int
Return the qsize of the internal buffer.
- Return type: int
- Type: Throttler.qsize
recv_count
If count of messages received by the throttler.
- Returns: int
reset(self) → void
Reset the state of the throttler.
send(self, msg) → void
Send the given message through the throttler.
- Parameters: msg (object) – The message to send.
sent_count
If count of messages sent from the throttler.
- Returns: int
used(self) → double
Return the percentage of maximum rate currently used.
- Returns: [0, 1.0].
- Return type: double
class TimeEvent
Bases: Event
TimeEvent(unicode name, UUID4 event_id, uint64_t ts_event, uint64_t ts_init)
Represents a time event occurring at the event timestamp.
- Parameters:
- name (str) – The event name.
- event_id (UUID4) – The event ID.
- ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the time event occurred.
- ts_init (uint64_t) – UNIX timestamp (nanoseconds) when the object was initialized.
id
UUID4
The event message identifier.
- Return type: UUID4
- Type: TimeEvent.id
name
str
Return the name of the time event.
- Return type: str
- Type: TimeEvent.name
ts_event
int
UNIX timestamp (nanoseconds) when the event occurred.
- Return type: int
- Type: TimeEvent.ts_event
ts_init
int
UNIX timestamp (nanoseconds) when the object was initialized.
- Return type: int
- Type: TimeEvent.ts_init
class TimeEventHandler
Bases: object
TimeEventHandler(TimeEvent event, handler: Callable[[TimeEvent], None])
Represents a time event with its associated handler.
event
The handlers event.
- Returns: TimeEvent
handle(self) → void
Call the handler with the contained time event.
component_state_from_str(unicode value) → ComponentState
component_state_to_str(ComponentState value) → unicode
component_trigger_from_str(unicode value) → ComponentTrigger
component_trigger_to_str(ComponentTrigger value) → unicode
create_pyo3_conversion_wrapper(callback) → Callable
deregister_component_clock(UUID4 instance_id, Clock clock) → void
init_logging(TraderId trader_id=None, unicode machine_id=None, UUID4 instance_id=None, LogLevel level_stdout=LogLevel.INFO, LogLevel level_file=LogLevel.OFF, unicode directory=None, unicode file_name=None, unicode file_format=None, dict component_levels: dict[ComponentId, LogLevel] = None, bool colors=True, bool bypass=False, bool print_config=False) → LogGuard
Initialize the logging system.
Provides an interface into the logging system implemented in Rust.
This function should only be called once per process, at the beginning of the application run. Subsequent calls will raise a RuntimeError, as there can only be one LogGuard per initialized system.
- Parameters:
- trader_id (TraderId , optional) – The trader ID for the logger.
- machine_id (str , optional) – The machine ID.
- instance_id (UUID4 , optional) – The instance ID.
- level_stdout (LogLevel, default
INFO
) – The minimum log level to write to stdout. - level_file (LogLevel, default
OFF
) – The minimum log level to write to a file. - directory (str , optional) – The path to the log file directory.
If
None
then will write to the current working directory. - file_name (str , optional) – The custom log file name (will use a ‘.log’ suffix for plain text or ‘.json’ for JSON).
If
None
will not log to a file (unless file_auto is True). - file_format (str { 'JSON' } , optional) – The log file format. If
None
(default) then will log in plain text. If set to ‘JSON’ then logs will be in JSON format. - component_levels (dict [ComponentId , LogLevel ]) – The additional per component log level filters, where keys are component IDs (e.g. actor/strategy IDs) and values are log levels.
- colors (bool , default True) – If ANSI codes should be used to produce colored log lines.
- bypass (bool , default False) – If the output for the core logging system is bypassed (useful for logging tests).
- print_config (bool , default False) – If the core logging configuration should be printed to stdout on initialization.
- Return type: LogGuard
- Raises: RuntimeError – If the logging system has already been initialized.
is_logging_initialized() → bool
is_logging_pyo3() → bool
is_matching_py(unicode topic, unicode pattern) → bool
log_color_from_str(unicode value) → LogColor
log_color_to_str(LogColor value) → unicode
log_header(TraderId trader_id, unicode machine_id, UUID4 instance_id, unicode component) → void
log_level_from_str(unicode value) → LogLevel
log_level_to_str(LogLevel value) → unicode
log_sysinfo(unicode component) → void
register_component_clock(UUID4 instance_id, Clock clock) → void
remove_instance_component_clocks(UUID4 instance_id) → void
set_logging_pyo3(bool value) → void
Executor
class TaskId
Bases: object
Represents a unique identifier for a task managed by the ActorExecutor.
This ID can be associated with a task that is either queued for execution or actively executing as an asyncio.Future.
value : str
classmethod create() → TaskId
Create and return a new task identifier with a UUID v4 value.
- Return type: TaskId
class ActorExecutor
Bases: object
Provides an executor for Actor and Strategy classes.
The executor is designed to handle asynchronous tasks for Actor and Strategy classes. This custom executor queues and executes tasks within a given event loop and is tailored for single-threaded applications.
The ActorExecutor maintains its internal state to manage both queued and active tasks, providing facilities for scheduling, cancellation, and monitoring. It can be used to create more controlled execution flows within complex asynchronous systems.
- Parameters:
- loop (AbstractEventLoop) – The event loop for the application.
- executor (Executor) – The inner executor to register.
- logger (Logger , optional) – The logger for the executor.
WARNING
This executor is not thread-safe and must be invoked from the same thread in which it was created. Special care should be taken to ensure thread consistency when integrating with multi-threaded applications.
reset() → None
Reset the executor.
This will cancel all queued and active tasks, and drain the internal queue without executing those tasks.
get_future(task_id: TaskId) → Future | None
Return the executing Future with the given task_id (if found).
- Parameters: task_id (TaskId) – The task identifier for the future.
- Return type:
asyncio.Future or
None
async shutdown() → None
Shutdown the executor in an async context.
This will cancel the inner worker task.
queue_for_executor(func: Callable[[...], Any], *args: Any, **kwargs: Any) → TaskId
Enqueue the given func to be executed 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.
- Return type: TaskId
run_in_executor(func: Callable[[...], Any], *args: Any, **kwargs: Any) → TaskId
Arrange for the given func to be called in the executor.
- 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.
- Return type: TaskId
queued_task_ids() → list[TaskId]
Return the queued task identifiers.
- Return type: list[TaskId]
active_task_ids() → list[TaskId]
Return the active task identifiers.
- Return type: list[TaskId]
has_queued_tasks() → bool
Return a value indicating whether there are any queued tasks.
- Return type: bool
has_active_tasks() → bool
Return a value indicating whether there are any active tasks.
- Return type: bool
cancel_task(task_id: TaskId) → None
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 active task identifier.
cancel_all_tasks() → None
Cancel all active and queued tasks.
Generators
class ClientOrderIdGenerator
Bases: IdentifierGenerator
ClientOrderIdGenerator(TraderId trader_id, StrategyId strategy_id, Clock clock, int initial_count=0)
Provides a generator for unique
`
ClientOrderId`(s).
- Parameters:
- trader_id (TraderId) – The trader ID for the generator.
- strategy_id (StrategyId) – The strategy ID for the generator.
- clock (Clock) – The clock for the generator.
- initial_count (int) – The initial count for the generator.
- Raises: ValueError – If initial_count is negative (< 0).
count
The count of IDs generated.
- Returns: int
generate(self) → ClientOrderId
Return a unique client order ID.
- Return type: ClientOrderId
reset(self) → void
Reset the ID generator.
All stateful fields are reset to their initial value.
set_count(self, int count) → void
Set the internal counter to the given count.
- Parameters: count (int) – The count to set.
class IdentifierGenerator
Bases: object
IdentifierGenerator(TraderId trader_id, Clock clock)
Provides a generator for unique ID strings.
class OrderListIdGenerator
Bases: IdentifierGenerator
OrderListIdGenerator(TraderId trader_id, StrategyId strategy_id, Clock clock, int initial_count=0)
Provides a generator for unique
`
OrderListId`(s).
- Parameters:
- trader_id (TraderId) – The trader ID for the generator.
- strategy_id (StrategyId) – The strategy ID for the generator.
- clock (Clock) – The clock for the generator.
- initial_count (int) – The initial count for the generator.
- Raises: ValueError – If initial_count is negative (< 0).
count
The count of IDs generated.
- Returns: int
generate(self) → OrderListId
Return a unique order list ID.
- Return type: OrderListId
reset(self) → void
Reset the ID generator.
All stateful fields are reset to their initial value.
set_count(self, int count) → void
Set the internal counter to the given count.
- Parameters: count (int) – The count to set.
class PositionIdGenerator
Bases: IdentifierGenerator
PositionIdGenerator(TraderId trader_id, Clock clock)
Provides a generator for unique PositionId(s).
- Parameters: trader_id (TraderId) – The trader ID tag for the generator.
generate(self, StrategyId strategy_id, bool flipped=False) → PositionId
Return a unique position ID.
- Parameters:
- strategy_id (StrategyId) – The strategy ID associated with the position.
- flipped (bool) – If the position is being flipped. If True, then the generated id will be appended with ‘F’.
- Return type: PositionId
get_count(self, StrategyId strategy_id) → int
Return the internal position count for the given strategy ID.
- Parameters: strategy_id (StrategyId) – The strategy ID associated with the count.
- Return type: int
reset(self) → void
Reset the ID generator.
All stateful fields are reset to their initial value.
set_count(self, StrategyId strategy_id, int count) → void
Set the internal position count for the given strategy ID.
- Parameters:
- strategy_id (StrategyId) – The strategy ID associated with the count.
- count (int) – The count to set.
- Raises: ValueError – If count is negative (< 0).
class InstrumentProvider
Bases: object
The base class for all instrument providers.
- Parameters: config (InstrumentProviderConfig , optional) – The instrument provider config.
WARNING
This class should not be used directly, but through a concrete subclass.
property count : int
Return the count of instruments held by the provider.
- Return type: int
async load_all_async(filters: dict | None = None) → None
Load the latest instruments into the provider asynchronously, optionally applying the given filters.
async load_ids_async(instrument_ids: list[InstrumentId], filters: dict | None = None) → None
Load the instruments for the given IDs into the provider, optionally applying the given filters.
- Parameters:
- instrument_ids (list [InstrumentId ]) – The instrument IDs to load.
- filters (frozendict *[*str , Any ] or dict *[*str , Any ] , optional) – The venue specific instrument loading filters to apply.
- Raises: ValueError – If any instrument_id.venue is not equal to self.venue.
async load_async(instrument_id: InstrumentId, filters: dict | None = None) → None
Load the instrument for the given ID into the provider asynchronously, optionally applying the given filters.
- Parameters:
- instrument_id (InstrumentId) – The instrument ID to load.
- filters (frozendict *[*str , Any ] or dict *[*str , Any ] , optional) – The venue specific instrument loading filters to apply.
- Raises: ValueError – If instrument_id.venue is not equal to self.venue.
async initialize(reload: bool = False) → None
Initialize the instrument provider.
- Parameters: reload (bool , default False) – If True, then will always reload instruments. If False, then will immediately return if already loaded.
load_all(filters: dict | None = None) → None
Load the latest instruments into the provider, optionally applying the given filters.
- Parameters: filters (frozendict *[*str , Any ] or dict *[*str , Any ] , optional) – The venue specific instrument loading filters to apply.
load_ids(instrument_ids: list[InstrumentId], filters: dict | None = None) → None
Load the instruments for the given IDs into the provider, optionally applying the given filters.
- Parameters:
- instrument_ids (list [InstrumentId ]) – The instrument IDs to load.
- filters (frozendict *[*str , Any ] or dict *[*str , Any ] , optional) – The venue specific instrument loading filters to apply.
load(instrument_id: InstrumentId, filters: dict | None = None) → None
Load the instrument for the given ID into the provider, optionally applying the given filters.
- Parameters:
- instrument_id (InstrumentId) – The instrument ID to load.
- filters (frozendict *[*str , Any ] or dict *[*str , Any ] , optional) – The venue specific instrument loading filters to apply.
add_currency(currency: Currency) → None
Add the given currency to the provider.
- Parameters: currency (Currency) – The currency to add.
add(instrument: Instrument) → None
Add the given instrument to the provider.
- Parameters: instrument (Instrument) – The instrument to add.
add_bulk(instruments: list[Instrument]) → None
Add the given instruments bulk to the provider.
- Parameters: instruments (list [Instrument ]) – The instruments to add.
list_all() → list[Instrument]
Return all loaded instruments.
- Return type: list[Instrument]
get_all() → dict[InstrumentId, Instrument]
Return all loaded instruments as a map keyed by instrument ID.
If no instruments loaded, will return an empty dict.
- Return type: dict[InstrumentId, Instrument]
currencies() → dict[str, Currency]
Return all currencies held by the instrument provider.
- Return type: dict[str, Currency]
currency(code: str) → Currency | None
Return the currency with the given code (if found).
- Parameters: code (str) – The currency code.
- Return type:
Currency or
None
- Raises: ValueError – If code is not a valid string.
find(instrument_id: InstrumentId) → Instrument | None
Return the instrument for the given instrument ID (if found).
- Parameters: instrument_id (InstrumentId) – The ID for the instrument
- Return type:
Instrument or
None