跳转至

第六章:执行系统

本章导读:本章解剖执行:订单生命周期、订单类型、时效指令(TIF)、订单模拟(OrderEmulator)、撮合引擎、执行算法、订单修改与执行质量。这是「发单」这件事的全部工程细节。

6.1 概述

执行系统管理从提交到成交的完整订单生命周期,包括订单路由、模拟和对账。

6.1.1 关键组件

  • ExecutionEngine:中央订单管理
  • MatchingEngine:模拟交易所撮合
  • OrderEmulator:订单模拟
  • Reconciliation:状态同步

6.1.2 架构

Text Only
┌─────────────────────────────────────────────────────────────┐
│                   ExecutionEngine                            │
│  ┌─────────────────────────────────────────────────────┐   │
│  │                   OrderManager                       │   │
│  │  ┌──────────┐  ┌──────────┐  ┌──────────┐         │   │
│  │  │  Order   │  │  Order   │  │  Order   │         │   │
│  │  │ Tracker  │  │ Router   │  │ Validator│         │   │
│  │  └──────────┘  └──────────┘  └──────────┘         │   │
│  └─────────────────────────────────────────────────────┘   │
│                           │                                  │
│  ┌────────────────────────┴────────────────────────┐        │
│  │              MatchingEngine                      │        │
│  │  ┌──────────┐  ┌──────────┐  ┌──────────┐      │        │
│  │  │  Price   │  │  Time    │  │  Fill    │      │        │
│  │  │ Priority │  │ Priority │  │ Handler  │      │        │
│  │  └──────────┘  └──────────┘  └──────────┘      │        │
│  └─────────────────────────────────────────────────┘        │
│                           │                                  │
│  ┌────────────────────────┴────────────────────────┐        │
│  │              ExecutionClients                    │        │
│  │  ┌──────────┐  ┌──────────┐  ┌──────────┐      │        │
│  │  │  Venue   │  │  Venue   │  │  Venue   │      │        │
│  │  │ Client 1 │  │ Client 2 │  │ Client 3 │      │        │
│  │  └──────────┘  └──────────┘  └──────────┘      │        │
│  └─────────────────────────────────────────────────┘        │
└─────────────────────────────────────────────────────────────┘

6.2 订单生命周期

6.2.1 订单状态

Text Only
┌─────────────┐
│ Initialized │
└──────┬──────┘
       │ submit_order()
       ▼
┌─────────────┐
│  Submitted  │
└──────┬──────┘
       │ venue accepts
       ▼
┌─────────────┐
│  Accepted   │
└──────┬──────┘
       │ partial fill
       ▼
┌─────────────┐     ┌─────────────┐
│PartiallyFilled│──▶│   Filled    │
└──────┬──────┘     └─────────────┘
       │ cancel
       ▼
┌─────────────┐
│  Canceled   │
└─────────────┘

6.2.2 状态转换

从 到 触发器
Initialized Submitted 策略提交订单
Submitted Accepted 交易所接受订单
Submitted Rejected 交易所拒绝订单
Accepted PartiallyFilled 收到部分成交
Accepted Filled 收到全部成交
Accepted Canceled 取消请求被接受
PartiallyFilled Filled 收到剩余成交
PartiallyFilled Canceled 取消请求被接受
Any Expired 订单过期

6.3 订单类型

6.3.1 基本订单类型

市价单:

Rust
MarketOrder {
    id: OrderId,
    instrument_id: InstrumentId,
    side: OrderSide,
    quantity: Quantity,
    time_in_force: TimeInForce,
    client_order_id: ClientOrderId,
    venue_order_id: Option<VenueOrderId>,
    status: OrderStatus,
}

限价单:

Rust
LimitOrder {
    id: OrderId,
    instrument_id: InstrumentId,
    side: OrderSide,
    quantity: Quantity,
    price: Price,
    time_in_force: TimeInForce,
    client_order_id: ClientOrderId,
    venue_order_id: Option<VenueOrderId>,
    status: OrderStatus,
}

止损市价单:

Rust
StopMarketOrder {
    id: OrderId,
    instrument_id: InstrumentId,
    side: OrderSide,
    quantity: Quantity,
    trigger_price: Price,
    time_in_force: TimeInForce,
    client_order_id: ClientOrderId,
    venue_order_id: Option<VenueOrderId>,
    status: OrderStatus,
}

6.3.2 高级订单类型

追踪止损:

Rust
TrailingStopOrder {
    id: OrderId,
    instrument_id: InstrumentId,
    side: OrderSide,
    quantity: Quantity,
    trigger_price: Price,
    trailing_offset: Decimal,
    time_in_force: TimeInForce,
    client_order_id: ClientOrderId,
    venue_order_id: Option<VenueOrderId>,
    status: OrderStatus,
}

