market-microstructure-traditional

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Market Microstructure (Traditional)

传统市场微观结构

Market microstructure studies how orders become trades and how trades become prices. Understanding these mechanics is essential for execution optimization, market making, and detecting informed flow. This skill covers limit order book (LOB) theory as applied to crypto markets on centralized exchanges, and compares LOB mechanics to the AMM-based structure of DEXes.
市场微观结构研究订单如何转化为交易,以及交易如何形成价格。理解这些机制对于优化执行策略、做市以及识别知情资金流至关重要。本技能涵盖适用于中心化交易所加密货币市场的限价订单簿(LOB)理论,并将LOB机制与基于自动做市商(AMM)的去中心化交易所(DEX)结构进行对比。

Core Concepts

核心概念

ConceptWhat It Tells You
Bid-ask spreadCost of immediacy — how much you pay to trade now vs later
Price impactHow your order moves the market price
Order book imbalanceShort-term directional predictor from queue sizes
Adverse selectionRisk of trading against informed counterparties
Inventory riskMarket maker exposure from accumulated positions
Execution qualityHow well your fills compare to a benchmark

概念作用
Bid-ask spread即时交易成本——立即交易与延迟交易的成本差异
Price impact你的订单对市场价格的影响程度
Order book imbalance通过挂单队列规模预测短期价格方向
Adverse selection与知情交易对手方交易的风险
Inventory risk做市商因持仓积累面临的风险
Execution quality你的成交情况与基准指标的对比表现

Bid-Ask Spread Decomposition

买卖价差分解

The bid-ask spread is not a single thing. It decomposes into three components (Roll, 1984; Glosten & Harris, 1988):
  1. Adverse selection — compensation for trading against informed traders
  2. Inventory holding — compensation for carrying risk
  3. Order processing — fixed costs of providing liquidity (fees, infrastructure)
买卖价差并非单一概念,它可分解为三个组成部分(Roll, 1984; Glosten & Harris, 1988):
  1. 逆向选择成本——与知情交易者交易的补偿
  2. 库存持有成本——承担持仓风险的补偿
  3. 订单处理成本——提供流动性的固定成本(手续费、基础设施成本)

Spread Measures

价差指标

python
undefined
python
undefined

Quoted spread: what you see on the order book

报价价差:订单簿上显示的价差

quoted_spread = best_ask - best_bid quoted_spread_bps = (best_ask - best_bid) / midprice * 10_000
quoted_spread = best_ask - best_bid quoted_spread_bps = (best_ask - best_bid) / midprice * 10_000

Effective spread: what you actually pay (accounts for price improvement)

有效价差:实际支付的成本(考虑价格优化)

effective_half_spread = abs(trade_price - midprice_at_trade) effective_spread_bps = effective_half_spread / midprice_at_trade * 10_000
effective_half_spread = abs(trade_price - midprice_at_trade) effective_spread_bps = effective_half_spread / midprice_at_trade * 10_000

Realized spread: market maker's actual profit (after price moves)

实现价差:做市商的实际利润(考虑交易后价格变动)

Measured at trade_price vs midprice N seconds later

以交易价格与N秒后的中间价对比计算

realized_spread = trade_sign * (trade_price - midprice_after_delay)

The **effective spread** matters most for execution quality.  The difference
between effective and realized spread measures adverse selection — what the
market maker loses to informed flow.

---
realized_spread = trade_sign * (trade_price - midprice_after_delay)

**有效价差**是衡量执行质量的核心指标。有效价差与实现价差的差值代表逆向选择成本——即做市商因知情资金流产生的损失。

---

Price Formation Models

价格形成模型

Glosten-Milgrom (1985)

Glosten-Milgrom模型(1985)

A sequential trade model where the market maker sets bid and ask prices to break even against a mix of informed and uninformed traders.
  • Market maker quotes reflect expected value conditional on trade direction
  • Spread exists purely due to adverse selection
  • Prices converge to true value as information is revealed through trades
Key insight: the spread is wider when:
  • Probability of informed trading (PIN) is higher
  • Information asymmetry is larger
  • Uninformed trading volume is lower
