Core - Loren1166/NautilusTrader- GitHub Wiki

Core 核心

The core subpackage groups core constants, functions and low-level components used throughout the framework. # 核心子包将整个框架中使用的核心常量、函数和底层组件分组。

The main focus here is on efficiency and re-usability as this forms the base layer of the entire framework. Message passing is a core design philosophy and the base massage types are contained here. # 这里的主要重点是效率和可重用性,因为这构成了整个框架的基础层。消息传递是核心设计理念,基本消息类型包含在此处。

A generic FiniteStateMachine operates with C-level enums, ensuring correct state transitions for both domain entities and more complex components. # 通用的有限状态机使用 C 级枚举进行操作,确保域实体和更复杂组件的正确状态转换。

Datetime 日期时间

This module provides efficient functions for performing standard datetime related operations. # 此模块提供用于执行标准日期时间相关操作的高效函数。

Functions include awareness/tz checks and conversions, as well as ISO 8601 conversion. # 函数包括感知/时区检查和转换,以及 ISO 8601 转换。

Functions 函数

def as_utc_index(data):
    """
    Ensure the given data has a DateTimeIndex which is tz-aware UTC.

    确保给定数据具有时区感知的 UTC DateTimeIndex。

    Parameters:
    参数:
        data (pd.Series or pd.DataFrame.) – The object to ensure is UTC.
        data (pd.Series 或 pd.DataFrame。) - 要确保为 UTC 的对象。

    Return type: pd.Series, pd.DataFrame or None
    """
    ...

def as_utc_timestamp(dt: datetime) -> datetime:
    """
    Ensure the given timestamp is tz-aware UTC.

    确保给定时间戳是时区感知的 UTC。

    Parameters: dt (datetime) – The timestamp to check.
    参数:dt (datetime) - 要检查的时间戳。

    Return type: datetime
    """
    ...

def dt_to_unix_nanos(dt: pd.Timestamp):
    """
    Return the UNIX time (nanoseconds) from the given datetime (UTC).

    从给定的日期时间 (UTC) 返回 UNIX 时间(纳秒)。

    Parameters: dt (pd.Timestamp) – The datetime to convert.
    参数:dt (pd.Timestamp) - 要转换的日期时间。

    Return type: uint64_t

    Warning:
        This function expects a pandas Timestamp as standard Python datetime objects are only accurate to 1 microsecond (μs).
        此函数需要 pandas Timestamp,因为标准 Python 日期时间对象仅精确到 1 微秒 (μs)。
    """
    ...

def format_iso8601(dt: datetime) -> str:
    """
    Format the given datetime to a millisecond accurate ISO 8601 specification string.

    将给定的日期时间格式化为精确到毫秒的 ISO 8601 规范字符串。

    Parameters: dt (datetime) – The input datetime to format.
    参数:dt (datetime) - 要格式化的输入日期时间。

    Returns: The formatted string.
    返回值:格式化的字符串。
    Return type: str
    """
    ...

def is_datetime_utc(dt: datetime) -> bool:
    """
    Return a value indicating whether the given timestamp is timezone aware UTC.

    返回值指示给定时间戳是否为时区感知的 UTC。

    Parameters: dt (datetime) – The datetime to check.
    参数:dt (datetime) - 要检查的日期时间。

    Returns: True if timezone aware UTC, else False.
    返回值:如果为时区感知的 UTC,则返回 True,否则返回 False。
    Return type: bool
    """
    ...

def is_tz_aware(time_object) -> bool:
    """
    Return a value indicating whether the given object is timezone aware.

    返回值指示给定对象是否为时区感知的。

    Parameters: time_object (datetime , pd.Timestamp , pd.Series , pd.DataFrame) – The time object to check.
    参数:time_object (datetime、pd.Timestamp、pd.Series、pd.DataFrame) - 要检查的时间对象。

    Returns: True if timezone aware, else False.
    返回值:如果为时区感知的,则返回 True,否则返回 False。
    Return type: bool
    """
    ...