冰山订单:

Rust
IcebergOrder {
    id: OrderId,
    instrument_id: InstrumentId,
    side: OrderSide,
    quantity: Quantity,
    price: Price,
    display_quantity: Quantity,
    time_in_force: TimeInForce,
    client_order_id: ClientOrderId,
    venue_order_id: Option<VenueOrderId>,
    status: OrderStatus,
}

市价转限价:

Rust
MarketToLimitOrder {
    id: OrderId,
    instrument_id: InstrumentId,
    side: OrderSide,
    quantity: Quantity,
    time_in_force: TimeInForce,
    client_order_id: ClientOrderId,
    venue_order_id: Option<VenueOrderId>,
    status: OrderStatus,
}

6.4 时效指令

6.4.1 TIF 类型

TIF 描述
GTC Good Till Canceled - 保持有效直到取消
IOC Immediate or Cancel - 立即成交或取消
FOK Fill or Kill - 立即全部成交或取消
GTD Good Till Date - 有效直到指定日期
DAY Day Order - 当日有效订单
AT_THE_OPEN 开盘时执行
AT_THE_CLOSE 收盘时执行

6.4.2 TIF 行为

GTC:

  • 订单保持有效直到显式取消
  • 可在多个交易时段部分成交
  • 受交易所特定过期政策约束

IOC:

  • 尝试立即成交
  • 取消任何未成交部分
  • 不创建挂单

FOK:

  • 尝试立即全部成交
  • 如无法全部成交则取消
  • 全有或全无执行

6.5 订单模拟

6.5.1 目的

订单模拟模拟交易所行为用于:

  • 无交易所连接的回测
  • 测试订单逻辑
  • 模拟复杂订单类型

6.5.2 模拟模式

价格成交:

  • 价格穿越触发价时成交
  • 模拟市价单行为

K线成交:

  • 下一根K线开盘/收盘时成交
  • 模拟基于K线的执行

报价成交:

  • 报价穿越触发价时成交
  • 模拟基于报价的执行

6.5.3 模拟配置

Rust
pub struct EmulationConfig {
    pub mode: EmulationMode,
    pub fill_model: FillModel,
    pub slippage_model: SlippageModel,
    pub fee_model: FeeModel,
    pub latency_model: LatencyModel,
}

6.6 撮合引擎

6.6.1 价格时间优先

撮合引擎实现价格时间优先:

价格优先:

  • 最优价格优先
  • 买入:最高价格优先
  • 卖出:最低价格优先

时间优先:

  • 同价格内,先到的订单优先
  • FIFO(先进先出)

6.6.2 撮合算法

Rust
pub fn match_order(&mut self, order: &Order) -> Vec<Fill> {
    let mut fills = Vec::new();

    // Get opposite side of book
    let levels = match order.side {
        OrderSide::Buy => &mut self.asks,
        OrderSide::Sell => &mut self.bids,
    };

    // Match against levels
    for level in levels.iter_mut() {
        if can_match(order, level) {
            let fill = create_fill(order, level);
            fills.push(fill);

            if order.is_filled() {
                break;
            }
        }
    }

    fills
}

6.6.3 成交类型

全部成交:

  • 全部订单数量成交
  • 单一成交事件

部分成交:

  • 部分订单数量成交
  • 可能多次成交事件

零成交:

  • 无数量成交
  • 订单保持活跃

6.7 执行算法

6.7.1 TWAP(时间加权平均价格)

Rust
pub struct TwapAlgorithm {
    pub start_time: UnixNanos,
    pub end_time: UnixNanos,
    pub slices: usize,
    pub side: OrderSide,
}

impl ExecutionAlgorithm for TwapAlgorithm {
    fn generate_orders(&self) -> Vec<Order> {
        let duration = self.end_time - self.start_time;
        let slice_duration = duration / self.slices as u64;
        let quantity = self.total_quantity / self.slices;

        (0..self.slices).map(|i| {
            Order::new(
                self.instrument_id,
                self.side,
                quantity,
                self.start_time + i * slice_duration,
            )
        }).collect()
    }
}

6.7.2 VWAP(成交量加权平均价格)

Rust
pub struct VwapAlgorithm {
    pub start_time: UnixNanos,
    pub end_time: UnixNanos,
    pub target_participation: f64,
    pub side: OrderSide,
}

