openfin-hyperliquid
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseHyperliquid Perps & Spot
Hyperliquid永续合约与现货
Playbook for trading perpetuals and spot on Hyperliquid through OpenFinance,
plus the real-time WebSocket for market data.
本指南介绍如何通过OpenFinance在Hyperliquid上进行永续合约与现货交易,以及获取实时WebSocket市场数据。
Prerequisite
前置条件
- User completed (API key + EVM wallet delegation).
openfin-setup - For trading: USDC in the user's wallet, then deposit USDC into the
Hyperliquid account via (send USDC to that deposit address; chain routing is handled automatically).
GET /agent/trading/deposit-address - For perp orders specifically: margin must be in the perp account, not
spot. Transfer with .
POST /agent/trading/transfer
- 用户已完成(API密钥 + EVM钱包授权)。
openfin-setup - 交易前:钱包中需有USDC,然后通过获取Hyperliquid账户的存款地址(向该地址发送USDC;链上路由将自动处理)。
GET /agent/trading/deposit-address - 永续合约订单专属要求:保证金必须在永续账户中,而非现货账户。可通过进行划转。
POST /agent/trading/transfer
Accounts & funding
账户与资金
- — Perpetual account summary. Returns
GET /agent/trading/account(accountValue, totalMarginUsed, totalNtlPos, totalRawUsd, withdrawable) and a list of open positions withmarginSummary,entryPx,positionValue,returnOnEquity,unrealizedPnl,liquidationPx, andleveragefor each asset.size - — Spot account summary. Returns a list of token balances with
GET /agent/trading/account/spotname, token ID, hold amount, total amount, and entry notional value per token held.coin - — Full portfolio view combining perp positions and spot balances in a single response (margin + equity + PnL + positions + token holdings with amounts and values).
GET /agent/trading/portfolio - — Current Hyperliquid API rate-limit status for the wallet. Returns cumulative volume traded, API calls used, and remaining allowed calls in the window.
GET /agent/trading/rate-limit - — Deposit address mapped to the authenticated wallet's Hyperliquid account. Send USDC to this address to fund the Hyperliquid account; chain routing to Hyperliquid is handled automatically.
GET /agent/trading/deposit-address - body
POST /agent/trading/transfer— Transfer USDC between the perp and spot accounts. Required before spot trading (funds must be in spot wallet to buy tokens) or before perp trading (funds in perp wallet).{amount, toPerp}= spot → perp;toPerp: true= perp → spot.false
- —— 永续账户摘要。返回
GET /agent/trading/account(账户价值、总保证金占用、总净持仓、总原生USD、可提取金额)以及持仓列表,每个持仓包含marginSummary(入场价)、entryPx(持仓价值)、positionValue(权益回报率)、returnOnEquity(未实现盈亏)、unrealizedPnl(强平价格)、liquidationPx(杠杆)和leverage(持仓量)。size - —— 现货账户摘要。返回代币余额列表,每个代币包含
GET /agent/trading/account/spot名称、代币ID、持有量、总量以及每个持币的入场名义价值。coin - —— 完整投资组合视图,合并永续持仓与现货余额,单次返回所有数据(保证金 + 权益 + 盈亏 + 持仓 + 代币持有量及价值)。
GET /agent/trading/portfolio - —— 当前钱包的Hyperliquid API速率限制状态。返回累计交易量、已使用API调用次数以及当前窗口内剩余允许调用次数。
GET /agent/trading/rate-limit - —— 与已授权钱包绑定的Hyperliquid账户存款地址。向该地址发送USDC即可为Hyperliquid账户充值;链上路由至Hyperliquid的流程将自动处理。
GET /agent/trading/deposit-address - 请求体
POST /agent/trading/transfer—— 在永续与现货账户间划转USDC。现货交易前需将资金划转至现货钱包,永续交易前需划转至永续钱包。{amount, toPerp}= 现货→永续;toPerp: true= 永续→现货。false
Market data (REST)
市场数据(REST接口)
- — Mid prices (midpoint between best bid and ask) for every listed asset. Returns a map of asset symbol → mid price string (e.g.
GET /agent/trading/market/mids).{"BTC": "70939.5", "ETH": "2500.0"} - (
GET /agent/trading/market/metas) — Market metadata and asset contexts: funding rates, open interest, mark/mid/oracle prices, impact prices, 24h base and notional volume, premium, previous day price. Pass?dex=for DEX-specific data.dex - — Perpetual contract metadata only. Returns
GET /agent/trading/market/perp-metasarray with each asset's name,universe(size precision),szDecimals,maxLeverage, andmarginTableIdflag. Use this to look up asset indices (isDelisted) andabefore placing orders — place-order body requires these.szDecimals - (
GET /agent/trading/market/spot-metas) — Spot market metadata and asset contexts. Returns?dex=(token pairs, names, indices, isCanonical) and context per pair (universe,prevDayPx,dayNtlVlm,dayBaseVlm,markPx,midPx,circulatingSupply,totalSupply).coin - — L2 orderbook for a coin (e.g.
GET /agent/trading/market/l2-book/:coin). Returns coin name, timestamp, and a two-level array of bids and asks, each withBTC(price),px(size), andsz(number of orders at that level).n - — Detailed spot token info by token ID. Returns name, maxSupply, totalSupply, circulatingSupply, szDecimals, weiDecimals, midPx, markPx, prevDayPx, deployer, deployTime, seededUsdc, futureEmissions.
GET /agent/trading/market/token/:tokenIdmust be the full hex hash from:tokenId(e.g.spot-metas), NOT a simple number.0xc1fb593aeffbeb02f85e0308e9956a90 - — Asset contexts across all DEXs on Hyperliquid: funding rate, open interest, mark/mid/ oracle prices, 24h volume, impact prices, premium, prev day price. Snapshot equivalent of the
GET /agent/trading/market/all-dexs-asset-ctxsWS channel.allDexsAssetCtxs
- —— 所有上市资产的中间价(最优买价与卖价的中点)。返回资产符号→中间价字符串的映射(例如
GET /agent/trading/market/mids)。{"BTC": "70939.5", "ETH": "2500.0"} - (
GET /agent/trading/market/metas) —— 市场元数据与资产上下文:资金费率、持仓量、标记/中间/预言机价格、冲击价格、24小时基准与名义交易量、溢价、前一日价格。传入?dex=参数可获取特定DEX的数据。dex - —— 仅返回永续合约元数据。返回
GET /agent/trading/market/perp-metas数组,包含每个资产的名称、universe(精度)、szDecimals(最大杠杆)、maxLeverage和marginTableId(是否退市)标记。下单前需使用此接口查询资产索引(isDelisted)和a——下单请求体需要这些参数。szDecimals - (
GET /agent/trading/market/spot-metas) —— 现货市场元数据与资产上下文。返回?dex=(代币对、名称、索引、是否标准代币)以及每个代币对的上下文(universe、prevDayPx、dayNtlVlm、dayBaseVlm、markPx、midPx、circulatingSupply、totalSupply)。coin - —— 单个币种的L2订单簿(例如
GET /agent/trading/market/l2-book/:coin)。返回币种名称、时间戳以及买卖盘的二级数组,每一项包含BTC(价格)、px(数量)和sz(该价位的订单数)。n - —— 通过代币ID获取现货代币详情。返回名称、最大供应量、总供应量、流通供应量、szDecimals、weiDecimals、中间价、标记价、前一日价格、部署者、部署时间、初始USDC注入量、未来释放量。
GET /agent/trading/market/token/:tokenId必须是:tokenId返回的完整十六进制哈希(例如spot-metas),而非简单数字。0xc1fb593aeffbeb02f85e0308e9956a90 - —— Hyperliquid上所有DEX的资产上下文:资金费率、持仓量、标记/中间/预言机价格、24小时交易量、冲击价格、溢价、前一日价格。相当于
GET /agent/trading/market/all-dexs-asset-ctxsWebSocket频道的快照版本。allDexsAssetCtxs
Historical candles (OHLCV)
历史K线(OHLCV)
Not a backend route — hit Hyperliquid's info endpoint directly:
http
POST https://api.hyperliquid.xyz/info
Content-Type: application/json
{
"type": "candleSnapshot",
"req": {
"coin": "BTC",
"interval": "1h", // 1m,3m,5m,15m,30m,1h,2h,4h,8h,12h,1d,3d,1w,1M
"startTime": 1706659200000, // ms
"endTime": 1706745600000 // ms, optional (defaults to now)
}
}Returns up to 5000 most recent candles. For HIP-3 spot tokens, prefix the coin
with the dex name, e.g. .
"xyz:XYZ100"此功能并非后端路由——需直接调用Hyperliquid的info端点:
http
POST https://api.hyperliquid.xyz/info
Content-Type: application/json
{
"type": "candleSnapshot",
"req": {
"coin": "BTC",
"interval": "1h", // 1m,3m,5m,15m,30m,1h,2h,4h,8h,12h,1d,3d,1w,1M
"startTime": 1706659200000, // 毫秒
"endTime": 1706745600000 // 毫秒,可选(默认当前时间)
}
}最多返回5000根最新K线。对于HIP-3现货代币,需在币种名称前添加DEX前缀,例如。
"xyz:XYZ100"Market data (WebSocket)
市场数据(WebSocket)
Hyperliquid exposes a real-time feed at .
wss://api.hyperliquid.xyz/wsSubscribe message shape:
json
{ "method": "subscribe", "subscription": { "type": "<channel>" } }Common channels:
- — funding rate, mark price, OI, 24h volume per asset
allDexsAssetCtxs - — real-time mid prices for every coin
allMids - (
l2Book) — orderbook updates{type, coin: "BTC"} - (
trades) — trade tape{type, coin} - (
candle) — streaming candles{type, coin, interval: "1m"} - /
orderUpdates/userFills— user-scoped; requires signinguserFundings
Hyperliquid提供实时数据流,地址为。
wss://api.hyperliquid.xyz/ws订阅消息格式:
json
{ "method": "subscribe", "subscription": { "type": "<channel>" } }常用频道:
- —— 每个资产的资金费率、标记价格、持仓量、24小时交易量
allDexsAssetCtxs - —— 所有币种的实时中间价
allMids - (
l2Book) —— 订单簿更新{type, coin: "BTC"} - (
trades) —— 交易记录{type, coin} - (
candle) —— 实时K线推送{type, coin, interval: "1m"} - /
orderUpdates/userFills—— 用户专属频道;需签名验证userFundings
Backend-managed WS
后端管理的WebSocket
The OpenFinance backend keeps one shared connection to
and caches the latest snapshot per channel.
Use this when multiple agents share the backend and you want a single
connection + consistent state. MCP tools:
wss://api.hyperliquid.xyz/ws- — start the shared backend subscription
subscribe_all_dexs_asset_ctxs - — stop it
unsubscribe_all_dexs_asset_ctxs - — read the latest cached snapshot
get_all_dexs_asset_ctxs - — is the backend's connection alive
get_ws_status
⚠ The array has no asset names — each entry maps by
index to the from . Call
at least once to build the index→name map.
allDexsAssetCtxsuniverseGET /agent/trading/market/metas/market/metasOpenFinance后端保持一个与的共享连接,并缓存每个频道的最新快照。当多个Agent共享后端且需要单一连接+一致状态时使用此方式。MCP工具:
wss://api.hyperliquid.xyz/ws- —— 启动后端共享订阅
subscribe_all_dexs_asset_ctxs - —— 停止订阅
unsubscribe_all_dexs_asset_ctxs - —— 读取最新缓存快照
get_all_dexs_asset_ctxs - —— 查询后端连接是否存活
get_ws_status
⚠ 数组不包含资产名称——每个条目通过索引与返回的对应。需至少调用一次来构建索引→名称的映射。
allDexsAssetCtxsGET /agent/trading/market/metasuniverse/market/metasDirect WS from the client
客户端直接连接WebSocket
For reactive UIs or per-client streams, open your own WS to
and subscribe. Don't expect the backend's
cache to reflect connections that weren't opened through it.
wss://api.hyperliquid.xyz/ws对于响应式UI或客户端专属流,可自行打开WebSocket连接至并订阅。此时后端缓存不会反映非通过其建立的连接状态。
wss://api.hyperliquid.xyz/wsOrders
订单
Placing orders
下单
-
— Place one or more orders. Each order needs
POST /agent/trading/orders(asset index froma),perp-metas(true=buy),b(price as string),p(size as string),s(reduce only),r(order type object withtorlimit). Body:triggerjson{ "orders": [{ "coin": "BTC", "is_buy": true, "sz": 0.01, "limit_px": 65000, "order_type": { "limit": { "tif": "Gtc" } }, "reduce_only": false }], "grouping": "na" // "na" | "normalTpsl" | "positionTpsl" }(time-in-force):tif- — good-till-cancelled (resting limit)
"Gtc" - — immediate-or-cancel (market-ish; cross the book for a fill)
"Ioc" - — add-liquidity-only (post-only; rejects if would be taker)
"Alo"
Grouping:groups take-profit/stop-loss child orders with a primary;"normalTpsl"attaches them to an existing position. Fetch market metas first to get correct asset indices and szDecimals."positionTpsl"
-
—— 下达一个或多个订单。每个订单需要
POST /agent/trading/orders(来自a的资产索引)、perp-metas(true=买入)、b(价格字符串)、p(数量字符串)、s(仅减仓)、r(订单类型对象,包含t或limit)。请求体:triggerjson{ "orders": [{ "coin": "BTC", "is_buy": true, "sz": 0.01, "limit_px": 65000, "order_type": { "limit": { "tif": "Gtc" } }, "reduce_only": false }], "grouping": "na" // "na" | "normalTpsl" | "positionTpsl" }(有效时间):tif- —— 取消前有效(挂单限价)
"Gtc" - —— 立即成交或取消(类市价;穿透订单簿成交)
"Ioc" - —— 仅增加流动性(仅挂单;若将成为吃单者则拒绝)
"Alo"
分组:将止盈/止损子订单与主订单分组;"normalTpsl"将其附加至现有持仓。下单前需先获取市场元数据以获取正确的资产索引和szDecimals。"positionTpsl"
Reading orders
查询订单
- — All currently open orders (compact). Returns array with
GET /agent/trading/orders,coin(B/A),side,limitPx,sz(order ID),oid,timestampper order.orderType - — Same but with full details:
GET /agent/trading/orders/details(original size),origSz,triggerPx,triggerCondition(client order ID),cloidflag.reduceOnly - — Historical orders (filled, cancelled, rejected). Adds
GET /agent/trading/orders/history(e.g.statusMsg,"filled"),"cancelled",filledSz,avgFillPx.cloid - — Single order's current status (
GET /agent/trading/orders/:oid/status,open,filled),cancelled,filledSz, remaining size.avgFillPx
- —— 所有当前挂单(精简版)。返回数组,每个订单包含
GET /agent/trading/orders、coin(买/卖)、side、limitPx、sz(订单ID)、oid、timestamp。orderType - —— 与上述接口相同,但返回完整详情:
GET /agent/trading/orders/details(原始数量)、origSz(触发价格)、triggerPx(触发条件)、triggerCondition(客户端订单ID)、cloid标记。reduceOnly - —— 历史订单(已成交、已取消、已拒绝)。新增
GET /agent/trading/orders/history(例如statusMsg、"filled")、"cancelled"(已成交数量)、filledSz(平均成交价格)、avgFillPx。cloid - —— 单个订单的当前状态(
GET /agent/trading/orders/:oid/status、open、filled)、cancelled、filledSz、剩余数量。avgFillPx
Cancel / modify
取消/修改订单
- body
DELETE /agent/trading/orders— Cancel one or more open orders.{cancels: [{a, o}]}= asset index (from market metas),a= order ID. Batch-cancellable.o - body
PUT /agent/trading/orders/:oid— Modify an existing open order by ID. Same order shape as place.{order: {...}}
- 请求体
DELETE /agent/trading/orders—— 取消一个或多个挂单。{cancels: [{a, o}]}= 资产索引(来自市场元数据),a= 订单ID。支持批量取消。o - 请求体
PUT /agent/trading/orders/:oid—— 通过订单ID修改现有挂单。订单格式与下单时相同。{order: {...}}
TWAP (Time-Weighted Average Price)
TWAP(时间加权平均价格)
- — Place a TWAP order that splits a large trade into smaller market-order slices over a specified duration to minimize price impact. Returns
POST /agent/trading/twapto track or terminate.twapId - — Get individual slice executions for all TWAPs. Returns fills with
GET /agent/trading/twap/fills,coin,side,fillPx,fillSz,feeUsdc, and the parenttimestamp.twapId - — Terminate an active TWAP. Stops further slices; already-filled slices remain settled.
DELETE /agent/trading/twap/:twapId
- —— 下达TWAP订单,将大额交易拆分为多个小额市价订单,在指定时间段内执行以最小化价格冲击。返回
POST /agent/trading/twap用于跟踪或终止订单。twapId - —— 获取所有TWAP订单的拆分执行记录。返回成交记录,包含
GET /agent/trading/twap/fills、coin、side、fillPx、fillSz、feeUsdc以及父订单timestamp。twapId - —— 终止活跃的TWAP订单。停止后续拆分订单;已成交部分将保持结算状态。
DELETE /agent/trading/twap/:twapId
Leverage & margin
杠杆与保证金
- body
POST /agent/trading/leverage— Set leverage + margin mode for an asset. Must be set BEFORE placing leveraged orders.{asset, isCross, leverage}= coin index,asset= cross margin (shared pool),isCross: true= isolated (per-position),false= max multiplier.leverage - body
POST /agent/trading/margin— Add or remove margin from an isolated-margin position. Positive{asset, isBuy, ntli}adds (lowers liquidation risk), negative removes (raises leverage). Only works on positions using isolated margin mode.ntli
- 请求体
POST /agent/trading/leverage—— 设置单个资产的杠杆+保证金模式。必须在下达杠杆订单前设置。{asset, isCross, leverage}= 币种索引,asset= 全仓保证金(共享保证金池),isCross: true= 逐仓保证金(按持仓隔离),false= 最大乘数。leverage - 请求体
POST /agent/trading/margin—— 为逐仓保证金持仓添加或移除保证金。{asset, isBuy, ntli}为正值时添加保证金(降低强平风险),负值时移除(提高杠杆)。仅适用于使用逐仓保证金模式的持仓。ntli
Fills & funding
成交记录与资金费率
- (
GET /agent/trading/fills) — Trade fill history. Returns fills with?aggregateByTime=false,coin(B/A),side(fill price),px,sz,feeUsdc,timestamp,oid,cloid(taker/maker),crossedflag.liquidation - (
GET /agent/trading/fills/by-time) — Same fill data, filtered by time window (Unix ms).?startTime=<ms>&endTime=<ms>optional (defaults to now).endTime - — Funding payment history for perp positions. Returns payments with
GET /agent/trading/funding,coin,fundingRateamount (positive = received, negative = paid),usdc, and position size at the time of payment.timestamp
- (
GET /agent/trading/fills) —— 交易成交历史。返回成交记录,包含?aggregateByTime=false、coin(买/卖)、side(成交价格)、px、sz、feeUsdc、timestamp、oid、cloid(吃单/挂单)、crossed(是否强平)标记。liquidation - (
GET /agent/trading/fills/by-time) —— 相同的成交数据,按时间窗口过滤(Unix毫秒)。?startTime=<ms>&endTime=<ms>可选(默认当前时间)。endTime - —— 永续持仓的资金费率支付历史。返回支付记录,包含
GET /agent/trading/funding、coin、fundingRate金额(正=收到,负=支付)、usdc以及支付时的持仓量。timestamp
Order-sizing gotchas
订单数量注意事项
- is in base asset (e.g. BTC, ETH), not USD. For BTC at $65k, 0.01 = $650 notional.
sz - ticks differ per asset — check
limit_pxforperp-metasand useszDecimals/formatHyperliquidPriceconventions.formatHyperliquidSize - Hyperliquid rejects prices too far from mid (price bands, ~5-10%). For aggressive fills cross the book but stay in-band.
- 以基础资产为单位(例如BTC、ETH),而非USD。例如BTC价格为65k美元时,0.01 BTC相当于650美元名义价值。
sz - 不同资产的最小变动单位不同——请查看
limit_px中的perp-metas,并遵循szDecimals/formatHyperliquidPrice规范。formatHyperliquidSize - Hyperliquid会拒绝与中间价偏差过大的价格(价格区间约5-10%)。若要激进成交,可穿透订单簿但需保持在价格区间内。
Margin modes
保证金模式
- Cross margin: all positions share one margin pool. Default.
- Isolated margin: margin pinned per position via .
POST /margin
Set on to pick the mode for a coin.
isCross: true/falsePOST /leverage- 全仓保证金:所有持仓共享一个保证金池。默认模式。
- 逐仓保证金:通过将保证金绑定至单个持仓。
POST /margin
在中设置来选择单个币种的保证金模式。
POST /leverageisCross: true/falseDon't
禁止操作
- Don't use for "buy now" — use
GtcorIocwith cross-book price.Alo - Don't expect the WS cache to be populated instantly on server boot — the backend auto-subscribes on startup but first message can take a few seconds.
- Don't put raw USD amounts in . It's base-asset.
sz - Don't forget to USDC from spot to perp before placing perp orders — they're separate balances.
transfer
- 不要使用订单来“立即买入”——应使用
Gtc或Ioc订单并设置穿透订单簿的价格。Alo - 不要期望服务器启动后WebSocket缓存立即填充——后端启动时会自动订阅,但第一条消息可能需要几秒时间。
- 不要在字段中输入原始USD金额。该字段为基础资产数量。
sz - 下达永续订单前不要忘记将USDC从现货账户划转至永续账户——两者余额相互独立。
MCP note
MCP说明
Tool names mirror the routes: ,
, ,
, , etc.
hyperliquid_place_orderhyperliquid_cancel_orderhyperliquid_get_account_summaryhyperliquid_get_all_midshyperliquid_usd_class_transfer工具名称与路由对应:、、、、等。",
hyperliquid_place_orderhyperliquid_cancel_orderhyperliquid_get_account_summaryhyperliquid_get_all_midshyperliquid_usd_class_transfer