这是一个连续交易模型,做市商通过设定买卖价格,在知情与非知情交易者的混合交易中实现盈亏平衡。
  • 做市商报价反映基于交易方向的预期价值
  • 价差完全由逆向选择因素产生
  • 随着交易披露信息,价格逐渐收敛至真实价值
核心结论:在以下场景下价差会扩大:
  • 知情交易概率(PIN)更高
  • 信息不对称程度更大
  • 非知情交易量更低

Kyle's Lambda (1985)

Kyle模型(1985)

Kyle models a single informed trader, noise traders, and a market maker. The market maker sets price as a linear function of net order flow:
price_change = lambda * net_order_flow
Lambda (λ) measures permanent price impact per unit of signed volume. Higher lambda = less liquid market. Lambda is estimated by regressing price changes on signed volume:
python
import numpy as np
from numpy.linalg import lstsq

def estimate_kyle_lambda(
    price_changes: np.ndarray,
    signed_volumes: np.ndarray,
) -> float:
    """Estimate Kyle's lambda from trade data.

    Args:
        price_changes: Midprice changes between trades.
        signed_volumes: Trade volume * trade_sign (+1 buy, -1 sell).

    Returns:
        Estimated lambda (price impact per unit volume).
    """
    X = signed_volumes.reshape(-1, 1)
    beta, _, _, _ = lstsq(X, price_changes, rcond=None)
    return float(beta[0])
See
references/price_formation.md
for full model derivations and the PIN model for measuring informed trading probability.

Kyle模型包含单一知情交易者、噪音交易者和做市商。做市商将价格设定为净订单流的线性函数:
price_change = lambda * net_order_flow
Lambda (λ) 衡量单位带符号交易量带来的永久性价格冲击。Lambda值越高,市场流动性越差。Lambda通过将价格变动对带符号交易量进行回归估算:
python
import numpy as np
from numpy.linalg import lstsq

def estimate_kyle_lambda(
    price_changes: np.ndarray,
    signed_volumes: np.ndarray,
) -> float:
    """从交易数据中估算Kyle模型的lambda值。

    参数:
        price_changes: 交易间的中间价变动。
        signed_volumes: 交易量*交易方向标识(+1为买入,-1为卖出)。

    返回:
        估算的lambda值(单位交易量的价格冲击)。
    """
    X = signed_volumes.reshape(-1, 1)
    beta, _, _, _ = lstsq(X, price_changes, rcond=None)
    return float(beta[0])
完整的模型推导及衡量知情交易概率的PIN模型,请参阅
references/price_formation.md

Price Impact Models

价格冲击模型

Temporary vs Permanent Impact (Almgren-Chriss)

临时冲击与永久冲击(Almgren-Chriss模型)

When executing a large order:
  • Temporary impact — price displacement that reverts after your order. Caused by consuming standing liquidity.
  • Permanent impact — information content of your trade that moves the equilibrium price. Does not revert.
total_impact = permanent_impact + temporary_impact
permanent = gamma * (shares / ADV)
temporary = eta * (shares / time_horizon) ^ alpha
Typical alpha values: 0.5-0.7 (square root impact is a robust empirical finding).
执行大额订单时:
  • 临时冲击——订单执行后会恢复的价格偏离,由消耗挂单流动性导致。
  • 永久冲击——交易包含的信息导致均衡价格变动,不会恢复。
total_impact = permanent_impact + temporary_impact
permanent = gamma * (shares / ADV)
temporary = eta * (shares / time_horizon) ^ alpha
典型alpha值:0.5-0.7(平方根冲击是经过验证的实证结论)。

Square Root Impact Law

平方根冲击定律

Empirically, price impact scales as the square root of order size relative to daily volume:
python
def square_root_impact(
    order_size: float,
    daily_volume: float,
    volatility: float,
    impact_coefficient: float = 0.1,
) -> float:
    """Estimate price impact using the square root model.

    Args:
        order_size: Number of units to trade.
        daily_volume: Average daily volume.
        volatility: Daily return volatility (decimal).
        impact_coefficient: Empirical constant (typically 0.05-0.20).

    Returns:
        Expected price impact as a fraction.
    """
    return impact_coefficient * volatility * (order_size / daily_volume) ** 0.5

