Risk - Loren1166/NautilusTrader- GitHub Wiki

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. 其中包括一个 PositionSizer 组件,交易策略可以使用该组件通过仓位调整来帮助进行风险管理。

class RiskEngine | 风险引擎

class RiskEngine(Component):
    """
    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. 
    RiskEngine 负责平台内的全局策略和投资组合风险。这包括交易前风险检查和交易后风险监控。

    Possible trading states: :
    可能的交易状态::
     - ACTIVE (trading is enabled). 
        ACTIVE(交易已启用)。

     REDUCING (only new orders or updates which reduce an open position are allowed).
     REDUCING(仅允许减少未平仓位的新的订单或更新)。
     HALTED (all trading commands except cancels are denied).
     HALTED(除取消以外的所有交易指令都被拒绝)。

    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. 
        如果 config 的类型不是 RiskEngineConfig,则引发 TypeError。
    """
    def __init__(
        self,
        portfolio: PortfolioFacade,
        msgbus: MessageBus,
        cache: Cache,
        clock: Clock,
        config: RiskEngineConfig | None = None
    ):
        ...

    @property
    def command_count(self) -> int:
        """
        The total count of commands received by the engine. 
        引擎收到的指令总数。

        Returns: int
        """
        ...

    @property
    def debug(self) -> bool:
        """
        If debug mode is active (will provide extra debug logging). 
        如果调试模式处于活动状态(将提供额外的调试日志)。

        Returns: bool
        """
        ...

    def degrade(self) -> None:
        """
        Degrade the component. 
        降级组件。

        While executing on_degrade() any exception will be logged and reraised, then the component will remain in a DEGRADING state. 
        在执行 on_degrade() 时,任何异常都将被记录并重新引发,然后组件将保持 DEGRADING 状态。

        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. 
        如果组件未处于可以执行此方法的有效状态,则组件状态将不会更改,并且会记录错误。
        """
        ...

    def dispose(self) -> None:
        """
        Dispose of the component. 
        处理组件。

        While executing on_dispose() any exception will be logged and reraised, then the component will remain in a DISPOSING state. 
        在执行 on_dispose() 时,任何异常都将被记录并重新引发,然后组件将保持 DISPOSING 状态。

        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. 
        如果组件未处于可以执行此方法的有效状态,则组件状态将不会更改,并且会记录错误。
        """
        ...

    @property
    def event_count(self) -> int:
        """
        The total count of events received by the engine. 
        引擎收到的事件总数。

        Returns: int
        """
        ...

    def execute(self, command: Command) -> None:
        """
        Execute the given command. 
        执行给定的指令。

        Parameters: 
        参数:
            command (Command) – The command to execute. 
            要执行的指令。
        """
        ...

    def fault(self) -> None:
        """
        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. 
        在执行 on_fault() 时,任何异常都将被记录并重新引发,然后组件将保持 FAULTING 状态。

        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
    def fully_qualified_name(cls) -> str:
        """
        Return the fully qualified name for the components class. 
        返回组件类的完全限定名称。

        Return type: str
        """
        ...

    @property
    def id(self) -> ComponentId:
        """
        The components ID. 
        组件的 ID。

        Returns: ComponentId
        """
        ...

    @property
    def is_bypassed(self) -> bool:
        """
        If the risk engine is completely bypassed. 
        如果完全绕过风险引擎。

        Returns: bool
        """
        ...

    @property
    def is_degraded(self) -> bool:
        """
        bool

        Return whether the current component state is DEGRADED. 
        返回当前组件状态是否为 DEGRADED。

        Return type: bool
        Type: Component.is_degraded
        """
        ...

    @property
    def is_disposed(self) -> bool:
        """
        bool

        Return whether the current component state is DISPOSED. 
        返回当前组件状态是否为 DISPOSED。

        Return type: bool
        Type: Component.is_disposed
        """
        ...

    @property
    def is_faulted(self) -> bool:
        """
        bool

        Return whether the current component state is FAULTED. 
        返回当前组件状态是否为 FAULTED。

        Return type: bool
        Type: Component.is_faulted
        """
        ...

    @property
    def is_initialized(self) -> bool:
        """
        bool

        Return whether the component has been initialized (component.state >= INITIALIZED). 
        返回组件是否已初始化 (component.state >= INITIALIZED)。

        Return type: bool
        Type: Component.is_initialized
        """
        ...

    @property
    def is_running(self) -> bool:
        """
        bool

        Return whether the current component state is RUNNING. 
        返回当前组件状态是否为 RUNNING。

        Return type: bool
        Type: Component.is_running
        """
        ...

    @property
    def is_stopped(self) -> bool:
        """
        bool

        Return whether the current component state is STOPPED. 
        返回当前组件状态是否为 STOPPED。

        Return type: bool
        Type: Component.is_stopped
        """
        ...

    def max_notional_per_order(self, instrument_id: InstrumentId):
        """
        Return the current maximum notional per order for the given instrument ID. 
        返回给定工具 ID 的当前每笔订单的最大名义价值。

        Return type: Decimal or None
        """
        ...

    def max_notionals_per_order(self) -> dict:
        """
        Return the current maximum notionals per order settings. 
        返回当前每笔订单的最大名义价值设置。

        Return type: dict[InstrumentId, Decimal]
        """
        ...

    def max_order_modify_rate(self) -> tuple:
        """
        Return the current maximum order modify rate limit setting. 
        返回当前最大订单修改速率限制设置。

        Returns: 
        返回值:
            The limit per timedelta interval. 
            每个 timedelta 间隔的限制。

        Return type: (int, timedelta)
        """
        ...

    def max_order_submit_rate(self) -> tuple:
        """
        Return the current maximum order submit rate limit setting. 
        返回当前最大订单提交速率限制设置。

        Returns: 
        返回值:
            The limit per timedelta interval. 
            每个 timedelta 间隔的限制。

        Return type: (int, timedelta)
        """
        ...

    def process(self, event: Event) -> None:
        """
        Process the given event. 
        处理给定事件。

        Parameters: 
        参数:
            event (Event) – The event to process. 
            要处理的事件。
        """
        ...

    def reset(self) -> None:
        """
        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. 
        在执行 on_reset() 时,任何异常都将被记录并重新引发,然后组件将保持 RESETTING 状态。

        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. 
        如果组件未处于可以执行此方法的有效状态,则组件状态将不会更改,并且会记录错误。
        """
        ...

    def resume(self) -> None:
        """
        Resume the component. 
        恢复组件。

        While executing on_resume() any exception will be logged and reraised, then the component will remain in a RESUMING state. 
        在执行 on_resume() 时,任何异常都将被记录并重新引发,然后组件将保持 RESUMING 状态。

        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. 
        如果组件未处于可以执行此方法的有效状态,则组件状态将不会更改,并且会记录错误。
        """
        ...

    def set_max_notional_per_order(
        self,
        instrument_id: InstrumentId,
        new_value
    ) -> None:
        """
        Set the maximum notional value per order for the given instrument ID. 
        为给定工具 ID 设置每笔订单的最大名义价值。

        Passing a new_value of None will disable the pre-trade risk max notional check. 
        传递 new_value 为 None 将禁用交易前风险最大名义价值检查。

        Parameters:
        参数:
            instrument_id (InstrumentId) – The instrument ID for the max notional. 
            最大名义价值的工具 ID。
            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. 
            如果 new_value 不是 decimal.Decimal 的有效输入,则引发 decimal.InvalidOperation。
            ValueError – If new_value is not None and not positive. 
            如果 new_value 不为 None 且不为正数,则引发 ValueError。
        """
        ...

    def set_trading_state(self, state: TradingState) -> None:
        """
        Set the trading state for the engine. 
        为引擎设置交易状态。

        Parameters: 
        参数:
            state (TradingState) – The state to set. 
            要设置的状态。
        """
        ...

    def start(self) -> None:
        """
        Start the component. 
        启动组件。

        While executing on_start() any exception will be logged and reraised, then the component will remain in a STARTING state. 
        在执行 on_start() 时,任何异常都将被记录并重新引发,然后组件将保持 STARTING 状态。

        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. 
        如果组件未处于可以执行此方法的有效状态,则组件状态将不会更改,并且会记录错误。
        """
        ...

    @property
    def state(self) -> ComponentState:
        """
        ComponentState

        Return the components current state. 
        返回组件的当前状态。

        Return type: ComponentState
        Type: Component.state
        """
        ...

    def stop(self) -> None:
        """
        Stop the component. 
        停止组件。

        While executing on_stop() any exception will be logged and reraised, then the component will remain in a STOPPING state. 
        在执行 on_stop() 时,任何异常都将被记录并重新引发,然后组件将保持 STOPPING 状态。

        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. 
        如果组件未处于可以执行此方法的有效状态,则组件状态将不会更改,并且会记录错误。
        """
        ...

    @property
    def trader_id(self) -> TraderId:
        """
        The trader ID associated with the component. 
        与组件关联的交易员 ID。

        Returns: TraderId
        """
        ...

    @property
    def trading_state(self) -> TradingState:
        """
        The current trading state for the engine. 
        引擎的当前交易状态。

        Returns: TradingState
        """
        ...

    @property
    def type(self) -> type:
        """
        The components type. 
        组件的类型。

        Returns: type
        """
        ...

class FixedRiskSizer | 固定风险调整器

class FixedRiskSizer(PositionSizer):
    """
    Provides position sizing calculations based on a given risk. 
    提供基于给定风险的仓位调整计算。

    Parameters: 
    参数:
        instrument (Instrument) – The instrument for position sizing. 
        用于仓位调整的工具。
    """
    def __init__(self, instrument: Instrument):
        ...

    def calculate(
        self,
        entry: Price,
        stop_loss: Price,
        equity: Money,
        risk: Decimal,
        commission_rate: Decimal = Decimal(0),
        exchange_rate: Decimal = Decimal(1),
        hard_limit: Decimal | None = None,
        unit_batch_size: Decimal = Decimal(1),
        units: int = 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). 
            佣金率 (>= 0)。
            hard_limit (Decimal , optional) – The hard limit for the total quantity (>= 0). 
            总数量的硬性限制 (>= 0)。
            unit_batch_size (Decimal) – The unit batch size (> 0). 
            单位批量大小 (> 0)。
            units (int) – The number of units to batch the position into (> 0). 
            要将仓位批量处理成的单位数 (> 0)。

        Raises:
        引发:
            ValueError – If risk_bp is not positive (> 0). 
            如果 risk_bp 不为正数 (> 0),则引发 ValueError。
            ValueError – If xrate is not positive (> 0). 
            如果 xrate 不为正数 (> 0),则引发 ValueError。
            ValueError – If commission_rate is negative (< 0). 
            如果 commission_rate 为负数 (< 0),则引发 ValueError。
            ValueError – If hard_limit is not None and is not positive (> 0). 
            如果 hard_limit 不为 None 且不为正数 (> 0),则引发 ValueError。
            ValueError – If unit_batch_size is not positive (> 0). 
            如果 unit_batch_size 不为正数 (> 0),则引发 ValueError。
            ValueError – If units is not positive (> 0). 
            如果 units 不为正数 (> 0),则引发 ValueError。

        Return type: Quantity
        """
        ...

    @property
    def instrument(self) -> Instrument:
        """
        The instrument for position sizing. 
        用于仓位调整的工具。

        Returns: Instrument
        """
        ...

    def update_instrument(self, instrument: Instrument) -> None:
        """
        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. 
            如果 instrument 不等于当前持有的工具,则引发 ValueError。
        """
        ...

class PositionSizer | 仓位调整器

class PositionSizer:
    """
    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. 
    此类不应直接使用,而应通过具体的子类使用。
    """
    def __init__(self, instrument: Instrument):
        ...

    def calculate(
        self,
        entry: Price,
        stop_loss: Price,
        equity: Money,
        risk: Decimal,
        commission_rate: Decimal = Decimal(0),
        exchange_rate: Decimal = Decimal(1),
        hard_limit: Decimal | None = None,
        unit_batch_size: Decimal = Decimal(1),
        units: int = 1
    ) -> Quantity:
        """
        Abstract method (implement in subclass). 
        抽象方法(在子类中实现)。
        """
        ...

    @property
    def instrument(self) -> Instrument:
        """
        The instrument for position sizing. 
        用于仓位调整的工具。

        Returns: Instrument
        """
        ...

    def update_instrument(self, instrument: Instrument) -> None:
        """
        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. 
            如果 instrument 不等于当前持有的工具,则引发 ValueError。
        """
        ...