Skip to content

Adapters3

Loren1166 edited this page Sep 25, 2024 · 4 revisions

Adapters 适配器

Introduction 简介

This developer guide provides instructions on how to develop an integration adapter for the NautilusTrader platform. Adapters provide connectivity to trading venues and data providers - converting their raw API into a unified interface.
本开发者指南提供了有关如何为 NautilusTrader 平台开发集成适配器的说明。适配器提供与交易场所和数据提供者的连接 - 将它们的原始 API 转换为统一接口。

Structure of an adapter 适配器的结构

An adapter typically consists of several components:
适配器通常由以下几个组件组成:

  • Instrument Provider: Supplies instrument definitions
    金融工具提供者:提供金融工具定义
  • Data Client: Handles live market data feeds and historical data requests
    数据客户端:处理实时市场数据源和历史数据请求
  • Execution Client: Handles order execution and management
    执行客户端:处理订单执行和管理
  • Configuration: Configures the client settings
    配置:配置客户端设置

Adapter implementation steps 适配器实现步骤

  1. Create a new Python subpackage for your adapter
    创建一个新的 Python 子包用于您的适配器
  2. Implement the Instrument Provider by inheriting from InstrumentProvider and implementing the necessary methods to load instruments
    通过继承 InstrumentProvider 并实现加载金融工具所需的方法来实现金融工具提供者
  3. Implement the Data Client by inheriting from either the LiveDataClient and LiveMarketDataClient class as applicable, providing implementations for the required methods
    通过继承 LiveDataClient 和 LiveMarketDataClient 类(如果适用)并为所需方法提供实现来实现数据客户端
  4. Implement the Execution Client by inheriting from LiveExecutionClient and providing implementations for the required methods
    通过继承 LiveExecutionClient 并为所需方法提供实现来实现执行客户端
  5. Create configuration classes to hold your adapter’s settings
    创建配置类来保存适配器的设置
  6. Test your adapter thoroughly to ensure all methods are correctly implemented and the adapter works as expected
    彻底测试您的适配器,以确保所有方法都已正确实施并且适配器按预期工作

Template for building an adapter 构建适配器的模板

Below is a step-by-step guide to building an adapter for a new data provider using the provided template.
以下是一个使用提供的模板构建新数据提供者适配器的分步指南。

InstrumentProvider 金融工具提供者

The InstrumentProvider supplies instrument definitions available on the venue. This includes loading all available instruments, specific instruments by ID, and applying filters to the instrument list.
金融工具提供者提供交易场所可用的金融工具定义。这包括加载所有可用金融工具、按 ID 加载特定金融工具以及对金融工具列表应用过滤器。

from nautilus_trader.common.providers import InstrumentProvider
from nautilus_trader.model.identifiers import InstrumentId

class TemplateInstrumentProvider(InstrumentProvider):
    """
    An example template of an ``InstrumentProvider`` showing the minimal methods which must be implemented for an integration to be complete.
    一个 ``InstrumentProvider`` 的示例模板,展示了集成完成所需实现的最小方法。
    """

    async def load_all_async(self, filters: dict | None = None) -> None:
        raise NotImplementedError("method `load_all_async` must be implemented in the subclass")

    async def load_ids_async(self, instrument_ids: list[InstrumentId], filters: dict | None = None) -> None:
        raise NotImplementedError("method `load_ids_async` must be implemented in the subclass")

    async def load_async(self, instrument_id: InstrumentId, filters: dict | None = None) -> None:
        raise NotImplementedError("method `load_async` must be implemented in the subclass")

Key Methods:
关键方法:

  • load_all_async: Loads all instruments asynchronously, optionally applying filters
    load_all_async: 异步加载所有金融工具,可以选择应用过滤器
  • load_ids_async: Loads specific instruments by their IDs
    load_ids_async: 按 ID 加载特定金融工具
  • load_async: Loads a single instrument by its ID
    load_async: 按 ID 加载单个金融工具

