Risk¶
The risk subpackage groups all risk specific components and tooling.
Included is a PositionSizer component which can be used by trading strategies to help with risk management through position sizing.
- class RiskEngine¶
Bases:
ComponentRiskEngine(PortfolioFacade portfolio, MessageBus msgbus, Cache cache, Clock clock, config: RiskEngineConfig | None = None) -> None
Provides a high-performance risk engine.
The RiskEngine is responsible for global strategy and portfolio risk within the platform. This includes both pre-trade risk checks and post-trade risk monitoring.
- Possible trading states:
ACTIVE(trading is enabled).REDUCING(only new orders or updates which reduce an open position are allowed).HALTED(all trading commands except cancels are denied).
- Parameters:
portfolio (PortfolioFacade) – The portfolio for the engine.
msgbus (MessageBus) – The message bus for the engine.
cache (Cache) – The cache for the engine.
clock (Clock) – The clock for the engine.
config (RiskEngineConfig, optional) – The configuration for the instance.
- Raises:
TypeError – If config is not of type RiskEngineConfig.
- command_count¶
The total count of commands received by the engine.
- Returns:
int
- debug¶
If debug mode is active (will provide extra debug logging).
- Returns:
bool
- degrade(self) void¶
Degrade the component.
While executing on_degrade() any exception will be logged and reraised, then the component will remain in a
DEGRADINGstate.Warning
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
- dispose(self) void¶
Dispose of the component.
While executing on_dispose() any exception will be logged and reraised, then the component will remain in a
DISPOSINGstate.Warning
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
- event_count¶
The total count of events received by the engine.
- Returns:
int
- execute(self, Command command) void¶
Execute the given command.
- Parameters:
command (Command) – The command to execute.
- fault(self) void¶
Fault the component.
Calling this method multiple times has the same effect as calling it once (it is idempotent). Once called, it cannot be reversed, and no other methods should be called on this instance.
While executing on_fault() any exception will be logged and reraised, then the component will remain in a
FAULTINGstate.Warning
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
- classmethod fully_qualified_name(cls) str¶
Return the fully qualified name for the components class.
- Return type:
str
References
- id¶
The components ID.
- Returns:
ComponentId
- is_bypassed¶
If the risk engine is completely bypassed.
- Returns:
bool
- is_degraded¶
bool
Return whether the current component state is
DEGRADED.- Return type:
bool
- Type:
- is_disposed¶
bool
Return whether the current component state is
DISPOSED.- Return type:
bool
- Type:
- is_faulted¶
bool
Return whether the current component state is
FAULTED.- Return type:
bool
- Type:
- is_initialized¶
bool
Return whether the component has been initialized (component.state >=
INITIALIZED).- Return type:
bool
- Type:
- is_running¶
bool
Return whether the current component state is
RUNNING.- Return type:
bool
- Type:
- is_stopped¶
bool
Return whether the current component state is
STOPPED.- Return type:
bool
- Type:
- max_notional_per_order(self, InstrumentId instrument_id)¶
Return the current maximum notional per order for the given instrument ID.
- Return type:
Decimal or
None
- max_notionals_per_order(self) dict¶
Return the current maximum notionals per order settings.
- Return type:
dict[InstrumentId, Decimal]
- max_order_modify_rate(self) tuple¶
Return the current maximum order modify rate limit setting.
- Returns:
The limit per timedelta interval.
- Return type:
(int, timedelta)
- max_order_submit_rate(self) tuple¶
Return the current maximum order submit rate limit setting.
- Returns:
The limit per timedelta interval.
- Return type:
(int, timedelta)
- process(self, Event event) void¶
Process the given event.
- Parameters:
event (Event) – The event to process.
- reset(self) void¶
Reset the component.
All stateful fields are reset to their initial value.
While executing on_reset() any exception will be logged and reraised, then the component will remain in a
RESETTINGstate.Warning
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
- resume(self) void¶
Resume the component.
While executing on_resume() any exception will be logged and reraised, then the component will remain in a
RESUMINGstate.Warning
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
- set_max_notional_per_order(self, InstrumentId instrument_id, new_value) void¶
Set the maximum notional value per order for the given instrument ID.
Passing a new_value of
Nonewill disable the pre-trade risk max notional check.- Parameters:
instrument_id (InstrumentId) – The instrument ID for the max notional.
new_value (integer, float, string or Decimal) – The max notional value to set.
- Raises:
decimal.InvalidOperation – If new_value not a valid input for decimal.Decimal.
ValueError – If new_value is not
Noneand not positive.
- set_trading_state(self, TradingState state) void¶
Set the trading state for the engine.
- Parameters:
state (TradingState) – The state to set.
- shutdown_system(self, str reason=None) void¶
Initiate a system-wide shutdown by generating and publishing a ShutdownSystem command.
The command is handled by the system’s NautilusKernel, which will invoke either stop (synchronously) or stop_async (asynchronously) depending on the execution context and the presence of an active event loop.
- Parameters:
reason (str, optional) – The reason for issuing the shutdown command.
- start(self) void¶
Start the component.
While executing on_start() any exception will be logged and reraised, then the component will remain in a
STARTINGstate.Warning
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
- state¶
ComponentState
Return the components current state.
- Return type:
ComponentState
- Type:
- stop(self) void¶
Stop the component.
While executing on_stop() any exception will be logged and reraised, then the component will remain in a
STOPPINGstate.Warning
Do not override.
If the component is not in a valid state from which to execute this method, then the component state will not change, and an error will be logged.
- trader_id¶
The trader ID associated with the component.
- Returns:
TraderId
- trading_state¶
The current trading state for the engine.
- Returns:
TradingState
- type¶
The components type.
- Returns:
type
- class FixedRiskSizer¶
Bases:
PositionSizerFixedRiskSizer(Instrument instrument)
Provides position sizing calculations based on a given risk.
- Parameters:
instrument (Instrument) – The instrument for position sizing.
- calculate(self, Price entry, Price stop_loss, Money equity, risk: Decimal, commission_rate: Decimal = Decimal(0), exchange_rate: Decimal = Decimal(1), hard_limit: Decimal | None = None, unit_batch_size: Decimal = Decimal(1), int units=1) Quantity¶
Calculate the position size quantity.
- Parameters:
entry (Price) – The entry price.
stop_loss (Price) – The stop loss price.
equity (Money) – The account equity.
risk (Decimal) – The risk percentage.
exchange_rate (Decimal) – The exchange rate for the instrument quote currency vs account currency.
commission_rate (Decimal) – The commission rate (>= 0).
hard_limit (Decimal, optional) – The hard limit for the total quantity (>= 0).
unit_batch_size (Decimal) – The unit batch size (> 0).
units (int) – The number of units to batch the position into (> 0).
- Raises:
ValueError – If risk_bp is not positive (> 0).
ValueError – If xrate is not positive (> 0).
ValueError – If commission_rate is negative (< 0).
ValueError – If hard_limit is not
Noneand is not positive (> 0).ValueError – If unit_batch_size is not positive (> 0).
ValueError – If units is not positive (> 0).
- Return type:
- instrument¶
The instrument for position sizing.
- Returns:
Instrument
- update_instrument(self, Instrument instrument) void¶
Update the internal instrument with the given instrument.
- Parameters:
instrument (Instrument) – The instrument for the update.
- Raises:
ValueError – If instrument does not equal the currently held instrument.
- class PositionSizer¶
Bases:
objectPositionSizer(Instrument instrument)
The base class for all position sizers.
- Parameters:
instrument (Instrument) – The instrument for position sizing.
Warning
This class should not be used directly, but through a concrete subclass.
- calculate(self, Price entry, Price stop_loss, Money equity, risk: Decimal, commission_rate: Decimal = Decimal(0), exchange_rate: Decimal = Decimal(1), hard_limit: Decimal | None = None, unit_batch_size: Decimal = Decimal(1), int units=1) Quantity¶
Abstract method (implement in subclass).
- instrument¶
The instrument for position sizing.
- Returns:
Instrument
- update_instrument(self, Instrument instrument) void¶
Update the internal instrument with the given instrument.
- Parameters:
instrument (Instrument) – The instrument for the update.
- Raises:
ValueError – If instrument does not equal the currently held instrument.