def is_tz_naive(time_object) -> bool:
    """
    Return a value indicating whether the given object is timezone naive.

    返回值指示给定对象是否为时区原始的。

    Parameters: time_object (datetime , pd.Timestamp , pd.DataFrame) – The time object to check.
    参数:time_object (datetime、pd.Timestamp、pd.DataFrame) - 要检查的时间对象。

    Returns: True if object timezone naive, else False.
    返回值:如果对象为时区原始的,则返回 True,否则返回 False。
    Return type: bool
    """
    ...

def maybe_dt_to_unix_nanos(dt: pd.Timestamp):
    """
    Return the UNIX time (nanoseconds) from the given datetime, or None.

    从给定的日期时间返回 UNIX 时间(纳秒),或者 None。

    If dt is None, then will return None.

    如果 dt 为 None,则返回 None。

    Parameters: dt (pd.Timestamp , optional) – The datetime to convert.
    参数:dt (pd.Timestamp,可选) - 要转换的日期时间。

    Return type: int64 or None

    Warning:
        If the input is not None then this function expects a pandas Timestamp as standard Python datetime objects are only accurate to 1 microsecond (μs).
        如果输入不为 None,则此函数需要 pandas Timestamp,因为标准 Python 日期时间对象仅精确到 1 微秒 (μs)。
    """
    ...

def maybe_unix_nanos_to_dt(nanos):
    """
    Return the datetime (UTC) from the given UNIX time (nanoseconds), or None.

    从给定的 UNIX 时间(纳秒)返回日期时间 (UTC),或者 None。

    If nanos is None, then will return None.

    如果 nanos 为 None,则返回 None。

    Parameters: nanos (int , optional) – The UNIX time (nanoseconds) to convert.
    参数:nanos (int,可选) - 要转换的 UNIX 时间(纳秒)。

    Return type: pd.Timestamp or None
    """
    ...

def unix_nanos_to_dt(nanos: int):
    """
    Return the datetime (UTC) from the given UNIX time (nanoseconds).

    从给定的 UNIX 时间(纳秒)返回日期时间 (UTC)。

    Parameters: nanos (uint64_t) – The UNIX time (nanoseconds) to convert.
    参数:nanos (uint64_t) - 要转换的 UNIX 时间(纳秒)。

    Return type: pd.Timestamp
    """
    ...

Finite-State Machine (FSM) 有限状态机 (FSM)

Defines a generic Finite-State Machine (FSM).

定义通用的有限状态机 (FSM)。

The FSM operates with a state-transition table of tuples and C-level enums. The intended use case is to ensure correct state transitions, as well as holding a deterministic state value.

FSM 使用元组和 C 级枚举的状态转换表进行操作。预期用例是确保正确的状态转换,以及保持确定性状态值。

class FiniteStateMachine 有限状态机

class FiniteStateMachine(object):
    """
    Provides a generic finite state machine.

    提供通用的有限状态机。

    Parameters:
    参数:
        state_transition_table (dict of tuples and states) – The state-transition table for the FSM consisting of a tuple of starting state and trigger as keys, and resulting states as values.
        state_transition_table(元组和状态的字典) - FSM 的状态转换表,由起始状态和触发器的元组作为键,结果状态作为值组成。
        initial_state (int / C Enum) – The initial state for the FSM.
        initial_state(int / C 枚举) - FSM 的初始状态。
        trigger_parser (Callable [ *[*int ] , str ] , optional) – The trigger parser needed to convert C Enum ints into strings. If None then will just print the integer.
        trigger_parser (Callable [*[*int],str],可选) - 将 C 枚举整数转换为字符串所需的触发器解析器。如果为 None,则只会打印整数。
        state_parser (Callable [ *[*int ] , str ] , optional) – The state parser needed to convert C Enum ints into strings. If None then will just print the integer.
        state_parser (Callable [*[*int],str],可选) - 将 C 枚举整数转换为字符串所需的状态解析器。如果为 None,则只会打印整数。
    Raises:
    引发:
        ValueError – If state_transition_table is empty.
        ValueError - 如果 state_transition_table 为空。
        ValueError – If state_transition_table key not tuple.
        ValueError - 如果 state_transition_table 键不是元组。
        ValueError – If trigger_parser not of type Callable or None.
        ValueError - 如果 trigger_parser 的类型不是 Callable 或 None。
        ValueError – If state_parser not of type Callable or None.
        ValueError - 如果 state_parser 的类型不是 Callable 或 None。
    """
    def __init__(self, state_transition_table: dict, initial_state: int, trigger_parser: Callable[[int], str] = str, state_parser: Callable[[int], str] = str):
        ...