DataClient 数据客户端

The LiveDataClient handles the subscription and management of data feeds that are not specifically related to market data. This might include news feeds, custom data streams, or other data sources that enhance trading strategies but do not directly represent market activity.
LiveDataClient 处理与市场数据没有特别关系的数据源的订阅和管理。这可能包括新闻源、自定义数据流或其他增强交易策略但并不直接代表市场活动的数据源。

from nautilus_trader.live.data_client import LiveDataClient
from nautilus_trader.model.data import DataType
from nautilus_trader.core.uuid import UUID4

class TemplateLiveDataClient(LiveDataClient):
    """
    An example of a ``LiveDataClient`` highlighting the overridable abstract methods.
    一个 ``LiveDataClient`` 的示例,突出显示了可覆盖的抽象方法。
    """

    async def _connect(self) -> None:
        raise NotImplementedError("method `_connect` must be implemented in the subclass")

    async def _disconnect(self) -> None:
        raise NotImplementedError("method `_disconnect` must be implemented in the subclass")

    def reset(self) -> None:
        raise NotImplementedError("method `reset` must be implemented in the subclass")

    def dispose(self) -> None:
        raise NotImplementedError("method `dispose` must be implemented in the subclass")

    async def _subscribe(self, data_type: DataType) -> None:
        raise NotImplementedError("method `_subscribe` must be implemented in the subclass")

    async def _unsubscribe(self, data_type: DataType) -> None:
        raise NotImplementedError("method `_unsubscribe` must be implemented in the subclass")

    async def _request(self, data_type: DataType, correlation_id: UUID4) -> None:
        raise NotImplementedError("method `_request` must be implemented in the subclass")

Key Methods:
关键方法:

  • _connect: Establishes a connection to the data provider
    _connect: 建立与数据提供者的连接
  • _disconnect: Closes the connection to the data provider
    _disconnect: 关闭与数据提供者的连接
  • reset: Resets the state of the client
    reset: 重置客户端的状态
  • dispose: Disposes of any resources held by the client
    dispose: 处理客户端持有的任何资源
  • _subscribe: Subscribes to a specific data type
    _subscribe: 订阅特定数据类型
  • _unsubscribe: Unsubscribes from a specific data type
    _unsubscribe: 取消订阅特定数据类型
  • _request: Requests data from the provider
    _request: 从提供者请求数据

MarketDataClient 市场数据客户端

The MarketDataClient handles market-specific data such as order books, top-of-book quotes and trade ticks, and instrument status updates. It focuses on providing historical and real-time market data that is essential for trading operations.
MarketDataClient 处理特定于市场的数据,例如订单簿、最佳报价和交易逐笔记录,以及金融工具状态更新。它专注于提供对交易操作至关重要的历史和实时市场数据。

from nautilus_trader.live.data_client import LiveMarketDataClient
from nautilus_trader.model.data import BarType, DataType
from nautilus_trader.model.enums import BookType
from nautilus_trader.model.identifiers import InstrumentId

class TemplateLiveMarketDataClient(LiveMarketDataClient):
    """
    An example of a ``LiveMarketDataClient`` highlighting the overridable abstract methods.
    一个 ``LiveMarketDataClient`` 的示例,突出显示了可覆盖的抽象方法。
    """

    async def _connect(self) -> None:
        raise NotImplementedError("method `_connect` must be implemented in the subclass")

    async def _disconnect(self) -> None:
        raise NotImplementedError("method `_disconnect` must be implemented in the subclass")

    def reset(self) -> None:
        raise NotImplementedError("method `reset` must be implemented in the subclass")

    def dispose(self) -> None:
        raise NotImplementedError("method `dispose` must be implemented in the subclass")

    async def _subscribe_instruments(self) -> None:
        raise NotImplementedError("method `_subscribe_instruments` must be implemented in the subclass")

    async def _unsubscribe_instruments(self) -> None:
        raise NotImplementedError("method `_unsubscribe_instruments` must be implemented in the subclass")

    async def _subscribe_order_book_deltas(self, instrument_id: InstrumentId, book_type: BookType, depth: int | None = None, kwargs: dict | None = None) -> None:
        raise NotImplementedError("method `_subscribe_order_book_deltas` must be implemented in the subclass")

    async def _unsubscribe_order_book_deltas(self, instrument_id: InstrumentId) -> None:
        raise NotImplementedError("method `_unsubscribe_order_book_deltas` must be implemented in the subclass")