实证研究显示,价格冲击与订单规模相对日交易量的平方根成正比:
python
def square_root_impact(
    order_size: float,
    daily_volume: float,
    volatility: float,
    impact_coefficient: float = 0.1,
) -> float:
    """使用平方根模型估算价格冲击。

    参数:
        order_size: 交易单位数量。
        daily_volume: 平均日交易量。
        volatility: 日收益波动率(小数形式)。
        impact_coefficient: 经验常数(通常为0.05-0.20)。

    返回:
        预期价格冲击比例。
    """
    return impact_coefficient * volatility * (order_size / daily_volume) ** 0.5

Order Book Imbalance

订单簿失衡

The ratio of bid-side to ask-side depth near the top of the book predicts short-term price direction:
python
def order_book_imbalance(
    bid_qty: float,
    ask_qty: float,
) -> float:
    """Compute order book imbalance.

    Returns:
        Imbalance in [-1, 1]. Positive = more bids (bullish).
    """
    total = bid_qty + ask_qty
    if total == 0:
        return 0.0
    return (bid_qty - ask_qty) / total
Imbalance at levels 1-5 is a strong short-term predictor (Cont et al., 2014). Deeper levels add predictive power but decay quickly.

订单簿顶部买卖盘深度的比例可预测短期价格方向:
python
def order_book_imbalance(
    bid_qty: float,
    ask_qty: float,
) -> float:
    """计算订单簿失衡度。

    返回:
        失衡度范围为[-1, 1]。正数代表买盘更强(看涨)。
    """
    total = bid_qty + ask_qty
    if total == 0:
        return 0.0
    return (bid_qty - ask_qty) / total
1-5档的失衡度是很强的短期价格预测指标(Cont et al., 2014)。更深档位的失衡度也有预测能力,但衰减速度更快。

Trade Arrival Processes

交易到达模型

Poisson Process

泊松过程

Simplest model: trades arrive at a constant rate λ. Inter-arrival times are exponentially distributed. Useful as a baseline but too simple for real order flow.
最简单的模型:交易以恒定速率λ到达,交易间隔呈指数分布。可用作基准模型,但对于真实订单流来说过于简化。

Hawkes Process

Hawkes过程

Self-exciting point process where each trade increases the probability of subsequent trades. Captures clustering in order flow:
intensity(t) = mu + sum(alpha * exp(-beta * (t - t_i)))
  • mu: baseline arrival rate
  • alpha: excitation magnitude (how much each event boosts intensity)
  • beta: decay rate (how fast excitation fades)
  • alpha/beta < 1: stationarity condition (branching ratio)
The branching ratio α/β measures the fraction of trades that are reactions rather than innovations. Typical values: 0.5-0.8 in crypto markets (high reactivity).

自激点过程,每笔交易会提高后续交易的概率,能够捕捉订单流的聚集特征:
intensity(t) = mu + sum(alpha * exp(-beta * (t - t_i)))
  • mu: 基准到达率
  • alpha: 激发幅度(每笔事件提高强度的程度)
  • beta: 衰减率(激发效果的消退速度)
  • alpha/beta < 1: 平稳性条件(分支比)
分支比α/β衡量交易中属于“反应型”而非“创新型”的比例。加密货币市场的典型值为0.5-0.8(高反应性)。

Market Maker Economics

做市商经济学

A market maker profits from the spread but faces three risks:
  1. Adverse selection — losing to informed traders
  2. Inventory risk — accumulated directional exposure
  3. Competition — other MMs narrowing the spread
做市商通过价差获利,但面临三类风险:
  1. 逆向选择——输给知情交易者
  2. 库存风险——积累的方向性敞口
  3. 竞争——其他做市商压缩价差

Avellaneda-Stoikov Model

Avellaneda-Stoikov模型

The optimal bid and ask quotes for a market maker with inventory
q
:
reservation_price = midprice - q * gamma * sigma^2 * T
optimal_spread = gamma * sigma^2 * T + (2/gamma) * ln(1 + gamma/k)
Where:
  • q
    : current inventory (positive = long)
  • gamma
    : risk aversion parameter
  • sigma
    : volatility
  • T
    : time remaining
  • k
    : order arrival rate parameter
Key insight: the reservation price skews away from inventory — a long market maker lowers their price to encourage sells.