impl ExecutionAlgorithm for VwapAlgorithm {
    fn generate_orders(&self) -> Vec<Order> {
        let volume_profile = self.get_volume_profile();
        let total_volume: f64 = volume_profile.iter().sum();

        volume_profile.iter().map(|&volume| {
            let quantity = volume / total_volume * self.total_quantity
                          * self.target_participation;
            Order::new(
                self.instrument_id,
                self.side,
                quantity,
                self.start_time,
            )
        }).collect()
    }
}

6.7.3 执行缺口

Rust
pub struct ImplementationShortfallAlgorithm {
    pub start_time: UnixNanos,
    pub end_time: UnixNanos,
    pub urgency: Urgency,
    pub side: OrderSide,
}

impl ExecutionAlgorithm for ImplementationShortfallAlgorithm {
    fn generate_orders(&self) -> Vec<Order> {
        // Balance market impact vs timing risk
        let schedule = self.compute_schedule();

        schedule.iter().map(|&(time, quantity)| {
            Order::new(
                self.instrument_id,
                self.side,
                quantity,
                time,
            )
        }).collect()
    }
}

6.8 订单修改

6.8.1 支持的修改

价格变更:

  • 修改限价价格
  • 修改止损价格
  • 修改触发价格

数量变更:

  • 增加数量
  • 减少数量
  • 不能减少到已成交数量以下

时效指令变更:

  • 修改 TIF
  • 修改过期时间

6.8.2 修改流程

  1. 验证:检查修改是否允许
  2. 取消:在交易所取消现有订单
  3. 重新提交:提交修改后的新订单
  4. 跟踪:更新订单跟踪

6.9 对账

6.9.1 对账类型

订单对账:

  • 比较本地订单与交易所订单
  • 识别缺失/额外订单
  • 更新订单状态

持仓对账:

  • 比较本地持仓与交易所持仓
  • 识别持仓不匹配
  • 更新持仓状态

余额对账:

  • 比较本地余额与交易所余额
  • 识别余额不匹配
  • 更新账户余额

6.9.2 对账流程

Rust
pub async fn reconcile(&self) -> Result<ReconciliationReport, Error> {
    // Query venue state
    let venue_orders = self.venue.get_open_orders().await?;
    let venue_positions = self.venue.get_positions().await?;
    let venue_balances = self.venue.get_balances().await?;

    // Compare with local state
    let order_diffs = self.compare_orders(&venue_orders);
    let position_diffs = self.compare_positions(&venue_positions);
    let balance_diffs = self.compare_balances(&venue_balances);

    // Reconcile differences
    self.reconcile_orders(order_diffs).await?;
    self.reconcile_positions(position_diffs).await?;
    self.reconcile_balances(balance_diffs).await?;

    Ok(ReconciliationReport::new(order_diffs, position_diffs, balance_diffs))
}

6.10 执行质量

6.10.1 指标

成交率:

  • 成交订单百分比
  • 部分成交率
  • 全部成交率

滑点:

  • 预期与实际成交价格差异
  • 市场影响
  • 时间成本

延迟:

  • 订单提交延迟
  • 成交确认延迟
  • 取消延迟

6.10.2 优化

订单路由:

  • 智能订单路由
  • 交易所选择
  • 流动性聚合

时机:

  • 订单时机优化
  • 市场条件适应
  • 基于紧急性的执行

6.11 总结

执行系统提供:

  • 完整的订单生命周期管理
  • **多种订单类型**具有高级功能
  • **真实模拟**用于回测
  • **复杂撮合**具有价格时间优先
  • **执行算法**用于优化执行
  • **全面对账**确保状态一致性

执行系统对于在回测和实盘环境中实现高质量交易执行至关重要。

小结:执行系统的复杂度藏在边界:订单类型与 TIF 的组合爆炸、模拟单如何在不下场的情况下验证策略、撮合引擎如何在回测里复刻交易所行为。执行质量那一节提醒你——省下的几个基点滑点,可能就是回测与实盘的差距。


过渡:执行讲完,下一章看数据从哪来、怎么被聚合与分发——没有数据,执行就是盲飞。


边界情况:The matching engine's replication of exchange behavior has blind spots (partial fills, iceberg semantics); backtest fills are not live fills.


失败模式:Execution quality is under-estimated by backtests — the few saved basis points of slippage are often the live net loss.


主线回扣:支撑 event-driven-uniformity——执行引擎、撮合引擎与模拟引擎共用事件语义,所以回测里的撮合与实盘的撮合是同一套逻辑。


练习:

1) OrderEmulator(订单模拟)解决了回测里的什么具体问题?不用它会怎样? 2) 撮合引擎在回测中复刻交易所行为,哪些细节复刻不了、会引发什么偏差? 3) 执行质量(TCA)指标里,哪一类滑点最容易被回测低估?