返回 Expert 笔记
Expert Day 116

Week 17 复习 / Week 17 Review — DEX 量化全栈

整合 Day 103-115 的所有 DEX 量化能力, 形成统一栈视图

2026-08-25
Phase 2 - MEV与DEX量化 (Day 103-116)
DEXStrategiesFullStackLibraryReviewPhase2End

日期: 2026-08-25 方向: MEV / DEX量化 阶段: Phase 2 - MEV与DEX量化 (Day 103-116) 标签: #DEXStrategies #FullStack #Library #Review #Phase2End


今日目标 / Today's Objectives

类型内容
学习整合 Day 103-115 的所有 DEX 量化能力, 形成统一栈视图
实操把分散脚本整合成 dex_strategies Python 库 v1
产出dex_strategies/ 目录 — 模块化代码 + tests + README

1. Phase 2 全景回顾 / Full Phase 2 Recap

1.1 DEX 量化能力图

┌────────────────── DEX 量化全栈 ──────────────────┐
│                                                   │
│  ┌── Data Layer ─────────────────────────────┐  │
│  │  - Subgraph (Day 114)                      │  │
│  │  - Mempool subscribe (Day 115)             │  │
│  │  - Flipside / Dune SDK                     │  │
│  └─────────────────────────────────────────────┘  │
│                                                   │
│  ┌── Analysis Layer ──────────────────────────┐  │
│  │  - LVR calculator (Day 111)                │  │
│  │  - Bribe efficiency (Day 112)              │  │
│  │  - MEV parser (Day 103)                    │  │
│  │  - Vault analytics (Day 113)               │  │
│  └─────────────────────────────────────────────┘  │
│                                                   │
│  ┌── Strategy Layer ──────────────────────────┐  │
│  │  - Router / SOR (Day 110)                  │  │
│  │  - Atomic arb searcher (Day 106)           │  │
│  │  - OFA filler logic (Day 108)              │  │
│  │  - Cross-domain arb (Day 107)              │  │
│  └─────────────────────────────────────────────┘  │
│                                                   │
│  ┌── Execution Layer ─────────────────────────┐  │
│  │  - Bundle submit (Day 104)                 │  │
│  │  - Multi-relay broadcast (Day 105)         │  │
│  │  - mev-boost interaction                   │  │
│  └─────────────────────────────────────────────┘  │
└───────────────────────────────────────────────────┘

1.2 关键数字回顾

项目数据
2024 全年 MEV~$925M
Validator 拿走比例~88%
Builder 集中度 (HHI)0.36
OFA / DEX volume share~30-40%
LVR (in 0.05% V3 ETH/USDC)~$12-14M/year
Curve bribery leverage~4x
Mempool tx delay (P50)~150ms
顶级 searcher 月利润$5-15M

2. dex_strategies 库结构 / Library Structure

dex_strategies/
├── __init__.py
├── data/
│   ├── __init__.py
│   ├── mempool.py           # Day 115
│   ├── subgraph.py          # Day 114
│   ├── flipside_client.py
│   └── dune_client.py
├── analytics/
│   ├── __init__.py
│   ├── lvr.py               # Day 111
│   ├── mev_parser.py        # Day 103
│   ├── bribe_efficiency.py  # Day 112
│   └── vault_metrics.py     # Day 113
├── strategy/
│   ├── __init__.py
│   ├── router.py            # Day 110
│   ├── atomic_arb.py        # Day 106
│   ├── ofa_filler.py        # Day 108
│   └── cross_domain.py      # Day 107
├── execution/
│   ├── __init__.py
│   ├── bundle.py            # Day 104
│   ├── relay.py             # Day 105
│   └── private_rpc.py
├── tests/
│   ├── test_router.py
│   ├── test_lvr.py
│   ├── test_mempool.py
│   └── conftest.py
├── examples/
│   ├── 01_basic_arb.py
│   ├── 02_lvr_dashboard.py
│   ├── 03_subgraph_monitor.py
│   └── 04_full_searcher.py
├── README.md
├── pyproject.toml
└── requirements.txt

2.1 pyproject.toml

