Strategies - Loren1166/NautilusTrader- GitHub Wiki
Strategies
策略
The heart of the NautilusTrader user experience is in writing and working with trading strategies. Defining a trading strategy is achieved by inheriting the Strategy class, and implementing the methods required by the users trading strategy logic.
NautilusTrader用户体验的核心在于编写和使用交易策略。定义交易策略通过继承 Strategy
类并实现用户交易策略逻辑所需的方法来完成。
Strategies can be added to Nautilus systems with any environment context and will start sending commands and receiving events based on their logic as soon as the system starts.
策略可以在任何环境上下文中添加到Nautilus系统,并在系统启动后根据它们的逻辑开始发送命令和接收事件。
Using the basic building blocks of data ingest, event handling, and order management (which we will discuss below), it's possible to implement any type of trading strategy including directional, momentum, re-balancing, pairs, market making etc.
通过使用数据摄取、事件处理和订单管理的基本构建模块(我们将在下面讨论),可以实现任何类型的交易策略,包括方向性、动量、再平衡、对冲、做市等策略。
info
See the Strategy API Reference for a complete description of all available methods.
查看 Strategy API
参考文档,获取所有可用方法的完整描述。
There are two main parts of a Nautilus trading strategy:
Nautilus交易策略主要由两部分组成:
- The strategy implementation itself, defined by inheriting the Strategy class
策略实现本身,通过继承Strategy
类定义 - The optional strategy configuration, defined by inheriting the StrategyConfig class
可选的策略配置,通过继承StrategyConfig
类定义
tip
Once a strategy is defined, the same source can be used for backtesting and live trading.
策略一旦定义,相同的源码可用于回测和实盘交易。
The main capabilities of a strategy include:
策略的主要功能包括:
- Historical data requests
历史数据请求 - Live data feed subscriptions
实时数据订阅 - Setting time alerts or timers
设置时间提醒或定时器 - Cache access
缓存访问 - Portfolio access
组合访问 - Creating and managing orders and positions
创建和管理订单及仓位
Strategy implementation
策略实现
Since a trading strategy is a class which inherits from Strategy
, you must define a constructor where you can handle initialization. Minimally the base/super class needs to be initialized:
由于交易策略是继承自 Strategy
的类,因此你必须定义一个构造函数来处理初始化。最小化的要求是初始化基类/父类:
from nautilus_trader.trading.strategy import Strategy
class MyStrategy(Strategy):
def __init__(self) -> None:
super().__init__() # <-- the super class must be called to initialize the strategy
From here, you can implement handlers as necessary to perform actions based on state transitions and events.
从这里开始,你可以根据需要实现处理程序,以根据状态转换和事件执行操作。
warning
Do not call components such as clock and logger in the __init__
constructor (which is prior to registration). This is because the systems clock and logging system have not yet been initialized.
不要在 __init__
构造函数中调用诸如时钟和日志记录器等组件(此时尚未注册)。这是因为系统时钟和日志记录系统尚未初始化。
Handlers
处理程序
Handlers are methods within the Strategy
class which may perform actions based on different types of events or on state changes. These methods are named with the prefix on_*
. You can choose to implement any or all of these handler methods depending on the specific goals and needs of your strategy.
处理程序是 Strategy
类中的方法,可能会根据不同类型的事件或状态变化执行操作。这些方法以 on_*
为前缀命名。你可以根据策略的特定目标和需求选择实现任意或全部的处理程序方法。
The purpose of having multiple handlers for similar types of events is to provide flexibility in handling granularity. This means that you can choose to respond to specific events with a dedicated handler, or use a more generic handler to react to a range of related events (using typical switch statement logic). The handlers are called in sequence from the most specific to the most general.
为类似类型的事件提供多个处理程序的目的是在处理粒度上提供灵活性。这意味着你可以选择使用专用的处理程序响应特定事件,或者使用更通用的处理程序对一系列相关事件做出反应(使用典型的开关语句逻辑)。处理程序按从最具体到最通用的顺序被调用。
Stateful actions
状态行为 These handlers are triggered by lifecycle state changes of the Strategy. It's recommended to: 这些处理程序是由策略的生命周期状态变化触发的。建议使用:
- Use the on_start method to initialize your strategy (e.g., fetch instruments, subscribe to data)
- 使用
on_start
方法初始化策略(例如,获取Instrument、订阅数据) - Use the on_stop method for cleanup tasks (e.g., cancel open orders, close open positions, unsubscribe from data)
- 使用
on_stop
方法进行清理任务(例如,取消未完成的订单,关闭未平仓位,退订数据)
def on_start(self) -> None:
def on_stop(self) -> None:
def on_resume(self) -> None:
def on_reset(self) -> None:
def on_dispose(self) -> None:
def on_degrade(self) -> None:
def on_fault(self) -> None:
def on_save(self) -> dict[str, bytes]: # Returns user-defined dictionary of state to be saved
def on_load(self, state: dict[str, bytes]) -> None:
Data handling
数据处理 These handlers receive data updates, including built-in market data and custom user-defined data. You can use these handlers to define actions upon receiving data object instances. 这些处理程序接收数据更新,包括内置市场数据和用户自定义数据。可以使用这些处理程序在接收到数据对象实例时定义操作。
from nautilus_trader.core.data import Data
from nautilus_trader.model.book import OrderBook
from nautilus_trader.model.data import Bar
from nautilus_trader.model.data import QuoteTick
from nautilus_trader.model.data import TradeTick
from nautilus_trader.model.data import OrderBookDeltas
from nautilus_trader.model.data import InstrumentClose
from nautilus_trader.model.data import InstrumentStatus
from nautilus_trader.model.instruments import Instrument
def on_order_book_deltas(self, deltas: OrderBookDeltas) -> None:
def on_order_book(self, order_book: OrderBook) -> None:
def on_quote_tick(self, tick: QuoteTick) -> None:
def on_trade_tick(self, tick: TradeTick) -> None:
def on_bar(self, bar: Bar) -> None:
def on_instrument(self, instrument: Instrument) -> None:
def on_instrument_status(self, data: InstrumentStatus) -> None:
def on_instrument_close(self, data: InstrumentClose) -> None:
def on_historical_data(self, data: Data) -> None:
def on_data(self, data: Data) -> None: # Custom data passed to this handler
Order management
订单管理 These handlers receive events related to orders. OrderEvent type messages are passed to handlers in the following sequence: 这些处理程序接收与订单相关的事件。OrderEvent 类型消息以以下顺序传递给处理程序:
- Specific handler (e.g., on_order_accepted, on_order_rejected, etc.)
- 特定处理程序(例如,
on_order_accepted
、on_order_rejected
等) - on_order_event(...)
- on_event(...)
from nautilus_trader.model.events import OrderAccepted
from nautilus_trader.model.events import OrderCanceled
from nautilus_trader.model.events import OrderCancelRejected
from nautilus_trader.model.events import OrderDenied
from nautilus_trader.model.events import OrderEmulated
from nautilus_trader.model.events import OrderEvent
from nautilus_trader.model.events import OrderExpired
from nautilus_trader.model.events import OrderFilled
from nautilus_trader.model.events import OrderInitialized
from nautilus_trader.model.events import OrderModifyRejected
from nautilus_trader.model.events import OrderPendingCancel
from nautilus_trader.model.events import OrderPendingUpdate
from nautilus_trader.model.events import OrderRejected
from nautilus_trader.model.events import OrderReleased
from nautilus_trader.model.events import OrderSubmitted
from nautilus_trader.model.events import OrderTriggered
from nautilus_trader.model.events import OrderUpdated
def on_order_initialized(self, event: OrderInitialized) -> None:
def on_order_denied(self, event: OrderDenied) -> None:
def on_order_emulated(self, event: OrderEmulated) -> None:
def on_order_released(self, event: OrderReleased) -> None:
def on_order_submitted(self, event: OrderSubmitted) -> None:
def on_order_rejected(self, event: OrderRejected) -> None:
def on_order_accepted(self, event: OrderAccepted) -> None:
def on_order_canceled(self, event: OrderCanceled) -> None:
def on_order_expired(self, event: OrderExpired) -> None:
def on_order_triggered(self, event: OrderTriggered) -> None:
def on_order_pending_update(self, event: OrderPendingUpdate) -> None:
def on_order_pending_cancel(self, event: OrderPendingCancel) -> None:
def on_order_modify_rejected(self, event: OrderModifyRejected) -> None:
def on_order_cancel_rejected(self, event: OrderCancelRejected) -> None:
def on_order_updated(self, event: OrderUpdated) -> None:
def on_order_filled(self, event: OrderFilled) -> None:
def on_order_event(self, event: OrderEvent) -> None: # All order event messages are eventually passed to this handler
Position management
持仓管理 These handlers receive events related to positions. PositionEvent type messages are passed to handlers in the following sequence: 这些处理程序接收与持仓相关的事件。PositionEvent 类型消息以以下顺序传递给处理程序:
- Specific handler (e.g., on_position_opened, on_position_changed, etc.)
- 特定处理程序(例如,
on_position_opened
、on_position_changed
等) - on_position_event(...)
- on_event(...)
from nautilus_trader.model.events import PositionChanged
from nautilus_trader.model.events import PositionClosed
from nautilus_trader.model.events import PositionEvent
from nautilus_trader.model.events import PositionOpened
def on_position_opened(self, event: PositionOpened) -> None:
def on_position_changed(self, event: PositionChanged) -> None:
def on_position_closed(self, event: PositionClosed) -> None:
def on_position_event(self, event: PositionEvent) -> None: # All position event messages are eventually passed to this handler
Generic event handling
通用事件处理 This handler will eventually receive all event messages which arrive at the strategy, including those for which no other specific handler exists. 此处理程序最终将接收到所有到达策略的事件消息,包括没有其他特定处理程序的消息。
from nautilus_trader.core.message import Event
def on_event(self, event: Event) -> None:
Handler example
处理程序示例
The following example shows a typical on_start handler method implementation (taken from the example EMA cross strategy). Here we can see the following:
以下示例展示了典型的 on_start
处理程序方法的实现(取自示例 EMA 交叉策略)。我们可以看到以下内容:
- Indicators being registered to receive bar updates
- 注册指标以接收K线更新
- Historical data being requested (to hydrate the indicators)
- 请求历史数据(以便填充指标)
- Live data being subscribed to
- 订阅实时数据
def on_start(self) -> None:
"""
Actions to be performed on strategy start.
在策略开始时执行的操作。
"""
self.instrument = self.cache.instrument(self.instrument_id)
if self.instrument is None:
self.log.error(f"Could not find instrument for {self.instrument_id}")
self.stop()
return
# Register the indicators for updating
# 注册指标以进行更新
self.register_indicator_for_bars(self.bar_type, self.fast_ema)
self.register_indicator_for_bars(self.bar_type, self.slow_ema)
# Get historical data
# 获取历史数据
self.request_bars(self.bar_type)
# Subscribe to live data
# 订阅实时数据
self.subscribe_bars(self.bar_type)
self.subscribe_quote_ticks(self.instrument_id)
Clock and timers
时钟和计时器 Strategies have access to a Clock which provides a number of methods for creating different timestamps, as well as setting time alerts or timers to trigger TimeEvents. 策略可以访问一个时钟,该时钟提供多种方法来创建不同的时间戳,以及设置时间警报或计时器以触发时间事件。
info
See the Clock API reference for a complete list of available methods.
信息
有关可用方法的完整列表,请参阅时钟 API 参考。
Current timestamps
当前时间戳 While there are multiple ways to obtain current timestamps, here are two commonly used methods as examples: 虽然有多种方法可以获取当前时间戳,以下是两种常用方法的示例:
To get the current UTC timestamp as a tz-aware pd.Timestamp:
获取当前 UTC 时间戳作为时区感知的 pd.Timestamp
:
import pandas as pd
now: pd.Timestamp = self.clock.utc_now()
To get the current UTC timestamp as nanoseconds since the UNIX epoch: 获取当前 UTC 时间戳作为自 UNIX 纪元以来的纳秒:
unix_nanos: int = self.clock.timestamp_ns()
Time alerts
时间提醒 Time alerts can be set which will result in a TimeEvent being dispatched to the on_event handler at the specified alert time. In a live context, this might be slightly delayed by a few microseconds. 可以设置时间提醒,这将导致在指定的提醒时间将 TimeEvent 发送到 on_event 处理程序。在实时环境中,这可能会延迟几微秒。
This example sets a time alert to trigger one minute from the current time: 此示例设置一个时间提醒,在当前时间的一分钟后触发:
self.clock.set_time_alert(
name="MyTimeAlert1",
alert_time=self.clock.utc_now() + pd.Timedelta(minutes=1),
)
Timers
计时器 Continuous timers can be set up which will generate a TimeEvent at regular intervals until the timer expires or is canceled. 可以设置连续计时器,这将在定期间隔生成 TimeEvent,直到计时器过期或被取消。
This example sets a timer to fire once per minute, starting immediately: 此示例设置一个计时器,立即开始每分钟触发一次:
self.clock.set_timer(
name="MyTimer1",
interval=pd.Timedelta(minutes=1),
)
Cache access
缓存访问 The trader instances central Cache can be accessed to fetch data and execution objects (orders, positions etc). There are many methods available often with filtering functionality, here we go through some basic use cases. 交易者实例的中央缓存可以访问,以获取数据和执行对象(订单、头寸等)。有许多可用的方法,通常具有过滤功能,下面我们将介绍一些基本用例。
Fetching data
获取数据 The following example shows how data can be fetched from the cache (assuming some instrument ID attribute is assigned): 以下示例展示了如何从缓存中获取数据(假设分配了一些Instrument ID 属性):
last_quote = self.cache.quote_tick(self.instrument_id)
last_trade = self.cache.trade_tick(self.instrument_id)
last_bar = self.cache.bar(bar_type)
Fetching execution objects
获取执行对象 The following example shows how individual order and position objects can be fetched from the cache: 以下示例展示了如何从缓存中获取单独的订单和头寸对象:
order = self.cache.order(client_order_id)
position = self.cache.position(position_id)
info
信息 See the Cache API Reference for a complete description of all available methods. 请参阅缓存 API 参考,以获取所有可用方法的完整描述。
Portfolio access
投资组合访问 The traders central Portfolio can be accessed to fetch account and positional information. The following shows a general outline of available methods. 交易者的中央投资组合可以访问,以获取账户和头寸信息。以下是可用方法的一般概述。
Account and positional information
账户和头寸信息
import decimal
from nautilus_trader.model.identifiers import Venue
from nautilus_trader.accounting.accounts.base import Account
from nautilus_trader.model.objects import Currency
from nautilus_trader.model.objects import Money
from nautilus_trader.model.identifiers import InstrumentId
def account(self, venue: Venue) -> Account
def balances_locked(self, venue: Venue) -> dict[Currency, Money]
def margins_init(self, venue: Venue) -> dict[Currency, Money]
def margins_maint(self, venue: Venue) -> dict[Currency, Money]
def unrealized_pnls(self, venue: Venue) -> dict[Currency, Money]
def net_exposures(self, venue: Venue) -> dict[Currency, Money]
def unrealized_pnl(self, instrument_id: InstrumentId) -> Money
def net_exposure(self, instrument_id: InstrumentId) -> Money
def net_position(self, instrument_id: InstrumentId) -> decimal.Decimal
def is_net_long(self, instrument_id: InstrumentId) -> bool
def is_net_short(self, instrument_id: InstrumentId) -> bool
def is_flat(self, instrument_id: InstrumentId) -> bool
def is_completely_flat(self) -> bool
info
信息 See the Portfolio API Reference for a complete description of all available methods. 请参阅投资组合 API 参考,以获取所有可用方法的完整描述。
Reports and analysis
报告和分析 The Portfolio also makes a PortfolioAnalyzer available, which can be fed with a flexible amount of data (to accommodate different lookback windows). The analyzer can provide tracking for and generating of performance metrics and statistics. 投资组合还提供了一个 PortfolioAnalyzer,可以输入灵活数量的数据(以适应不同的回溯窗口)。分析器可以提供性能指标和统计数据的跟踪和生成。
info
信息 See the PortfolioAnalyzer API Reference for a complete description of all available methods. 请参阅 PortfolioAnalyzer API 参考,以获取所有可用方法的完整描述。
info
信息 See the Portfolio statistics guide. 请参阅投资组合统计指南。
Trading commands
交易命令 NautilusTrader offers a comprehensive suite of trading commands, enabling granular order management tailored for algorithmic trading. These commands are essential for executing strategies, managing risk, and ensuring seamless interaction with various trading venues. In the following sections, we will delve into the specifics of each command and its use cases. NautilusTrader 提供了一整套全面的交易命令,使得针对算法交易的细粒度订单管理成为可能。这些命令对于执行策略、管理风险以及确保与各种交易平台的无缝互动至关重要。在接下来的章节中,我们将深入探讨每个命令的具体内容及其用例。
info
信息 The Execution guide explains the flow through the system, and can be helpful to read in conjunction with the below. 执行指南解释了系统的流程,可以与下面的内容一起阅读。
Submitting orders
提交订单 An OrderFactory is provided on the base class for every Strategy as a convenience, reducing the amount of boilerplate required to create different Order objects (although these objects can still be initialized directly with the Order.init(...) constructor if the trader prefers). 每个策略的基类提供了一个 OrderFactory,作为一种便利,减少了创建不同订单对象所需的样板代码(尽管如果交易者愿意,这些对象仍然可以直接使用 Order.init(...) 构造函数进行初始化)。
The component a SubmitOrder or SubmitOrderList command will flow to for execution depends on the following: SubmitOrder 或 SubmitOrderList 命令流向的组件取决于以下内容:
- If an emulation_trigger is specified, the command will firstly be sent to the OrderEmulator 如果指定了 emulation_trigger,命令将首先发送到 OrderEmulator。
- If an exec_algorithm_id is specified (with no emulation_trigger), the command will firstly be sent to the relevant ExecAlgorithm 如果指定了 exec_algorithm_id(没有 emulation_trigger),命令将首先发送到相关的 ExecAlgorithm。
- Otherwise, the command will firstly be sent to the RiskEngine 否则,命令将首先发送到 RiskEngine。
This example submits a LIMIT BUY order for emulation (see OrderEmulator): 此示例提交一个用于模拟的 LIMIT BUY 订单(见 OrderEmulator):
from nautilus_trader.model.enums import OrderSide
from nautilus_trader.model.enums import TriggerType
from nautilus_trader.model.orders import LimitOrder
def buy(self) -> None:
"""
Users simple buy method (example).
用户简单的买入方法(示例)。
"""
order: LimitOrder = self.order_factory.limit(
instrument_id=self.instrument_id,
order_side=OrderSide.BUY,
quantity=self.instrument.make_qty(self.trade_size),
price=self.instrument.make_price(5000.00),
emulation_trigger=TriggerType.LAST_TRADE,
)
self.submit_order(order)
info
信息 You can specify both order emulation and an execution algorithm. 您可以同时指定订单模拟和执行算法。
This example submits a MARKET BUY order to a TWAP execution algorithm: 此示例提交一个 MARKET BUY 订单给 TWAP 执行算法:
from nautilus_trader.model.enums import OrderSide
from nautilus_trader.model.enums import TimeInForce
from nautilus_trader.model.identifiers import ExecAlgorithmId
def buy(self) -> None:
"""
Users simple buy method (example).
用户简单的买入方法(示例)。
"""
order: MarketOrder = self.order_factory.market(
instrument_id=self.instrument_id,
order_side=OrderSide.BUY,
quantity=self.instrument.make_qty(self.trade_size),
time_in_force=TimeInForce.FOK,
exec_algorithm_id=ExecAlgorithmId("TWAP"),
exec_algorithm_params={"horizon_secs": 20, "interval_secs": 2.5},
)
self.submit_order(order)
Canceling orders
取消订单 Orders can be canceled individually, as a batch, or all orders for an instrument (with an optional side filter). 可以单独取消订单、批量取消订单,或者取消某个Instrument的所有订单(可选的侧面过滤)。
If the order is already closed or already pending cancel, then a warning will be logged. 如果订单已经关闭或已经待取消,则会记录警告。
If the order is currently open then the status will become PENDING_CANCEL. 如果订单当前是开放状态,则状态将变为 PENDING_CANCEL。
The component a CancelOrder, CancelAllOrders or BatchCancelOrders command will flow to for execution depends on the following: CancelOrder、CancelAllOrders 或 BatchCancelOrders 命令流向的组件取决于以下内容:
- If the order is currently emulated, the command will firstly be sent to the OrderEmulator 如果订单当前被模拟,命令将首先发送到 OrderEmulator。
- If an exec_algorithm_id is specified (with no emulation_trigger), and the order is still active within the local system, the command will firstly be sent to the relevant ExecAlgorithm 如果指定了 exec_algorithm_id(没有 emulation_trigger),并且订单仍在本地系统中有效,命令将首先发送到相关的 ExecAlgorithm。
- Otherwise, the order will firstly be sent to the ExecutionEngine 否则,订单将首先发送到 ExecutionEngine。
info
信息 Any managed GTD timer will also be canceled after the command has left the strategy. 任何管理的 GTD 计时器在命令离开策略后也将被取消。
The following shows how to cancel an individual order: 以下示例展示了如何取消单个订单:
self.cancel_order(order)
The following shows how to cancel a batch of orders: 以下示例展示了如何取消一批订单:
from nautilus_trader.model import Order
my_order_list: list[Order] = [order1, order2, order3]
self.cancel_orders(my_order_list)
The following shows how to cancel all orders: 以下示例展示了如何取消所有订单:
self.cancel_all_orders()
Modifying orders
修改订单 Orders can be modified individually when emulated, or open on a venue (if supported). 订单可以在被模拟时或在交易平台(如果支持)时单独修改。
If the order is already closed or already pending cancel, then a warning will be logged. If the order is currently open then the status will become PENDING_UPDATE. 如果订单已经关闭或已经待取消,则会记录警告。如果订单当前是开放状态,则状态将变为 PENDING_UPDATE。
warning
警告 At least one value must differ from the original order for the command to be valid. 命令必须至少有一个值与原始订单不同才能有效。
The component a ModifyOrder command will flow to for execution depends on the following: ModifyOrder 命令流向的组件取决于以下内容:
- If the order is currently emulated, the command will firstly be sent to the OrderEmulator 如果订单当前被模拟,命令将首先发送到 OrderEmulator。
- Otherwise, the order will firstly be sent to the RiskEngine 否则,订单将首先发送到 RiskEngine。
info
信息 Once an order is under the control of an execution algorithm, it cannot be directly modified by a strategy (only canceled). 一旦订单受到执行算法的控制,就不能被策略直接修改(只能取消)。
The following shows how to modify the size of LIMIT BUY order currently open on a venue: 以下示例展示了如何修改在交易平台当前开放的 LIMIT BUY 订单的大小:
from nautilus_trader.model import Quantity
new_quantity: Quantity = Quantity.from_int(5)
self.modify_order(order, new_quantity)
info
信息 The price and trigger price can also be modified (when emulated or supported by a venue). 价格和触发价格也可以修改(当被模拟或交易平台支持时)。
Strategy configuration
策略配置 The main purpose of a separate configuration class is to provide total flexibility over where and how a trading strategy can be instantiated. This includes being able to serialize strategies and their configurations over the wire, making distributed backtesting and firing up remote live trading possible. 单独配置类的主要目的是提供在何处以及如何实例化交易策略的完全灵活性。这包括能够通过网络序列化策略及其配置,使分布式回测和启动远程实盘交易成为可能。
This configuration flexibility is actually opt-in, in that you can actually choose not to have any strategy configuration beyond the parameters you choose to pass into your strategies' constructor. If you would like to run distributed backtests or launch live trading servers remotely, then you will need to define a configuration. 这种配置灵活性实际上是选择性的,您可以选择不使用任何策略配置,只需传递您选择的参数到策略构造函数中。如果您想运行分布式回测或远程启动实盘交易服务器,那么您需要定义一个配置。
Here is an example configuration: 以下是一个配置示例:
from decimal import Decimal
from nautilus_trader.config import StrategyConfig
from nautilus_trader.model.data import BarType
from nautilus_trader.model.identifiers import InstrumentId
from nautilus_trader.trading.strategy import Strategy
class MyStrategyConfig(StrategyConfig):
instrument_id: InstrumentId
bar_type: BarType
fast_ema_period: int = 10
slow_ema_period: int = 20
trade_size: Decimal
order_id_tag: str
note
备注 Even though it often makes sense to define a strategy which will trade a single instrument. The number of instruments a single strategy can work with is only limited by machine resources. 即使通常定义一个交易单一Instrument的策略是合理的,但单一策略可以处理的Instrument数量仅受机器资源的限制。
Managed GTD expiry
管理 GTD 过期 It's possible for the strategy to manage expiry for orders with a time in force of GTD (Good 'till Date). This may be desirable if the exchange/broker does not support this time in force option, or for any reason you prefer the strategy to manage this. 策略可以管理具有 GTD(有效至日期)时间限制的订单的过期。如果交易所/经纪商不支持此时间限制选项,或者您希望策略管理此选项,这可能是可取的。
To use this option, pass manage_gtd_expiry=True to your StrategyConfig. When an order is submitted with a time in force of GTD, the strategy will automatically start an internal time alert. Once the internal GTD time alert is reached, the order will be canceled (if not already closed). 要使用此选项,请将 manage_gtd_expiry=True 传递给您的 StrategyConfig。当以 GTD 的时间限制提交订单时,策略将自动启动内部时间提醒。一旦达到内部 GTD 时间提醒,订单将被取消(如果尚未关闭)。
Some venues (such as Binance Futures) support the GTD time in force, so to avoid conflicts when using managed_gtd_expiry you should set use_gtd=False for your execution client config. 一些交易平台(如 Binance Futures)支持 GTD 时间限制,因此在使用 managed_gtd_expiry 时,应将 use_gtd=False 设置为您的执行客户端配置。
Multiple strategies
多个策略 If you intend running multiple instances of the same strategy, with different configurations (such as trading different instruments), then you will need to define a unique order_id_tag for each of these strategies (as shown above). 如果您打算运行相同策略的多个实例,具有不同的配置(例如交易不同的Instrument),则需要为每个策略定义一个唯一的 order_id_tag(如上所示)。
note
备注 The platform has built-in safety measures in the event that two strategies share a duplicated strategy ID, then an exception will be raised that the strategy ID has already been registered. 如果两个策略共享重复的策略 ID,平台具有内置的安全措施,那么将引发异常,指出策略 ID 已经注册。
The reason for this is that the system must be able to identify which strategy various commands and events belong to. A strategy ID is made up of the strategy class name, and the strategies order_id_tag separated by a hyphen. For example the above config would result in a strategy ID of MyStrategy-001. 这样做的原因是系统必须能够识别各种命令和事件属于哪个策略。策略 ID 由策略类名称和策略的 order_id_tag 组成,用连字符分隔。例如,上面的配置将生成 MyStrategy-001 的策略 ID。
note
备注 See the StrategyId API Reference for further details. 请参阅 StrategyId API 参考以获取更多详细信息。
Previous
之前 Architecture 架构
Next
下一个 Instruments Instrument
Strategy implementation
策略实现
Handlers
处理程序
Clock and timers
时钟和计时器
Cache access
缓存访问
Portfolio access
投资组合访问
Trading commands
交易命令
Strategy configuration
策略配置
Managed GTD expiry
管理 GTD 过期
Multiple strategies
多个策略
© 2024 Nautech Systems Pty Ltd. All rights reserved. © 2024 Nautech Systems Pty Ltd. 版权所有。