持有库存
q
的做市商最优买卖报价:
reservation_price = midprice - q * gamma * sigma^2 * T
optimal_spread = gamma * sigma^2 * T + (2/gamma) * ln(1 + gamma/k)
参数说明:
  • q
    : 当前库存(正数代表多头)
  • gamma
    : 风险厌恶参数
  • sigma
    : 波动率
  • T
    : 剩余时间
  • k
    : 订单到达率参数
核心结论:保留价格会偏离当前库存方向——持有多头的做市商会降低报价以鼓励卖出。

Execution Quality Measurement

执行质量衡量

VWAP Benchmark

VWAP基准

Volume-Weighted Average Price is the standard benchmark for passive execution:
python
def vwap(prices: list[float], volumes: list[float]) -> float:
    """Compute VWAP from trade prices and volumes."""
    pv_sum = sum(p * v for p, v in zip(prices, volumes))
    v_sum = sum(volumes)
    return pv_sum / v_sum if v_sum > 0 else 0.0
成交量加权平均价格(VWAP)是被动执行的标准基准:
python
def vwap(prices: list[float], volumes: list[float]) -> float:
    """根据交易价格和成交量计算VWAP。"""
    pv_sum = sum(p * v for p, v in zip(prices, volumes))
    v_sum = sum(volumes)
    return pv_sum / v_sum if v_sum > 0 else 0.0

Execution quality vs VWAP

相对于VWAP的执行质量

slippage_vs_vwap = (avg_fill_price - vwap_benchmark) / vwap_benchmark * 10_000
undefined
slippage_vs_vwap = (avg_fill_price - vwap_benchmark) / vwap_benchmark * 10_000
undefined

Implementation Shortfall

执行缺口

Measures total cost of executing vs the decision price (Perold, 1988):
implementation_shortfall = (execution_price - decision_price) * quantity
Decomposes into:
  • Delay cost: price drift between decision and first fill
  • Market impact: price move caused by your order
  • Timing cost: cost of breaking the order into slices
  • Opportunity cost: value of unfilled portions
See
references/execution_quality.md
for complete methodology.

衡量从决策到执行的总成本(Perold, 1988):
implementation_shortfall = (execution_price - decision_price) * quantity
可分解为:
  • 延迟成本: 决策到首次成交期间的价格漂移
  • 市场冲击: 你的订单导致的价格变动
  • 时间成本: 将订单拆分为多个批次的成本
  • 机会成本: 未成交部分的价值损失
完整方法请参阅
references/execution_quality.md

CEX Order Book vs DEX AMM

CEX订单簿 vs DEX AMM

DimensionCEX (LOB)DEX (AMM)
Price discoveryLimit orders express willingness to tradeAlgorithmic curve (x·y=k)
SpreadSet by competing market makersDetermined by pool depth and fee tier
DepthVisible order bookImplicit from TVL and curve shape
Adverse selectionMMs reprice on informationLPs suffer impermanent loss
ExecutionPrice-time priorityFirst-come via block inclusion
LatencyMicrosecondsBlock time (400ms Solana, 12s Ethereum)
MEVFront-running is harder (colocated MMs)Sandwich attacks are endemic
FeesMaker/taker (often maker rebate)Fixed tier (e.g., 5, 30, 100 bps)
When to use CEX: large orders, latency-sensitive strategies, tight spreads needed, BTC/ETH/major pairs.
When to use DEX: long-tail tokens, censorship resistance, composability with DeFi, transparent execution.
See
references/cex_vs_dex.md
for detailed structural comparison.

维度CEX(LOB)DEX(AMM)
价格发现限价订单表达交易意愿算法曲线(x·y=k)
价差由竞争做市商设定由资金池深度和手续费层级决定
深度可见订单簿由TVL和曲线形态隐含
逆向选择做市商根据信息重新定价流动性提供者遭受无常损失
执行规则价格-时间优先区块打包顺序优先
延迟微秒级区块时间(Solana为400ms,以太坊为12s)
MEV抢先交易难度较高(托管做市商)三明治攻击普遍存在
手续费做市/吃单手续费(通常做市商有返佣)固定层级(如5、30、100个基点)
何时使用CEX: 大额订单、低延迟策略、需要窄价差、BTC/ETH等主流币种。
何时使用DEX: 长尾代币、抗审查需求、与DeFi组合使用、执行透明。
详细结构对比请参阅
references/cex_vs_dex.md