[project]
name = "dex_strategies"
version = "0.1.0"
description = "DEX quant + MEV utilities for institutional research"
requires-python = ">=3.10"
dependencies = [
    "web3>=6.0",
    "eth-account",
    "eth-abi",
    "websocket-client",
    "requests",
    "numpy",
    "pandas",
    "networkx",
    "flipside",
    "python-dotenv",
]

[project.optional-dependencies]
dev = ["pytest", "pytest-cov", "black", "ruff", "mypy"]
test = ["pytest", "responses", "pytest-mock"]

[build-system]
requires = ["setuptools>=61.0"]
build-backend = "setuptools.build_meta"

2.2 __init__.py 顶层入口

"""dex_strategies — institutional DEX quant toolkit."""

from .analytics.lvr import lvr_v2_annual, lvr_v3_annual, fee_revenue_annual
from .analytics.mev_parser import find_sandwich, calc_searcher_pnl
from .strategy.router import find_best_route
from .strategy.atomic_arb import detect_arb_opportunity, build_arb_bundle
from .data.mempool import MempoolListener
from .data.subgraph import SubgraphClient
from .execution.bundle import BundleClient

__version__ = "0.1.0"
__all__ = [
    "lvr_v2_annual", "lvr_v3_annual", "fee_revenue_annual",
    "find_sandwich", "calc_searcher_pnl",
    "find_best_route",
    "detect_arb_opportunity", "build_arb_bundle",
    "MempoolListener",
    "SubgraphClient",
    "BundleClient",
]

2.3 examples/04_full_searcher.py — 端到端示例

"""End-to-end searcher example combining mempool + arb + bundle submit."""
import asyncio
from dex_strategies import (
    MempoolListener,
    detect_arb_opportunity,
    build_arb_bundle,
    BundleClient,
)


async def main():
    listener = MempoolListener(ws_url="ws://localhost:8545")
    bundle_client = BundleClient(
        relay_urls=[
            "https://relay.flashbots.net",
            "https://relay.ultrasound.money",
        ],
    )
    
    async for tx in listener.stream_decoded_swaps():
        # Day 110: route check + Day 106: arb detect
        opp = detect_arb_opportunity(tx)
        if opp is None or opp["expected_profit_usd"] < 100:
            continue
        
        bundle = build_arb_bundle(opp)
        result = await bundle_client.submit_to_all_relays(bundle)
        print(f"submitted to {len(result)} relays  expected=${opp['expected_profit_usd']:.0f}")


if __name__ == "__main__":
    asyncio.run(main())

2.4 tests/test_lvr.py

import pytest
from dex_strategies.analytics.lvr import lvr_v2_annual, lvr_v3_annual

def test_lvr_v2_basic():
    # σ=80%, pool=$10M → LVR = $800K
    assert abs(lvr_v2_annual(0.8, 10_000_000) - 800_000) < 1

def test_lvr_v3_in_range():
    # narrow range = high leverage
    val = lvr_v3_annual(0.8, 10_000_000, range_low=2900, range_high=3100, current_price=3000)
    assert val > 800_000   # > V2 baseline

def test_lvr_v3_out_of_range():
    val = lvr_v3_annual(0.8, 10_000_000, range_low=2900, range_high=3100, current_price=3500)
    assert val == 0

2.5 README 框架

# dex_strategies

> Institutional DEX quant toolkit.
> Built across Phase 2 (Day 103-116) of the Web3 Quant Mastery program.

## Modules

- `data/` — mempool subscribe, subgraph client, Flipside/Dune SDK
- `analytics/` — LVR, MEV parser, bribery efficiency, vault metrics
- `strategy/` — DEX router, atomic arb, OFA filler, cross-domain
- `execution/` — bundle build/submit, multi-relay, private RPC

## Quickstart

```bash
pip install -e ".[dev]"
export ETH_RPC=https://eth.llamarpc.com
python -m examples.02_lvr_dashboard

Examples

FileWhat it does
01_basic_arb.pyFind V2/V3 spread
02_lvr_dashboard.pyLVR vs fee revenue chart
03_subgraph_monitor.pyWatch swap volume hourly
04_full_searcher.pyEnd-to-end live searcher (testnet only)

---

## 3. 核心抽象 / Key Abstractions

### 3.1 Pool 抽象

```python
@dataclass
class PoolState:
    address: str
    protocol: str  # "v2", "v3", "curve", "balancer"
    token0: str
    token1: str
    reserves: tuple   # (r0, r1) for V2; (sqrt_price, liquidity, tick) for V3
    fee_bps: int
    block_number: int

    def quote(self, token_in: str, amount_in: int) -> int:
        # Polymorphic per protocol
        ...