Properties 属性

    @property
    def state(self):
        """
        The current state of the FSM.

        FSM 的当前状态。

        Returns:
            int / C Enum
        """
        ...

    @property
    def state_string(self) -> str:
        """
        str

        Return the current state as a string.

        将当前状态作为字符串返回。

        Return type: str
        Type: FiniteStateMachine.state_string
        """
        ...

Methods 方法

    def trigger(self, trigger: int) -> void:
        """
        Process the FSM with the given trigger. The trigger must be valid for the FSMs current state.

        使用给定的触发器处理 FSM。触发器必须对 FSM 的当前状态有效。

        Parameters: trigger (int / C Enum) – The trigger to combine with the current state providing the key for the transition table lookup.
        参数:trigger (int / C 枚举) - 与当前状态组合以提供转换表查找键的触发器。
        Raises: InvalidStateTrigger – If the state and trigger combination is not found in the transition table.
        引发:InvalidStateTrigger - 如果在转换表中找不到状态和触发器组合。
        """
        ...

exception InvalidStateTrigger 无效状态触发器

Bases: Exception

class InvalidStateTrigger(Exception):
    """
    Represents an invalid trigger for the current state.

    表示当前状态的无效触发器。
    """
    def __init__(self):
        ...

Methods 方法

    def add_note(self):
        """
        Exception.add_note(note) – add a note to the exception

        Exception.add_note(note) - 向异常添加注释
        """
        ...

    @property
    def args(self):
        """
        """
        ...

    def with_traceback(self):
        """
        Exception.with_traceback(tb) – set self._traceback_ to tb and return self.

        Exception.with_traceback(tb) - 将 self._traceback_ 设置为 tb 并返回 self。
        """
        ...

Message 消息

class Command 命令

Bases: object

class Command(object):
    """
    The base class for all command messages.

    所有命令消息的基类。

    Parameters:
    参数:
        command_id (UUID4) – The command ID.
        command_id (UUID4) - 命令 ID。
        ts_init (uint64_t) – UNIX timestamp (nanoseconds) when the object was initialized.
        ts_init (uint64_t) - 对象初始化时的 UNIX 时间戳(纳秒)。
    Warning:
        This class should not be used directly, but through a concrete subclass.
        此类不应直接使用,而应通过具体的子类使用。
    """
    def __init__(self, command_id: UUID4, ts_init: int):
        ...

Properties 属性

    @property
    def id(self) -> UUID4:
        """
        The command message ID.

        命令消息 ID。

        Returns:
            UUID4
        """
        ...

    @property
    def ts_init(self) -> int:
        """
        UNIX timestamp (nanoseconds) when the object was initialized.

        对象初始化时的 UNIX 时间戳(纳秒)。

        Returns:
            uint64_t
        """
        ...

class Document 文档

Bases: object

class Document(object):
    """
    The base class for all document messages.

    所有文档消息的基类。

    Parameters:
    参数:
        document_id (UUID4) – The command ID.
        document_id (UUID4) - 命令 ID。
        ts_init (uint64_t) – UNIX timestamp (nanoseconds) when the object was initialized.
        ts_init (uint64_t) - 对象初始化时的 UNIX 时间戳(纳秒)。

    Warning:
        This class should not be used directly, but through a concrete subclass.
        此类不应直接使用,而应通过具体的子类使用。
    """
    def __init__(self, document_id: UUID4, ts_init: int):
        ...