Maker/Taker Fee Structures

做市/吃单手续费结构

CEX fee tiers create incentive asymmetries:
TierMaker FeeTaker FeeNet Spread Required
VIP 00.10%0.10%20 bps to break even
VIP 50.02%0.05%7 bps to break even
VIP 9-0.005%0.03%2.5 bps + rebate income
At high tiers, maker rebates mean market makers are paid to provide liquidity. This fundamentally changes strategy economics:
python
def maker_pnl_per_trade(
    spread_captured_bps: float,
    maker_fee_bps: float,
    adverse_selection_bps: float,
) -> float:
    """Compute market maker P&L per round trip.

    Args:
        spread_captured_bps: Half-spread captured on each side.
        maker_fee_bps: Maker fee (negative = rebate).
        adverse_selection_bps: Expected loss to informed flow.

    Returns:
        Net P&L in basis points per round trip.
    """
    gross = 2 * spread_captured_bps  # earn half-spread on each leg
    fees = 2 * maker_fee_bps         # pay/receive fee on each leg
    return gross - fees - adverse_selection_bps

CEX手续费层级会产生激励不对称:
层级做市商手续费吃单手续费盈亏平衡所需净价差
VIP 00.10%0.10%20个基点
VIP 50.02%0.05%7个基点
VIP 9-0.005%0.03%2.5个基点 + 返佣收入
在高级别层级,做市商返佣意味着做市商提供流动性会获得报酬,这从根本上改变了策略经济学:
python
def maker_pnl_per_trade(
    spread_captured_bps: float,
    maker_fee_bps: float,
    adverse_selection_bps: float,
) -> float:
    """计算做市商每轮交易的盈亏。

    参数:
        spread_captured_bps: 每边获取的半价差(基点)。
        maker_fee_bps: 做市商手续费(负数代表返佣)。
        adverse_selection_bps: 预期因知情资金流产生的损失(基点)。

    返回:
        每轮交易的净盈亏(基点)。
    """
    gross = 2 * spread_captured_bps  # 每边赚取半价差
    fees = 2 * maker_fee_bps         # 每边支付/收取手续费
    return gross - fees - adverse_selection_bps

Files

文件

References

参考文档

  • references/price_formation.md
    — Glosten-Milgrom, Kyle model, PIN model, spread decomposition
  • references/execution_quality.md
    — VWAP, TWAP, implementation shortfall, slippage decomposition
  • references/cex_vs_dex.md
    — Structural comparison of LOB vs AMM, hybrid models, routing decisions
  • references/price_formation.md
    — Glosten-Milgrom模型、Kyle模型、PIN模型、价差分解
  • references/execution_quality.md
    — VWAP、TWAP、执行缺口、滑点分解
  • references/cex_vs_dex.md
    — LOB与AMM的结构对比、混合模型、路由决策

Scripts

脚本

  • scripts/spread_analysis.py
    — Analyze bid-ask spreads, compute effective/realized/quoted spread from trade data (--demo mode with synthetic order book)
  • scripts/market_maker_sim.py
    — Market maker simulation with inventory management and P&L (--demo mode with synthetic price path)

  • scripts/spread_analysis.py
    — 分析买卖价差,从交易数据计算有效/实现/报价价差(--demo模式使用合成订单簿)
  • scripts/market_maker_sim.py
    — 包含库存管理和盈亏计算的做市商模拟(--demo模式使用合成价格路径)

Dependencies

依赖项

bash
uv pip install numpy pandas scipy matplotlib

bash
uv pip install numpy pandas scipy matplotlib

Related Skills

相关技能

  • market-microstructure — On-chain DEX microstructure (AMM-specific)
  • slippage-modeling — Execution cost estimation and modeling
  • liquidity-analysis — Pool and order book depth analysis
  • order-execution — Practical execution algorithms
  • mev-analysis — MEV risk in on-chain execution
  • market-microstructure — 链上DEX微观结构(AMM专属)
  • slippage-modeling — 执行成本估算与建模
  • liquidity-analysis — 资金池与订单簿深度分析
  • order-execution — 实用执行算法
  • mev-analysis — 链上执行中的MEV风险