Key Methods:
关键方法:

  • _connect: Establishes a connection to the venues APIs
    _connect: 建立与交易场所 API 的连接
  • _disconnect: Closes the connection to the venues APIs
    _disconnect: 关闭与交易场所 API 的连接
  • reset: Resets the state of the client
    reset: 重置客户端的状态
  • dispose: Disposes of any resources held by the client
    dispose: 处理客户端持有的任何资源
  • _subscribe_instruments: Subscribes to market data for multiple instruments
    _subscribe_instruments: 订阅多个金融工具的市场数据
  • _unsubscribe_instruments: Unsubscribes from market data for multiple instruments
    _unsubscribe_instruments: 取消订阅多个金融工具的市场数据
  • _subscribe_order_book_deltas: Subscribes to order book delta updates
    _subscribe_order_book_deltas: 订阅订单簿增量更新
  • _unsubscribe_order_book_deltas: Unsubscribes from order book delta updates
    _unsubscribe_order_book_deltas: 取消订阅订单簿增量更新

ExecutionClient 执行客户端

The ExecutionClient is responsible for order management, including submission, modification, and cancellation of orders. It is a crucial component of the adapter that interacts with the venues trading system to manage and execute trades.
执行客户端负责订单管理,包括订单的提交、修改和取消。它是适配器的一个关键组件,与交易场所的交易系统交互以管理和执行交易。

from nautilus_trader.execution.messages import BatchCancelOrders, CancelAllOrders, CancelOrder, ModifyOrder, SubmitOrder
from nautilus_trader.execution.reports import FillReport, OrderStatusReport, PositionStatusReport
from nautilus_trader.live.execution_client import LiveExecutionClient
from nautilus_trader.model.identifiers import ClientOrderId, InstrumentId, VenueOrderId

class TemplateLiveExecutionClient(LiveExecutionClient):
    """
    An example of a ``LiveExecutionClient`` highlighting the method requirements.
    一个 ``LiveExecutionClient`` 的示例,突出显示了方法要求。
    """

    async def _connect(self) -> None:
        raise NotImplementedError("method `_connect` must be implemented in the subclass")

    async def _disconnect(self) -> None:
        raise NotImplementedError("method `_disconnect` must be implemented in the subclass")

    async def _submit_order(self, command: SubmitOrder) -> None:
        raise NotImplementedError("method `_submit_order` must be implemented in the subclass")

    async def _modify_order(self, command: ModifyOrder) -> None:
        raise NotImplementedError("method `_modify_order` must be implemented in the subclass")

    async def _cancel_order(self, command: CancelOrder) -> None:
        raise NotImplementedError("method `_cancel_order` must be implemented in the subclass")

    async def _cancel_all_orders(self, command: CancelAllOrders) -> None:
        raise NotImplementedError("method `_cancel_all_orders` must be implemented in the subclass")

    async def _batch_cancel_orders(self, command: BatchCancelOrders) -> None:
        raise NotImplementedError("method `_batch_cancel_orders` must be implemented in the subclass")  

    async def generate_order_status_report(
        self, instrument_id: InstrumentId, client_order_id: ClientOrderId | None = None, venue_order_id: VenueOrderId | None = None
    ) -> OrderStatusReport | None:
        raise NotImplementedError("method `generate_order_status_report` must be implemented in the subclass")

    async def generate_order_status_reports(
        self, instrument_id: InstrumentId | None = None, start: pd.Timestamp | None = None, end: pd.Timestamp | None = None, open_only: bool = False
    ) -> list[OrderStatusReport]:
        raise NotImplementedError("method `generate_order_status_reports` must be implemented in the subclass")

    async def generate_fill_reports(
        self, instrument_id: InstrumentId | None = None, venue_order_id: VenueOrderId | None = None, start: pd.Timestamp | None = None, end: pd.Timestamp | None = None
    ) -> list[FillReport]:
        raise NotImplementedError("method `generate_fill_reports` must be implemented in the subclass")

    async def generate_position_status_reports(
        self, instrument_id: InstrumentId | None = None, start: pd.Timestamp | None = None, end: pd.Timestamp | None = None
    ) -> list[PositionStatusReport]:
        raise NotImplementedError("method `generate_position_status_reports` must be implemented in the subclass")

