永续合约做市 (Hyperliquid / dYdX / GMX)
三大 DEX perp 架构对比、funding rate 机制、做市奖励项目、liquidation engine、API 接入
日期: 2026-07-27 方向: 量化 / 微观结构 / 做市 阶段: Phase 2 - 市场微观结构与做市 (Day 75-88) 标签: #Perp #Hyperliquid #dYdX #GMX #Funding #DEX
今日目标
| 类型 | 内容 |
|---|---|
| 学习 | 三大 DEX perp 架构对比、funding rate 机制、做市奖励项目、liquidation engine、API 接入 |
| 实操 | 抓取 Hyperliquid 实时 L2 book + funding + open interest,比较与 CEX 数据 |
| 产出 | hyper_data.py:Hyperliquid 完整数据接入 + 做市机会分析 + funding arbitrage |
永续合约 (perp) 是 crypto 的"主战场"——日均成交 $100B+,是现货 5-10 倍。三大 DEX perp 平台各有架构创新。
一、Perp 是什么?为什么做市机会丰富?
1.1 永续合约定义
- 没有到期日的期货合约
- 用 funding rate 机制让合约价格 ≈ spot price
- funding 每 8h(CEX)或 1h(Hyperliquid)/ 每 block(GMX)结算
1.2 funding rate 机制
premium = (perp_price - spot_price) / spot_price
funding_rate = clamp(premium + interest_rate, -0.75%, +0.75%)
every funding period:
if funding_rate > 0: long pays short
else: short pays long
直觉:long > short → premium > 0 → long 付 funding 给 short → suppression 套利空间。
1.3 做市机会丰富的原因
- Spread 普遍宽 vs 现货(liquidity 集中但 vol 大)
- Funding rate 套利:spot long + perp short 锁差
- Cross-venue mispricing:Binance vs Bybit vs DEX 不同时段差 5-50 bps
- Liquidation cascading:清算时 spread 暴增 100x,做市可顺势 widen
二、三大 DEX Perp 架构对比
| 维度 | dYdX v4 | GMX v2 | Hyperliquid |
|---|---|---|---|
| 架构 | 独立 Cosmos appchain | Solana / Arbitrum AMM-like | 独立 L1 (custom) |
| 撮合 | LOB(链下 → 链上结算) | Oracle priced AMM (GLP/GM) | LOB(全链上) |
| 做市方 | 显式 maker(订单簿挂单) | LP 池(被动) | 显式 maker |
| 价格来源 | 撮合发现 | Chainlink + median | 撮合发现 |
| 流动性形式 | 限价挂单 | LP 资金池被动接 | 限价挂单 |
| maker fee | -1 bps (rebate) | N/A (LP earns spread) | -1 bps to 1 bps |
| taker fee | 5 bps | 5-7 bps | 3.5-7 bps |
| funding rate | 1h 计算,CEX 平均 | counter-position-based | 1h |
| liquidation | 拍卖 → 流动性提供方接 | LP 池接 + 清算费 | tiered liquidation engine |
| TPS | 1000+ | block time | 200K (claimed) |
| 去中心化程度 | high (validator set) | medium | medium (centralized seq) |
| 接近 CEX UX | medium | low | very high |
2.1 dYdX v4
- 全链上 LOB on Cosmos chain
- 撮合通过 validator network
- API 类似 CEX(限价挂单、IOC、stop)
- Maker 程序:volume share rewards
2.2 GMX v2
- LP 池(GLP / GM)做交易对手
- Trader 用 oracle 价格直接成交,无 spread 滑点(除 fee)
- LP 承担 OI imbalance 风险(funding 调节)
- 不是"传统"做市机会,但 LP 等于"做市"
2.3 Hyperliquid(重点)
- 独立 L1,自研共识
- 完全 onchain LOB(包括订单流)
- API 类似 Binance(REST + WS)
- 做市 incentive:HLP 池 + 季度 maker rewards
三、Hyperliquid 数据接入
3.1 REST API
Base URL: https://api.hyperliquid.xyz
POST /info
body: { "type": <type>, ...filters }
types:
- "meta" -> universe, asset config
- "l2Book" -> orderbook snapshot
- "allMids" -> all asset mid prices
- "metaAndAssetCtxs" -> per-asset funding, OI, mark, oracle
- "candleSnapshot" -> klines
- "userState" -> 自己的 position
3.2 真实样例响应:L2 Book
import requests
r = requests.post("https://api.hyperliquid.xyz/info",
json={"type": "l2Book", "coin": "BTC"}).json()
print(r)
{
"coin": "BTC",
"time": 1709337600000,
"levels": [
[
{"px": "62150.0", "sz": "1.234", "n": 3},
{"px": "62149.5", "sz": "0.500", "n": 1},
{"px": "62149.0", "sz": "2.100", "n": 5}
],
[
{"px": "62150.5", "sz": "0.789", "n": 2},
{"px": "62151.0", "sz": "1.456", "n": 4},
{"px": "62151.5", "sz": "3.200", "n": 7}
]
]
}
levels[0] = bids, levels[1] = asks。每档 (price, size, num_orders)。
3.3 funding & open interest
r = requests.post("https://api.hyperliquid.xyz/info",
json={"type": "metaAndAssetCtxs"}).json()
# r[1] = list of asset contexts, in same order as r[0]['universe']
btc_idx = next(i for i,a in enumerate(r[0]["universe"]) if a["name"]=="BTC")
btc_ctx = r[1][btc_idx]
{
"funding": "0.0000125", // 1h funding rate
"openInterest": "1234.567", // BTC 单位
"premium": "-0.000023",
"oraclePx": "62148.50",
"markPx": "62150.10",
"midPx": "62150.25",
"impactPxs": ["62149.0","62151.5"], // 衡量大单 impact
"dayNtlVlm": "234567890.12",
"prevDayPx": "61234.50"
}
impactPxs 是 Hyperliquid 独有:估计 +-$10K size 立即 impact。
3.4 WebSocket
wss://api.hyperliquid.xyz/ws
subscribe message:
{
"method": "subscribe",
"subscription": {
"type": "l2Book",
"coin": "BTC"
}
}
每次 push 完整 snapshot(不是增量)— 简化但 bandwidth 高
其它 subscription types:
- "trades" coin
- "candle" coin, interval
- "bbo" coin (best bid/offer)
- "userEvents" user (private)
- "userFills" user
3.5 真实 trade event
{
"channel": "trades",
"data": [
{"coin":"BTC","px":"62150.10","sz":"0.012",
"side":"B","time":1709337600234,"hash":"0x..."}
]
}
side: "B" = buy aggressor, "A" = sell aggressor。
四、代码实现:hyper_data.py
"""
hyper_data.py — Hyperliquid 数据接入 + 做市机会分析
依赖:requests, pandas, numpy, websockets
"""
import requests, json, asyncio, websockets
import pandas as pd, numpy as np
from collections import deque
BASE_URL = "https://api.hyperliquid.xyz"
WS_URL = "wss://api.hyperliquid.xyz/ws"
# ----------------------------------------------------------
# 1. REST 函数
# ----------------------------------------------------------
def get_meta_ctxs():
r = requests.post(f"{BASE_URL}/info",
json={"type":"metaAndAssetCtxs"}, timeout=5).json()
universe = r[0]["universe"]
ctxs = r[1]
rows = []
for a, c in zip(universe, ctxs):
rows.append({
"coin": a["name"],
"max_lev": int(a.get("maxLeverage", 0)),
"funding_1h": float(c.get("funding", 0)),
"funding_8h_equiv": float(c.get("funding", 0)) * 8,
"open_interest": float(c.get("openInterest", 0)),
"premium": float(c.get("premium", 0)),
"mark_px": float(c.get("markPx", 0)),
"oracle_px": float(c.get("oraclePx", 0)),
"mid_px": float(c.get("midPx", 0)),
"day_vol_usd": float(c.get("dayNtlVlm", 0)),
"prev_day_px": float(c.get("prevDayPx", 0)),
})
return pd.DataFrame(rows)
def get_l2_book(coin: str = "BTC", n_levels: int = 20):
r = requests.post(f"{BASE_URL}/info",
json={"type":"l2Book","coin":coin}).json()
bids = [(float(x["px"]), float(x["sz"]), x["n"]) for x in r["levels"][0][:n_levels]]
asks = [(float(x["px"]), float(x["sz"]), x["n"]) for x in r["levels"][1][:n_levels]]
return {
"coin": coin,
"time": r["time"],
"bids": bids,
"asks": asks,
"best_bid": bids[0][0] if bids else None,
"best_ask": asks[0][0] if asks else None,
"spread_bps": (asks[0][0] - bids[0][0]) / asks[0][0] * 1e4 if (bids and asks) else None,
"depth_5_bid": sum(s for _,s,_ in bids[:5]),
"depth_5_ask": sum(s for _,s,_ in asks[:5]),
}
def get_candles(coin="BTC", interval="1h", limit=24):
r = requests.post(f"{BASE_URL}/info", json={
"type":"candleSnapshot",
"req":{"coin":coin,"interval":interval,
"startTime": int(pd.Timestamp.now().timestamp()*1000)
- limit*3600*1000,
"endTime": int(pd.Timestamp.now().timestamp()*1000)}
}).json()
df = pd.DataFrame(r)
if df.empty: return df
for c in ["o","h","l","c","v"]:
df[c] = df[c].astype(float)
df["t"] = pd.to_datetime(df["t"], unit="ms")
return df
# ----------------------------------------------------------
# 2. 做市机会扫描
# ----------------------------------------------------------
def mm_opportunity_scanner(min_oi_usd=1e6, min_spread_bps=2.0):
"""
扫所有 perp,找 spread 宽且有一定 OI 的做市候选
"""
meta = get_meta_ctxs()
out = []
for _, row in meta.iterrows():
oi_usd = row["open_interest"] * row["mark_px"]
if oi_usd < min_oi_usd: continue
try:
book = get_l2_book(row["coin"])
except Exception:
continue
if book["spread_bps"] is None or book["spread_bps"] < min_spread_bps:
continue
out.append({
"coin": row["coin"],
"spread_bps": book["spread_bps"],
"oi_usd": oi_usd,
"day_vol_usd": row["day_vol_usd"],
"funding_1h": row["funding_1h"]*1e4, # bps
"depth_5_bid": book["depth_5_bid"],
"depth_5_ask": book["depth_5_ask"],
})
return pd.DataFrame(out).sort_values("spread_bps", ascending=False)
# ----------------------------------------------------------
# 3. funding rate 套利监控
# ----------------------------------------------------------
def funding_arb_signal(coin="BTC", binance_funding_8h=None):
"""
比较 Hyperliquid funding 与 Binance funding
"""
meta = get_meta_ctxs()
row = meta[meta["coin"] == coin].iloc[0]
hl_funding_8h = row["funding_8h_equiv"] * 1e4 # bps
if binance_funding_8h is None:
# fetch Binance
r = requests.get("https://fapi.binance.com/fapi/v1/premiumIndex",
params={"symbol":f"{coin}USDT"}).json()
binance_funding_8h = float(r["lastFundingRate"]) * 1e4
diff = hl_funding_8h - binance_funding_8h
return {
"hl_funding_8h_bps": hl_funding_8h,
"binance_funding_8h_bps": binance_funding_8h,
"diff_bps": diff,
"annualized_arb_bps": diff * 3 * 365 # 8h 周期 365×3 倍
}
# ----------------------------------------------------------
# 4. WebSocket 实时 spread 监控
# ----------------------------------------------------------
async def stream_bbo(coin="BTC", duration_s=60):
spreads = deque(maxlen=1000)
async with websockets.connect(WS_URL) as ws:
await ws.send(json.dumps({"method":"subscribe",
"subscription":{"type":"bbo","coin":coin}}))
start = pd.Timestamp.now()
while (pd.Timestamp.now() - start).total_seconds() < duration_s:
raw = await ws.recv()
msg = json.loads(raw)
if msg.get("channel") == "bbo":
bid = float(msg["data"]["bbo"][0]["px"])
ask = float(msg["data"]["bbo"][1]["px"])
spreads.append((ask - bid) / ((ask+bid)/2) * 1e4)
return list(spreads)
# ----------------------------------------------------------
# 5. 演示
# ----------------------------------------------------------
if __name__ == "__main__":
# 5.1 全市场扫描
print("=== Hyperliquid Perp Markets ===")
scan = mm_opportunity_scanner(min_oi_usd=1e6, min_spread_bps=1.0)
print(scan.head(20).to_string())
# 5.2 BTC L2 book
print("\n=== BTC L2 Book ===")
book = get_l2_book("BTC", n_levels=5)
print(json.dumps({k:(v if not isinstance(v,float) else round(v,4))
for k,v in book.items() if k not in ["bids","asks"]},
indent=2))
print("Top 5 bids:", book["bids"])
print("Top 5 asks:", book["asks"])
# 5.3 funding rate arb
print("\n=== BTC Funding Arbitrage ===")
arb = funding_arb_signal("BTC")
print(arb)
# 5.4 1h kline
print("\n=== BTC 1h candles (last 24h) ===")
df = get_candles("BTC", "1h", 24)
print(df.tail(5))
预期输出:
=== Hyperliquid Perp Markets ===
coin spread_bps oi_usd day_vol_usd funding_1h depth_5_bid depth_5_ask
0 HYPE 12.4 45000000 120000000 2.31 5000.0 4800.0
1 WIF 8.2 32000000 88000000 1.85 12000.0 11500.0
2 PURR 6.5 12000000 35000000 0.95 8000.0 7500.0
...
=== BTC L2 Book ===
{
"coin":"BTC", "time": 1709337600000,
"best_bid": 62150.0, "best_ask": 62150.5,
"spread_bps": 0.0805, "depth_5_bid": 5.234, "depth_5_ask": 5.789
}
...
=== BTC Funding Arbitrage ===
{'hl_funding_8h_bps': 1.0, 'binance_funding_8h_bps': 0.5,
'diff_bps': 0.5, 'annualized_arb_bps': 547.5}
4.1 多 venue 同步监控(生产 mm 必需)
async def cross_venue_monitor():
"""
同时订阅 Hyperliquid + Binance + Bybit BTC,找跨所价差
"""
venues = {
"HL": ("wss://api.hyperliquid.xyz/ws",
{"method":"subscribe",
"subscription":{"type":"bbo","coin":"BTC"}}),
"Binance": ("wss://fstream.binance.com/ws/btcusdt@bookTicker", None),
"Bybit": ("wss://stream.bybit.com/v5/public/linear",
{"op":"subscribe","args":["orderbook.1.BTCUSDT"]}),
}
# 并发订阅,组合 mid 计算 cross-venue mispricing
...
五、做市策略:Hyperliquid 适应
5.1 主要差异 vs Binance
| 项 | Binance Futures | Hyperliquid |
|---|---|---|
| Latency | < 10ms (colo) | 100-500ms |
| 撮合最快频率 | 微秒 | 200ms block time |
| Cancel rate limit | 1200/min | 150-300/s(更宽松但 batch 鼓励) |
| API stability | very high | improving |
| Funding 周期 | 8h | 1h(更频繁) |
5.2 策略调整
- Wider initial spread — 200ms latency 让 stale quote 风险高,比 Binance 多加 2-3 bps
- Lower fill rate target — order count vs fill ratio 接受更低(因 latency)
- Funding-aware:1h funding 让 funding-arb 信号更新更频繁
- Cross-venue mid:用 Binance mid + premium 估 fair value,而非纯 HL mid
5.3 HLP (Hyperliquid Pool) 做市机会
HLP 是 HL 的"被动 LP" 池:
- 类 GMX 但做 LOB 后端
- 任何人可存 USDC 进 HLP,分润成交 PnL + funding
- HLP 在 LOB 里挂被动单(被吃即赚 spread)
特殊机会:HLP 的"吃单速率"由协议参数决定,可计算 expected APY。
六、CEX vs DEX Perp 对比 (深度)
| 维度 | Binance/Bybit (CEX) | Hyperliquid | dYdX | GMX |
|---|---|---|---|---|
| 撮合粒度 | µs | 200ms block | block | block |
| 做市效率 | maximal | 接近 CEX | 接近 CEX | LP-only |
| 资本要求 | KYC + USDT | wallet only | wallet only | wallet only |
| counterparty | exchange | smart contract | smart contract | LP pool |
| transparency | private order book | public on-chain | public | trader vs LP |
| funding mech | premium-based | premium-based | CEX avg | OI imbalance |
| liquidation | maintenance margin | tiered | tiered | LP backstop |
| MEV exposure | none | sequencer 隐私 | low | high (oracle update) |
| typical maker | retail + prop firm | retail + small prop | growing | LPs |
6.1 哪类做市机会在哪里更好?
| 机会类型 | 最佳场所 |
|---|---|
| HFT µs MM | Binance/OKX (colo) |
| Cross-venue arb | 多 CEX + Hyperliquid |
| Funding rate arb | HL + Binance pair |
| Long-tail token MM | HL(先发优势) |
| Passive LP-style | GMX GLP |
| MEV-hedged MM | HL(mempool privacy) |
七、风险与陷阱
-
Hyperliquid sequencer 中心化 单点失败 → 一段时间不可交易,库存裸暴露。修复:HL 头寸不超过总 portfolio 的 30%。
-
Funding rate spikes meme coin perp 可能 funding 50 bps/8h(瞬态 spike)。多头一夜亏 5%。修复:funding > 阈值时强制减仓。
-
Oracle delay (GMX) GMX 用 Chainlink,1 min 才更新。GMX MM bot 在 oracle 跳前抢交易 = 显著 alpha,但被官方限制。
-
HL withdrawal 队列 USDC 出 HL 桥到 ETH 主网有 4 hr 延迟(fraud proof window)。临时缺资 → 不能 hedge → 库存裸。
-
API rate limit 不一 Binance 1200 weight/min;HL 比较宽松但 burst 限制不同。生产 MM 需要 venue-specific rate limit handler。
-
DEX 上 long tail 流动性 illusion 某 meme perp display $5M OI 但实际 50 个 wallet。一个 whale 出走 spread 立刻 100x。
-
抽税 / 提现限制 美国 / 欧洲监管影响 dYdX、GMX 用户。HL 仍 grey area。生产策略要考虑 KYC tier。
八、关键速查
Hyperliquid endpoints:
POST https://api.hyperliquid.xyz/info (read)
POST https://api.hyperliquid.xyz/exchange (write, signed)
WS wss://api.hyperliquid.xyz/ws
Info types:
l2Book / allMids / metaAndAssetCtxs / candleSnapshot
userState / userFills / userFunding
WS subscriptions:
l2Book / trades / candle / bbo / userEvents
Funding:
perp = spot · (1 + premium)
premium > 0 → long pays short
Cross-venue arb expected:
diff_bps · 3 funding_per_day · 365 = APY bps
三大 DEX perp 速记
dYdX v4 — 完全 LOB on Cosmos chain,CEX-like API
GMX v2 — LP 池被动接,oracle priced,无 spread
Hyperliquid — 全链上 LOB,自研 L1,最接近 Binance
九、面试题
Q1: Hyperliquid 与 Binance Futures 的核心架构差异?
A: (i) HL 是独立 L1,所有订单流上链;Binance 集中式 matching engine。(ii) HL 自研共识,200ms block time;Binance µs;(iii) HL maker/taker fee 类似,但 maker rebate 程序通过 HLP 分润,间接给做市商;(iv) HL withdrawal 经 ETH 桥需 fraud-proof window;(v) HL 完全无 KYC,Binance 视司法管辖区严格。
Q2: GMX LP(GLP)如何"做市"?
A: GLP 持有多种资产(ETH、BTC、USDC等),按 weights。Trader 用 oracle 价格直接和 GLP swap/open position。Trader 长期 PnL → GLP 短期承担(trader 赢 GLP 亏,反之)。"做市"在这里 = 提供 capital 让 trader 有对手。LP 收益 = trading fee + funding 不平衡的 net + price exposure to GLP basket。
Q3: 跨 venue funding arb 如何执行?
A: 例:HL BTC funding 1 bps/8h、Binance 0.5 bps/8h,差 0.5 bps。 Strategy: Binance long BTC perp + HL short BTC perp,每 8h 净收 0.5 bps。 Steps: (i) 对 USDT/USDC 各放 50% 抵押;(ii) 锁仓 size 相同;(iii) 监控两边的 funding,任一出现负值时关仓;(iv) 总 PnL ≈ funding diff − fee × 2 − spread × 2。年化 0.5 bps × 3 × 365 = 547 bps(5.5% APY),高位 carry。
Q4: 在 HL 做市策略与 Binance 做市策略的关键不同点?
A: (i) latency:HL 200ms vs Binance < 10ms → HL 用 wider spread;(ii) funding 周期 1h vs 8h → HL funding 信号更高频;(iii) cancellation 限制:HL 鼓励 batch;(iv) HL 用户更窄群体(crypto-native),noise 流量比 Binance 小 → adverse selection 比例高 → 必须更保守 inventory;(v) HL 资产范围有限(150+ vs Binance 300+),策略 cross-asset 选择少。
Q5: 评估一个 DEX perp 平台的"做市友好度",你会看什么?
A: 检查项:
- maker fee schedule — rebate vs flat
- API quality — REST + WS 完整性、文档、stability
- rate limit — 能否支持 high-freq cancel/replace
- funding rate machanism — 是否易被 manipulation
- liquidation engine fairness — 是否给 maker 优先 fill
- deposit/withdraw friction — 资金能否 30min 内进出
- maker rewards program — 季度/月度 maker volume rewards
- OI cap & tier — 大户进入会否被 reject
- DEX 是否被 sequencer 抢跑 — privacy guarantees
- historical uptime + incident response
明日预告
Day 88:Week 13 复习与 DEX vs CEX 做市完整对比 — Phase 2 收官。把 14 天的内容压缩成一份**"DEX vs CEX 做市对比报告"**:架构、数学、策略、收益、风险五维度。这份报告将作为简历/面试用的 capstone 产出,证明你掌握了从 LOB 微观结构到 V3 LP 数学到永续 hedge 的完整链条。