3.2 Bundle 抽象

@dataclass
class Bundle:
    txs: list[bytes]
    target_block: int
    revert_allowed: list[bytes] = field(default_factory=list)
    min_timestamp: int = 0
    max_timestamp: int = 0

    def to_flashbots_payload(self) -> dict:
        return {
            "txs": [tx.hex() for tx in self.txs],
            "blockNumber": hex(self.target_block),
            "minTimestamp": self.min_timestamp,
            "maxTimestamp": self.max_timestamp,
            "revertingTxHashes": [t.hex() for t in self.revert_allowed],
        }

3.3 Strategy 接口

class Strategy(ABC):
    @abstractmethod
    def evaluate(self, tx: dict, state: dict) -> dict | None:
        """Return opportunity dict or None."""
    
    @abstractmethod
    def construct_bundle(self, opp: dict) -> Bundle:
        ...

4. Phase 2 关键学习总结 / Key Insights

4.1 MEV 是 DeFi 的"暗物质"

DeFi 表面是 LP fee + swap volume, 但其下 MEV 流量超过 protocol fee。任何 DEX 设计如果不考虑 MEV, 都是不完整的

4.2 Builder 集中是真正的 Ethereum 风险

PBS 解决了 validator 中心化, 但把问题转移到 builder。ePBS、SUAVE、Atlas 都是为了解决这个问题, 但都还在演进中

4.3 OFA 是 DEX 的下一代

UniswapX/CoW/Fusion 不是优化, 是范式转移。未来 5 年 DEX volume 60%+ 走 intent-based

4.4 LVR 重新定义了 LP 经济

Hayden Adams 的 LVR 公式让 LP 经济从直觉变成可量化。很多曾经"高 APY"的 V3 池实际净亏损

4.5 数据基础设施是隐形 alpha

机构间策略相似度高, 真正分胜负的是基础设施:node、mempool、私有 builder relationship。

4.6 Liquidity Wars 在演化

ve 模型创造了元层经济, 但长期看 liquidity 战争从 emission 转向 solver / OFA filler 关系。


5. 真实数据快照 / Snapshot Data

指标 (2025-Q3)数值
Total MEV YTD~$700M
Validator MEV uplift+35-45% staking yield
OFA share of DEX volume~35%
Top atomic arb monthly$5-15M (单 bot)
V3 ETH/USDC 0.05% LVR~$12M/yr
Curve bribe ROI~4x
Yearn V3 TVL~$300M
Aera DAO TVL~$500M
Goldsky subgraphs500+

6. 经济学综合 / Economic Synthesis

DEX 量化的资本流动总览(年度):

User swap 总量:                   ~$3 trillion
LP fee 收入:                      ~$2-3 billion
LVR loss to LP:                   ~$1-1.5 billion (重叠在 fee 之内, 不可加)
MEV total extracted:              ~$925M
  - Validator (88%):              ~$815M
  - Builder (~3%):                ~$28M
  - Searcher (~9%):               ~$80M
  - LP loss component (LVR-MEV):  ~$700M (重叠)
OFA solver / filler 收入:        ~$200-400M
Vault management 收入:            ~$50-100M
Liquidity wars bribery:          ~$50-100M

7. 机构视角 — Phase 2 应用 / Institutional Application

机构 quant 团队搭建路线图 (基于 Phase 2 内容):

Month 1-2: Data infra
  ✓ Erigon node + WS
  ✓ Subgraph for top 20 pools
  ✓ Mempool listener
  ✓ Flipside / Dune accounts

Month 3-4: Analytics
  ✓ LVR dashboard for 50 V3 pools
  ✓ MEV monitor (sandwich/arb detection)
  ✓ Vault TVL true-vs-stated

Month 5-6: Strategy
  ✓ Atomic arb searcher (testnet → mainnet小额)
  ✓ OFA filler bot (CoW solver)
  ✓ V3 active LP (Arrakis style)