Properties 属性

    @property
    def id(self) -> UUID4:
        """
        The document message ID.

        文档消息 ID。

        Returns:
            UUID4
        """
        ...

    @property
    def ts_init(self) -> int:
        """
        UNIX timestamp (nanoseconds) when the object was initialized.

        对象初始化时的 UNIX 时间戳(纳秒)。

        Returns:
            uint64_t
        """
        ...

class Event 事件

Bases: object

class Event(object):
    """
    The abstract base class for all event messages.

    所有事件消息的抽象基类。

    Warning:
        This class should not be used directly, but through a concrete subclass.
        此类不应直接使用,而应通过具体的子类使用。
    """
    def __init__(self):
        ...

Properties 属性

    @property
    def id(self) -> UUID4:
        """
        UUID4

        The event message identifier.

        事件消息标识符。

        Return type: UUID4
        Type: Event.id
        """
        ...

    @property
    def ts_event(self) -> int:
        """
        int

        UNIX timestamp (nanoseconds) when the event occurred.

        事件发生时的 UNIX 时间戳(纳秒)。

        Return type: int
        Type: Event.ts_event
        """
        ...

    @property
    def ts_init(self) -> int:
        """
        int

        UNIX timestamp (nanoseconds) when the object was initialized.

        对象初始化时的 UNIX 时间戳(纳秒)。

        Return type: int
        Type: Event.ts_init
        """
        ...

class Request 请求

Bases: object

class Request(object):
    """
    The base class for all request messages.

    所有请求消息的基类。

    Parameters:
    参数:
        callback (Callable [ *[*Any ] , None ]) – The delegate to call with the response.
        callback (Callable [*[*Any],None]) - 使用响应调用的委托。
        request_id (UUID4) – The request ID.
        request_id (UUID4) - 请求 ID。
        ts_init (uint64_t) – UNIX timestamp (nanoseconds) when the object was initialized.
        ts_init (uint64_t) - 对象初始化时的 UNIX 时间戳(纳秒)。
    Warning:
        This class should not be used directly, but through a concrete subclass.
        此类不应直接使用,而应通过具体的子类使用。
    """
    def __init__(self, callback, request_id: UUID4, ts_init: int):
        ...

Properties 属性

    @property
    def callback(self):
        """
        The callback for the response.

        响应的回调函数。

        Returns:
            Callable
        """
        ...

    @property
    def id(self) -> UUID4:
        """
        The request message ID.

        请求消息 ID。

        Returns:
            UUID4
        """
        ...

    @property
    def ts_init(self) -> int:
        """
        UNIX timestamp (nanoseconds) when the object was initialized.

        对象初始化时的 UNIX 时间戳(纳秒)。

        Returns:
            uint64_t
        """
        ...

class Response 响应

Bases: object

class Response(object):
    """
    The base class for all response messages.

    所有响应消息的基类。

    Parameters:
    参数:
        correlation_id (UUID4) – The correlation ID.
        correlation_id (UUID4) - 相关 ID。
        response_id (UUID4) – The response ID.
        response_id (UUID4) - 响应 ID。
        ts_init (uint64_t) – UNIX timestamp (nanoseconds) when the object was initialized.
        ts_init (uint64_t) - 对象初始化时的 UNIX 时间戳(纳秒)。
    Warning:
        This class should not be used directly, but through a concrete subclass.
        此类不应直接使用,而应通过具体的子类使用。
    """
    def __init__(self, correlation_id: UUID4, response_id: UUID4, ts_init: int):
        ...

Properties 属性

    @property
    def correlation_id(self) -> UUID4:
        """
        The response correlation ID.

        响应相关 ID。

        Returns:
            UUID4
        """
        ...

    @property
    def id(self) -> UUID4:
        """
        The response message ID.

        响应消息 ID。

        Returns:
            UUID4
        """
        ...

    @property
    def ts_init(self) -> int:
        """
        UNIX timestamp (nanoseconds) when the object was initialized.

        对象初始化时的 UNIX 时间戳(纳秒)。

        Returns:
            uint64_t
        """
        ...

