-
Notifications
You must be signed in to change notification settings - Fork 0
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. # 核心基础层之上引入了更多特定领域的通用概念。实现了 ID 缓存,一个具有测试和实时实现的基本时钟,可以控制许多计时器实例。
Trading domain specific components for generating Order and Identifier objects, common logging components, a high performance Queue and UUID4 factory. # 用于生成订单和标识符对象的交易领域特定组件、通用日志记录组件、高性能队列和 UUID4 工厂。
class Environment(Enum):
"""
Represents the environment context for a Nautilus system.
表示 Nautilus 系统的环境上下文。
"""
BACKTEST = 'backtest'
SANDBOX = 'sandbox'
LIVE = 'live'
The Actor class allows traders to implement their own customized components.
Actor 类允许交易者实现他们自己的自定义组件。
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.
用户可以从 Actor 继承,并可以选择覆盖任何以“on”命名的事件处理程序方法。该类不是以独立的方式完全初始化的,预期的用法是将 actor 传递给 Trader,以便它们可以完全“连接”到平台。如果 Actor 尝试在没有管理 Trader 实例的情况下运行,则会引发异常。
Bases: Component
class Actor(Component):
"""
The base class for all actor components.
所有执行器组件的基类。
Parameters:
参数:
config (ActorConfig , optional) – The actor configuration.
config (ActorConfig,可选) - 执行器配置。
Raises: TypeError – If config is not of type ActorConfig.
引发:TypeError - 如果 config 的类型不是 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.
不要在注册之前的 __init__ 中调用组件,例如时钟和记录器。
"""
def __init__(self, config: ActorConfig | None = None):
...
@property
def cache(self) :
"""
The read-only cache for the actor.
执行器的只读缓存。
Returns:
CacheFacade
"""
...
@property
def clock(self):
"""
The actors clock.
执行器的时钟。
Returns:
Clock
"""
...
@property
def config(self):
"""
The actors configuration.
执行器的配置。
Returns:
NautilusConfig
"""
...
@property
def id(self) -> ComponentId:
"""
The components ID.
组件 ID。
Returns:
ComponentId
"""
...
@property
def is_degraded(self) -> bool:
"""
bool
Return whether the current component state is DEGRADED.
返回当前组件状态是否为 DEGRADED。
Returns:
bool
"""
...
@property
def is_disposed(self) -> bool:
"""
bool
Return whether the current component state is DISPOSED.
返回当前组件状态是否为 DISPOSED。
Returns:
bool
"""
...
@property
def is_faulted(self) -> bool:
"""
bool
Return whether the current component state is FAULTED.
返回当前组件状态是否为 FAULTED。
Returns:
bool
"""
...
@property
def is_initialized(self) -> bool:
"""
bool
Return whether the component has been initialized (component.state >= INITIALIZED).
返回组件是否已初始化 (component.state >= INITIALIZED)。
Returns:
bool
"""
...
@property
def is_running(self) -> bool:
"""
bool
Return whether the current component state is RUNNING.
返回当前组件状态是否为 RUNNING。
Returns:
bool
"""
...
@property
def is_stopped(self) -> bool:
"""
bool
Return whether the current component state is STOPPED.
返回当前组件状态是否为 STOPPED。
Returns:
bool
"""
...
@property
def log(self) :
"""
The actors logger.
执行器的日志记录器。
Returns:
Logger
"""
...
@property
def msgbus(self):
"""
The message bus for the actor (if registered).
执行器的消息总线(如果已注册)。
Returns:
MessageBus or None
"""
...
@property
def portfolio(self):
"""
The read-only portfolio for the actor.
执行器的只读投资组合。
Returns:
PortfolioFacade
"""
...
@property
def registered_indicators(self):
"""
Return the registered indicators for the strategy.
返回策略的已注册指标。
Return type: list[Indicator]
"""
...
@property
def state(self) -> ComponentState:
"""
ComponentState
Return the components current state.
返回组件的当前状态。
Return type: ComponentState
Type: Component.state
"""
...
@property
def trader_id(self):
"""
The trader ID associated with the component.
与组件关联的交易者 ID。
Returns:
TraderId
"""
...
@property
def type(self):
"""
The components type.
组件类型。
Returns:
type
"""
...
def active_task_ids(self) -> list:
"""
Return the active task identifiers.
返回活动的 task 标识符。
Return type: list[TaskId]
"""
...
def add_synthetic(self, synthetic: SyntheticInstrument) -> void:
"""
Add the created synthetic instrument to the cache.
将创建的合成交易品种添加到缓存中。
Parameters: synthetic (SyntheticInstrument) – The synthetic instrument to add to the cache.
参数:synthetic (SyntheticInstrument) - 要添加到缓存中的合成交易品种。
Raises: KeyError – If synthetic is already in the cache.
引发:KeyError - 如果合成交易品种已存在于缓存中。
"""
...
def cancel_all_tasks(self) -> void:
"""
Cancel all queued and active tasks.
取消所有排队和活动的 task。
"""
...
def cancel_task(self, task_id: TaskId) -> void:
"""
Cancel the task with the given task_id (if queued or active).
取消具有给定 task_id 的任务(如果已排队或活动)。
If the task is not found then a warning is logged.
如果未找到任务,则会记录警告。
Parameters: task_id (TaskId) – The task identifier.
参数:task_id (TaskId) – 任务标识符。
"""
...
def 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.
警告:
不要覆盖。
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 deregister_warning_event(self, event) -> void:
"""
Deregister the given event type from warning log levels.
从警告日志级别取消注册给定的事件类型。
Parameters: event (type) – The event class to deregister.
参数:event (type) - 要取消注册的事件类。
"""
...
def 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.
警告:
不要覆盖。
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 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.
警告:
不要覆盖。
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
"""
...
def handle_bar(self, bar: Bar) -> void:
"""
Handle the given bar data.
处理给定的 bar 数据。
If state is RUNNING then passes to on_bar.
如果状态为 RUNNING,则传递给 on_bar。
Parameters: bar (Bar) – The bar received.
参数:bar (Bar) - 接收到的 bar。
Warning:
System method (not intended to be called by user code).
系统方法(不打算由用户代码调用)。
"""
...
def handle_bars(self, bars: list) -> void:
"""
Handle the given historical bar data by handling each bar individually.
通过单独处理每个 bar 来处理给定的历史 bar 数据。
Parameters: bars (list [Bar ]) – The bars to handle.
参数:bars (list [Bar ]) - 要处理的 bar。
Warning:
System method (not intended to be called by user code).
系统方法(不打算由用户代码调用)。
"""
...
def handle_data(self, data: Data) -> void:
"""
Handle the given data.
处理给定的数据。
If state is RUNNING then passes to on_data.
如果状态为 RUNNING,则传递给 on_data。
Parameters: data (Data) – The data received.
参数:data (Data) - 接收到的数据。
Warning:
System method (not intended to be called by user code).
系统方法(不打算由用户代码调用)。
"""
...
def handle_event(self, event: Event) -> void:
"""
Handle the given event.
处理给定的事件。
If state is RUNNING then passes to on_event.
如果状态为 RUNNING,则传递给 on_event。
Parameters: event (Event) – The event received.
参数:event (Event) - 接收到的事件。
Warning:
System method (not intended to be called by user code).
系统方法(不打算由用户代码调用)。
"""
...
def handle_historical_data(self, data) -> void:
"""
Handle the given historical data.
处理给定的历史数据。
Parameters: data (Data) – The historical data received.
参数:data (Data) - 接收到的历史数据。
Warning:
System method (not intended to be called by user code).
系统方法(不打算由用户代码调用)。
"""
...
def handle_instrument(self, instrument: Instrument) -> void:
"""
Handle the given instrument.
处理给定的Instrument。
Passes to on_instrument if state is RUNNING.
如果状态为 RUNNING,则传递给 on_instrument。
Parameters: instrument (Instrument) – The instrument received.
参数:instrument (Instrument) - 接收到的Instrument。
Warning:
System method (not intended to be called by user code).
系统方法(不打算由用户代码调用)。
"""
...
def handle_instrument_close(self, update: InstrumentClose) -> void:
"""
Handle the given instrument close update.
处理给定的Instrument关闭更新。
If state is RUNNING then passes to on_instrument_close.
如果状态为 RUNNING,则传递给 on_instrument_close。
Parameters: update (InstrumentClose) – The update received.
参数:update (InstrumentClose) - 接收到的更新。
Warning:
System method (not intended to be called by user code).
系统方法(不打算由用户代码调用)。
"""
...
def handle_instrument_status(self, data: InstrumentStatus) -> void:
"""
Handle the given instrument status update.
处理给定的Instrument状态更新。
If state is RUNNING then passes to on_instrument_status.
如果状态为 RUNNING,则传递给 on_instrument_status。
Parameters: data (InstrumentStatus) – The status update received.
参数:data (InstrumentStatus) - 接收到的状态更新。
Warning:
System method (not intended to be called by user code).
系统方法(不打算由用户代码调用)。
"""
...
def handle_instruments(self, instruments: list) -> void:
"""
Handle the given instruments data by handling each instrument individually.
通过单独处理每个Instrument来处理给定的Instrument数据。
Parameters: instruments (list [Instrument ]) – The instruments received.
参数:instruments (list [Instrument ]) - 接收到的Instrument。
Warning:
System method (not intended to be called by user code).
系统方法(不打算由用户代码调用)。
"""
...
def handle_order_book(self, order_book: OrderBook) -> void:
"""
Handle the given order book.
处理给定的订单簿。
Passes to on_order_book if state is RUNNING.
如果状态为 RUNNING,则传递给 on_order_book。
Parameters: order_book (OrderBook) – The order book received.
参数:order_book (OrderBook) - 接收到的订单簿。
Warning:
System method (not intended to be called by user code).
系统方法(不打算由用户代码调用)。
"""
...
def 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.
如果状态为 RUNNING,则传递给 on_order_book_deltas。如果为订阅设置了 pyo3_conversion 标志,则增量将为 nautilus_pyo3.OrderBookDeltas。
Parameters: deltas (OrderBookDeltas or nautilus_pyo3.OrderBookDeltas) – The order book deltas received.
参数:deltas (OrderBookDeltas or nautilus_pyo3.OrderBookDeltas) - 接收到的订单簿增量。
Warning:
System method (not intended to be called by user code).
系统方法(不打算由用户代码调用)。
"""
...
def handle_quote_tick(self, tick: QuoteTick) -> void:
"""
Handle the given quote tick.
处理给定的报价 tick。
If state is RUNNING then passes to on_quote_tick.
如果状态为 RUNNING,则传递给 on_quote_tick。
Parameters: tick (QuoteTick) – The tick received.
参数:tick (QuoteTick) - 接收到的 tick。
Warning:
System method (not intended to be called by user code).
系统方法(不打算由用户代码调用)。
"""
...
def handle_quote_ticks(self, ticks: list) -> void:
"""
Handle the given historical quote tick data by handling each tick individually.
通过单独处理每个 tick 来处理给定的历史报价 tick 数据。
Parameters: ticks (list [QuoteTick ]) – The ticks received.
参数:ticks (list [QuoteTick ]) - 接收到的 tick。
Warning:
System method (not intended to be called by user code).
系统方法(不打算由用户代码调用)。
"""
...
def handle_trade_tick(self, tick: TradeTick) -> void:
"""
Handle the given trade tick.
处理给定的交易 tick。
If state is RUNNING then passes to on_trade_tick.
如果状态为 RUNNING,则传递给 on_trade_tick。
Parameters: tick (TradeTick) – The tick received.
参数:tick (TradeTick) - 接收到的 tick。
Warning:
System method (not intended to be called by user code).
系统方法(不打算由用户代码调用)。
"""
...
def handle_trade_ticks(self, ticks: list) -> void:
"""
Handle the given historical trade tick data by handling each tick individually.
通过单独处理每个 tick 来处理给定的历史交易 tick 数据。
Parameters: ticks (list [TradeTick ]) – The ticks received.
参数:ticks (list [TradeTick ]) - 接收到的 tick。
Warning:
System method (not intended to be called by user code).
系统方法(不打算由用户代码调用)。
"""
...
def has_active_tasks(self) -> bool:
"""
Return a value indicating whether there are any active tasks.
返回值指示是否有任何活动的 task。
Return type: bool
"""
...
def has_any_tasks(self) -> bool:
"""
Return a value indicating whether there are any queued or active tasks.
返回值指示是否有任何排队或活动的 task。
Return type: bool
"""
...
def has_pending_requests(self) -> bool:
"""
Return whether the actor is pending processing for any requests.
返回 actor 是否正在等待处理任何请求。
Returns: True if any requests are pending, else False.
返回值:如果有任何请求正在等待处理,则返回 True,否则返回 False。
Return type: bool
"""
...
def has_queued_tasks(self) -> bool:
"""
Return a value indicating whether there are any queued tasks.
返回值指示是否有任何排队的 task。
Return type: bool
"""
...
def indicators_initialized(self) -> bool:
"""
Return a value indicating whether all indicators are initialized.
返回值指示是否所有指标都已初始化。
Returns: True if all initialized, else False
返回值:如果所有指标都已初始化,则返回 True,否则返回 False。
Return type: bool
"""
...
def is_pending_request(self, request_id: UUID4) -> bool:
"""
Return whether the request for the given identifier is pending processing.
返回给定标识符的请求是否正在等待处理。
Parameters: request_id (UUID4) – The request ID to check.
参数:request_id (UUID4) - 要检查的请求 ID。
Returns: True if request is pending, else False.
返回值:如果请求正在等待处理,则返回 True,否则返回 False。
Return type: bool
"""
...
def load(self, state: dict) -> void:
"""
Load the actor/strategy state from the give state dictionary.
从给定的状态字典加载 actor/strategy 状态。
Calls on_load and passes the state.
调用 on_load 并传递状态。
Parameters: state (dict *[*str , object ]) – The state dictionary.
参数:state (dict *[*str , object ]) - 状态字典。
Raises: RuntimeError – If actor/strategy is not registered with a trader.
引发:RuntimeError - 如果 actor/strategy 未在交易者处注册。
Warning:
Exceptions raised will be caught, logged, and reraised.
引发的异常将被捕获、记录并重新引发。
"""
...
def on_bar(self, bar: Bar) -> void:
"""
Actions to be performed when running and receives a bar.
运行时执行的操作以及接收到的 bar。
Parameters: bar (Bar) – The bar received.
参数:bar (Bar) - 接收到的 bar。
Warning:
System method (not intended to be called by user code).
系统方法(不打算由用户代码调用)。
"""
...
def on_data(self, data: Data) -> void:
"""
Actions to be performed when running and receives data.
运行时执行的操作以及接收到的数据。
Parameters: data (Data) – The data received.
参数:data (Data) - 接收到的数据。
Warning:
System method (not intended to be called by user code).
系统方法(不打算由用户代码调用)。
"""
...
def 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.
应该在 actor 实现中重写。
"""
...
def 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).
系统方法(不打算由用户代码调用)。
"""
...
def on_event(self, event: Event) -> void:
"""
Actions to be performed running and receives an event.
运行时执行的操作以及接收到的事件。
Parameters: event (Event) – The event received.
参数:event (Event) - 接收到的事件。
Warning:
System method (not intended to be called by user code).
系统方法(不打算由用户代码调用)。
"""
...
def on_fault(self) -> void:
"""
Actions to be performed on fault.
出现故障时执行的操作。
Cleanup any resources used by the actor here.
在此处清理 actor 使用的任何资源。
Warning:
System method (not intended to be called by user code).
系统方法(不打算由用户代码调用)。
Should be overridden in the actor implementation.
应该在 actor 实现中重写。
"""
...
def on_historical_data(self, data) -> void:
"""
Actions to be performed when running and receives historical data.
运行时执行的操作以及接收到的历史数据。
Parameters: data (Data) – The historical data received.
参数:data (Data) - 接收到的历史数据。
Warning:
System method (not intended to be called by user code).
系统方法(不打算由用户代码调用)。
"""
...
def on_instrument(self, instrument: Instrument) -> void:
"""
Actions to be performed when running and receives an instrument.
运行时执行的操作以及接收到的Instrument。
Parameters: instrument (Instrument) – The instrument received.
参数:instrument (Instrument) - 接收到的Instrument。
Warning:
System method (not intended to be called by user code).
系统方法(不打算由用户代码调用)。
"""
...
def on_instrument_close(self, update: InstrumentClose) -> void:
"""
Actions to be performed when running and receives an instrument close update.
运行时执行的操作以及接收到的Instrument关闭更新。
Parameters: update (InstrumentClose) – The instrument close received.
参数:update (InstrumentClose) - 接收到的Instrument关闭。
Warning:
System method (not intended to be called by user code).
系统方法(不打算由用户代码调用)。
"""
...
def on_instrument_status(self, data: InstrumentStatus) -> void:
"""
Actions to be performed when running and receives an instrument status update.
运行时执行的操作以及接收到的Instrument状态更新。
Parameters: data (InstrumentStatus) – The instrument status update received.
参数:data (InstrumentStatus) - 接收到的Instrument状态更新。
Warning:
System method (not intended to be called by user code).
系统方法(不打算由用户代码调用)。
"""
...
def on_load(self, state: dict) -> void:
"""
Actions to be performed when the actor state is loaded.
加载 actor 状态时执行的操作。
Saved state values will be contained in the give state dictionary.
保存的状态值将包含在给定的状态字典中。
Warning:
System method (not intended to be called by user code).
系统方法(不打算由用户代码调用)。
"""
...
def on_order_book(self, order_book: OrderBook) -> void:
"""
Actions to be performed when running and receives an order book.
运行时执行的操作以及接收到的订单簿。
Parameters: order_book (OrderBook) – The order book received.
参数:order_book (OrderBook) - 接收到的订单簿。
Warning:
System method (not intended to be called by user code).
系统方法(不打算由用户代码调用)。
"""
...
def 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.
参数:deltas (OrderBookDeltas or nautilus_pyo3.OrderBookDeltas) - 接收到的订单簿增量。
Warning:
System method (not intended to be called by user code).
系统方法(不打算由用户代码调用)。
"""
...
def on_quote_tick(self, tick: QuoteTick) -> void:
"""
Actions to be performed when running and receives a quote tick.
运行时执行的操作以及接收到的报价 tick。
Parameters: tick (QuoteTick) – The tick received.
参数:tick (QuoteTick) - 接收到的 tick。
Warning:
System method (not intended to be called by user code).
系统方法(不打算由用户代码调用)。
"""
...
def 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.
应该在用户实现中重写。
"""
...
def on_resume(self) -> void:
"""
Actions to be performed on resume.
恢复时执行的操作。
Warning:
System method (not intended to be called by user code).
系统方法(不打算由用户代码调用)。
"""
...
def on_save(self) -> dict:
"""
Actions to be performed when the actor state is saved.
保存 actor 状态时执行的操作。
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).
系统方法(不打算由用户代码调用)。
"""
...
def 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.
应该在用户实现中重写。
"""
...
def 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.
应该在用户实现中重写。
"""
...
def on_trade_tick(self, tick: TradeTick) -> void:
"""
Actions to be performed when running and receives a trade tick.
运行时执行的操作以及接收到的交易 tick。
Parameters: tick (TradeTick) – The tick received.
参数:tick (TradeTick) - 接收到的 tick。
Warning:
System method (not intended to be called by user code).
系统方法(不打算由用户代码调用)。
"""
...
def pending_requests(self) -> set:
"""
Return the request IDs which are currently pending processing.
返回当前正在等待处理的请求 ID。
Return type: set[UUID4]
"""
...
def publish_data(self, data_type: DataType, data: Data) -> void:
"""
Publish the given data to the message bus.
将给定的数据发布到消息总线。
Parameters:
参数:
data_type (DataType) – The data type being published.
data_type (DataType) - 正在发布的数据类型。
data (Data) – The data to publish.
data (Data) - 要发布的数据。
"""
...
def publish_signal(self, name: str, value, ts_event: int=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 is case-insensitive and will be capitalized (e.g., ‘example’ becomes ‘SignalExample’).
name (str) - 正在发布的信号的名称。信号名称不区分大小写,并且将大写(例如,“example”变为“SignalExample”)。
value (object) – The signal data to publish.
value (object) - 要发布的信号数据。
ts_event (uint64_t , optional) – UNIX timestamp (nanoseconds) when the signal event occurred. If None then will timestamp current time.
ts_event (uint64_t,可选) - 信号事件发生时的 UNIX 时间戳(纳秒)。如果为 None,则将使用当前时间作为时间戳。
"""
...
def queue_for_executor(self, func: Callable, args: tuple=None, kwargs: dict=None):
"""
Queues the callable func to be executed as fn(*args, **kwargs) sequentially.
将可调用函数 func 排队,以便按顺序执行为 fn(*args, **kwargs)。
Parameters:
参数:
func (Callable) – The function to be executed.
func (Callable) - 要执行的函数。
args (positional arguments) – The positional arguments for the call to func.
args(位置参数) - 对 func 的调用的位置参数。
kwargs (arbitrary keyword arguments) – The keyword arguments for the call to func.
kwargs(任意关键字参数) - 对 func 的调用的关键字参数。
Raises: TypeError – If func is not of type Callable.
引发:TypeError - 如果 func 的类型不是 Callable。
"""
...
def queued_task_ids(self) -> list:
"""
Return the queued task identifiers.
返回排队的 task 标识符。
Return type: list[TaskId]
"""
...
def register_base(self, portfolio: PortfolioFacade, msgbus: MessageBus, cache: CacheFacade, clock: Clock) -> void:
"""
Register with a trader.
向交易者注册。
Parameters:
参数:
portfolio (PortfolioFacade) – The read-only portfolio for the actor.
portfolio (PortfolioFacade) - actor 的只读投资组合。
msgbus (MessageBus) – The message bus for the actor.
msgbus (MessageBus) - actor 的消息总线。
cache (CacheFacade) – The read-only cache for the actor.
cache (CacheFacade) - actor 的只读缓存。
clock (Clock) – The clock for the actor.
clock (Clock) - actor 的时钟。
Warning:
System method (not intended to be called by user code).
系统方法(不打算由用户代码调用)。
"""
...
def register_executor(self, loop, executor: Executor) -> void:
"""
Register the given Executor for the actor.
为 actor 注册给定的 Executor。
Parameters:
参数:
loop (asyncio.AsbtractEventLoop) – The event loop of the application.
```python
loop (asyncio.AsbtractEventLoop) - 应用程序的事件循环。
executor (concurrent.futures.Executor) – The executor to register.
executor (concurrent.futures.Executor) - 要注册的执行器。
Raises: TypeError – If executor is not of type concurrent.futures.Executor
引发:TypeError - 如果 executor 的类型不是 concurrent.futures.Executor。
"""
...
def register_indicator_for_bars(self, bar_type: BarType, indicator: Indicator) -> void:
"""
Register the given indicator with the actor/strategy to receive bar data for the given bar type.
向 actor/strategy 注册给定的指标,以便接收给定 bar 类型的 bar 数据。
Parameters:
参数:
bar_type (BarType) – The bar type for bar updates.
bar_type (BarType) - bar 更新的 bar 类型。
indicator (Indicator) – The indicator to register.
indicator (Indicator) - 要注册的指标。
"""
...
def register_indicator_for_quote_ticks(self, instrument_id: InstrumentId, indicator: Indicator) -> void:
"""
Register the given indicator with the actor/strategy to receive quote tick data for the given instrument ID.
向 actor/strategy 注册给定的指标,以便接收给定Instrument ID 的报价 tick 数据。
Parameters:
参数:
instrument_id (InstrumentId) – The instrument ID for tick updates.
instrument_id (InstrumentId) - tick 更新的Instrument ID。
indicator (Indicator) – The indicator to register.
indicator (Indicator) - 要注册的指标。
"""
...
def register_indicator_for_trade_ticks(self, instrument_id: InstrumentId, indicator) -> void:
"""
Register the given indicator with the actor/strategy to receive trade tick data for the given instrument ID.
向 actor/strategy 注册给定的指标,以便接收给定Instrument ID 的交易 tick 数据。
Parameters:
参数:
instrument_id (InstrumentId) – The instrument ID for tick updates.
instrument_id (InstrumentId) - tick 更新的Instrument ID。
indicator (indicator) – The indicator to register.
indicator (indicator) - 要注册的指标。
"""
...
def register_warning_event(self, event) -> void:
"""
Register the given event type for warning log levels.
为警告日志级别注册给定的事件类型。
Parameters: event (type) – The event class to register.
参数:event (type) - 要注册的事件类。
"""
...
def request_bars(self, bar_type: BarType, start: datetime=None, end: datetime=None, client_id: ClientId=None, callback=None) -> UUID4:
"""
Request historical Bar data.
请求历史 Bar 数据。
If end is None then will request up to the most recent data.
如果 end 为 None,则将请求最多到最新数据。
Parameters:
参数:
bar_type (BarType) – The bar type for the request.
bar_type (BarType) - 请求的 bar 类型。
start (datetime , optional) – The start datetime (UTC) of request time range (inclusive).
start (datetime,可选) - 请求时间范围的开始日期时间(UTC)(含)。
end (datetime , optional) – The end datetime (UTC) of request time range. The inclusiveness depends on individual data client implementation.
end (datetime,可选) - 请求时间范围的结束日期时间(UTC)。包含性取决于各个数据客户端的实现。
client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.
client_id (ClientId,可选) - 命令的特定客户端 ID。如果为 None,则将从Instrument ID 中的平台推断出来。
callback (Callable [ [UUID4 ] , None ] , optional) – The registered callback, to be called with the request ID when the response has completed processing.
callback (Callable [ [UUID4 ] , None ],可选) - 注册的回调函数,当响应完成处理时,将使用请求 ID 调用该回调函数。
Returns: The request_id for the request.
返回值:请求的 request_id。
Return type: UUID4
Raises:
引发:
ValueError – If start and end are not None and start is >= end.
ValueError - 如果 start 和 end 不为 None 并且 start >= end。
TypeError – If callback is not None and not of type Callable.
TypeError - 如果 callback 不为 None 并且类型不是 Callable。
"""
...
def request_data(self, data_type: DataType, client_id: ClientId, callback=None) -> UUID4:
"""
Request custom data for the given data type from the given data client.
从给定的数据客户端请求给定数据类型的自定义数据。
Parameters:
参数:
data_type (DataType) – The data type for the request.
data_type (DataType) - 请求的数据类型。
client_id (ClientId) – The data client ID.
client_id (ClientId) - 数据客户端 ID。
callback (Callable [ [UUID4 ] , None ] , optional) – The registered callback, to be called with the request ID when the response has completed processing.
callback (Callable [ [UUID4 ] , None ],可选) - 注册的回调函数,当响应完成处理时,将使用请求 ID 调用该回调函数。
Returns: The request_id for the request.
返回值:请求的 request_id。
Return type: UUID4
Raises: TypeError – If callback is not None and not of type Callable.
引发:TypeError - 如果 callback 不为 None 并且类型不是 Callable。
"""
...
def request_instrument(self, instrument_id: InstrumentId, start: datetime=None, end: datetime=None, client_id: ClientId=None, callback=None) -> UUID4:
"""
Request Instrument data for the given instrument ID.
请求给定Instrument ID 的Instrument数据。
If end is None then will request up to the most recent data.
如果 end 为 None,则将请求最多到最新数据。
Parameters:
参数:
instrument_id (InstrumentId) – The instrument ID for the request.
instrument_id (InstrumentId) - 请求的Instrument ID。
start (datetime , optional) – The start datetime (UTC) of request time range (inclusive).
start (datetime,可选) - 请求时间范围的开始日期时间(UTC)(含)。
end (datetime , optional) – The end datetime (UTC) of request time range. The inclusiveness depends on individual data client implementation.
end (datetime,可选) - 请求时间范围的结束日期时间(UTC)。包含性取决于各个数据客户端的实现。
client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.
client_id (ClientId,可选) - 命令的特定客户端 ID。如果为 None,则将从Instrument ID 中的平台推断出来。
callback (Callable [ [UUID4 ] , None ] , optional) – The registered callback, to be called with the request ID when the response has completed processing.
callback (Callable [ [UUID4 ] , None ],可选) - 注册的回调函数,当响应完成处理时,将使用请求 ID 调用该回调函数。
Returns: The request_id for the request.
返回值:请求的 request_id。
Return type: UUID4
Raises:
引发:
ValueError – If start and end are not None and start is >= end.
ValueError - 如果 start 和 end 不为 None 并且 start >= end。
TypeError – If callback is not None and not of type Callable.
TypeError - 如果 callback 不为 None 并且类型不是 Callable。
"""
...
def request_instruments(self, venue: Venue, start: datetime=None, end: datetime=None, client_id: ClientId=None, callback=None) -> UUID4:
"""
Request all Instrument data for the given venue.
请求给定平台的所有Instrument数据。
If end is None then will request up to the most recent data.
如果 end 为 None,则将请求最多到最新数据。
Parameters:
参数:
venue (Venue) – The venue for the request.
venue (Venue) - 请求的平台。
start (datetime , optional) – The start datetime (UTC) of request time range (inclusive).
start (datetime,可选) - 请求时间范围的开始日期时间(UTC)(含)。
end (datetime , optional) – The end datetime (UTC) of request time range. The inclusiveness depends on individual data client implementation.
end (datetime,可选) - 请求时间范围的结束日期时间(UTC)。包含性取决于各个数据客户端的实现。
client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.
client_id (ClientId,可选) - 命令的特定客户端 ID。如果为 None,则将从Instrument ID 中的平台推断出来。
callback (Callable [ [UUID4 ] , None ] , optional) – The registered callback, to be called with the request ID when the response has completed processing.
callback (Callable [ [UUID4 ] , None ],可选) - 注册的回调函数,当响应完成处理时,将使用请求 ID 调用该回调函数。
Returns: The request_id for the request.
返回值:请求的 request_id。
Return type: UUID4
Raises:
引发:
ValueError – If start and end are not None and start is >= end.
ValueError - 如果 start 和 end 不为 None 并且 start >= end。
TypeError – If callback is not None and not of type Callable.
TypeError - 如果 callback 不为 None 并且类型不是 Callable。
"""
...
def request_order_book_snapshot(self, instrument_id: InstrumentId, limit: int, client_id: ClientId=None, callback=None) -> UUID4:
"""
Request an order book snapshot.
请求订单簿快照。
Parameters:
参数:
instrument_id (InstrumentId) – The instrument ID for the order book snapshot request.
instrument_id (InstrumentId) - 订单簿快照请求的Instrument ID。
limit (int , optional) – The limit on the depth of the order book snapshot (default is None).
limit (int,可选) - 订单簿快照深度的限制(默认为 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.
client_id (ClientId,可选) - 命令的特定客户端 ID。如果为 None,则将从Instrument ID 中的平台推断出来。
callback (Callable [ [UUID4 ] , None ] , optional) – The registered callback, to be called with the request ID when the response has completed processing.
callback (Callable [ [UUID4 ] , None ],可选) - 注册的回调函数,当响应完成处理时,将使用请求 ID 调用该回调函数。
Returns: The request_id for the request.
返回值:请求的 request_id。
Return type: UUID4
Raises:
引发:
ValueError – If the instrument_id is None.
ValueError - 如果 instrument_id 为 None。
TypeError – If callback is not None and not of type Callable.
TypeError - 如果 callback 不为 None 并且类型不是 Callable。
"""
...
def request_quote_ticks(self, instrument_id: InstrumentId, start: datetime=None, end: datetime=None, client_id: ClientId=None, callback=None) -> UUID4:
"""
Request historical QuoteTick data.
请求历史报价 Tick 数据。
If end is None then will request up to the most recent data.
如果 end 为 None,则将请求最多到最新数据。
Parameters:
参数:
instrument_id (InstrumentId) – The tick instrument ID for the request.
instrument_id (InstrumentId) - 请求的 tick Instrument ID。
start (datetime , optional) – The start datetime (UTC) of request time range (inclusive).
start (datetime,可选) - 请求时间范围的开始日期时间(UTC)(含)。
end (datetime , optional) – The end datetime (UTC) of request time range. The inclusiveness depends on individual data client implementation.
end (datetime,可选) - 请求时间范围的结束日期时间(UTC)。包含性取决于各个数据客户端的实现。
client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.
client_id (ClientId,可选) - 命令的特定客户端 ID。如果为 None,则将从Instrument ID 中的平台推断出来。
callback (Callable [ [UUID4 ] , None ] , optional) – The registered callback, to be called with the request ID when the response has completed processing.
callback (Callable [ [UUID4 ] , None ],可选) - 注册的回调函数,当响应完成处理时,将使用请求 ID 调用该回调函数。
Returns: The request_id for the request.
返回值:请求的 request_id。
Return type: UUID4
Raises:
引发:
ValueError – If start and end are not None and start is >= end.
ValueError - 如果 start 和 end 不为 None 并且 start >= end。
TypeError – If callback is not None and not of type Callable.
TypeError - 如果 callback 不为 None 并且类型不是 Callable。
"""
...
def request_trade_ticks(self, instrument_id: InstrumentId, start: datetime=None, end: datetime=None, client_id: ClientId=None, callback=None) -> UUID4:
"""
Request historical TradeTick data.
请求历史交易 Tick 数据。
If end is None then will request up to the most recent data.
如果 end 为 None,则将请求最多到最新数据。
Parameters:
参数:
instrument_id (InstrumentId) – The tick instrument ID for the request.
instrument_id (InstrumentId) - 请求的 tick Instrument ID。
start (datetime , optional) – The start datetime (UTC) of request time range (inclusive).
start (datetime,可选) - 请求时间范围的开始日期时间(UTC)(含)。
end (datetime , optional) – The end datetime (UTC) of request time range. The inclusiveness depends on individual data client implementation.
end (datetime,可选) - 请求时间范围的结束日期时间(UTC)。包含性取决于各个数据客户端的实现。
client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.
client_id (ClientId,可选) - 命令的特定客户端 ID。如果为 None,则将从Instrument ID 中的平台推断出来。
callback (Callable [ [UUID4 ] , None ] , optional) – The registered callback, to be called with the request ID when the response has completed processing.
callback (Callable [ [UUID4 ] , None ],可选) - 注册的回调函数,当响应完成处理时,将使用请求 ID 调用该回调函数。
Returns: The request_id for the request.
返回值:请求的 request_id。
Return type: UUID4
Raises:
引发:
ValueError – If start and end are not None and start is >= end.
ValueError - 如果 start 和 end 不为 None 并且 start >= end。
TypeError – If callback is not None and not of type Callable.
TypeError - 如果 callback 不为 None 并且类型不是 Callable。
"""
...
def 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.
警告:
不要覆盖。
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) -> void:
"""
Resume the component.
While executing on_resume() any exception will be logged and reraised, then the component will remain in a RESUMING state.
警告:
不要覆盖。
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 run_in_executor(self, func: Callable, args: tuple=None, kwargs: dict=None):
"""
Schedules the callable func to be executed as fn(*args, **kwargs).
计划可调用函数 func 以 fn(*args, **kwargs) 的形式执行。
Parameters:
参数:
func (Callable) – The function to be executed.
func (Callable) - 要执行的函数。
args (positional arguments) – The positional arguments for the call to func.
args(位置参数) - 对 func 的调用的位置参数。
kwargs (arbitrary keyword arguments) – The keyword arguments for the call to func.
kwargs(任意关键字参数) - 对 func 的调用的关键字参数。
Returns: The unique task identifier for the execution. This also corresponds to any future objects memory address.
返回值:执行的唯一 task 标识符。这也对应于任何 future 对象的内存地址。
Return type: TaskId
Raises: TypeError – If func is not of type Callable.
引发:TypeError - 如果 func 的类型不是 Callable。
"""
...
def save(self) -> dict:
"""
Return the actor/strategy state dictionary to be saved.
返回要保存的 actor/strategy 状态字典。
Calls on_save.
调用 on_save。
Raises: RuntimeError – If actor/strategy is not registered with a trader.
引发:RuntimeError - 如果 actor/strategy 未在交易者处注册。
Warning:
Exceptions raised will be caught, logged, and reraised.
引发的异常将被捕获、记录并重新引发。
"""
...
def 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.
警告:
不要覆盖。
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 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.
警告:
不要覆盖。
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 subscribe_bars(self, bar_type: BarType, client_id: ClientId=None, await_partial: bool=False) -> void:
"""
Subscribe to streaming Bar data for the given bar type.
订阅给定 bar 类型的流式 Bar 数据。
Parameters:
参数:
bar_type (BarType) – The bar type to subscribe to.
bar_type (BarType) - 要订阅的 bar 类型。
client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.
client_id (ClientId,可选) - 命令的特定客户端 ID。如果为 None,则将从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.
await_partial (bool,默认 False) - bar 聚合器是否应在主动聚合新 bar 之前等待历史部分 bar 的到来。
"""
...
def subscribe_data(self, data_type: DataType, client_id: ClientId=None) -> void:
"""
Subscribe to data of the given data type.
订阅给定数据类型的数据。
Parameters:
参数:
data_type (DataType) – The data type to subscribe to.
data_type (DataType) - 要订阅的数据类型。
client_id (ClientId , optional) – The data client ID. If supplied then a Subscribe command will be sent to the corresponding data client.
client_id (ClientId,可选) - 数据客户端 ID。如果提供,则将向相应的数据客户端发送 Subscribe 命令。
"""
...
def subscribe_instrument(self, instrument_id: InstrumentId, client_id: ClientId=None) -> void:
"""
Subscribe to update Instrument data for the given instrument ID.
订阅给定Instrument ID 的更新Instrument数据。
Parameters:
参数:
instrument_id (InstrumentId) – The instrument ID for the subscription.
instrument_id (InstrumentId) - 订阅的Instrument ID。
client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.
client_id (ClientId,可选) - 命令的特定客户端 ID。如果为 None,则将从Instrument ID 中的平台推断出来。
"""
...
def subscribe_instrument_close(self, instrument_id: InstrumentId, client_id: ClientId=None) -> void:
"""
Subscribe to close updates for the given instrument ID.
订阅给定Instrument ID 的收盘价更新。
Parameters:
参数:
instrument_id (InstrumentId) – The instrument to subscribe to status updates for.
instrument_id (InstrumentId) - 要订阅状态更新的Instrument。
client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.
client_id (ClientId,可选) - 命令的特定客户端 ID。如果为 None,则将从Instrument ID 中的平台推断出来。
"""
...
def subscribe_instrument_status(self, instrument_id: InstrumentId, client_id: ClientId=None) -> void:
"""
Subscribe to status updates for the given instrument ID.
订阅给定Instrument ID 的状态更新。
Parameters:
参数:
instrument_id (InstrumentId) – The instrument to subscribe to status updates for.
instrument_id (InstrumentId) - 要订阅状态更新的Instrument。
client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.
client_id (ClientId,可选) - 命令的特定客户端 ID。如果为 None,则将从Instrument ID 中的平台推断出来。
"""
...
def subscribe_instruments(self, venue: Venue, client_id: ClientId=None) -> void:
"""
Subscribe to update Instrument data for the given venue.
订阅给定平台的更新Instrument数据。
Parameters:
参数:
venue (Venue) – The venue for the subscription.
venue (Venue) - 订阅的平台。
client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue.
client_id (ClientId,可选) - 命令的特定客户端 ID。如果为 None,则将从平台推断出来。
"""
...
def subscribe_order_book_at_interval(self, instrument_id: InstrumentId, book_type=BookType.L2_MBP, depth: int=0, interval_ms: int=1000, kwargs: dict=None, client_id: ClientId=None, managed: bool=True) -> void:
"""
Subscribe to an OrderBook at a specified interval for the given instrument ID.
以指定的间隔订阅给定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).
数据引擎将只为每个Instrument维护一个订单簿。因此,流的级别、深度和 kwargs 将根据最后一个订阅请求进行设置(这也会影响所有订阅者)。
Parameters:
参数:
instrument_id (InstrumentId) – The order book instrument ID to subscribe to.
instrument_id (InstrumentId) - 要订阅的订单簿Instrument ID。
book_type (BookType {L1_MBP, L2_MBP, L3_MBO}) – The order book type.
book_type (BookType {L1_MBP, L2_MBP, L3_MBO}) - 订单簿类型。
depth (int , optional) – The maximum depth for the order book. A depth of 0 is maximum depth.
depth (int,可选) - 订单簿的最大深度。深度为 0 表示最大深度。
interval_ms (int) – The order book snapshot interval in milliseconds (must be positive).
interval_ms (int) - 订单簿快照间隔(以毫秒为单位)(必须为正数)。
kwargs (dict , optional) – The keyword arguments for exchange specific parameters.
kwargs (dict,可选) - 交换特定参数的关键字参数。
client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.
client_id (ClientId,可选) - 命令的特定客户端 ID。如果为 None,则将从Instrument ID 中的平台推断出来。
managed (bool , default True) – If an order book should be managed by the data engine based on the subscribed feed.
managed (bool,默认 True) - 是否应根据订阅的源由数据引擎管理订单簿。
Raises:
引发:
ValueError – If depth is negative (< 0).
ValueError - 如果 depth 为负数(< 0)。
ValueError – If interval_ms is not positive (> 0).
ValueError - 如果 interval_ms 不是正数(> 0)。
Warning:
Consider subscribing to order book deltas if you need intervals less than 100 milliseconds.
如果需要小于 100 毫秒的间隔,请考虑订阅订单簿增量。
"""
...
def subscribe_order_book_deltas(self, instrument_id: InstrumentId, book_type=BookType.L2_MBP, depth: int=0, kwargs: dict=None, client_id: ClientId=None, managed: bool=True, pyo3_conversion: bool=False) -> void:
"""
Subscribe to the order book data stream, being a snapshot then deltas for the given instrument ID.
订阅订单簿数据流,即给定Instrument ID 的快照,然后是增量。
Parameters:
参数:
instrument_id (InstrumentId) – The order book instrument ID to subscribe to.
instrument_id (InstrumentId) - 要订阅的订单簿Instrument ID。
book_type (BookType {L1_MBP, L2_MBP, L3_MBO}) – The order book type.
book_type (BookType {L1_MBP, L2_MBP, L3_MBO}) - 订单簿类型。
depth (int , optional) – The maximum depth for the order book. A depth of 0 is maximum depth.
depth (int,可选) - 订单簿的最大深度。深度为 0 表示最大深度。
kwargs (dict , optional) – The keyword arguments for exchange specific parameters.
kwargs (dict,可选) - 交换特定参数的关键字参数。
client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.
client_id (ClientId,可选) - 命令的特定客户端 ID。如果为 None,则将从Instrument ID 中的平台推断出来。
managed (bool , default True) – If an order book should be managed by the data engine based on the subscribed feed.
managed (bool,默认 True) - 是否应根据订阅的源由数据引擎管理订单簿。
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.
pyo3_conversion (bool,默认 False) - 在传递给 on_order_book_deltas 处理程序之前,是否应将接收到的增量转换为 nautilus_pyo3.OrderBookDeltas。
"""
...
def subscribe_quote_ticks(self, instrument_id: InstrumentId, client_id: ClientId=None) -> void:
"""
Subscribe to streaming QuoteTick data for the given instrument ID.
订阅给定Instrument ID 的流式报价 Tick 数据。
Parameters:
参数:
instrument_id (InstrumentId) – The tick instrument to subscribe to.
instrument_id (InstrumentId) - 要订阅的 tick Instrument。
client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.
client_id (ClientId,可选) - 命令的特定客户端 ID。如果为 None,则将从Instrument ID 中的平台推断出来。
"""
...
def subscribe_signal(self, name: str='') -> 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*’).
参数:name (str,可选) - 要订阅的信号的名称。如果没有提供或传递空字符串,则订阅将包含所有信号。信号名称不区分大小写,并且将大写(例如,“example”变为“SignalExample*”)。
"""
...
def subscribe_trade_ticks(self, instrument_id: InstrumentId, client_id: ClientId=None) -> void:
"""
Subscribe to streaming TradeTick data for the given instrument ID.
订阅给定Instrument ID 的流式交易 Tick 数据。
Parameters:
参数:
instrument_id (InstrumentId) – The tick instrument to subscribe to.
instrument_id (InstrumentId) - 要订阅的 tick Instrument。
client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.
client_id (ClientId,可选) - 命令的特定客户端 ID。如果为 None,则将从Instrument ID 中的平台推断出来。
"""
...
def to_importable_config(self) -> ImportableActorConfig:
"""
Returns an importable configuration for this actor.
返回此 actor 的可导入配置。
Return type: ImportableActorConfig
"""
...
def unsubscribe_bars(self, bar_type: BarType, client_id: ClientId=None) -> void:
"""
Unsubscribe from streaming Bar data for the given bar type.
取消订阅给定 bar 类型的流式 Bar 数据。
Parameters:
参数:
bar_type (BarType) – The bar type to unsubscribe from.
bar_type (BarType) - 要取消订阅的 bar 类型。
client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.
client_id (ClientId,可选) - 命令的特定客户端 ID。如果为 None,则将从Instrument ID 中的平台推断出来。
"""
...
def unsubscribe_data(self, data_type: DataType, client_id: ClientId=None) -> void:
"""
Unsubscribe from data of the given data type.
取消订阅给定数据类型的数据。
Parameters:
参数:
data_type (DataType) – The data type to unsubscribe from.
data_type (DataType) - 要取消订阅的数据类型。
client_id (ClientId , optional) – The data client ID. If supplied then an Unsubscribe command will be sent to the data client.
client_id (ClientId,可选) - 数据客户端 ID。如果提供,则将向数据客户端发送 Unsubscribe 命令。
"""
...
def unsubscribe_instrument(self, instrument_id: InstrumentId, client_id: ClientId=None) -> void:
"""
Unsubscribe from update Instrument data for the given instrument ID.
取消订阅给定Instrument ID 的更新Instrument数据。
Parameters:
参数:
instrument_id (InstrumentId) – The instrument to unsubscribe from.
instrument_id (InstrumentId) - 要取消订阅的Instrument。
client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.
client_id (ClientId,可选) - 命令的特定客户端 ID。如果为 None,则将从Instrument ID 中的平台推断出来。
"""
...
def unsubscribe_instrument_status(self, instrument_id: InstrumentId, client_id: ClientId=None) -> void:
"""
Unsubscribe to status updates of the given venue.
取消订阅给定平台的状态更新。
Parameters:
参数:
instrument_id (InstrumentId) – The instrument to unsubscribe to status updates for.
instrument_id (InstrumentId) - 要取消订阅状态更新的Instrument。
client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue.
client_id (ClientId,可选) - 命令的特定客户端 ID。如果为 None,则将从平台推断出来。
"""
...
def unsubscribe_instruments(self, venue: Venue, client_id: ClientId=None) -> void:
"""
Unsubscribe from update Instrument data for the given venue.
取消订阅给定平台的更新Instrument数据。
Parameters:
参数:
venue (Venue) – The venue for the subscription.
```python
venue (Venue) - 订阅的场所。
client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue.
client_id (ClientId,可选) - 命令的特定客户端 ID。如果为 None,则将从场所推断出来。
"""
...
def unsubscribe_order_book_at_interval(self, instrument_id: InstrumentId, interval_ms: int=1000, client_id: ClientId=None) -> void:
"""
Unsubscribe from an OrderBook at a specified interval for the given instrument ID.
以指定的间隔取消订阅给定Instrument ID 的订单簿。
The interval must match the previously subscribed interval.
间隔必须与之前订阅的间隔匹配。
Parameters:
参数:
instrument_id (InstrumentId) – The order book instrument to subscribe to.
instrument_id (InstrumentId) - 要订阅的订单簿Instrument。
interval_ms (int) – The order book snapshot interval in milliseconds.
interval_ms (int) - 订单簿快照间隔(以毫秒为单位)。
client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.
client_id (ClientId,可选) - 命令的特定客户端 ID。如果为 None,则将从Instrument ID 中的场所推断出来。
"""
...
def unsubscribe_order_book_deltas(self, instrument_id: InstrumentId, client_id: ClientId=None) -> void:
"""
Unsubscribe the order book deltas stream for the given instrument ID.
取消订阅给定Instrument ID 的订单簿增量流。
Parameters:
参数:
instrument_id (InstrumentId) – The order book instrument to subscribe to.
instrument_id (InstrumentId) - 要订阅的订单簿Instrument。
client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.
client_id (ClientId,可选) - 命令的特定客户端 ID。如果为 None,则将从Instrument ID 中的场所推断出来。
"""
...
def unsubscribe_quote_ticks(self, instrument_id: InstrumentId, client_id: ClientId=None) -> void:
"""
Unsubscribe from streaming QuoteTick data for the given instrument ID.
取消订阅给定Instrument ID 的流式报价 Tick 数据。
Parameters:
参数:
instrument_id (InstrumentId) – The tick instrument to unsubscribe from.
instrument_id (InstrumentId) - 要取消订阅的 tick Instrument。
client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.
client_id (ClientId,可选) - 命令的特定客户端 ID。如果为 None,则将从Instrument ID 中的场所推断出来。
"""
...
def unsubscribe_trade_ticks(self, instrument_id: InstrumentId, client_id: ClientId=None) -> void:
"""
Unsubscribe from streaming TradeTick data for the given instrument ID.
取消订阅给定Instrument ID 的流式交易 Tick 数据。
Parameters:
参数:
instrument_id (InstrumentId) – The tick instrument ID to unsubscribe from.
instrument_id (InstrumentId) - 要取消订阅的 tick Instrument ID。
client_id (ClientId , optional) – The specific client ID for the command. If None then will be inferred from the venue in the instrument ID.
client_id (ClientId,可选) - 命令的特定客户端 ID。如果为 None,则将从Instrument ID 中的场所推断出来。
"""
...
def update_synthetic(self, synthetic: SyntheticInstrument) -> void:
"""
Update the synthetic instrument in the cache.
更新缓存中的合成Instrument。
Parameters: synthetic (SyntheticInstrument) – The synthetic instrument to update in the cache.
参数:synthetic (SyntheticInstrument) - 要在缓存中更新的合成Instrument。
Raises: KeyError – If synthetic does not already exist in the cache.
引发:KeyError - 如果合成Instrument在缓存中不存在。
"""
...
Bases: object
class OrderFactory(object):
"""
A factory class which provides different order types.
提供不同订单类型的工厂类。
The TraderId tag and StrategyId tag will be inserted into all IDs generated.
TraderId 标签和 StrategyId 标签将被插入到生成的所有 ID 中。
Parameters:
参数:
trader_id (TraderId) – The trader ID (only numerical tag sent to venue).
trader_id (TraderId) - 交易者 ID(仅数字标签发送到场所)。
strategy_id (StrategyId) – The strategy ID (only numerical tag sent to venue).
strategy_id (StrategyId) - 策略 ID(仅数字标签发送到场所)。
clock (Clock) – The clock for the factory.
clock (Clock) - 工厂的时钟。
cache (CacheFacade , optional) – The cache facade for the order factory.
cache (CacheFacade,可选) - 订单工厂的缓存外观。
initial_order_id_count (int , optional) – The initial order ID count for the factory.
initial_order_id_count (int,可选) - 工厂的初始订单 ID 计数。
initial_order_list_id_count (int , optional) – The initial order list ID count for the factory.
initial_order_list_id_count (int,可选) - 工厂的初始订单列表 ID 计数。
Raises:
引发:
ValueError – If initial_order_id_count is negative (< 0).
ValueError - 如果 initial_order_id_count 为负数 (< 0)。
ValueError – If initial_order_list_id_count is negative (< 0).
ValueError - 如果 initial_order_list_id_count 为负数 (< 0)。
"""
def __init__(self, trader_id: TraderId, strategy_id: StrategyId, clock: Clock, cache: CacheFacade | None = None, initial_order_id_count: int = 0, initial_order_list_id_count: int = 0):
...
@property
def strategy_id(self):
"""
The order factories trading strategy ID.
订单工厂的交易策略 ID。
Returns:
StrategyId
"""
...
@property
def trader_id(self):
"""
The order factories trader ID.
订单工厂的交易者 ID。
Returns:
TraderId
"""
...
def bracket(self, instrument_id: InstrumentId, order_side: OrderSide, quantity: Quantity, entry_trigger_price: Price = None, entry_price: Price = None, sl_trigger_price: Price = None, tp_trigger_price: Price = None, tp_price: Price = None, entry_order_type=OrderType.MARKET, tp_order_type=OrderType.LIMIT, time_in_force=TimeInForce.GTC, sl_time_in_force=TimeInForce.GTC, tp_time_in_force=TimeInForce.GTC, expire_time: datetime = None, entry_post_only: bool = False, tp_post_only: bool = True, quote_quantity: bool = False, emulation_trigger=TriggerType.NO_TRIGGER, trigger_instrument_id: InstrumentId = None, contingency_type=ContingencyType.OUO, entry_exec_algorithm_id: ExecAlgorithmId = None, sl_exec_algorithm_id: ExecAlgorithmId = None, tp_exec_algorithm_id: ExecAlgorithmId = None, entry_exec_algorithm_params: dict = None, tp_exec_algorithm_params: dict = None, sl_exec_algorithm_params: dict = None, entry_tags: list = None, tp_tags: list = None, sl_tags: list = None, entry_client_order_id: ClientOrderId = None, tp_client_order_id: ClientOrderId = None, sl_client_order_id: ClientOrderId = None) -> OrderList:
"""
Create a bracket order with optional entry of take-profit order types.
创建具有可选止盈订单类型输入的括号订单。
The stop-loss order will always be STOP_MARKET.
止损订单将始终为 STOP_MARKET。
Parameters:
参数:
instrument_id (InstrumentId) – The orders instrument ID.
instrument_id (InstrumentId) - 订单的Instrument ID。
order_side (OrderSide {BUY, SELL}) – The entry orders side.
order_side (OrderSide {BUY, SELL}) - 入场订单方向。
quantity (Quantity) – The entry orders quantity (> 0).
quantity (Quantity) - 入场订单数量 (> 0)。
entry_trigger_price (Price , optional) – The entry order trigger price (STOP).
entry_trigger_price (Price,可选) - 入场订单触发价格 (STOP)。
entry_price (Price , optional) – The entry order price (LIMIT).
entry_price (Price,可选) - 入场订单价格 (LIMIT)。
sl_trigger_price (Price) – The stop-loss child order trigger price (STOP).
sl_trigger_price (Price) - 止损子订单触发价格 (STOP)。
tp_trigger_price (Price , optional) – The take-profit child order trigger price (STOP).
tp_trigger_price (Price,可选) - 止盈子订单触发价格 (STOP)。
tp_price (Price , optional) – The take-profit child order price (LIMIT).
tp_price (Price,可选) - 止盈子订单价格 (LIMIT)。
entry_order_type (OrderType {MARKET, LIMIT, LIMIT_IF_TOUCHED, MARKET_IF_TOUCHED}, default MARKET) – The entry order type.
entry_order_type (OrderType {MARKET, LIMIT, LIMIT_IF_TOUCHED, MARKET_IF_TOUCHED},默认 MARKET) - 入场订单类型。
tp_order_type (OrderType {LIMIT, LIMIT_IF_TOUCHED, MARKET_IF_TOUCHED}, default LIMIT) – The take-profit order type.
tp_order_type (OrderType {LIMIT, LIMIT_IF_TOUCHED, MARKET_IF_TOUCHED},默认 LIMIT) - 止盈订单类型。
time_in_force (TimeInForce, default GTC) – The entry orders time in force.
time_in_force (TimeInForce,默认 GTC) - 入场订单的有效时间。
sl_time_in_force (TimeInForce, default GTC) – The stop-loss orders time in force.
sl_time_in_force (TimeInForce,默认 GTC) - 止损订单的有效时间。
tp_time_in_force (TimeInForce, default GTC) – The take-profit orders time in force.
tp_time_in_force (TimeInForce,默认 GTC) - 止盈订单的有效时间。
expire_time (datetime , optional) – The order expiration (for GTD orders).
expire_time (datetime,可选) - 订单到期时间(对于 GTD 订单)。
entry_post_only (bool , default False) – If the entry order will only provide liquidity (make a market).
entry_post_only (bool,默认 False) - 入场订单是否只提供流动性(做市)。
tp_post_only (bool , default False) – If the take-profit order will only provide liquidity (make a market).
tp_post_only (bool,默认 False) - 止盈订单是否只提供流动性(做市)。
quote_quantity (bool) – If order quantity is denominated in the quote currency.
quote_quantity (bool) - 订单数量是否以报价货币计价。
emulation_trigger (TriggerType, default NO_TRIGGER) – The emulation trigger type for the entry, as well as the TP and SL bracket orders.
emulation_trigger (TriggerType,默认 NO_TRIGGER) - 入场以及止盈和止损括号订单的模拟触发类型。
trigger_instrument_id (InstrumentId , optional) – The emulation trigger instrument ID for the order (if None then will be the instrument_id).
trigger_instrument_id (InstrumentId,可选) - 订单的模拟触发Instrument ID(如果为 None,则将为 instrument_id)。
contingency_type (ContingencyType, default OUO) – The contingency type for the TP and SL bracket orders.
contingency_type (ContingencyType,默认 OUO) - 止盈和止损括号订单的意外事件类型。
entry_exec_algorithm_id (ExecAlgorithmId , optional) – The entry order execution algorithm ID.
entry_exec_algorithm_id (ExecAlgorithmId,可选) - 入场订单执行算法 ID。
sl_exec_algorithm_id (ExecAlgorithmId , optional) – The stop-loss order execution algorithm ID.
sl_exec_algorithm_id (ExecAlgorithmId,可选) - 止损订单执行算法 ID。
tp_exec_algorithm_id (ExecAlgorithmId , optional) – The take-profit order execution algorithm ID.
tp_exec_algorithm_id (ExecAlgorithmId,可选) - 止盈订单执行算法 ID。
entry_exec_algorithm_params (dict *[*str , Any ] , optional) – The execution algorithm parameters for the order.
entry_exec_algorithm_params (dict *[*str,Any],可选) - 订单的执行算法参数。
tp_exec_algorithm_params (dict *[*str , Any ] , optional) – The execution algorithm parameters for the order.
tp_exec_algorithm_params (dict *[*str,Any],可选) - 订单的执行算法参数。
sl_exec_algorithm_params (dict *[*str , Any ] , optional) – The execution algorithm parameters for the order.
sl_exec_algorithm_params (dict *[*str,Any],可选) - 订单的执行算法参数。
entry_tags (list *[*str ] , default [ "ENTRY" ]) – The custom user tags for the entry order.
entry_tags (list *[*str],默认 ["ENTRY"]) - 入场订单的自定义用户标签。
tp_tags (list *[*str ] , default [ "TAKE_PROFIT" ]) – The custom user tags for the take-profit order.
tp_tags (list *[*str],默认 ["TAKE_PROFIT"]) - 止盈订单的自定义用户标签。
sl_tags (list *[*str ] , default [ "STOP_LOSS" ]) – The custom user tags for the stop-loss order.
sl_tags (list *[*str],默认 ["STOP_LOSS"]) - 止损订单的自定义用户标签。
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.
entry_client_order_id (ClientOrderId,可选) - 订单的自定义客户端订单 ID。如果没有提供客户端订单 ID,则工厂将生成一个。
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.
tp_client_order_id (ClientOrderId,可选) - 订单的自定义客户端订单 ID。如果没有提供客户端订单 ID,则工厂将生成一个。
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.
sl_client_order_id (ClientOrderId,可选) - 订单的自定义客户端订单 ID。如果没有提供客户端订单 ID,则工厂将生成一个。
Return type: OrderList
"""
...
def create_list(self, orders: list) -> OrderList:
"""
Return a new order list containing the given orders.
返回包含给定订单的新订单列表。
Parameters: orders (list [Order ]) – The orders for the list.
参数:orders (list [Order ]) - 列表的订单。
Return type: OrderList
Raises: ValueError – If orders is empty.
引发:ValueError - 如果 orders 为空。
"""
...
def generate_client_order_id(self) -> ClientOrderId:
"""
Generate and return a new client order ID.
生成并返回一个新的客户端订单 ID。
The identifier will be the next in the logical sequence.
标识符将是逻辑序列中的下一个。
Return type: ClientOrderId
"""
...
def generate_order_list_id(self) -> OrderListId:
"""
Generate and return a new order list ID.
生成并返回一个新的订单列表 ID。
The identifier will be the next in the logical sequence.
标识符将是逻辑序列中的下一个。
Return type: OrderListId
"""
...
def limit(self, instrument_id: InstrumentId, order_side: OrderSide, quantity: Quantity, price: Price, time_in_force=TimeInForce.GTC, expire_time: datetime = None, post_only: bool = False, reduce_only: bool = False, quote_quantity: bool = False, display_qty: Quantity = None, emulation_trigger=TriggerType.NO_TRIGGER, trigger_instrument_id: InstrumentId = None, exec_algorithm_id: ExecAlgorithmId = None, exec_algorithm_params: dict = None, tags: list = None, client_order_id: ClientOrderId = None):
"""
Create a new LIMIT order.
创建一个新的限价订单。
Parameters:
参数:
instrument_id (InstrumentId) – The orders instrument ID.
instrument_id (InstrumentId) - 订单的Instrument ID。
order_side (OrderSide {BUY, SELL}) – The orders side.
order_side (OrderSide {BUY, SELL}) - 订单方向。
quantity (Quantity) – The orders quantity (> 0).
quantity (Quantity) - 订单数量 (> 0)。
price (Price) – The orders price.
price (Price) - 订单价格。
time_in_force (TimeInForce {GTC, IOC, FOK, GTD, DAY, AT_THE_OPEN, AT_THE_CLOSE}, default GTC) – The orders time in force.
time_in_force (TimeInForce {GTC, IOC, FOK, GTD, DAY, AT_THE_OPEN, AT_THE_CLOSE},默认 GTC) - 订单的有效时间。
expire_time (datetime , optional) – The order expiration (for GTD orders).
expire_time (datetime,可选) - 订单到期时间(对于 GTD 订单)。
post_only (bool , default False) – If the order will only provide liquidity (make a market).
post_only (bool,默认 False) - 订单是否只提供流动性(做市)。
reduce_only (bool , default False) – If the order carries the ‘reduce-only’ execution instruction.
reduce_only (bool,默认 False) - 订单是否带有“仅减仓”执行指令。
quote_quantity (bool) – If the order quantity is denominated in the quote currency.
quote_quantity (bool) - 订单数量是否以报价货币计价。
display_qty (Quantity , optional) – The quantity of the order to display on the public book (iceberg).
display_qty (Quantity,可选) - 要在公共订单簿上显示的订单数量(冰山订单)。
emulation_trigger (TriggerType, default NO_TRIGGER) – The orders emulation trigger.
emulation_trigger (TriggerType,默认 NO_TRIGGER) - 订单的模拟触发器。
trigger_instrument_id (InstrumentId , optional) – The emulation trigger instrument ID for the order (if None then will be the instrument_id).
trigger_instrument_id (InstrumentId,可选) - 订单的模拟触发Instrument ID(如果为 None,则将为 instrument_id)。
exec_algorithm_id (ExecAlgorithmId , optional) – The execution algorithm ID for the order.
exec_algorithm_id (ExecAlgorithmId,可选) - 订单的执行算法 ID。
exec_algorithm_params (dict *[*str , Any ] , optional) – The execution algorithm parameters for the order.
exec_algorithm_params (dict *[*str,Any],可选) - 订单的执行算法参数。
tags (list *[*str ] , optional) – The custom user tags for the order.
tags (list *[*str],可选) - 订单的自定义用户标签。
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.
client_order_id (ClientOrderId,可选) - 订单的自定义客户端订单 ID。如果没有提供客户端订单 ID,则工厂将生成一个。
Return type: LimitOrder
Raises:
引发:
ValueError – If quantity is not positive (> 0).
ValueError - 如果数量不是正数 (> 0)。
ValueError – If time_in_force is GTD and expire_time <= UNIX epoch.
ValueError - 如果 time_in_force 为 GTD 且 expire_time <= UNIX epoch。
ValueError – If display_qty is negative (< 0) or greater than quantity.
ValueError - 如果 display_qty 为负数 (< 0) 或大于数量。
"""
...
def limit_if_touched(self, instrument_id: InstrumentId, order_side: OrderSide, quantity: Quantity, price: Price, trigger_price: Price, trigger_type=TriggerType.DEFAULT, time_in_force=TimeInForce.GTC, expire_time: datetime = None, post_only: bool = False, reduce_only: bool = False, quote_quantity: bool = False, display_qty: Quantity = None, emulation_trigger=TriggerType.NO_TRIGGER, trigger_instrument_id: InstrumentId = None, exec_algorithm_id: ExecAlgorithmId = None, exec_algorithm_params: dict = None, tags: list = None, client_order_id: ClientOrderId = None):
"""
Create a new LIMIT_IF_TOUCHED (LIT) conditional order.
创建一个新的限价触及订单 (LIT)。
Parameters:
参数:
instrument_id (InstrumentId) – The orders instrument ID.
instrument_id (InstrumentId) - 订单的Instrument ID。
order_side (OrderSide {BUY, SELL}) – The orders side.
order_side (OrderSide {BUY, SELL}) - 订单方向。
quantity (Quantity) – The orders quantity (> 0).
quantity (Quantity) - 订单数量 (> 0)。
price (Price) – The orders limit price.
price (Price) - 订单限价。
trigger_price (Price) – The orders trigger stop price.
trigger_price (Price) - 订单触发止损价格。
trigger_type (TriggerType, default DEFAULT) – The order trigger type.
trigger_type (TriggerType,默认 DEFAULT) - 订单触发类型。
time_in_force (TimeInForce {GTC, IOC, FOK, GTD, DAY}, default GTC) – The orders time in force.
time_in_force (TimeInForce {GTC, IOC, FOK, GTD, DAY},默认 GTC) - 订单的有效时间。
expire_time (datetime , optional) – The order expiration (for GTD orders).
expire_time (datetime,可选) - 订单到期时间(对于 GTD 订单)。
post_only (bool , default False) – If the order will only provide liquidity (make a market).
post_only (bool,默认 False) - 订单是否只提供流动性(做市)。
reduce_only (bool , default False) – If the order carries the ‘reduce-only’ execution instruction.
reduce_only (bool,默认 False) - 订单是否带有“仅减仓”执行指令。
quote_quantity (bool) – If the order quantity is denominated in the quote currency.
quote_quantity (bool) - 订单数量是否以报价货币计价。
display_qty (Quantity , optional) – The quantity of the order to display on the public book (iceberg).
display_qty (Quantity,可选) - 要在公共订单簿上显示的订单数量(冰山订单)。
emulation_trigger (TriggerType, default NO_TRIGGER) – The orders emulation trigger.
emulation_trigger (TriggerType,默认 NO_TRIGGER) - 订单的模拟触发器。
trigger_instrument_id (InstrumentId , optional) – The emulation trigger instrument ID for the order (if None then will be the instrument_id).
trigger_instrument_id (InstrumentId,可选) - 订单的模拟触发Instrument ID(如果为 None,则将为 instrument_id)。
exec_algorithm_id (ExecAlgorithmId , optional) – The execution algorithm ID for the order.
exec_algorithm_id (ExecAlgorithmId,可选) - 订单的执行算法 ID。
exec_algorithm_params (dict *[*str , Any ] , optional) – The execution algorithm parameters for the order.
exec_algorithm_params (dict *[*str,Any],可选) - 订单的执行算法参数。
tags (list *[*str ] , optional) – The custom user tags for the order.
tags (list *[*str],可选) - 订单的自定义用户标签。
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.
client_order_id (ClientOrderId,可选) - 订单的自定义客户端订单 ID。如果没有提供客户端订单 ID,则工厂将生成一个。
Return type: LimitIfTouchedOrder
Raises:
引发:
ValueError – If quantity is not positive (> 0).
ValueError - 如果数量不是正数 (> 0)。
ValueError – If trigger_type is NO_TRIGGER.
ValueError - 如果 trigger_type 为 NO_TRIGGER。
ValueError – If time_in_force is AT_THE_OPEN or AT_THE_CLOSE.
ValueError - 如果 time_in_force 为 AT_THE_OPEN 或 AT_THE_CLOSE。
ValueError – If time_in_force is GTD and expire_time <= UNIX epoch.
ValueError - 如果 time_in_force 为 GTD 且 expire_time <= UNIX epoch。
ValueError – If display_qty is negative (< 0) or greater than quantity.
ValueError - 如果 display_qty 为负数 (< 0) 或大于数量。
"""
...
def market(self, instrument_id: InstrumentId, order_side: OrderSide, quantity: Quantity, time_in_force=TimeInForce.GTC, reduce_only: bool = False, quote_quantity: bool = False, exec_algorithm_id: ExecAlgorithmId = None, exec_algorithm_params: dict = None, tags: list = None, client_order_id: ClientOrderId = None):
"""
Create a new MARKET order.
创建一个新的市价订单。
Parameters:
参数:
instrument_id (InstrumentId) – The orders instrument ID.
instrument_id (InstrumentId) - 订单的Instrument ID。
order_side (OrderSide {BUY, SELL}) – The orders side.
order_side (OrderSide {BUY, SELL}) - 订单方向。
quantity (Quantity) – The orders quantity (> 0).
quantity (Quantity) - 订单数量 (> 0)。
time_in_force (TimeInForce {GTC, IOC, FOK, DAY, AT_THE_OPEN, AT_THE_CLOSE}, default GTC) – The orders time in force. Often not applicable for market orders.
time_in_force (TimeInForce {GTC, IOC, FOK, DAY, AT_THE_OPEN, AT_THE_CLOSE},默认 GTC) - 订单的有效时间。通常不适用于市价订单。
reduce_only (bool , default False) – If the order carries the ‘reduce-only’ execution instruction.
reduce_only (bool,默认 False) - 订单是否带有“仅减仓”执行指令。
quote_quantity (bool) – If the order quantity is denominated in the quote currency.
quote_quantity (bool) - 订单数量是否以报价货币计价。
exec_algorithm_id (ExecAlgorithmId , optional) – The execution algorithm ID for the order.
exec_algorithm_id (ExecAlgorithmId,可选) - 订单的执行算法 ID。
exec_algorithm_params (dict *[*str , Any ] , optional) – The execution algorithm parameters for the order.
exec_algorithm_params (dict *[*str,Any],可选) - 订单的执行算法参数。
tags (list *[*str ] , optional) – The custom user tags for the order.
tags (list *[*str],可选) - 订单的自定义用户标签。
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.
client_order_id (ClientOrderId,可选) - 订单的自定义客户端订单 ID。如果没有提供客户端订单 ID,则工厂将生成一个。
Return type: MarketOrder
Raises:
引发:
ValueError – If quantity is not positive (> 0).
ValueError - 如果数量不是正数 (> 0)。
ValueError – If time_in_force is GTD.
ValueError - 如果 time_in_force 为 GTD。
"""
...
def market_if_touched(self, instrument_id: InstrumentId, order_side: OrderSide, quantity: Quantity, trigger_price: Price, trigger_type=TriggerType.DEFAULT, time_in_force=TimeInForce.GTC, expire_time: datetime = None, reduce_only: bool = False, quote_quantity: bool = False, emulation_trigger=TriggerType.NO_TRIGGER, trigger_instrument_id: InstrumentId = None, exec_algorithm_id: ExecAlgorithmId = None, exec_algorithm_params: dict = None, tags: list = None, client_order_id: ClientOrderId = None):
"""
Create a new MARKET_IF_TOUCHED (MIT) conditional order.
创建一个新的市价触及订单 (MIT)。
Parameters:
参数:
instrument_id (InstrumentId) – The orders instrument ID.
instrument_id (InstrumentId) - 订单的Instrument ID。
order_side (OrderSide {BUY, SELL}) – The orders side.
order_side (OrderSide {BUY, SELL}) - 订单方向。
quantity (Quantity) – The orders quantity (> 0).
quantity (Quantity) - 订单数量 (> 0)。
trigger_price (Price) – The orders trigger price (STOP).
trigger_price (Price) - 订单触发价格 (STOP)。
trigger_type (TriggerType, default DEFAULT) – The order trigger type.
trigger_type (TriggerType,默认 DEFAULT) - 订单触发类型。
time_in_force (TimeInForce {GTC, IOC, FOK, GTD, DAY}, default GTC) – The orders time in force.
time_in_force (TimeInForce {GTC, IOC, FOK, GTD, DAY},默认 GTC) - 订单的有效时间。
expire_time (datetime , optional) – The order expiration (for GTD orders).
expire_time (datetime,可选) - 订单到期时间(对于 GTD 订单)。
reduce_only (bool , default False) – If the order carries the ‘reduce-only’ execution instruction.
reduce_only (bool,默认 False) - 订单是否带有“仅减仓”执行指令。
quote_quantity (bool) – If the order quantity is denominated in the quote currency.
quote_quantity (bool) - 订单数量是否以报价货币计价。
emulation_trigger (TriggerType, default NO_TRIGGER) – The orders emulation trigger.
emulation_trigger (TriggerType,默认 NO_TRIGGER) - 订单的模拟触发器。
trigger_instrument_id (InstrumentId , optional) – The emulation trigger instrument ID for the order (if None then will be the instrument_id).
trigger_instrument_id (InstrumentId,可选) - 订单的模拟触发Instrument ID(如果为 None,则将为 instrument_id)。
exec_algorithm_id (ExecAlgorithmId , optional) – The execution algorithm ID for the order.
exec_algorithm_id (ExecAlgorithmId,可选) - 订单的执行算法 ID。
exec_algorithm_params (dict *[*str , Any ] , optional) – The execution algorithm parameters for the order.
exec_algorithm_params (dict *[*str,Any],可选) - 订单的执行算法参数。
tags (list *[*str ] , optional) – The custom user tags for the order.
tags (list *[*str],可选) - 订单的自定义用户标签。
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.
client_order_id (ClientOrderId,可选) - 订单的自定义客户端订单 ID。如果没有提供客户端订单 ID,则工厂将生成一个。
Return type: MarketIfTouchedOrder
Raises:
引发:
ValueError – If quantity is not positive (> 0).
ValueError - 如果数量不是正数 (> 0)。
ValueError – If trigger_type is NO_TRIGGER.
ValueError - 如果 trigger_type 为 NO_TRIGGER。
ValueError – If time_in_force is AT_THE_OPEN or AT_THE_CLOSE.
ValueError - 如果 time_in_force 为 AT_THE_OPEN 或 AT_THE_CLOSE。
ValueError – If time_in_force is GTD and expire_time <= UNIX epoch.
ValueError - 如果 time_in_force 为 GTD 且 expire_time <= UNIX epoch。
"""
...
def market_to_limit(self, instrument_id: InstrumentId, order_side: OrderSide, quantity: Quantity, time_in_force=TimeInForce.GTC, expire_time: datetime = None, reduce_only: bool = False, quote_quantity: bool = False, display_qty: Quantity = None, exec_algorithm_id: ExecAlgorithmId = None, exec_algorithm_params: dict = None, tags: list = None, client_order_id: ClientOrderId = None):
"""
Create a new MARKET order.
创建一个新的市价订单。
Parameters:
参数:
instrument_id (InstrumentId) – The orders instrument ID.
instrument_id (InstrumentId) - 订单的Instrument ID。
order_side (OrderSide {BUY, SELL}) – The orders side.
order_side (OrderSide {BUY, SELL}) - 订单方向。
quantity (Quantity) – The orders quantity (> 0).
```python
quantity (Quantity) - 订单数量 (> 0)。
time_in_force (TimeInForce {GTC, GTD, IOC, FOK}, default GTC) – The orders time in force.
time_in_force (TimeInForce {GTC, GTD, IOC, FOK},默认 GTC) - 订单的有效时间。
expire_time (datetime , optional) – The order expiration (for GTD orders).
expire_time (datetime,可选) - 订单到期时间(对于 GTD 订单)。
reduce_only (bool , default False) – If the order carries the ‘reduce-only’ execution instruction.
reduce_only (bool,默认 False) - 订单是否带有“仅减仓”执行指令。
quote_quantity (bool) – If the order quantity is denominated in the quote currency.
quote_quantity (bool) - 订单数量是否以报价货币计价。
display_qty (Quantity , optional) – The quantity of the limit order to display on the public book (iceberg).
display_qty (Quantity,可选) - 要在公共订单簿上显示的限价订单数量(冰山订单)。
exec_algorithm_id (ExecAlgorithmId , optional) – The execution algorithm ID for the order.
exec_algorithm_id (ExecAlgorithmId,可选) - 订单的执行算法 ID。
exec_algorithm_params (dict *[*str , Any ] , optional) – The execution algorithm parameters for the order.
exec_algorithm_params (dict *[*str,Any],可选) - 订单的执行算法参数。
tags (list *[*str ] , optional) – The custom user tags for the order.
tags (list *[*str],可选) - 订单的自定义用户标签。
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.
client_order_id (ClientOrderId,可选) - 订单的自定义客户端订单 ID。如果没有提供客户端订单 ID,则工厂将生成一个。
Return type: MarketToLimitOrder
Raises:
引发:
ValueError – If quantity is not positive (> 0).
ValueError - 如果数量不是正数 (> 0)。
ValueError – If time_in_force is AT_THE_OPEN or AT_THE_CLOSE.
ValueError - 如果 time_in_force 为 AT_THE_OPEN 或 AT_THE_CLOSE。
"""
...
def reset(self) -> void:
"""
Reset the order factory.
重置订单工厂。
All stateful fields are reset to their initial value.
所有有状态字段都重置为其初始值。
"""
...
def set_client_order_id_count(self, count: int) -> void:
"""
Set the internal order ID generator count to the given count.
将内部订单 ID 生成器计数设置为给定计数。
Parameters: count (int) – The count to set.
参数:count (int) - 要设置的计数。
Warning:
System method (not intended to be called by user code).
系统方法(不打算由用户代码调用)。
"""
...
def set_order_list_id_count(self, count: int) -> void:
"""
Set the internal order list ID generator count to the given count.
将内部订单列表 ID 生成器计数设置为给定计数。
Parameters: count (int) – The count to set.
参数:count (int) - 要设置的计数。
Warning:
System method (not intended to be called by user code).
系统方法(不打算由用户代码调用)。
"""
...
def stop_limit(self, instrument_id: InstrumentId, order_side: OrderSide, quantity: Quantity, price: Price, trigger_price: Price, trigger_type=TriggerType.DEFAULT, time_in_force=TimeInForce.GTC, expire_time: datetime = None, post_only: bool = False, reduce_only: bool = False, quote_quantity: bool = False, display_qty: Quantity = None, emulation_trigger=TriggerType.NO_TRIGGER, trigger_instrument_id: InstrumentId = None, exec_algorithm_id: ExecAlgorithmId = None, exec_algorithm_params: dict = None, tags: list = None, client_order_id: ClientOrderId = None):
"""
Create a new STOP_LIMIT conditional order.
创建一个新的止损限价订单。
Parameters:
参数:
instrument_id (InstrumentId) – The orders instrument ID.
instrument_id (InstrumentId) - 订单的Instrument ID。
order_side (OrderSide {BUY, SELL}) – The orders side.
order_side (OrderSide {BUY, SELL}) - 订单方向。
quantity (Quantity) – The orders quantity (> 0).
quantity (Quantity) - 订单数量 (> 0)。
price (Price) – The orders limit price.
price (Price) - 订单限价。
trigger_price (Price) – The orders trigger stop price.
trigger_price (Price) - 订单触发止损价格。
trigger_type (TriggerType, default DEFAULT) – The order trigger type.
trigger_type (TriggerType,默认 DEFAULT) - 订单触发类型。
time_in_force (TimeInForce {GTC, IOC, FOK, GTD, DAY}, default GTC) – The orders time in force.
time_in_force (TimeInForce {GTC, IOC, FOK, GTD, DAY},默认 GTC) - 订单的有效时间。
expire_time (datetime , optional) – The order expiration (for GTD orders).
expire_time (datetime,可选) - 订单到期时间(对于 GTD 订单)。
post_only (bool , default False) – If the order will only provide liquidity (make a market).
post_only (bool,默认 False) - 订单是否只提供流动性(做市)。
reduce_only (bool , default False) – If the order carries the ‘reduce-only’ execution instruction.
reduce_only (bool,默认 False) - 订单是否带有“仅减仓”执行指令。
quote_quantity (bool) – If the order quantity is denominated in the quote currency.
quote_quantity (bool) - 订单数量是否以报价货币计价。
display_qty (Quantity , optional) – The quantity of the order to display on the public book (iceberg).
display_qty (Quantity,可选) - 要在公共订单簿上显示的订单数量(冰山订单)。
emulation_trigger (TriggerType, default NO_TRIGGER) – The orders emulation trigger.
emulation_trigger (TriggerType,默认 NO_TRIGGER) - 订单的模拟触发器。
trigger_instrument_id (InstrumentId , optional) – The emulation trigger instrument ID for the order (if None then will be the instrument_id).
trigger_instrument_id (InstrumentId,可选) - 订单的模拟触发Instrument ID(如果为 None,则将为 instrument_id)。
exec_algorithm_id (ExecAlgorithmId , optional) – The execution algorithm ID for the order.
exec_algorithm_id (ExecAlgorithmId,可选) - 订单的执行算法 ID。
exec_algorithm_params (dict *[*str , Any ] , optional) – The execution algorithm parameters for the order.
exec_algorithm_params (dict *[*str,Any],可选) - 订单的执行算法参数。
tags (list *[*str ] , optional) – The custom user tags for the order.
tags (list *[*str],可选) - 订单的自定义用户标签。
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.
client_order_id (ClientOrderId,可选) - 订单的自定义客户端订单 ID。如果没有提供客户端订单 ID,则工厂将生成一个。
Return type: StopLimitOrder
Raises:
引发:
ValueError – If quantity is not positive (> 0).
ValueError - 如果数量不是正数 (> 0)。
ValueError – If trigger_type is NO_TRIGGER.
ValueError - 如果 trigger_type 为 NO_TRIGGER。
ValueError – If time_in_force is AT_THE_OPEN or AT_THE_CLOSE.
ValueError - 如果 time_in_force 为 AT_THE_OPEN 或 AT_THE_CLOSE。
ValueError – If time_in_force is GTD and expire_time <= UNIX epoch.
ValueError - 如果 time_in_force 为 GTD 且 expire_time <= UNIX epoch。
ValueError – If display_qty is negative (< 0) or greater than quantity.
ValueError - 如果 display_qty 为负数 (< 0) 或大于数量。
"""
...
def stop_market(self, instrument_id: InstrumentId, order_side: OrderSide, quantity: Quantity, trigger_price: Price, trigger_type=TriggerType.DEFAULT, time_in_force=TimeInForce.GTC, expire_time: datetime = None, reduce_only: bool = False, quote_quantity: bool = False, emulation_trigger=TriggerType.NO_TRIGGER, trigger_instrument_id: InstrumentId = None, exec_algorithm_id: ExecAlgorithmId = None, exec_algorithm_params: dict = None, tags: list = None, client_order_id: ClientOrderId = None):
"""
Create a new STOP_MARKET conditional order.
创建一个新的止损市价订单。
Parameters:
参数:
instrument_id (InstrumentId) – The orders instrument ID.
instrument_id (InstrumentId) - 订单的Instrument ID。
order_side (OrderSide {BUY, SELL}) – The orders side.
order_side (OrderSide {BUY, SELL}) - 订单方向。
quantity (Quantity) – The orders quantity (> 0).
quantity (Quantity) - 订单数量 (> 0)。
trigger_price (Price) – The orders trigger price (STOP).
trigger_price (Price) - 订单触发价格 (STOP)。
trigger_type (TriggerType, default DEFAULT) – The order trigger type.
trigger_type (TriggerType,默认 DEFAULT) - 订单触发类型。
time_in_force (TimeInForce {GTC, IOC, FOK, GTD, DAY}, default GTC) – The orders time in force.
time_in_force (TimeInForce {GTC, IOC, FOK, GTD, DAY},默认 GTC) - 订单的有效时间。
expire_time (datetime , optional) – The order expiration (for GTD orders).
expire_time (datetime,可选) - 订单到期时间(对于 GTD 订单)。
reduce_only (bool , default False) – If the order carries the ‘reduce-only’ execution instruction.
reduce_only (bool,默认 False) - 订单是否带有“仅减仓”执行指令。
quote_quantity (bool) – If the order quantity is denominated in the quote currency.
quote_quantity (bool) - 订单数量是否以报价货币计价。
emulation_trigger (TriggerType, default NO_TRIGGER) – The orders emulation trigger.
emulation_trigger (TriggerType,默认 NO_TRIGGER) - 订单的模拟触发器。
trigger_instrument_id (InstrumentId , optional) – The emulation trigger instrument ID for the order (if None then will be the instrument_id).
trigger_instrument_id (InstrumentId,可选) - 订单的模拟触发Instrument ID(如果为 None,则将为 instrument_id)。
exec_algorithm_id (ExecAlgorithmId , optional) – The execution algorithm ID for the order.
exec_algorithm_id (ExecAlgorithmId,可选) - 订单的执行算法 ID。
exec_algorithm_params (dict *[*str , Any ] , optional) – The execution algorithm parameters for the order.
exec_algorithm_params (dict *[*str,Any],可选) - 订单的执行算法参数。
tags (list *[*str ] , optional) – The custom user tags for the order.
tags (list *[*str],可选) - 订单的自定义用户标签。
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.
client_order_id (ClientOrderId,可选) - 订单的自定义客户端订单 ID。如果没有提供客户端订单 ID,则工厂将生成一个。
Return type: StopMarketOrder
Raises:
引发:
ValueError – If quantity is not positive (> 0).
ValueError - 如果数量不是正数 (> 0)。
ValueError – If trigger_type is NO_TRIGGER.
ValueError - 如果 trigger_type 为 NO_TRIGGER。
ValueError – If time_in_force is AT_THE_OPEN or AT_THE_CLOSE.
ValueError - 如果 time_in_force 为 AT_THE_OPEN 或 AT_THE_CLOSE。
ValueError – If time_in_force is GTD and expire_time <= UNIX epoch.
ValueError - 如果 time_in_force 为 GTD 且 expire_time <= UNIX epoch。
"""
...
def trailing_stop_limit(self, instrument_id: InstrumentId, order_side: OrderSide, quantity: Quantity, limit_offset: Decimal, trailing_offset: Decimal, price: Price = None, trigger_price: Price = None, trigger_type=TriggerType.DEFAULT, trailing_offset_type=TrailingOffsetType.PRICE, time_in_force=TimeInForce.GTC, expire_time: datetime = None, post_only: bool = False, reduce_only: bool = False, quote_quantity: bool = False, display_qty: Quantity = None, emulation_trigger=TriggerType.NO_TRIGGER, trigger_instrument_id: InstrumentId = None, exec_algorithm_id: ExecAlgorithmId = None, exec_algorithm_params: dict = None, tags: list = None, client_order_id: ClientOrderId = None):
"""
Create a new TRAILING_STOP_LIMIT conditional order.
创建一个新的追踪止损限价订单。
Parameters:
参数:
instrument_id (InstrumentId) – The orders instrument ID.
instrument_id (InstrumentId) - 订单的Instrument ID。
order_side (OrderSide {BUY, SELL}) – The orders side.
order_side (OrderSide {BUY, SELL}) - 订单方向。
quantity (Quantity) – The orders quantity (> 0).
quantity (Quantity) - 订单数量 (> 0)。
trailing_offset (Decimal) – The trailing offset for the trigger price (STOP).
trailing_offset (Decimal) - 触发价格 (STOP) 的追踪偏移量。
limit_offset (Decimal) – The trailing offset for the order price (LIMIT).
limit_offset (Decimal) - 订单价格 (LIMIT) 的追踪偏移量。
price (Price , optional) – The order price (LIMIT). If None then will typically default to the delta of market price and limit_offset.
price (Price,可选) - 订单价格 (LIMIT)。如果为 None,则通常默认为市场价格和 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_price (Price,可选) - 订单触发价格 (STOP)。如果为 None,则通常默认为市场价格和 trailing_offset 的差值。
trigger_type (TriggerType, default DEFAULT) – The order trigger type.
trigger_type (TriggerType,默认 DEFAULT) - 订单触发类型。
trailing_offset_type (TrailingOffsetType, default PRICE) – The order trailing offset type.
trailing_offset_type (TrailingOffsetType,默认 PRICE) - 订单追踪偏移量类型。
time_in_force (TimeInForce {GTC, IOC, FOK, GTD, DAY}, default GTC) – The orders time in force.
time_in_force (TimeInForce {GTC, IOC, FOK, GTD, DAY},默认 GTC) - 订单的有效时间。
expire_time (datetime , optional) – The order expiration (for GTD orders).
expire_time (datetime,可选) - 订单到期时间(对于 GTD 订单)。
post_only (bool , default False) – If the order will only provide liquidity (make a market).
post_only (bool,默认 False) - 订单是否只提供流动性(做市)。
reduce_only (bool , default False) – If the order carries the ‘reduce-only’ execution instruction.
reduce_only (bool,默认 False) - 订单是否带有“仅减仓”执行指令。
quote_quantity (bool) – If the order quantity is denominated in the quote currency.
quote_quantity (bool) - 订单数量是否以报价货币计价。
display_qty (Quantity , optional) – The quantity of the order to display on the public book (iceberg).
display_qty (Quantity,可选) - 要在公共订单簿上显示的订单数量(冰山订单)。
emulation_trigger (TriggerType, default NO_TRIGGER) – The orders emulation trigger.
emulation_trigger (TriggerType,默认 NO_TRIGGER) - 订单的模拟触发器。
trigger_instrument_id (InstrumentId , optional) – The emulation trigger instrument ID for the order (if None then will be the instrument_id).
trigger_instrument_id (InstrumentId,可选) - 订单的模拟触发Instrument ID(如果为 None,则将为 instrument_id)。
exec_algorithm_id (ExecAlgorithmId , optional) – The execution algorithm ID for the order.
exec_algorithm_id (ExecAlgorithmId,可选) - 订单的执行算法 ID。
exec_algorithm_params (dict *[*str , Any ] , optional) – The execution algorithm parameters for the order.
exec_algorithm_params (dict *[*str,Any],可选) - 订单的执行算法参数。
tags (list *[*str ] , optional) – The custom user tags for the order.
tags (list *[*str],可选) - 订单的自定义用户标签。
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.
client_order_id (ClientOrderId,可选) - 订单的自定义客户端订单 ID。如果没有提供客户端订单 ID,则工厂将生成一个。
Return type: TrailingStopLimitOrder
Raises:
引发:
ValueError – If quantity is not positive (> 0).
ValueError - 如果数量不是正数 (> 0)。
ValueError – If trigger_type is NO_TRIGGER.
ValueError - 如果 trigger_type 为 NO_TRIGGER。
ValueError – If trailing_offset_type is NO_TRAILING_OFFSET.
ValueError - 如果 trailing_offset_type 为 NO_TRAILING_OFFSET。
ValueError – If time_in_force is AT_THE_OPEN or AT_THE_CLOSE.
ValueError - 如果 time_in_force 为 AT_THE_OPEN 或 AT_THE_CLOSE。
ValueError – If time_in_force is GTD and expire_time <= UNIX epoch.
ValueError - 如果 time_in_force 为 GTD 且 expire_time <= UNIX epoch。
ValueError – If display_qty is negative (< 0) or greater than quantity.
ValueError - 如果 display_qty 为负数 (< 0) 或大于数量。
"""
...
def trailing_stop_market(self, instrument_id: InstrumentId, order_side: OrderSide, quantity: Quantity, trailing_offset: Decimal, trigger_price: Price = None, trigger_type=TriggerType.DEFAULT, trailing_offset_type=TrailingOffsetType.PRICE, time_in_force=TimeInForce.GTC, expire_time: datetime = None, reduce_only: bool = False, quote_quantity: bool = False, emulation_trigger=TriggerType.NO_TRIGGER, trigger_instrument_id: InstrumentId = None, exec_algorithm_id: ExecAlgorithmId = None, exec_algorithm_params: dict = None, tags: list = None, client_order_id: ClientOrderId = None):
"""
Create a new TRAILING_STOP_MARKET conditional order.
创建一个新的追踪止损市价订单。
Parameters:
参数:
instrument_id (InstrumentId) – The orders instrument ID.
instrument_id (InstrumentId) - 订单的Instrument ID。
order_side (OrderSide {BUY, SELL}) – The orders side.
order_side (OrderSide {BUY, SELL}) - 订单方向。
quantity (Quantity) – The orders quantity (> 0).
quantity (Quantity) - 订单数量 (> 0)。
trailing_offset (Decimal) – The trailing offset for the trigger price (STOP).
trailing_offset (Decimal) - 触发价格 (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_price (Price,可选) - 订单触发价格 (STOP)。如果为 None,则通常默认为市场价格和 trailing_offset 的差值。
trigger_type (TriggerType, default DEFAULT) – The order trigger type.
trigger_type (TriggerType,默认 DEFAULT) - 订单触发类型。
trailing_offset_type (TrailingOffsetType, default PRICE) – The order trailing offset type.
trailing_offset_type (TrailingOffsetType,默认 PRICE) - 订单追踪偏移量类型。
time_in_force (TimeInForce {GTC, IOC, FOK, GTD, DAY}, default GTC) – The orders time in force.
time_in_force (TimeInForce {GTC, IOC, FOK, GTD, DAY},默认 GTC) - 订单的有效时间。
expire_time (datetime , optional) – The order expiration (for GTD orders).
expire_time (datetime,可选) - 订单到期时间(对于 GTD 订单)。
reduce_only (bool , default False) – If the order carries the ‘reduce-only’ execution instruction.
reduce_only (bool,默认 False) - 订单是否带有“仅减仓”执行指令。
quote_quantity (bool) – If the order quantity is denominated in the quote currency.
quote_quantity (bool) - 订单数量是否以报价货币计价。
emulation_trigger (TriggerType, default NO_TRIGGER) – The orders emulation trigger.
emulation_trigger (TriggerType,默认 NO_TRIGGER) - 订单的模拟触发器。
exec_algorithm_id (ExecAlgorithmId , optional) – The execution algorithm ID for the order.
exec_algorithm_id (ExecAlgorithmId,可选) - 订单的执行算法 ID。
exec_algorithm_params (dict *[*str , Any ] , optional) – The execution algorithm parameters for the order.
exec_algorithm_params (dict *[*str,Any],可选) - 订单的执行算法参数。
tags (list *[*str ] , optional) – The custom user tags for the order.
tags (list *[*str],可选) - 订单的自定义用户标签。
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.
client_order_id (ClientOrderId,可选) - 订单的自定义客户端订单 ID。如果没有提供客户端订单 ID,则工厂将生成一个。
Return type: TrailingStopMarketOrder
Raises:
引发:
ValueError – If quantity is not positive (> 0).
ValueError - 如果数量不是正数 (> 0)。
ValueError – If trigger_type is NO_TRIGGER.
ValueError - 如果 trigger_type 为 NO_TRIGGER。
ValueError – If trailing_offset_type is NO_TRAILING_OFFSET.
ValueError - 如果 trailing_offset_type 为 NO_TRAILING_OFFSET。
ValueError – If time_in_force is AT_THE_OPEN or AT_THE_CLOSE.
ValueError - 如果 time_in_force 为 AT_THE_OPEN 或 AT_THE_CLOSE。
ValueError – If time_in_force is GTD and expire_time <= UNIX epoch.
ValueError - 如果 time_in_force 为 GTD 且 expire_time <= UNIX epoch。
"""
...
Bases: object
class Clock(object):
"""
The base class for all clocks.
所有时钟的基类。
Warning:
This class should not be used directly, but through a concrete subclass.
此类不应直接使用,而应通过具体的子类使用。
"""
def __init__(self):
...
@property
def timer_count(self) -> int:
"""
int
Return the count of active timers running in the clock.
返回时钟中运行的活动计时器数量。
Return type: int
Type: Clock.timer_count
"""
...
@property
def timer_names(self) -> list[str]:
"""
list[str]
Return the names of active timers running in the clock.
返回时钟中运行的活动计时器的名称。
Return type: list[str]
Type: Clock.timer_names
"""
...
def cancel_timer(self, name: str) -> void:
"""
Cancel the timer corresponding to the given label.
取消与给定标签对应的计时器。
Parameters: name (str) – The name for the timer to cancel.
参数:name (str) - 要取消的计时器的名称。
Raises:
引发:
ValueError – If name is not a valid string.
ValueError - 如果 name 不是有效的字符串。
KeyError – If name is not an active timer name for this clock.
KeyError - 如果 name 不是此时钟的活动计时器名称。
"""
...
def cancel_timers(self) -> void:
"""
Cancel all timers.
取消所有计时器。
"""
...
def local_now(self, 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).
参数:tz (tzinfo,可选) - 本地时区(如果为 None,则假定目标时区为系统本地时区)。
Returns: tz-aware in local timezone.
返回值:本地时区中的 tz 感知时间。
Return type: datetime
"""
...
def next_time_ns(self, name: str) -> int:
"""
Find a particular timer.
查找特定的计时器。
Parameters: name (str) – The name of the timer.
参数:name (str) - 计时器的名称。
Return type: uint64_t
Raises: ValueError – If name is not a valid string.
引发:ValueError - 如果 name 不是有效的字符串。
"""
...
def register_default_handler(self, handler) -> void:
"""
Register the given handler as the clocks default handler.
将给定的处理程序注册为时钟的默认处理程序。
Parameters: handler (Callable [ [TimeEvent ] , None ]) – The handler to register.
参数:handler (Callable [ [TimeEvent ],None ]) - 要注册的处理程序。
Raises: TypeError – If handler is not of type Callable.
引发:TypeError - 如果 handler 的类型不是 Callable。
"""
...
def set_time_alert(self, name: str, alert_time: datetime, callback=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 handler is passed then the default handler (if registered) will receive the TimeEvent.
当达到时间时,处理程序将被传递包含计时器唯一名称的 TimeEvent。如果没有传递处理程序,则默认处理程序(如果已注册)将接收 TimeEvent。
Parameters:
参数:
name (str) – The name for the alert (must be unique for this clock).
name (str) - 警报的名称(必须对此时钟唯一)。
alert_time (datetime) – The time for the alert.
alert_time (datetime) - 警报的时间。
callback (Callable [ [TimeEvent ] , None ] , optional) – The callback to receive time events.
callback (Callable [ [TimeEvent ],None ],可选) - 接收时间事件的回调函数。
Raises:
引发:
ValueError – If name is not a valid string.
ValueError - 如果 name 不是有效的字符串。
KeyError – If name is not unique for this clock.
KeyError - 如果 name 对此时钟不唯一。
TypeError – If handler is not of type Callable or None.
TypeError - 如果 handler 的类型不是 Callable 或 None。
ValueError – If handler is None and no default handler is registered.
ValueError - 如果 handler 为 None 并且没有注册默认处理程序。
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).
如果 alert_time 在过去或当前时间,则将立即生成时间事件(而不是无效并导致条件检查失败)。
"""
...
def set_time_alert_ns(self, name: str, alert_time_ns: int, callback=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.
当达到时间时,处理程序将被传递包含计时器唯一名称的 TimeEvent。如果没有传递回调函数,则默认处理程序(如果已注册)将接收 TimeEvent。
Parameters:
参数:
name (str) – The name for the alert (must be unique for this clock).
name (str) - 警报的名称(必须对此时钟唯一)。
alert_time_ns (uint64_t) – The UNIX time (nanoseconds) for the alert.
alert_time_ns (uint64_t) - 警报的 UNIX 时间(纳秒)。
callback (Callable [ [TimeEvent ] , None ] , optional) – The callback to receive time events.
callback (Callable [ [TimeEvent ],None ],可选) - 接收时间事件的回调函数。
Raises:
引发:
ValueError – If name is not a valid string.
ValueError - 如果 name 不是有效的字符串。
ValueError – If name is not unique for this clock.
ValueError - 如果 name 对此时钟不唯一。
TypeError – If callback is not of type Callable or None.
TypeError - 如果 callback 的类型不是 Callable 或 None。
ValueError – If callback is None and no default handler is registered.
ValueError - 如果 callback 为 None 并且没有注册默认处理程序。
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).
如果 alert_time_ns 在过去或当前时间,则将立即生成时间事件(而不是无效并导致条件检查失败)。
"""
...
def set_timer(self, name: str, interval: timedelta, start_time: datetime=None, stop_time: datetime=None, callback=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.
计时器将从开始时间运行(可选地运行到停止时间)。当达到间隔时,处理程序将被传递包含计时器唯一名称的 TimeEvent。如果没有传递处理程序,则默认处理程序(如果已注册)将接收 TimeEvent。
Parameters:
参数:
name (str) – The name for the timer (must be unique for this clock).
name (str) - 计时器的名称(必须对此时钟唯一)。
interval (timedelta) – The time interval for the timer.
interval (timedelta) - 计时器的时间间隔。
start_time (datetime , optional) – The start time for the timer (if None then starts immediately).
start_time (datetime,可选) - 计时器的开始时间(如果为 None,则立即开始)。
stop_time (datetime , optional) – The stop time for the timer (if None then repeats indefinitely).
stop_time (datetime,可选) - 计时器的停止时间(如果为 None,则无限重复)。
callback (Callable [ [TimeEvent ] , None ] , optional) – The callback to receive time events.
callback (Callable [ [TimeEvent ],None ],可选) - 接收时间事件的回调函数。
Raises:
引发:
ValueError – If name is not a valid string.
ValueError - 如果 name 不是有效的字符串。
KeyError – If name is not unique for this clock.
KeyError - 如果 name 对此时钟不唯一。
ValueError – If interval is not positive (> 0).
ValueError - 如果 interval 不是正数 (> 0)。
ValueError – If stop_time is not None and stop_time < time now.
ValueError - 如果 stop_time 不为 None 且 stop_time < 当前时间。
ValueError – If stop_time is not None and start_time + interval > stop_time.
ValueError - 如果 stop_time 不为 None 且 start_time + interval > stop_time。
TypeError – If handler is not of type Callable or None.
TypeError - 如果 handler 的类型不是 Callable 或 None。
ValueError – If handler is None and no default handler is registered.
ValueError - 如果 handler 为 None 并且没有注册默认处理程序。
"""
...
def set_timer_ns(self, name: str, interval_ns: int, start_time_ns: int, stop_time_ns: int, callback=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.
计时器将从开始时间运行到停止时间。当达到间隔时,处理程序将被传递包含计时器唯一名称的 TimeEvent。如果没有传递处理程序,则默认处理程序(如果已注册)将接收 TimeEvent。
Parameters:
参数:
name (str) – The name for the timer (must be unique for this clock).
```python
name (str) - 计时器的名称(必须对此时钟唯一)。
interval_ns (uint64_t) – The time interval (nanoseconds) for the timer.
interval_ns (uint64_t) - 计时器的时间间隔(纳秒)。
start_time_ns (uint64_t) – The start UNIX time (nanoseconds) for the timer.
start_time_ns (uint64_t) - 计时器的开始 UNIX 时间(纳秒)。
stop_time_ns (uint64_t) – The stop UNIX time (nanoseconds) for the timer.
stop_time_ns (uint64_t) - 计时器的停止 UNIX 时间(纳秒)。
callback (Callable [ [TimeEvent ] , None ] , optional) – The callback to receive time events.
callback (Callable [ [TimeEvent ],None ],可选) - 接收时间事件的回调函数。
Raises:
引发:
ValueError – If name is not a valid string.
ValueError - 如果 name 不是有效的字符串。
KeyError – If name is not unique for this clock.
KeyError - 如果 name 对此时钟不唯一。
ValueError – If interval is not positive (> 0).
ValueError - 如果 interval 不是正数 (> 0)。
ValueError – If stop_time is not None and stop_time < time now.
ValueError - 如果 stop_time 不为 None 且 stop_time < 当前时间。
ValueError – If stop_time is not None and start_time + interval > stop_time.
ValueError - 如果 stop_time 不为 None 且 start_time + interval > stop_time。
TypeError – If callback is not of type Callable or None.
TypeError - 如果 callback 的类型不是 Callable 或 None。
ValueError – If callback is None and no default handler is registered.
ValueError - 如果 callback 为 None 并且没有注册默认处理程序。
"""
...
def timestamp(self) -> float:
"""
Return the current UNIX time in seconds.
返回当前 UNIX 时间(以秒为单位)。
Return type: double
"""
...
def timestamp_ms(self) -> int:
"""
Return the current UNIX time in milliseconds (ms).
返回当前 UNIX 时间(以毫秒为单位)。
Return type: uint64_t
"""
...
def timestamp_ns(self) -> int:
"""
Return the current UNIX time in nanoseconds (ns).
返回当前 UNIX 时间(以纳秒为单位)。
Return type: uint64_t
"""
...
def utc_now(self) -> datetime:
"""
Return the current time (UTC).
返回当前时间 (UTC)。
Returns: The current tz-aware UTC time of the clock.
返回值:时钟当前的 tz 感知 UTC 时间。
Return type: datetime
"""
...
Bases: object
class Component(object):
"""
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.
因此,如果组件没有通过构造函数接收消息总线,则它将处于 PRE_INITIALIZED 状态,否则,如果传递了消息总线,则它将处于 INITIALIZED 状态。
Parameters:
参数:
clock (Clock) – The clock for the component.
clock (Clock) - 组件的时钟。
trader_id (TraderId , optional) – The trader ID associated with the component.
trader_id (TraderId,可选) - 与组件关联的交易者 ID。
component_id (Identifier , optional) – The component ID. If None is passed then the identifier will be taken from type(self)._name_.
component_id (Identifier,可选) - 组件 ID。如果传递 None,则将从 type(self)._name_ 获取标识符。
component_name (str , optional) – The custom component name.
component_name (str,可选) - 自定义组件名称。
msgbus (MessageBus , optional) – The message bus for the component (required before initialized).
msgbus (MessageBus,可选) - 组件的消息总线(初始化之前需要)。
config (NautilusConfig , optional) – The configuration for the component.
config (NautilusConfig,可选) - 组件的配置。
Raises:
引发:
ValueError – If component_name is not a valid string.
ValueError - 如果 component_name 不是有效的字符串。
TypeError – If config is not of type NautilusConfig.
TypeError - 如果 config 的类型不是 NautilusConfig。
Warning:
This class should not be used directly, but through a concrete subclass.
此类不应直接使用,而应通过具体的子类使用。
"""
def __init__(self, clock: Clock, trader_id: TraderId = None, component_id: Identifier = None, component_name: str = None, msgbus: MessageBus = None, config: NautilusConfig | None = None):
...
@property
def id(self) -> ComponentId:
"""
The components ID.
组件 ID。
Returns:
ComponentId
"""
...
@property
def is_degraded(self) -> bool:
"""
bool
Return whether the current component state is DEGRADED.
返回当前组件状态是否为 DEGRADED。
Returns:
bool
"""
...
@property
def is_disposed(self) -> bool:
"""
bool
Return whether the current component state is DISPOSED.
返回当前组件状态是否为 DISPOSED。
Returns:
bool
"""
...
@property
def is_faulted(self) -> bool:
"""
bool
Return whether the current component state is FAULTED.
返回当前组件状态是否为 FAULTED。
Returns:
bool
"""
...
@property
def is_initialized(self) -> bool:
"""
bool
Return whether the component has been initialized (component.state >= INITIALIZED).
返回组件是否已初始化 (component.state >= INITIALIZED)。
Returns:
bool
"""
...
@property
def is_running(self) -> bool:
"""
bool
Return whether the current component state is RUNNING.
返回当前组件状态是否为 RUNNING。
Returns:
bool
"""
...
@property
def is_stopped(self) -> bool:
"""
bool
Return whether the current component state is STOPPED.
返回当前组件状态是否为 STOPPED。
Returns:
bool
"""
...
@property
def state(self) -> ComponentState:
"""
ComponentState
Return the components current state.
返回组件的当前状态。
Return type: ComponentState
Type: Component.state
"""
...
@property
def trader_id(self):
"""
The trader ID associated with the component.
与组件关联的交易者 ID。
Returns:
TraderId
"""
...
@property
def type(self):
"""
The components type.
组件类型。
Returns:
type
"""
...
def 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.
警告:
不要覆盖。
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) -> 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.
警告:
不要覆盖。
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 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.
警告:
不要覆盖。
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
"""
...
def 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.
警告:
不要覆盖。
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) -> void:
"""
Resume the component.
While executing on_resume() any exception will be logged and reraised, then the component will remain in a RESUMING state.
警告:
不要覆盖。
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 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.
警告:
不要覆盖。
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 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.
警告:
不要覆盖。
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.
如果组件未处于可执行此方法的有效状态,则组件状态将不会更改,并且将记录错误。
"""
...
Bases: object
class ComponentFSMFactory(object):
"""
Provides a generic component Finite-State Machine.
提供通用的组件有限状态机。
"""
def __init__(self):
...
@staticmethod
def get_state_transition_table() -> dict:
"""
The default state transition table.
默认状态转换表。
Returns: C Enums.
返回值:C 枚举。
Return type: dict[int, int]
"""
...
Bases: Clock
class LiveClock(Clock):
"""
Provides a monotonic clock for live trading.
为实时交易提供单调时钟。
All times are tz-aware UTC.
所有时间都是 tz 感知的 UTC 时间。
Parameters:
参数:
loop (asyncio.AbstractEventLoop) – The event loop for the clocks timers.
loop (asyncio.AbstractEventLoop) - 时钟计时器的事件循环。
"""
def __init__(self):
...
@property
def timer_count(self) -> int:
"""
int
Type: LiveClock.timer_count
"""
...
@property
def timer_names(self) -> list[str]:
"""
list[str]
Type: LiveClock.timer_names
"""
...
def cancel_timer(self, name: str) -> void:
"""
"""
...
def cancel_timers(self) -> void:
"""
"""
...
def local_now(self, 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).
参数:tz (tzinfo,可选) - 本地时区(如果为 None,则假定目标时区为系统本地时区)。
Returns: tz-aware in local timezone.
返回值:本地时区中的 tz 感知时间。
Return type: datetime
"""
...
def next_time_ns(self, name: str) -> int:
"""
"""
...
def register_default_handler(self, callback) -> void:
"""
"""
...
def set_time_alert(self, name: str, alert_time: datetime, callback=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 handler is passed then the default handler (if registered) will receive the TimeEvent.
当达到时间时,处理程序将被传递包含计时器唯一名称的 TimeEvent。如果没有传递处理程序,则默认处理程序(如果已注册)将接收 TimeEvent。
Parameters:
参数:
name (str) – The name for the alert (must be unique for this clock).
name (str) - 警报的名称(必须对此时钟唯一)。
alert_time (datetime) – The time for the alert.
alert_time (datetime) - 警报的时间。
callback (Callable [ [TimeEvent ] , None ] , optional) – The callback to receive time events.
callback (Callable [ [TimeEvent ],None ],可选) - 接收时间事件的回调函数。
Raises:
引发:
ValueError – If name is not a valid string.
ValueError - 如果 name 不是有效的字符串。
KeyError – If name is not unique for this clock.
KeyError - 如果 name 对此时钟不唯一。
TypeError – If handler is not of type Callable or None.
TypeError - 如果 handler 的类型不是 Callable 或 None。
ValueError – If handler is None and no default handler is registered.
ValueError - 如果 handler 为 None 并且没有注册默认处理程序。
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).
如果 alert_time 在过去或当前时间,则将立即生成时间事件(而不是无效并导致条件检查失败)。
"""
...
def set_time_alert_ns(self, name: str, alert_time_ns: int, callback=None) -> void:
"""
"""
...
def set_timer(self, name: str, interval: timedelta, start_time: datetime=None, stop_time: datetime=None, callback=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.
计时器将从开始时间运行(可选地运行到停止时间)。当达到间隔时,处理程序将被传递包含计时器唯一名称的 TimeEvent。如果没有传递处理程序,则默认处理程序(如果已注册)将接收 TimeEvent。
Parameters:
参数:
name (str) – The name for the timer (must be unique for this clock).
name (str) - 计时器的名称(必须对此时钟唯一)。
interval (timedelta) – The time interval for the timer.
interval (timedelta) - 计时器的时间间隔。
start_time (datetime , optional) – The start time for the timer (if None then starts immediately).
start_time (datetime,可选) - 计时器的开始时间(如果为 None,则立即开始)。
stop_time (datetime , optional) – The stop time for the timer (if None then repeats indefinitely).
stop_time (datetime,可选) - 计时器的停止时间(如果为 None,则无限重复)。
callback (Callable [ [TimeEvent ] , None ] , optional) – The callback to receive time events.
callback (Callable [ [TimeEvent ],None ],可选) - 接收时间事件的回调函数。
Raises:
引发:
ValueError – If name is not a valid string.
ValueError - 如果 name 不是有效的字符串。
KeyError – If name is not unique for this clock.
KeyError - 如果 name 对此时钟不唯一。
ValueError – If interval is not positive (> 0).
ValueError - 如果 interval 不是正数 (> 0)。
ValueError – If stop_time is not None and stop_time < time now.
ValueError - 如果 stop_time 不为 None 且 stop_time < 当前时间。
ValueError – If stop_time is not None and start_time + interval > stop_time.
ValueError - 如果 stop_time 不为 None 且 start_time + interval > stop_time。
TypeError – If handler is not of type Callable or None.
TypeError - 如果 handler 的类型不是 Callable 或 None。
ValueError – If handler is None and no default handler is registered.
ValueError - 如果 handler 为 None 并且没有注册默认处理程序。
"""
...
def set_timer_ns(self, name: str, interval_ns: int, start_time_ns: int, stop_time_ns: int, callback=None) -> void:
"""
"""
...
def timestamp(self) -> float:
"""
"""
...
def timestamp_ms(self) -> int:
"""
"""
...
def timestamp_ns(self) -> int:
"""
"""
...
def utc_now(self) -> datetime:
"""
Return the current time (UTC).
返回当前时间 (UTC)。
Returns: The current tz-aware UTC time of the clock.
返回值:时钟当前的 tz 感知 UTC 时间。
Return type: datetime
"""
...
class LogGuard(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.
提供一个 LogGuard,它作为令牌来表示日志记录系统的初始化。它还确保在实例销毁时全局日志记录器刷新任何缓冲记录。
"""
def __init__(self):
...
Bases: object
class Logger(object):
"""
Provides a logger adapter into the logging system.
提供日志记录系统中的日志记录器适配器。
Parameters:
参数:
name (str) – The name of the logger. This will appear within each log line.
name (str) - 日志记录器的名称。这将出现在每个日志行中。
"""
def __init__(self, name: str) -> None:
...
@property
def name(self) -> str:
"""
str
Return the name of the logger.
返回日志记录器的名称。
Return type: str
Type: Logger.name
"""
...
def debug(self, message: str, color=LogColor.NORMAL) -> void:
"""
Log the given DEBUG level message.
记录给定的 DEBUG 级别的消息。
Parameters:
参数:
message (str) – The log message text (valid UTF-8).
message (str) - 日志消息文本(有效的 UTF-8)。
color (LogColor , optional) – The log message color.
color (LogColor,可选) - 日志消息颜色。
"""
...
def error(self, message: str, color=LogColor.RED) -> void:
"""
Log the given ERROR level message.
记录给定的 ERROR 级别的消息。
Parameters:
参数:
message (str) – The log message text (valid UTF-8).
message (str) - 日志消息文本(有效的 UTF-8)。
color (LogColor , optional) – The log message color.
color (LogColor,可选) - 日志消息颜色。
"""
...
def exception(self, message: str, ex) -> void:
"""
Log the given exception including stack trace information.
记录给定的异常,包括堆栈跟踪信息。
Parameters:
参数:
message (str) – The log message text (valid UTF-8).
message (str) - 日志消息文本(有效的 UTF-8)。
ex (Exception) – The exception to log.
ex (Exception) - 要记录的异常。
"""
...
def info(self, message: str, color=LogColor.NORMAL) -> void:
"""
Log the given INFO level message.
记录给定的 INFO 级别的消息。
Parameters:
参数:
message (str) – The log message text (valid UTF-8).
message (str) - 日志消息文本(有效的 UTF-8)。
color (LogColor , optional) – The log message color.
color (LogColor,可选) - 日志消息颜色。
"""
...
def warning(self, message: str, color=LogColor.YELLOW) -> void:
"""
Log the given WARNING level message.
记录给定的 WARNING 级别的消息。
Parameters:
参数:
message (str) – The log message text (valid UTF-8).
message (str) - 日志消息文本(有效的 UTF-8)。
color (LogColor , optional) – The log message color.
color (LogColor,可选) - 日志消息颜色。
"""
...
class MessageBus(object):
"""
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.
总线为发布/订阅、请求/回复以及向注册端点直接进行点对点消息传递提供生产者和消费者 API。
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.
通配符中的星号匹配任何字符零次或多次。例如,comp* 匹配任何以 comp 开头的字符串,这意味着 comp、complete 和 computer 都匹配。
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.
问号匹配单个字符一次。例如,c?mp 匹配 camp 和 comp。问号也可以使用多次。例如,c??p 将匹配上述两个示例和 coop。
Parameters:
参数:
trader_id (TraderId) – The trader ID associated with the message bus.
trader_id (TraderId) - 与消息总线关联的交易者 ID。
clock (Clock) – The clock for the message bus.
clock (Clock) - 消息总线的时钟。
name (str , optional) – The custom name for the message bus.
name (str,可选) - 消息总线的自定义名称。
serializer (Serializer , optional) – The serializer for database operations.
serializer (Serializer,可选) - 数据库操作的序列化器。
database (nautilus_pyo3.RedisMessageBusDatabase , optional) – The backing database for the message bus.
database (nautilus_pyo3.RedisMessageBusDatabase,可选) - 消息总线的后备数据库。
config (MessageBusConfig , optional) – The configuration for the message bus.
config (MessageBusConfig,可选) - 消息总线的配置。
Raises: ValueError – If name is not None and not a valid string.
引发:ValueError - 如果 name 不为 None 并且不是有效的字符串。
Warning:
This message bus is not thread-safe and must be called from the same thread as the event loop.
此消息总线不是线程安全的,必须从与事件循环相同的线程调用。
"""
def __init__(self, trader_id: TraderId, clock: Clock, instance_id: UUID4 = None, name: str = None, serializer: Serializer = None, database=None, config: Any | None = None) -> None:
...
@property
def has_backing(self):
"""
If the message bus has a database backing.
如果消息总线有数据库支持。
Returns:
bool
"""
...
@property
def pub_count(self):
"""
The count of messages published by the bus.
总线发布的消息计数。
Returns:
uint64_t
"""
...
@property
def req_count(self):
"""
The count of requests processed by the bus.
总线处理的请求计数。
Returns:
uint64_t
"""
...
@property
def res_count(self):
"""
The count of responses processed by the bus.
总线处理的响应计数。
Returns:
uint64_t
"""
...
@property
def sent_count(self):
"""
The count of messages sent through the bus.
通过总线发送的消息计数。
Returns:
uint64_t
"""
...
@property
def serializer(self):
"""
The serializer for the bus.
总线的序列化器。
Returns:
Serializer
"""
...
@property
def trader_id(self):
"""
The trader ID associated with the bus.
与总线关联的交易者 ID。
Returns:
TraderId
"""
...
def add_streaming_type(self, cls) -> void:
"""
Register the given type for external->internal message bus streaming.
注册给定类型以用于外部到内部消息总线流。
Parameters: type (cls) – The type to add for streaming.
参数:type (cls) - 要添加到流的类型。
"""
...
def deregister(self, endpoint: str, handler) -> void:
"""
Deregister the given handler from the endpoint address.
从端点地址取消注册给定的处理程序。
Parameters:
参数:
endpoint (str) – The endpoint address to deregister.
endpoint (str) - 要取消注册的端点地址。
handler (Callable [ *[*Any ] , None ]) – The handler to deregister.
handler (Callable [*[*Any],None]) - 要取消注册的处理程序。
Raises:
引发:
ValueError – If endpoint is not a valid string.
ValueError - 如果 endpoint 不是有效的字符串。
ValueError – If handler is not of type Callable.
ValueError - 如果 handler 的类型不是 Callable。
KeyError – If endpoint is not registered.
KeyError - 如果端点未注册。
ValueError – If handler is not registered at the endpoint.
ValueError - 如果处理程序未在端点注册。
"""
...
def dispose(self) -> void:
"""
Dispose of the message bus which will close the internal channel and thread.
释放消息总线,这将关闭内部通道和线程。
"""
...
def endpoints(self) -> list:
"""
Return all endpoint addresses registered with the message bus.
返回在消息总线中注册的所有端点地址。
Return type: list[str]
"""
...
def has_subscribers(self, pattern: str=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.
参数:pattern (str,可选) - 主题过滤器。可以包含通配符 * 和 ?。如果为 None,则查询所有主题。
Return type: bool
"""
...
def is_pending_request(self, request_id: UUID4) -> bool:
"""
Return if the given request_id is still pending a response.
返回给定的 request_id 是否仍在等待响应。
Parameters: request_id (UUID4) – The request ID to check (to match the correlation_id).
参数:request_id (UUID4) - 要检查的请求 ID(以匹配 correlation_id)。
Return type: bool
"""
...
def is_streaming_type(self, cls) -> bool:
"""
Return whether the given type has been registered for external message streaming.
返回给定类型是否已注册用于外部消息流。
Returns: True if registered, else False.
返回值:如果已注册,则返回 True,否则返回 False。
Return type: bool
"""
...
def is_subscribed(self, topic: str, handler) -> 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.
topic (str) - 订阅的主题。
handler (Callable [ *[*Any ] , None ]) – The handler of the subscription.
handler (Callable [*[*Any],None]) - 订阅的处理程序。
Return type: bool
"""
...
def publish(self, topic: str, msg, external_pub: bool=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.
topic (str) - 要发布到的主题。
msg (object) – The message to publish.
msg (object) - 要发布的消息。
external_pub (bool , default True) – If the message should also be published externally.
external_pub (bool,默认 True) - 消息是否也应在外部发布。
"""
...
def register(self, endpoint: str, handler) -> void:
"""
Register the given handler to receive messages at the endpoint address.
注册给定的处理程序以在端点地址接收消息。
Parameters:
参数:
endpoint (str) – The endpoint address to register.
endpoint (str) - 要注册的端点地址。
handler (Callable [ *[*Any ] , None ]) – The handler for the registration.
handler (Callable [*[*Any],None]) - 注册的处理程序。
Raises:
引发:
ValueError – If endpoint is not a valid string.
ValueError - 如果 endpoint 不是有效的字符串。
ValueError – If handler is not of type Callable.
ValueError - 如果 handler 的类型不是 Callable。
KeyError – If endpoint already registered.
KeyError - 如果端点已注册。
"""
...
def request(self, endpoint: str, request: Request) -> void:
"""
Handle the given request.
处理给定的请求。
Will log an error if the correlation ID already exists.
```python
如果相关 ID 已存在,则会记录错误。
Parameters:
参数:
endpoint (str) – The endpoint address to send the request to.
endpoint (str) - 要将请求发送到的端点地址。
request (Request) – The request to handle.
request (Request) - 要处理的请求。
"""
...
def response(self, response: Response) -> void:
"""
Handle the given response.
处理给定的响应。
Will log an error if the correlation ID is not found.
如果未找到相关 ID,则会记录错误。
Parameters: response (Response) – The response to handle
参数:response (Response) - 要处理的响应。
"""
...
def send(self, endpoint: str, msg) -> void:
"""
Send the given message to the given endpoint address.
将给定消息发送到给定端点地址。
Parameters:
参数:
endpoint (str) – The endpoint address to send the message to.
endpoint (str) - 要将消息发送到的端点地址。
msg (object) – The message to send.
msg (object) - 要发送的消息。
"""
...
def subscribe(self, topic: str, handler, priority: int=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 ?.
topic (str) - 订阅的主题。可以包含通配符 * 和 ?。
handler (Callable [ *[*Any ] , None ]) – The handler for the subscription.
handler (Callable [*[*Any],None]) - 订阅的处理程序。
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.
priority (int,可选) - 订阅的优先级。确定接收正在处理的消息的处理程序的顺序,优先级较高的处理程序将在优先级较低的处理程序之前接收消息。
Raises:
引发:
ValueError – If topic is not a valid string.
ValueError - 如果 topic 不是有效的字符串。
ValueError – If handler is not of type Callable.
ValueError - 如果 handler 的类型不是 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.
分配优先级处理是一项高级功能,大多数用户通常不需要它。只有在确定自己在做什么的情况下,才应为订阅分配更高的优先级。如果分配了不合适的优先级,则处理程序可能会在核心系统组件能够处理必要的计算并为逻辑上合理的行为产生潜在副作用之前收到消息。
"""
...
def subscriptions(self, pattern: str=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.
参数:pattern (str,可选) - 主题模式过滤器。可以包含通配符 * 和 ?。如果为 None,则查询所有主题。
Return type: list[Subscription]
"""
...
def topics(self) -> list:
"""
Return all topics with active subscribers.
返回具有活动订阅者的所有主题。
Return type: list[str]
"""
...
def unsubscribe(self, topic: str, handler) -> 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 ?.
topic (str,可选) - 要取消订阅的主题。可以包含通配符 * 和 ?。
handler (Callable [ *[*Any ] , None ]) – The handler for the subscription.
handler (Callable [*[*Any],None]) - 订阅的处理程序。
Raises:
引发:
ValueError – If topic is not a valid string.
ValueError - 如果 topic 不是有效的字符串。
ValueError – If handler is not of type Callable.
ValueError - 如果 handler 的类型不是 Callable。
"""
...
Bases: object
class Subscription(object):
"""
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 ?.
topic (str) - 订阅的主题。可以包含通配符 * 和 ?。
handler (Callable [ *[*Message ] , None ]) – The handler for the subscription.
handler (Callable [*[*Message],None]) - 订阅的处理程序。
priority (int) – The priority for the subscription.
priority (int) - 订阅的优先级。
Raises:
引发:
ValueError – If topic is not a valid string.
ValueError - 如果 topic 不是有效的字符串。
ValueError – If handler is not of type Callable.
ValueError - 如果 handler 的类型不是 Callable。
ValueError – If priority is negative (< 0).
ValueError - 如果 priority 为负数 (< 0)。
"""
def __init__(self, topic: str, handler, priority: int = 0):
...
@property
def handler(self):
"""
The handler for the subscription.
订阅的处理程序。
Returns:
Callable
"""
...
@property
def priority(self):
"""
The priority for the subscription.
订阅的优先级。
Returns:
int
"""
...
@property
def topic(self):
"""
The topic for the subscription.
订阅的主题。
Returns:
str
"""
...
Bases: Clock
class TestClock(Clock):
"""
Provides a monotonic clock for backtesting and unit testing.
为回测和单元测试提供单调时钟。
"""
def __init__(self):
...
@property
def timer_count(self) -> int:
"""
int
Type: TestClock.timer_count
"""
...
@property
def timer_names(self) -> list[str]:
"""
list[str]
Type: TestClock.timer_names
"""
...
def advance_time(self, to_time_ns: int, set_time: bool = True) -> list:
"""
Advance the clocks time to the given to_time_ns.
将时钟时间提前到给定的 to_time_ns。
Parameters:
参数:
to_time_ns (uint64_t) – The UNIX time (nanoseconds) to advance the clock to.
to_time_ns (uint64_t) - 要将时钟提前到的 UNIX 时间(纳秒)。
set_time (bool) – If the clock should also be set to the given to_time_ns.
set_time (bool) - 时钟是否也应设置为给定的 to_time_ns。
Returns: Sorted chronologically.
返回值:按时间顺序排序。
Return type: list[TimeEventHandler]
Raises: ValueError – If to_time_ns is < the clocks current time.
引发:ValueError - 如果 to_time_ns 小于时钟的当前时间。
"""
...
def cancel_timer(self, name: str) -> void:
"""
"""
...
def cancel_timers(self) -> void:
"""
"""
...
def local_now(self, 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).
参数:tz (tzinfo,可选) - 本地时区(如果为 None,则假定目标时区为系统本地时区)。
Returns: tz-aware in local timezone.
返回值:本地时区中的 tz 感知时间。
Return type: datetime
"""
...
def next_time_ns(self, name: str) -> int:
"""
"""
...
def register_default_handler(self, callback) -> void:
"""
"""
...
def set_time(self, to_time_ns: int) -> void:
"""
Set the clocks datetime to the given time (UTC).
将时钟日期时间设置为给定时间 (UTC)。
Parameters: to_time_ns (uint64_t) – The UNIX time (nanoseconds) to set.
参数:to_time_ns (uint64_t) - 要设置的 UNIX 时间(纳秒)。
"""
...
def set_time_alert(self, name: str, alert_time: datetime, callback=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 handler is passed then the default handler (if registered) will receive the TimeEvent.
当达到时间时,处理程序将被传递包含计时器唯一名称的 TimeEvent。如果没有传递处理程序,则默认处理程序(如果已注册)将接收 TimeEvent。
Parameters:
参数:
name (str) – The name for the alert (must be unique for this clock).
name (str) - 警报的名称(必须对此时钟唯一)。
alert_time (datetime) – The time for the alert.
alert_time (datetime) - 警报的时间。
callback (Callable [ [TimeEvent ] , None ] , optional) – The callback to receive time events.
callback (Callable [ [TimeEvent ],None ],可选) - 接收时间事件的回调函数。
Raises:
引发:
ValueError – If name is not a valid string.
ValueError - 如果 name 不是有效的字符串。
KeyError – If name is not unique for this clock.
KeyError - 如果 name 对此时钟不唯一。
TypeError – If handler is not of type Callable or None.
TypeError - 如果 handler 的类型不是 Callable 或 None。
ValueError – If handler is None and no default handler is registered.
ValueError - 如果 handler 为 None 并且没有注册默认处理程序。
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).
如果 alert_time 在过去或当前时间,则将立即生成时间事件(而不是无效并导致条件检查失败)。
"""
...
def set_time_alert_ns(self, name: str, alert_time_ns: int, callback=None) -> void:
"""
"""
...
def set_timer(self, name: str, interval: timedelta, start_time: datetime=None, stop_time: datetime=None, callback=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.
计时器将从开始时间运行(可选地运行到停止时间)。当达到间隔时,处理程序将被传递包含计时器唯一名称的 TimeEvent。如果没有传递处理程序,则默认处理程序(如果已注册)将接收 TimeEvent。
Parameters:
参数:
name (str) – The name for the timer (must be unique for this clock).
name (str) - 计时器的名称(必须对此时钟唯一)。
interval (timedelta) – The time interval for the timer.
interval (timedelta) - 计时器的时间间隔。
start_time (datetime , optional) – The start time for the timer (if None then starts immediately).
start_time (datetime,可选) - 计时器的开始时间(如果为 None,则立即开始)。
stop_time (datetime , optional) – The stop time for the timer (if None then repeats indefinitely).
stop_time (datetime,可选) - 计时器的停止时间(如果为 None,则无限重复)。
callback (Callable [ [TimeEvent ] , None ] , optional) – The callback to receive time events.
callback (Callable [ [TimeEvent ],None ],可选) - 接收时间事件的回调函数。
Raises:
引发:
ValueError – If name is not a valid string.
ValueError - 如果 name 不是有效的字符串。
KeyError – If name is not unique for this clock.
KeyError - 如果 name 对此时钟不唯一。
ValueError – If interval is not positive (> 0).
ValueError - 如果 interval 不是正数 (> 0)。
ValueError – If stop_time is not None and stop_time < time now.
ValueError - 如果 stop_time 不为 None 且 stop_time < 当前时间。
ValueError – If stop_time is not None and start_time + interval > stop_time.
ValueError - 如果 stop_time 不为 None 且 start_time + interval > stop_time。
TypeError – If handler is not of type Callable or None.
TypeError - 如果 handler 的类型不是 Callable 或 None。
ValueError – If handler is None and no default handler is registered.
ValueError - 如果 handler 为 None 并且没有注册默认处理程序。
"""
...
def set_timer_ns(self, name: str, interval_ns: int, start_time_ns: int, stop_time_ns: int, callback=None) -> void:
"""
"""
...
def timestamp(self) -> float:
"""
"""
...
def timestamp_ms(self) -> int:
"""
"""
...
def timestamp_ns(self) -> int:
"""
"""
...
def utc_now(self) -> datetime:
"""
Return the current time (UTC).
返回当前时间 (UTC)。
Returns: The current tz-aware UTC time of the clock.
返回值:时钟当前的 tz 感知 UTC 时间。
Return type: datetime
"""
...
Bases: object
class Throttler(object):
"""
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.
将消息限制在给定的最大限制间隔速率内。如果提供了 output_drop 处理程序,则会丢弃超过速率限制的消息。否则,将缓冲消息直到在速率限制内,然后发送。
Parameters:
参数:
name (str) – The unique name of the throttler.
name (str) - 节流器的唯一名称。
limit (int) – The limit setting for the throttling.
limit (int) - 节流的限制设置。
interval (timedelta) – The interval setting for the throttling.
interval (timedelta) - 节流的间隔设置。
clock (Clock) – The clock for the throttler.
clock (Clock) - 节流器的时钟。
output_send (Callable [ *[*Any ] , None ]) – The output handler to send messages from the throttler.
output_send (Callable [*[*Any],None]) - 用于从节流器发送消息的输出处理程序。
output_drop (Callable [ *[*Any ] , None ] , optional) – The output handler to drop messages from the throttler. If None then messages will be buffered.
output_drop (Callable [*[*Any],None],可选) - 用于从节流器丢弃消息的输出处理程序。如果为 None,则消息将被缓冲。
Raises:
引发:
ValueError – If name is not a valid string.
ValueError - 如果 name 不是有效的字符串。
ValueError – If limit is not positive (> 0).
ValueError - 如果 limit 不是正数 (> 0)。
ValueError – If interval is not positive (> 0).
ValueError - 如果 interval 不是正数 (> 0)。
ValueError – If output_send is not of type Callable.
ValueError - 如果 output_send 的类型不是 Callable。
ValueError – If output_drop is not of type Callable or None.
ValueError - 如果 output_drop 的类型不是 Callable 或 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.
内部缓冲队列是无界的,因此有界队列应该在上游。
"""
def __init__(self, name: str, limit: int, interval: timedelta, clock: Clock, output_send, output_drop=None) -> None:
...
@property
def interval(self) -> timedelta:
"""
The interval for the throttler rate.
节流器速率的间隔。
Returns:
timedelta
"""
...
@property
def is_limiting(self):
"""
If the throttler is currently limiting messages (buffering or dropping).
如果节流器当前正在限制消息(缓冲或丢弃)。
Returns:
bool
"""
...
@property
def limit(self):
"""
The limit for the throttler rate.
节流器速率的限制。
Returns:
int
"""
...
@property
def name(self):
"""
The name of the throttler.
节流器的名称。
Returns:
str
"""
...
@property
def qsize(self) -> int:
"""
int
Return the qsize of the internal buffer.
返回内部缓冲区的 qsize。
Return type: int
Type: Throttler.qsize
"""
...
@property
def recv_count(self):
"""
If count of messages received by the throttler.
节流器接收的消息计数。
Returns:
int
"""
...
@property
def sent_count(self):
"""
If count of messages sent from the throttler.
从节流器发送的消息计数。
Returns:
int
"""
...
def reset(self) -> void:
"""
Reset the state of the throttler.
重置节流器的状态。
"""
...
def send(self, msg) -> void:
"""
Send the given message through the throttler.
通过节流器发送给定消息。
Parameters: msg (object) – The message to send.
参数:msg (object) - 要发送的消息。
"""
...
def used(self) -> float:
"""
Return the percentage of maximum rate currently used.
返回当前使用的最大速率的百分比。
Returns: [0, 1.0].
返回值:[0, 1.0]。
Return type: double
"""
...
Bases: Event
class TimeEvent(Event):
"""
Represents a time event occurring at the event timestamp.
表示在事件时间戳发生的事件时间。
Parameters:
参数:
name (str) – The event name.
name (str) - 事件名称。
event_id (UUID4) – The event ID.
event_id (UUID4) - 事件 ID。
ts_event (uint64_t) – UNIX timestamp (nanoseconds) when the time event occurred.
ts_event (uint64_t) - 时间事件发生时的 UNIX 时间戳(纳秒)。
ts_init (uint64_t) – UNIX timestamp (nanoseconds) when the object was initialized.
ts_init (uint64_t) - 对象初始化时的 UNIX 时间戳(纳秒)。
"""
def __init__(self, name: str, event_id: UUID4, ts_event: int, ts_init: int):
...
@property
def id(self) -> UUID4:
"""
UUID4
The event message identifier.
事件消息标识符。
Return type: UUID4
Type: TimeEvent.id
"""
...
@property
def name(self) -> str:
"""
str
Return the name of the time event.
返回时间事件的名称。
Return type: str
Type: TimeEvent.name
"""
...
@property
def ts_event(self) -> int:
"""
int
UNIX timestamp (nanoseconds) when the event occurred.
事件发生时的 UNIX 时间戳(纳秒)。
Return type: int
Type: TimeEvent.ts_event
"""
...
@property
def ts_init(self) -> int:
"""
int
UNIX timestamp (nanoseconds) when the object was initialized.
对象初始化时的 UNIX 时间戳(纳秒)。
Return type: int
Type: TimeEvent.ts_init
"""
...
Bases: object
class TimeEventHandler(object):
"""
Represents a time event with its associated handler.
表示时间事件及其关联的处理程序。
"""
def __init__(self, event: TimeEvent, handler):
...
@property
def event(self):
"""
The handlers event.
处理程序的事件。
Returns:
TimeEvent
"""
...
def handle(self) -> void:
"""
Call the handler with the contained time event.
使用包含的时间事件调用处理程序。
"""
...
def component_state_from_str(value: str) -> ComponentState:
"""
"""
...
def component_state_to_str(value: ComponentState) -> str:
"""
"""
...
def component_trigger_from_str(value: str):
"""
"""
...
def component_trigger_to_str(value: ComponentTrigger) -> str:
"""
"""
...
def create_pyo3_conversion_wrapper(callback):
"""
"""
...
def deregister_component_clock(instance_id: UUID4, clock: Clock) -> void:
"""
"""
...
def init_logging(trader_id: TraderId = None, machine_id: str = None, instance_id: UUID4 = None, level_stdout=LogLevel.INFO, level_file=LogLevel.OFF, directory: str = None, file_name: str = None, file_format: str = None, component_levels: dict = None, colors: bool = True, bypass: bool = False, print_config: bool = False):
"""
Initialize the logging system.
初始化日志记录系统。
Acts as an interface into the logging system implemented in Rust with the log crate.
充当使用 log crate 在 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.
此函数应每个进程只调用一次,在应用程序运行开始时调用。后续调用将引发 RuntimeError,因为每个初始化的系统只能有一个 LogGuard。
Parameters:
参数:
trader_id (TraderId , optional) – The trader ID for the logger.
trader_id (TraderId,可选) - 日志记录器的交易者 ID。
machine_id (str , optional) – The machine ID.
machine_id (str,可选) - 机器 ID。
instance_id (UUID4 , optional) – The instance ID.
instance_id (UUID4,可选) - 实例 ID。
level_stdout (LogLevel, default INFO) – The minimum log level to write to stdout.
level_stdout (LogLevel,默认 INFO) - 写入标准输出的最低日志级别。
level_file (LogLevel, default OFF) – The minimum log level to write to a file.
level_file (LogLevel,默认 OFF) - 写入文件的最低日志级别。
directory (str , optional) – The path to the log file directory. If None then will write to the current working directory.
directory (str,可选) - 日志文件目录的路径。如果为 None,则将写入当前工作目录。
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_name (str,可选) - 自定义日志文件名(将对纯文本使用“.log”后缀,对 JSON 使用“.json”)。如果为 None,则不会记录到文件(除非 file_auto 为 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.
file_format (str {'JSON'},可选) - 日志文件格式。如果为 None(默认值),则将以纯文本格式记录。如果设置为“JSON”,则日志将采用 JSON 格式。
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.
component_levels (dict [ComponentId,LogLevel]) - 每个组件的附加日志级别过滤器,其中键是组件 ID(例如,执行器/策略 ID),值是日志级别。
colors (bool , default True) – If ANSI codes should be used to produce colored log lines.
colors (bool,默认 True) - 是否应使用 ANSI 代码生成彩色日志行。
bypass (bool , default False) – If the output for the core logging system is bypassed (useful for logging tests).
bypass (bool,默认 False) - 是否绕过核心日志记录系统的输出(对日志记录测试很有用)。
print_config (bool , default False) – If the core logging configuration should be printed to stdout on initialization.
print_config (bool,默认 False) - 是否应在初始化时将核心日志记录配置打印到标准输出。
Return type: LogGuard
Raises: RuntimeError – If the logging system has already been initialized.
引发:RuntimeError - 如果日志记录系统已初始化。
"""
...
def is_logging_initialized() -> bool:
"""
"""
...
def is_logging_pyo3() -> bool:
"""
"""
...
def is_matching_py(topic: str, pattern: str) -> bool:
"""
"""
...
def log_color_from_str(value: str):
"""
"""
...
def log_color_to_str(value: LogColor) -> str:
"""
"""
...
def log_header(trader_id: TraderId, machine_id: str, instance_id: UUID4, component: str) -> void:
"""
"""
...
def log_level_from_str(value: str):
"""
"""
...
def log_level_to_str(value: LogLevel) -> str:
"""
"""
...
def log_sysinfo(component: str) -> void:
"""
"""
...
def register_component_clock(instance_id: UUID4, clock: Clock) -> void:
"""
"""
...
def remove_instance_component_clocks(instance_id: UUID4) -> void:
"""
"""
...
def set_logging_pyo3(value: bool) -> void:
"""
"""
...
class TaskId(object):
"""
Represents a unique identifier for a task managed by the ActorExecutor.
表示 ActorExecutor 管理的任务的唯一标识符。
This ID can be associated with a task that is either queued for execution or actively executing as an asyncio.Future.
此 ID 可以与排队执行或作为 asyncio.Future 积极执行的任务相关联。
"""
def __init__(self):
...
value: str
@classmethod
def create(cls) -> 'TaskId':
"""
Create and return a new task identifier with a UUID v4 value.
创建并返回一个具有 UUID v4 值的新任务标识符。
Return type: TaskId
"""
...
class ActorExecutor(object):
"""
Provides an executor for Actor and Strategy classes.
为 Actor 和 Strategy 类提供执行器。
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.
执行器旨在处理 Actor 和 Strategy 类的异步任务。此自定义执行器在给定的事件循环中排队和执行任务,并且专为单线程应用程序量身定制。
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.
ActorExecutor 维护其内部状态以管理排队和活动任务,提供用于调度、取消和监控的工具。它可以用于在复杂的异步系统中创建更受控的执行流。
Parameters:
参数:
loop (AbstractEventLoop) – The event loop for the application.
loop (AbstractEventLoop) - 应用程序的事件循环。
executor (Executor) – The inner executor to register.
executor (Executor) - 要注册的内部执行器。
logger (Logger , optional) – The logger for the executor.
logger (Logger,可选) - 执行器的日志记录器。
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.
此执行器不是线程安全的,必须从创建它的同一线程中调用。与多线程应用程序集成时,应特别注意确保线程一致性。
"""
def __init__(self, loop: AbstractEventLoop, executor: Executor, logger: Logger | None = None):
...
def reset(self) -> None:
"""
Reset the executor.
重置执行器。
This will cancel all queued and active tasks, and drain the internal queue without executing those tasks.
这将取消所有排队和活动的任务,并清空内部队列而不执行这些任务。
"""
...
def get_future(self, task_id: TaskId):
"""
Return the executing Future with the given task_id (if found).
返回具有给定 task_id 的正在执行的 Future(如果找到)。
Parameters: task_id (TaskId) – The task identifier for the future.
参数:task_id (TaskId) - Future 的任务标识符。
Return type: asyncio.Future or None
"""
...
async def shutdown(self) -> None:
"""
Shutdown the executor in an async context.
在异步上下文中关闭执行器。
This will cancel the inner worker task.
这将取消内部工作任务。
"""
...
def queue_for_executor(self, func: Callable[[...], Any], *args: Any, **kwargs: Any) -> TaskId:
"""
Enqueue the given func to be executed sequentially.
将给定的 func 排队以便按顺序执行。
Parameters:
参数:
func (Callable) – The function to be executed.
func (Callable) - 要执行的函数。
args (positional arguments) – The positional arguments for the call to func.
args(位置参数) - 对 func 的调用的位置参数。
kwargs (arbitrary keyword arguments) – The keyword arguments for the call to func.
kwargs(任意关键字参数) - 对 func 的调用的关键字参数。
Return type: TaskId
"""
...
def run_in_executor(self, func: Callable[[...], Any], *args: Any, **kwargs: Any) -> TaskId:
"""
Arrange for the given func to be called in the executor.
安排在执行器中调用给定的 func。
Parameters:
参数:
func (Callable) – The function to be executed.
func (Callable) - 要执行的函数。
args (positional arguments) – The positional arguments for the call to func.
args(位置参数) - 对 func 的调用的位置参数。
kwargs (arbitrary keyword arguments) – The keyword arguments for the call to func.
kwargs(任意关键字参数) - 对 func 的调用的关键字参数。
Return type: TaskId
"""
...
def queued_task_ids(self) -> list[TaskId]:
"""
Return the queued task identifiers.
返回排队的 task 标识符。
Return type: list[TaskId]
"""
...
def active_task_ids(self) -> list[TaskId]:
"""
```python
Return the active task identifiers.
返回活动的 task 标识符。
Return type: list[TaskId]
"""
...
def has_queued_tasks(self) -> bool:
"""
Return a value indicating whether there are any queued tasks.
返回值指示是否有任何排队的 task。
Return type: bool
"""
...
def has_active_tasks(self) -> bool:
"""
Return a value indicating whether there are any active tasks.
返回值指示是否有任何活动的 task。
Return type: bool
"""
...
def cancel_task(self, task_id: TaskId) -> None:
"""
Cancel the task with the given task_id (if queued or active).
取消具有给定 task_id 的任务(如果已排队或活动)。
If the task is not found then a warning is logged.
如果未找到任务,则会记录警告。
Parameters: task_id (TaskId) – The active task identifier.
参数:task_id (TaskId) - 活动的 task 标识符。
"""
...
def cancel_all_tasks(self) -> None:
"""
Cancel all active and queued tasks.
取消所有活动和排队的任务。
"""
...
Bases: IdentifierGenerator
class ClientOrderIdGenerator(IdentifierGenerator):
"""
Provides a generator for unique `ClientOrderId`(s).
提供唯一 `ClientOrderId` 的生成器。
Parameters:
参数:
trader_id (TraderId) – The trader ID for the generator.
trader_id (TraderId) - 生成器的交易者 ID。
strategy_id (StrategyId) – The strategy ID for the generator.
strategy_id (StrategyId) - 生成器的策略 ID。
clock (Clock) – The clock for the generator.
clock (Clock) - 生成器的时钟。
initial_count (int) – The initial count for the generator.
initial_count (int) - 生成器的初始计数。
Raises: ValueError – If initial_count is negative (< 0).
引发:ValueError - 如果 initial_count 为负数 (< 0)。
"""
def __init__(self, trader_id: TraderId, strategy_id: StrategyId, clock: Clock, initial_count: int = 0):
...
@property
def count(self):
"""
The count of IDs generated.
生成的 ID 计数。
Returns:
int
"""
...
def generate(self) -> ClientOrderId:
"""
Return a unique client order ID.
返回唯一的客户端订单 ID。
Return type: ClientOrderId
"""
...
def reset(self) -> void:
"""
Reset the ID generator.
重置 ID 生成器。
All stateful fields are reset to their initial value.
所有有状态字段都重置为其初始值。
"""
...
def set_count(self, count: int) -> void:
"""
Set the internal counter to the given count.
将内部计数器设置为给定计数。
Parameters: count (int) – The count to set.
参数:count (int) - 要设置的计数。
"""
...
Bases: object
class IdentifierGenerator(object):
"""
Provides a generator for unique ID strings.
提供唯一 ID 字符串的生成器。
Parameters:
参数:
trader_id (TraderId) – The ID tag for the trader.
trader_id (TraderId) - 交易者的 ID 标签。
clock (Clock) – The internal clock.
clock (Clock) - 内部时钟。
"""
def __init__(self, trader_id: TraderId, clock: Clock):
...
Bases: IdentifierGenerator
class OrderListIdGenerator(IdentifierGenerator):
"""
Provides a generator for unique `OrderListId`(s).
提供唯一 `OrderListId` 的生成器。
Parameters:
参数:
trader_id (TraderId) – The trader ID for the generator.
trader_id (TraderId) - 生成器的交易者 ID。
strategy_id (StrategyId) – The strategy ID for the generator.
strategy_id (StrategyId) - 生成器的策略 ID。
clock (Clock) – The clock for the generator.
clock (Clock) - 生成器的时钟。
initial_count (int) – The initial count for the generator.
initial_count (int) - 生成器的初始计数。
Raises: ValueError – If initial_count is negative (< 0).
引发:ValueError - 如果 initial_count 为负数 (< 0)。
"""
def __init__(self, trader_id: TraderId, strategy_id: StrategyId, clock: Clock, initial_count: int = 0):
...
@property
def count(self):
"""
The count of IDs generated.
生成的 ID 计数。
Returns:
int
"""
...
def generate(self) -> OrderListId:
"""
Return a unique order list ID.
返回唯一的订单列表 ID。
Return type: OrderListId
"""
...
def reset(self) -> void:
"""
Reset the ID generator.
重置 ID 生成器。
All stateful fields are reset to their initial value.
所有有状态字段都重置为其初始值。
"""
...
def set_count(self, count: int) -> void:
"""
Set the internal counter to the given count.
将内部计数器设置为给定计数。
Parameters: count (int) – The count to set.
参数:count (int) - 要设置的计数。
"""
...
Bases: IdentifierGenerator
class PositionIdGenerator(IdentifierGenerator):
"""
Provides a generator for unique PositionId(s).
提供唯一 PositionId 的生成器。
Parameters:
参数:
trader_id (TraderId) – The trader ID tag for the generator.
trader_id (TraderId) - 生成器的交易者 ID 标签。
"""
def __init__(self, trader_id: TraderId, clock: Clock):
...
def generate(self, strategy_id: StrategyId, flipped: bool=False) -> PositionId:
"""
Return a unique position ID.
返回唯一的持仓 ID。
Parameters:
参数:
strategy_id (StrategyId) – The strategy ID associated with the position.
strategy_id (StrategyId) - 与持仓关联的策略 ID。
flipped (bool) – If the position is being flipped. If True then the generated id will be appended with ‘F’.
flipped (bool) - 持仓是否正在翻转。如果为 True,则生成的 ID 将附加“F”。
Return type: PositionId
"""
...
def get_count(self, strategy_id: StrategyId) -> int:
"""
Return the internal position count for the given strategy ID.
返回给定策略 ID 的内部持仓计数。
Parameters: strategy_id (StrategyId) – The strategy ID associated with the count.
参数:strategy_id (StrategyId) - 与计数关联的策略 ID。
Return type: int
"""
...
def reset(self) -> void:
"""
Reset the ID generator.
重置 ID 生成器。
All stateful fields are reset to their initial value.
所有有状态字段都重置为其初始值。
"""
...
def set_count(self, strategy_id: StrategyId, count: int) -> void:
"""
Set the internal position count for the given strategy ID.
为给定策略 ID 设置内部持仓计数。
Parameters:
参数:
strategy_id (StrategyId) – The strategy ID associated with the count.
strategy_id (StrategyId) - 与计数关联的策略 ID。
count (int) – The count to set.
count (int) - 要设置的计数。
Raises: ValueError – If count is negative (< 0).
引发:ValueError - 如果 count 为负数 (< 0)。
"""
...
Bases: object
class InstrumentProvider(object):
"""
The base class for all instrument providers.
所有Instrument提供器的基类。
Parameters:
参数:
config (InstrumentProviderConfig , optional) – The instrument provider config.
config (InstrumentProviderConfig,可选) - Instrument提供器配置。
Warning:
This class should not be used directly, but through a concrete subclass.
此类不应直接使用,而应通过具体的子类使用。
"""
def __init__(self, config: InstrumentProviderConfig | None = None):
...
@property
def count(self) -> int:
"""
Return the count of instruments held by the provider.
返回提供器持有的Instrument数量。
Return type: int
"""
...
async def load_all_async(self, filters: dict | None = None) -> None:
"""
Load the latest instruments into the provider asynchronously, optionally applying the given filters.
异步加载最新的Instrument到提供器中,可以选择应用给定的过滤器。
"""
...
async def load_ids_async(self, instrument_ids: list[InstrumentId], filters: dict | None = None) -> None:
"""
Load the instruments for the given IDs into the provider, optionally applying the given filters.
加载给定 ID 的Instrument到提供器中,可以选择应用给定的过滤器。
Parameters:
参数:
instrument_ids (list [InstrumentId ]) – The instrument IDs to load.
instrument_ids (list [InstrumentId ]) - 要加载的Instrument ID。
filters (frozendict *[*str , Any ] or dict *[*str , Any ] , optional) – The venue specific instrument loading filters to apply.
filters (frozendict *[*str,Any] 或 dict *[*str,Any],可选) - 要应用的特定场所的Instrument加载过滤器。
Raises: ValueError – If any instrument_id.venue is not equal to self.venue.
引发:ValueError - 如果任何 instrument_id.venue 不等于 self.venue。
"""
...
async def load_async(self, instrument_id: InstrumentId, filters: dict | None = None) -> None:
"""
Load the instrument for the given ID into the provider asynchronously, optionally applying the given filters.
异步加载给定 ID 的Instrument到提供器中,可以选择应用给定的过滤器。
Parameters:
参数:
instrument_id (InstrumentId) – The instrument ID to load.
instrument_id (InstrumentId) - 要加载的Instrument ID。
filters (frozendict *[*str , Any ] or dict *[*str , Any ] , optional) – The venue specific instrument loading filters to apply.
filters (frozendict *[*str,Any] 或 dict *[*str,Any],可选) - 要应用的特定场所的Instrument加载过滤器。
Raises: ValueError – If instrument_id.venue is not equal to self.venue.
引发:ValueError - 如果 instrument_id.venue 不等于 self.venue。
"""
...
async def initialize(self) -> None:
"""
Initialize the instrument provider.
初始化Instrument提供器。
If initialize() then will immediately return.
如果 initialize(),则将立即返回。
"""
...
def load_all(self, filters: dict | None = None) -> None:
"""
Load the latest instruments into the provider, optionally applying the given filters.
加载最新的Instrument到提供器中,可以选择应用给定的过滤器。
Parameters: filters (frozendict *[*str , Any ] or dict *[*str , Any ] , optional) – The venue specific instrument loading filters to apply.
参数:filters (frozendict *[*str,Any] 或 dict *[*str,Any],可选) - 要应用的特定场所的Instrument加载过滤器。
"""
...
def load_ids(self, instrument_ids: list[InstrumentId], filters: dict | None = None) -> None:
"""
Load the instruments for the given IDs into the provider, optionally applying the given filters.
加载给定 ID 的Instrument到提供器中,可以选择应用给定的过滤器。
Parameters:
参数:
instrument_ids (list [InstrumentId ]) – The instrument IDs to load.
instrument_ids (list [InstrumentId ]) - 要加载的Instrument ID。
filters (frozendict *[*str , Any ] or dict *[*str , Any ] , optional) – The venue specific instrument loading filters to apply.
filters (frozendict *[*str,Any] 或 dict *[*str,Any],可选) - 要应用的特定场所的Instrument加载过滤器。
"""
...
def load(self, instrument_id: InstrumentId, filters: dict | None = None) -> None:
"""
Load the instrument for the given ID into the provider, optionally applying the given filters.
加载给定 ID 的Instrument到提供器中,可以选择应用给定的过滤器。
Parameters:
参数:
instrument_id (InstrumentId) – The instrument ID to load.
instrument_id (InstrumentId) - 要加载的Instrument ID。
filters (frozendict *[*str , Any ] or dict *[*str , Any ] , optional) – The venue specific instrument loading filters to apply.
filters (frozendict *[*str,Any] 或 dict *[*str,Any],可选) - 要应用的特定场所的Instrument加载过滤器。
"""
...
def add_currency(self, currency: Currency) -> None:
"""
Add the given currency to the provider.
将给定的货币添加到提供器。
Parameters: currency (Currency) – The currency to add.
参数:currency (Currency) - 要添加的货币。
"""
...
def add(self, instrument: Instrument) -> None:
"""
Add the given instrument to the provider.
将给定的Instrument添加到提供器。
Parameters: instrument (Instrument) – The instrument to add.
参数:instrument (Instrument) - 要添加的Instrument。
"""
...
def add_bulk(self, instruments: list[Instrument]) -> None:
"""
Add the given instruments bulk to the provider.
将给定的Instrument批量添加到提供器。
Parameters: instruments (list [Instrument ]) – The instruments to add.
参数:instruments (list [Instrument ]) - 要添加的Instrument。
"""
...
def list_all(self) -> list[Instrument]:
"""
Return all loaded instruments.
返回所有已加载的Instrument。
Return type: list[Instrument]
"""
...
def get_all(self) -> dict[InstrumentId, Instrument]:
"""
Return all loaded instruments as a map keyed by instrument ID.
返回所有已加载的Instrument,以Instrument ID 为键的映射。
If no instruments loaded, will return an empty dict.
如果没有加载Instrument,则返回一个空字典。
Return type: dict[InstrumentId, Instrument]
"""
...
def currencies(self) -> dict[str, Currency]:
"""
Return all currencies held by the instrument provider.
返回Instrument提供器持有的所有货币。
Return type: dict[str, Currency]
"""
...
def currency(self, code: str):
"""
Return the currency with the given code (if found).
返回具有给定代码的货币(如果找到)。
Parameters: code (str) – The currency code.
参数:code (str) - 货币代码。
Return type: Currency or None
Raises: ValueError – If code is not a valid string.
引发:ValueError - 如果 code 不是有效的字符串。
"""
...
def find(self, instrument_id: InstrumentId):
"""
Return the instrument for the given instrument ID (if found).
返回给定Instrument ID 的Instrument(如果找到)。
Parameters: instrument_id (InstrumentId) – The ID for the instrument
参数:instrument_id (InstrumentId) - Instrument的 ID。
Return type: Instrument or None
"""
...