返回题库

价差计算器

Spread Calculator

专题
Systems & Architecture / 系统与架构
难度
L2
来源
MyntBit

题目详情

在高频交易和做市策略中,买卖价差是评估市场流动性和交易成本的关键指标。绝对价差提供原始价格差,相对价差将此成本对标中间价进行归一化,便于跨品种比较。维护精确的限价订单簿是计算这些指标的前提。

任务:实现 SpreadCalculator 类,从限价订单簿计算绝对价差、相对价差和中间价。

英文原题

In high-frequency trading and market making, the bid-ask spread is a crucial metric for evaluating market liquidity and transaction costs. The absolute spread provides the raw price difference, while the relative spread normalizes this cost against the asset's mid-price to facilitate comparison across different instruments. Maintaining an accurate limit order book is essential for calculating these top-of-book metrics in real-time.
Task
Implement a SpreadCalculator class that maintains a Level

解析

问题分析

买卖价差是市场流动性的核心指标。有效价差衡量实际成交价格与报价中点的偏差。在量化交易中,实时计算价差有助于评估交易成本、选择执行场所和检测流动性变化。

实现

struct SpreadMetrics { double quoted_spread, effective_spread, realized_spread; };
SpreadMetrics computeSpread(double bid, double ask, double trade_price, double future_mid) {
    double mid = (bid + ask) / 2.0;
    return {
        (ask - bid) / mid * 10000.0,          // quoted spread (bps)
        std::abs(trade_price - mid) / mid * 20000.0, // effective spread (bps)
        (trade_price - future_mid) / mid * 10000.0   // realized spread (bps)
    };
}

复杂度与边界

  • 时间复杂度:O(1) 纯算术运算
  • 空间复杂度:O(1)
  • 边界条件:(1) bid=0 或 ask=0 时退出一侧 (2) mid=0 时返回 0 (3) 负价差表明交叉市场

英文解析

Analysis

Bid-ask spread is the core metric for market liquidity. Effective spread measures deviation of actual trade price from the quote midpoint. In quantitative trading, real-time spread calculation helps assess trading costs, select execution venues, and detect liquidity changes.

Solution

struct SpreadMetrics { double quoted_spread, effective_spread, realized_spread; };
SpreadMetrics computeSpread(double bid, double ask, double trade_price, double future_mid) {
    double mid = (bid + ask) / 2.0;
    return {
        (ask - bid) / mid * 10000.0,          // quoted spread (bps)
        std::abs(trade_price - mid) / mid * 20000.0, // effective spread (bps)
        (trade_price - future_mid) / mid * 10000.0   // realized spread (bps)
    };
}

Complexity & Edge Cases

  • Time complexity: O(1) pure arithmetic
  • Space complexity: O(1)
  • Edge cases: (1) bid=0 or ask=0: one side missing (2) mid=0: return 0 (3) Negative spread indicates crossed market

Key Considerations

  1. Mid-price definition: Spread = best_ask - best_bid; mid = (best_ask + best_bid) / 2; must handle missing bid or ask (one-sided book)
  2. Effective spread: Realized spread measures actual execution cost — (execution_price - mid_at_submission_time) for buys, (mid_at_submission_time - execution_price) for sells
  3. Tick size normalization: Spread in price units vs tick units differ; normalize to tick size for cross-product comparison
  4. Stale quotes: Spread computed from stale quotes understates true cost; must verify quote freshness before computing spread metrics