Stats 统计数据

Functions 函数

def basis_points_as_percentage(basis_points: float) -> float:
    """
    Return the given basis points expressed as a percentage where 100% = 1.0.

    返回以百分比表示的给定基点,其中 100% = 1.0。

    Parameters: basis_points (double) – The basis points to convert to percentage.
    参数:basis_points (double) - 要转换为百分比的基点。

    Return type: double
    """
    ...

def fast_mad(values: ndarray) -> float:
    """
    Return the mean absolute deviation from the given values.

    从给定值返回平均绝对偏差。

    Parameters: values (numpy.ndarray) – The array for the calculation.
    参数:values (numpy.ndarray) - 计算的数组。

    Return type: double
    """
    ...

def fast_mad_with_mean(values: ndarray, mean: float) -> float:
    """
    Return the mean absolute deviation from the given values and mean.

    从给定值和平均值返回平均绝对偏差。

    Parameters:
    参数:
        values (numpy.ndarray) – The array for the calculation.
        values (numpy.ndarray) - 计算的数组。
        mean (double) – The pre-calculated mean of the given values.
        mean (double) - 给定值的预先计算的平均值。

    Return type: double
    """
    ...

def fast_mean(values: ndarray) -> float:
    """
    Return the average value for numpy.ndarray values.

    返回 numpy.ndarray 值的平均值。

    Parameters: values (numpy.ndarray) – The array to evaluate.
    参数:values (numpy.ndarray) - 要评估的数组。

    Return type: double
    """
    ...

def fast_mean_iterated(values: ndarray, next_value: float, current_value: float, expected_length: int, drop_left: bool = True) -> float:
    """
    Return the calculated average from the given inputs.

    从给定的输入返回计算的平均值。

    Parameters:
    参数:
        values (list *[*double ]) – The values for the calculation.
        values (list *[*double ]) - 计算的值。
        next_value (double) – The next input value for the average.
        next_value (double) - 平均值的下一个输入值。
        current_value (double) – The current value for the average.
        current_value (double) - 平均值的当前值。
        expected_length (int) – The expected length of the inputs.
        expected_length (int) - 输入的预期长度。
        drop_left (bool) – If the value to be dropped should be from the left side of the inputs (index 0).
        drop_left (bool) - 是否应从输入的左侧(索引 0)删除该值。

    Return type: double
    """
    ...

def fast_std(values: ndarray) -> float:
    """
    Return the standard deviation from the given values.

    从给定值返回标准偏差。

    Parameters: values (numpy.ndarray) – The array for the calculation.
    参数:values (numpy.ndarray) - 计算的数组。

    Return type: double
    """
    ...

def fast_std_with_mean(values: ndarray, mean: float) -> float:
    """
    Return the standard deviation from the given values and mean.

    从给定值和平均值返回标准偏差。

    Parameters:
    参数:
        values (numpy.ndarray) – The array for the calculation.
        values (numpy.ndarray) - 计算的数组。
        mean (double) – The pre-calculated mean of the given values.
        mean (double) - 给定值的预先计算的平均值。

    Return type: double
    """
    ...

UUID 通用唯一标识符

class UUID4 通用唯一标识符版本 4

Bases: object

class UUID4(object):
    """
    Represents a pseudo-random UUID (universally unique identifier) version 4 based on a 128-bit label as specified in RFC 4122.

    表示基于 RFC 4122 中指定的 128 位标签的伪随机 UUID(通用唯一标识符)版本 4。

    Parameters:
    参数:
        value (str , optional) – The UUID value. If None then a value will be generated.
        value (str,可选) - UUID 值。如果为 None,则将生成一个值。
    Warning:
        Panics at runtime if value is not None and not a valid UUID.
        如果 value 不为 None 并且不是有效的 UUID,则在运行时会出现恐慌。
    """
    def __init__(self, value: str = None):
        ...

Properties 属性

    @property
    def value(self) -> str:
        """
        str

        Type: UUID4.value
        """
        ...