Month 7+: Execution
  ✓ Bundle submission with multi-relay
  ✓ Private builder relationship
  ✓ ePBS / SUAVE 接入预案

预算估算:

  • Infra: $50-100K/year
  • Tooling: $30-50K/year
  • Capital deployment: $5-50M (取决于策略)
  • Team: 3-5 quant + 2-3 eng → ~$2-4M/year

对应 ROI: 年化 15-30% on 部署资金, top quartile 40-80%.


8. 风险与陷阱(Phase 2 综合) / Combined Risks

  1. Strategy decay: 任何 alpha 在公开 6-12 个月后衰减 80%+
  2. Builder/relay 集中: 业务全部依赖 1-2 家中介
  3. 协议升级 (V4, OFA, ePBS): 大量 codebase 重写
  4. Regulatory shock: SEC 把 sandwich 定罪 / KYC 要求 OFA solver
  5. 节点 / mempool service 服务商单点故障
  6. LVR / inventory 风险: 做 LP 或 active MM 都承担市场风险
  7. Bridge / cross-chain hack: 跨域策略风险敞口
  8. Smart contract bug: 自营 Executor 合约 bug 直接亏全部资金

9. 面试题 — Phase 2 综合 / Combined Interview Questions

  1. 画出 DEX 量化资本流向图,从 user swap 到 LP/searcher/builder/validator 的所有现金流。
  2. 如果你是一家 a16z / Paradigm 投资的 DEX 量化 startup CEO, 用 100M 起步资金, 1-3 年策略 roadmap?
  3. 比较 ETH mainnet 与 Solana DEX 量化的本质差异 (Jito, mempool 缺失, slot duration)。
  4. OFA/SUAVE 让传统 atomic arb 的价值缩水。下一代 DEX 量化的 alpha 来源在哪?
  5. 设计一个 DEX 量化 fund 的合规风控框架, 给机构 LP 看的 due diligence package 应包含哪些内容?
  6. 当 ePBS 上线后, Flashbots Relay、Builder、Searcher 的市场结构会如何重构? 给 5-year 预测.
  7. 机构客户委托一个 vault 给你管理 $50M, 偏好 Curve/Balancer LP. 你会用 ve-bribe 还是直接 LP? Why?
  8. 写一个 dex_strategies 库的 production deployment checklist (>= 15 项)。

10. Phase 2 完成检验 / Completion Checklist

  • MEV 生态全景理解 (Day 103-109)
  • DEX 路由算法实现 (Day 110)
  • LVR 计算与理解 (Day 111)
  • Liquidity wars + bribe 模型 (Day 112)
  • Vault 架构对比 (Day 113)
  • 链上数据基础设施 (Day 114)
  • 实时交易基础设施 (Day 115)
  • dex_strategies v1 库整合 (Day 116)

硬性产出:

  • 14 篇 Expert Day 笔记
  • 14 个独立 .py / .md 文件
  • 1 个综合 Python 库 (dex_strategies)
  • 8+ 个面试题答案库
  • 多个真实合约地址 + API endpoint 速查

11. 下一阶段预告 / Next Phase Preview

Phase 3 (Day 117+): On-chain Quant 实战 + 机构对接 方向待定,可能涵盖:

  • Lending market quant (清算引擎、利率曲线 alpha)
  • Restaking / LRT economics
  • 机构 best-execution 系统设计
  • Compliance + risk reporting 自动化
  • Cross-asset strategies (RWA, tokenized treasury)

Phase 2 to Phase 3 桥梁: dex_strategies 库将作为 Phase 3 多个项目的基础设施。


12. 关键速查(Phase 2 总览) / Master Quick Reference

概念关键文件 / 公式
MEV parsingDay 103 mev_parse.py
Bundle submitDay 104 bundle.py
Builder sharemevboost.pics
Atomic arbDay 106 searcher.py
OFA comparisonDay 108 ofa_compare.md
RouterDay 110 router.py
LVR formulaσ²/8 × pool_value
Bribe ROI~4x leverage on Curve
Vault standardERC-4626
SubgraphDay 114 subgraph_demo
MempoolDay 115 mempool.py
Master librarydex_strategies/ (Day 116)

Phase 2 完结。 dex_strategies v1 库就绪 ✓