Key Methods:
关键方法:

  • _connect: Establishes a connection to the venues APIs
    _connect: 建立与交易场所 API 的连接
  • _disconnect: Closes the connection to the venues APIs
    _disconnect: 关闭与交易场所 API 的连接
  • _submit_order: Submits a new order to the venue
    _submit_order: 向交易场所提交新订单
  • _modify_order: Modifies an existing order on the venue
    _modify_order: 修改交易场所上的现有订单
  • _cancel_order: Cancels a specific order on the venue
    _cancel_order: 取消交易场所上的特定订单
  • _cancel_all_orders: Cancels all orders for an instrument on the venue
    _cancel_all_orders: 取消交易场所上金融工具的所有订单
  • _batch_cancel_orders: Cancels a batch of orders for an instrument on the venue
    _batch_cancel_orders: 取消交易场所上金融工具的一批订单
  • generate_order_status_report: Generates a report for a specific order on the venue
    generate_order_status_report: 生成交易场所上特定订单的报告
  • generate_order_status_reports: Generates reports for all orders on the venue
    generate_order_status_reports: 生成交易场所上所有订单的报告
  • generate_fill_reports: Generates reports for filled orders on the venue
    generate_fill_reports: 生成交易场所上已成交订单的报告
  • generate_position_status_reports: Generates reports for position status on the venue
    generate_position_status_reports: 生成交易场所上头寸状态的报告

Configuration 配置

The configuration file defines settings specific to the adapter, such as API keys and connection details. These settings are essential for initializing and managing the adapter’s connection to the data provider.
配置文件定义特定于适配器的设置,例如 API 密钥和连接详细信息。这些设置对于初始化和管理适配器与数据提供者的连接至关重要。

from nautilus_trader.config import LiveDataClientConfig, LiveExecClientConfig

class TemplateDataClientConfig(LiveDataClientConfig):
    """
    Configuration for ``TemplateDataClient`` instances.
    ``TemplateDataClient`` 实例的配置。
    """

    api_key: str
    api_secret: str
    base_url: str

class TemplateExecClientConfig(LiveExecClientConfig):
    """
    Configuration for ``TemplateExecClient`` instances.
    ``TemplateExecClient`` 实例的配置。
    """

    api_key: str
    api_secret: str
    base_url: str

Key Attributes:
关键属性:

  • api_key: The API key for authenticating with the data provider
    api_key: 用于向数据提供者进行身份验证的 API 密钥
  • api_secret: The API secret for authenticating with the data provider
    api_secret: 用于向数据提供者进行身份验证的 API 密钥
  • base_url: The base URL for connecting to the data provider’s API
    base_url: 用于连接到数据提供者 API 的基本 URL
文档 (Documentation)
入门 (Getting Started)
概念 (Concepts)
教程 (Tutorials)
集成 (Integrations)
Python API
Rust API[未翻译]
开发者指南 (Developer Guide)
Clone this wiki locally