Hyperliquid作为高性能去中心化交易所,提供了完善的API接口供开发者进行程序化交易和数据分析。本文将详细介绍Hyperliquid的WebSocket实时数据流、HTTP REST接口以及接口限流规则,帮助开发者快速接入Hyperliquid生态。
| 环境 | HTTP端点 | WebSocket端点 |
|---|---|---|
| 主网 | https://api.hyperliquid.xyz | wss://api.hyperliquid.xyz/ws |
| 测试网 | https://api.hyperliquid-testnet.xyz | wss://api.hyperliquid-testnet.xyz/ws |
Hyperliquid官方和社区提供了多种语言的SDK:
Hyperliquid的HTTP API主要分为两大类:Info端点(查询信息)和Exchange端点(交易操作)。
Info端点用于获取交易所和用户相关信息,所有请求都使用POST方法发送到 https://api.hyperliquid.xyz/info。
json{
"type": "<请求类型>",
// 其他参数...
}
json// 请求
{
"type": "allMids"
}
// 响应
{
"APE": "4.33245",
"ARB": "1.21695",
...
}
json// 请求
{
"type": "openOrders",
"user": "0x..." // 42字符十六进制地址
}
// 响应
[
{
"coin": "BTC",
"limitPx": "29792.0",
"oid": 91490942,
"side": "A",
"sz": "0.0",
"timestamp": 1681247412573
}
]
json// 请求
{
"type": "clearinghouseState",
"user": "0x..."
}
// 响应
{
"assetPositions": [...],
"marginSummary": {
"accountValue": 1000.0,
"totalNtlPos": 500.0,
"totalRawUsd": 500.0,
"totalMarginUsed": 100.0
},
"withdrawable": 900.0
}
json// 请求
{
"type": "l2Book",
"coin": "BTC"
}
// 响应包含买卖盘深度数据
json// 请求
{
"type": "meta"
}
// 响应包含所有交易对信息、资产索引等
返回时间范围数据的接口最多返回500个元素。要查询更大范围,使用最后返回的时间戳作为下一次请求的 startTime。
coin 使用 meta 响应中返回的名称coin 格式为 PURR/USDC 或 @{index}(如 @107 表示HYPE)Exchange端点用于执行交易操作,所有请求发送到 https://api.hyperliquid.xyz/exchange,需要签名认证。
json{
"action": {
"type": "<操作类型>",
// 操作参数
},
"nonce": 1704067200000, // 毫秒时间戳
"signature": {
// EIP-712签名数据
},
"vaultAddress": "0x..." // 可选,用于子账户或金库
}
json{
"action": {
"type": "order",
"orders": [{
"a": 0, // 资产索引
"b": true, // 是否买入
"p": "50000", // 价格
"s": "0.1", // 数量
"r": false, // 是否reduceOnly
"t": {
"limit": {
"tif": "Gtc" // Good-Til-Cancelled
}
}
}],
"grouping": "na"
},
"nonce": 1704067200000,
"signature": {...}
}
订单类型 (TIF):
Gtc (Good-Til-Cancelled): 订单持续有效直到成交或取消Ioc (Immediate-Or-Cancel): 立即成交或取消未成交部分Alo (Add-Liquidity-Only): Post-Only,只做Makerjson{
"action": {
"type": "cancel",
"cancels": [{
"a": 0, // 资产索引
"oid": 12345678 // 订单ID
}]
},
"nonce": 1704067200000,
"signature": {...}
}
json{
"action": {
"type": "cancelByCloid",
"cancels": [{
"asset": 0,
"cloid": "0x1234..." // 客户端订单ID
}]
},
"nonce": 1704067200000,
"signature": {...}
}
json{
"action": {
"type": "modify",
"oid": 12345678,
"order": {
"a": 0,
"b": true,
"p": "51000",
"s": "0.2",
"r": false,
"t": { "limit": { "tif": "Gtc" } }
}
},
"nonce": 1704067200000,
"signature": {...}
}
json{
"action": {
"type": "usdcTransfer",
"destination": "0x...",
"amount": "100.0"
},
"nonce": 1704067200000,
"signature": {...}
}
json{
"action": {
"type": "twapOrder",
"twap": {
"a": 0,
"b": true,
"s": "1.0",
"r": false,
"m": 10, // 分钟数
"t": { "limit": { "tif": "Gtc" } }
}
},
"nonce": 1704067200000,
"signature": {...}
}
WebSocket提供实时数据流,适合需要低延迟数据更新的场景。
bashwscat -c wss://api.hyperliquid.xyz/ws
重要提示: 所有自动化用户应处理服务器断开连接并优雅重连。断开可能定期发生且无通知。重连期间错过的数据将在重连时的快照确认中呈现。
json{
"method": "subscribe",
"subscription": {
"type": "<订阅类型>",
// 其他参数
}
}
json{
"method": "subscribe",
"subscription": { "type": "allMids" }
}
json{
"method": "subscribe",
"subscription": {
"type": "trades",
"coin": "BTC"
}
}
json{
"method": "subscribe",
"subscription": {
"type": "l2Book",
"coin": "BTC"
}
}
支持的间隔: 1m, 3m, 5m, 15m, 30m, 1h, 2h, 4h, 8h, 12h, 1d, 3d, 1w, 1M
json{
"method": "subscribe",
"subscription": {
"type": "candle",
"coin": "BTC",
"interval": "1h"
}
}
json{
"method": "subscribe",
"subscription": {
"type": "orderUpdates",
"user": "0x..."
}
}
json{
"method": "subscribe",
"subscription": {
"type": "userFills",
"user": "0x..."
}
}
json{
"method": "subscribe",
"subscription": {
"type": "userFundings",
"user": "0x..."
}
}
json{
"method": "subscribe",
"subscription": {
"type": "notification",
"user": "0x..."
}
}
json{
"method": "subscribe",
"subscription": {
"type": "clearinghouseState",
"user": "0x..."
}
}
json{
"method": "subscribe",
"subscription": {
"type": "openOrders",
"user": "0x..."
}
}
json{
"method": "subscribe",
"subscription": {
"type": "activeAssetCtx",
"coin": "BTC"
}
}
json{
"method": "unsubscribe",
"subscription": { ... } // 与订阅时相同的对象
}
WebSocket也可用于发送交易请求,与HTTP Exchange端点功能相同:
json{
"method": "post",
"id": "unique-request-id",
"request": {
"action": { ... },
"nonce": 1704067200000,
"signature": { ... }
}
}
权重计算:
| 请求类型 | 权重 |
|---|---|
| Exchange API请求 | 1 + floor(batch_length / 40) |
| 单个操作 | 1 |
| 79个批量订单 | 2 |
| l2Book, allMids, clearinghouseState, orderStatus, spotClearinghouseState, exchangeStatus | 2 |
| userRole | 60 |
| 其他Info请求 | 20 |
| Explorer API请求 | 40 |
额外权重(按返回项目数):
recentTrades, historicalOrders, userFills, userFillsByTime, fundingHistory, userFunding, nonUserFundingUpdates, twapHistory, userTwapSliceFills, userTwapSliceFillsByTime, delegatorHistory, delegatorRewards, validatorStats: 每20个项目增加权重candleSnapshot: 每60个项目增加权重| 限制项 | 数值 |
|---|---|
| 最大WebSocket连接数 | 10 |
| 每分钟新WebSocket连接数 | 30 |
| 最大WebSocket订阅数 | 1000 |
| 用户特定订阅的唯一用户数 | 10 |
| 每分钟WebSocket消息数 | 2000 |
| 同时进行中的POST消息数 | 100 |
rpc.hyperliquid.xyz/evm: 每分钟100个请求地址级别限制按用户计算,子账户视为独立用户。
min(limit + 100000, limit * 2)此限制仅适用于操作(actions),不适用于信息查询(info requests)。
在高拥堵期间,地址被限制使用其做市商份额百分比2倍的区块空间。
WebSocket延迟最低,适合实时数据更新:
pythonimport asyncio
import websockets
import json
async def subscribe_trades():
uri = "wss://api.hyperliquid.xyz/ws"
async with websockets.connect(uri) as ws:
# 订阅BTC交易数据
subscribe_msg = {
"method": "subscribe",
"subscription": {"type": "trades", "coin": "BTC"}
}
await ws.send(json.dumps(subscribe_msg))
async for msg in ws:
data = json.loads(msg)
print(data)
pythonimport asyncio
import websockets
import json
async def connect_with_reconnect():
while True:
try:
async with websockets.connect("wss://api.hyperliquid.xyz/ws") as ws:
# 处理消息
async for msg in ws:
process_message(msg)
except Exception as e:
print(f"Disconnected: {e}, reconnecting...")
await asyncio.sleep(5)
使用Python SDK进行签名:
pythonfrom hyperliquid.exchange import Exchange
from hyperliquid.utils import constants
# 初始化
exchange = Exchange(
"0x你的私钥",
constants.MAINNET_API_URL
)
# 下单
order_result = exchange.order("BTC", True, 0.1, 50000, {"limit": {"tif": "Gtc"}})
pythonimport time
from collections import deque
class RateLimiter:
def __init__(self, max_weight=1200, window=60):
self.max_weight = max_weight
self.window = window
self.requests = deque()
def can_request(self, weight=1):
now = time.time()
# 清理过期请求
while self.requests and self.requests[0][0] < now - self.window:
self.requests.popleft()
# 检查权重
current_weight = sum(w for _, w in self.requests)
if current_weight + weight <= self.max_weight:
self.requests.append((now, weight))
return True
return False
def wait_time(self, weight=1):
if not self.requests:
return 0
# 计算需要等待的时间
current_weight = sum(w for _, w in self.requests)
if current_weight + weight <= self.max_weight:
return 0
return self.requests[0][0] + self.window - time.time()
pythondef get_asset_index(coin, meta, spot_meta):
"""获取资产索引"""
# 永续合约
for i, asset in enumerate(meta['universe']):
if asset['name'] == coin:
return i
# 现货
for i, asset in enumerate(spot_meta['universe']):
if asset['name'] == coin:
return 10000 + i
return None
Hyperliquid提供了完整的WebSocket和HTTP API接口,支持程序化交易和数据分析。关键要点:
开发者应根据实际需求选择合适的数据获取方式,并严格遵守限流规则,确保稳定可靠的API接入。
本文作者:yowayimono
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!