BlogDeveloper

Hyperliquid API: Endpoints, Rate Limits & Code

Complete Hyperliquid API guide: POST /info and /exchange endpoints, API wallets, EIP-712 signing, tested rate limits, WebSocket feeds, and historical data.

HydromancerTeam
Hyperliquid API Guide: Endpoints, Rate Limits, WebSocket and Code

The Hyperliquid API is the official programmatic interface to Hyperliquid's on-chain order-book exchange (HyperCore). It has three components: a public POST /info endpoint for market and account data (no API key required), a cryptographically signed POST /exchange endpoint for placing and canceling orders, and a wss://.../ws WebSocket for live market and account streams.

The public API is free and built for live trading state rather than deep archival queries. REST traffic shares a budget of 1,200 weight per minute per IP, and historical endpoints cap out at roughly 5,000 recent candles per market and interval and 10,000 recent fills per wallet.

Component Mainnet Address Testnet Address Auth Required Key Limit
Info (Read) POST https://api.hyperliquid.xyz/info POST https://api.hyperliquid-testnet.xyz/info None 1,200 weight/min per IP
Exchange (Trade) POST https://api.hyperliquid.xyz/exchange POST https://api.hyperliquid-testnet.xyz/exchange EIP-712 signature (Wallet or API Wallet) 10,000 actions + 1 per $1 USDC traded
WebSocket (Live) wss://api.hyperliquid.xyz/ws wss://api.hyperliquid-testnet.xyz/ws None 10 connections / 1,000 subs per IP; 60s idle timeout
Need HyperEVM instead? This guide covers HyperCore, where Hyperliquid's perpetual and spot order books live. For smart contracts on HyperEVM (Mainnet Chain ID 999, Testnet 998), use an Ethereum JSON-RPC endpoint—see Hyperliquid RPC vs. Data API.

What Is the Hyperliquid API?

Unlike centralized exchanges that expose dozens of REST URL paths, Hyperliquid collapses all reads onto POST /info and all state-changing trades onto POST /exchange. A JSON "type" field in the request body determines which dataset or action the server executes.

  • Reading data is completely open: Anyone can query prices, order books, funding rates, candles, or any wallet's positions and fills without creating an account or API key.
  • Trading uses EIP-712 signatures: Every order, cancel, leverage update, or transfer sent to /exchange must be cryptographically signed by your main wallet or an authorized API wallet (also called an agent wallet).
  • Live data belongs on WebSockets: Polling /info exhausts the 1,200-weight IP limit quickly; production bots and dashboards subscribe over wss://api.hyperliquid.xyz/ws.

Quickstart: Your First Hyperliquid API Request

You can query live Hyperliquid market data immediately with curl or Python—no signup, wallet, or API key needed.

cURL: Fetch the BTC Order Book

code
curl -X POST https://api.hyperliquid.xyz/info \
  -H "Content-Type: application/json" \
  -d '{"type": "l2Book", "coin": "BTC"}'

Python: Fetch Every Market's Mid Price

code
import requests

INFO_URL = "https://api.hyperliquid.xyz/info"

mids = requests.post(INFO_URL, json={"type": "allMids"}).json()
print("Total markets:", len(mids))  # Returned 1,294 mid prices on mainnet
print("BTC mid price:", mids["BTC"])

Hyperliquid API Endpoints Reference (POST /info)

Every POST /info request consumes weight against your IP's 1,200 points/minute allowance, as documented on Hyperliquid's rate limits page. Time-range and history requests add extra weight per 20 items returned (per 60 items for candles).

Market Data Endpoints

What you need JSON request body (POST /info) Weight
Current mid price of every market {"type": "allMids"} 2
L2 order book (top 20 levels per side) {"type": "l2Book", "coin": "BTC"} 2
All perp specs (max leverage, szDecimals) {"type": "meta"} 20
Mark, oracle, funding, OI, 24h volume (all perps) {"type": "metaAndAssetCtxs"} 20
Spot pairs and token metadata {"type": "spotMeta"} 20
HIP-3 deployer markets (stocks, commodities, FX) {"type": "perpDexs"}, then meta with "dex": "xyz" 20
Historical OHLCV candles {"type": "candleSnapshot", "req": {"coin": "BTC", "interval": "1h", "startTime": ..., "endTime": ...}} 20 + extra
Historical funding rates {"type": "fundingHistory", "coin": "BTC", "startTime": ...} 20 + extra
Markets at open interest cap {"type": "perpsAtOpenInterestCap"} 20

Practical tips for market queries:

  • metaAndAssetCtxs is the workhorse call for dashboards: one weight-20 request returns every perp's mark price, oracle price, mid price, funding rate, open interest, and 24-hour volume.
  • l2Book supports optional "nSigFigs": 2 through 5 to aggregate levels into wider price buckets. For order-by-order depth beyond 20 levels, see BBO vs. L2Book vs. L4Book.
  • Coin naming rules: Native perps use plain tickers (BTC), HIP-3 markets prefix the deployer (xyz:SP500), and spot pairs use @<index> (except PURR/USDC). Always pull live names from meta and spotMeta rather than hard-coding them.

Account & Wallet Endpoints

Every wallet state on Hyperliquid is public—pass any 0x... main account or sub-account address as "user". Timestamps are Unix milliseconds.

What you need JSON request body (POST /info) Weight
Perp positions, margin, liquidation prices {"type": "clearinghouseState", "user": "0x..."} 2
Spot token balances {"type": "spotClearinghouseState", "user": "0x..."} 2
Open orders (including TP/SL triggers) {"type": "frontendOpenOrders", "user": "0x..."} 20
Recent fills (up to 2,000) {"type": "userFills", "user": "0x..."} 20 + extra
Fills in a time range (paginatable) {"type": "userFillsByTime", "user": "0x...", "startTime": ...} 20 + extra
Historical orders (up to 2,000) {"type": "historicalOrders", "user": "0x..."} 20 + extra
Deposits, withdrawals, transfers {"type": "userNonFundingLedgerUpdates", "user": "0x...", "startTime": ...} 20 + extra
Funding payments {"type": "userFunding", "user": "0x...", "startTime": ...} 20 + extra
Fee tier & trading fee rates {"type": "userFees", "user": "0x..."} 20
Remaining /exchange trading allowance {"type": "userRateLimit", "user": "0x..."} 20
Account role (normal, sub-account, vault, or agent) {"type": "userRole", "user": "0x..."} 60
Unified account catch: Wallets using Hyperliquid's unified account mode hold collateral in spot. Query both clearinghouseState and spotClearinghouseState or you will undercount account equity.

Hyperliquid API Rate Limits and History Caps (Documented vs. Tested)

Hyperliquid enforces three separate limit systems: IP-based REST weight (1,200/min), address-based trading action allowance, and WebSocket connection/subscription caps. In addition, candles and fills only go back a fixed recent window, and time-range responses are paged at 500 items (2,000 for fills).

To verify how the API behaves in practice, we ran live tests against Hyperliquid Mainnet and Testnet. Here is what the official docs state next to what the API actually returned:

Limit Documented Limit Observed Live Behavior (Tested)
REST weight per IP 1,200 weight / minute; l2Book, allMids, clearinghouseState = 2; most /info calls = 20 (~60 req/min); userRole = 60 Most wallet requests cost 2 or 20
Fills per response Max 2,000 userFills stopped at exactly 2,000 fills on a busy wallet
Wallet fill history 10,000 most recent fills Paging userFillsByTime on a very active wallet returned 16,192 fills (more than the documented 10,000), none older than ~10 hours
Time-range responses 500 items per page (2,000 for fills) fundingHistory for 60 days returned exactly 500 hourly rows (~21 days)
Candle history 5,000 most recent candles Requesting 10 days of 1m BTC candles returned 5,112 candles (~3.5 days)
Trading allowance 10,000 + 1 per $1 USDC traded Matched exactly: a wallet with $2,824,512 volume had a userRateLimit cap of 2,834,512
Batched order allowance 1 + floor(n/40) IP weight; n address allowance A batch of 3 orders consumed 3 from address allowance (cancels counted the same)
Scheduled cancel (dead man's switch) Auto-cancels orders if bot goes silent Refused on testnet: requires $1,000,000 traded volume
WebSocket idle timeout Closed after 60s without traffic Sending {"method": "ping"} every 50s kept the socket open past 70 seconds
WebSocket connection limits 10 open/IP, 30 new/min, 1,000 subs, 10 unique users across user streams, 2,000 msgs/min Not tested
Hyperliquid API history limits: 10 days of 1-minute candles returned about 3.5 days, 60 days of funding history returned about 21 days, and a very active wallet's fills reached back only about 10 hours.

Paginating userFillsByTime Without Dropping Fills

When paging fill history, start the next page at the exact timestamp of the last fill and deduplicate—do not add +1 ms, because multiple fills can share a millisecond boundary:

code
import time
import requests

INFO_URL = "https://api.hyperliquid.xyz/info"

def fetch_recent_fills(user: str, start_ms: int) -> list[dict]:
    fills, seen = [], set()
    end_ms = int(time.time() * 1000)

    while True:
        page = requests.post(INFO_URL, json={
            "type": "userFillsByTime",
            "user": user,
            "startTime": start_ms,
            "endTime": end_ms,
        }).json()

        for f in page:
            key = (f["coin"], f["tid"], f["oid"], f["side"])
            if key not in seen:
                seen.add(key)
                fills.append(f)

        if len(page) < 2000:
            return fills
        start_ms = page[-1]["time"]  # Reuse exact timestamp; seen set handles overlaps

To monitor your remaining trading budget before hitting the 1-request-per-10-seconds throttle, check userRateLimit:

code
def remaining_allowance(user: str) -> int:
    r = requests.post(INFO_URL, json={"type": "userRateLimit", "user": user}).json()
    return r["nRequestsCap"] - r["nRequestsUsed"]

For burst rules, congestion throttling, and request-reduction patterns, see Hyperliquid API Rate Limits Explained.

Authentication: API Wallets, EIP-712 Signing & SDKs

Hyperliquid does not issue traditional exchange API keys. Instead, you authorize a dedicated API wallet (agent wallet)—a separate cryptographic key pair approved by your main account to sign trades on its behalf.

How a Hyperliquid API wallet works: the main wallet approves an API wallet for up to 180 days, the API wallet signs orders with a fresh nonce, and /exchange accepts them only from an approved signer. The API wallet can't withdraw, and its own address reads as an empty account.

How to Create a Hyperliquid API Wallet

  1. Connect your funded main wallet at app.hyperliquid.xyz/API.
  2. Name the API wallet (one unnamed + up to three named keys per master account; two more per sub-account) and click Generate.
  3. Set an expiry (maximum 180 days).
  4. Copy the private key immediately, then click Authorize API Wallet and sign with your main wallet.

Three non-negotiable security rules:

  • No withdrawal power: An API wallet can place and cancel orders, but cannot withdraw funds or approve builder fees. Still treat the private key like a password—a leaked key can burn margin via bad trades.
  • One API wallet per bot process: Nonces are tracked per signing key; two processes sharing one key can reject each other's orders.
  • Never reuse expired keys: Once removed or expired, nonce history may clear, creating replay risk. Always generate a fresh key. (See Hyperliquid Security.)

Official & Community SDKs (Use One for EIP-712 Signing)

Hyperliquid uses two distinct EIP-712 signing schemes (L1 Action vs. user-signed actions) with strict canonical formatting (for example, stripping trailing zeros from prices before hashing). Hand-written signing code is a common source of opaque failures, so use an established SDK:

Language SDK Status
Python hyperliquid-python-sdk Official (Info + Exchange classes)
TypeScript @nktkas/hyperliquid, hyperliquid Community
Rust hypersdk Community (listed in Hyperliquid docs)
Go go-hyperliquid Community

(Audit community SDKs before passing them a private key.)

Placing & Canceling Your First Order (Python, Testnet)

Install the official SDK (pip install hyperliquid-python-sdk), pass your API wallet private key as the signer, and pass your main wallet address as account_address. The example buys at $50,000, so check the current BTC price first: the order only rests if it's below market.

code
import os
from eth_account import Account
from hyperliquid.exchange import Exchange
from hyperliquid.utils import constants

agent = Account.from_key(os.environ["HL_AGENT_KEY"])
main_address = os.environ["HL_MAIN_ADDRESS"]

# Always test on TESTNET_API_URL before switching to MAINNET_API_URL
exchange = Exchange(agent, constants.TESTNET_API_URL, account_address=main_address)

# Place a resting limit buy far below market, then cancel it
res = exchange.order("BTC", True, 0.0003, 50000, {"limit": {"tif": "Gtc"}})
if res.get("status") != "ok":
    raise RuntimeError(res.get("response"))

status = res["response"]["data"]["statuses"][0]
print("Order status:", status)

if "resting" in status:
    cancel_res = exchange.cancel("BTC", status["resting"]["oid"])
    print("Cancel result:", cancel_res)

Order Formatting Rules & Asset IDs

  • Minimum order value: $10 notional.
  • Price & size precision: Prices allow at most 5 significant figures (whole numbers exempt) and 6 - szDecimals decimal places for perps (8 - szDecimals for spot). Sizes round to szDecimals. See our Hyperliquid tick size & rounding helper.
  • Market orders: Hyperliquid has no native market order; the Python SDK submits an IOC limit order with 5% default slippage—always set slippage explicitly.
  • Asset IDs differ between mainnet and testnet: For example, BTC perp is 0 on mainnet and 3 on testnet; HYPE/USDC spot is 10107 on mainnet and 11035 on testnet. Look IDs up dynamically from meta / spotMeta (10000 + index for spot, 100000 + dex_idx * 10000 + index for HIP-3).

Need test USDC or faucets? See our Hyperliquid Testnet Guide for setup, faucets, and mainnet migration gotchas.

Hyperliquid WebSocket API: Streaming Live Data

Connect to wss://api.hyperliquid.xyz/ws and send a JSON subscribe payload. Always include a 50-second ping heartbeat, or the server closes quiet connections after 60 seconds:

code
import asyncio
import json
import websockets

async def stream_btc_trades():
    async with websockets.connect("wss://api.hyperliquid.xyz/ws") as ws:
        await ws.send(json.dumps({
            "method": "subscribe",
            "subscription": {"type": "trades", "coin": "BTC"},
        }))

        async def heartbeat():
            while True:
                await asyncio.sleep(50)
                await ws.send(json.dumps({"method": "ping"}))

        asyncio.create_task(heartbeat())

        async for raw in ws:
            msg = json.loads(raw)
            if msg.get("channel") == "trades":
                for t in msg["data"]:
                    print(t["coin"], t["side"], t["sz"], "@", t["px"])

asyncio.run(stream_btc_trades())
  • Available market channels: trades, l2Book, bbo, allMids, candle.
  • Available account channels: userFills, orderUpdates, userFundings, userNonFundingLedgerUpdates, clearinghouseState, openOrders.
  • Reconnect caveat: Public WebSocket channels drop messages while disconnected, and history channels emit an initial isSnapshot: true batch on reconnect—deduplicate against your REST snapshot. You can also send POST requests over the socket via {"method": "post", ...}.
  • Multi-market limitation: trades, l2Book, bbo and candle take one coin per subscription. For all-market subscriptions, reconnect replay, and L4 order-level streams, see Hyperliquid Data Feeds.

How to Get Full Historical Hyperliquid Data

Because the public API stops at ~5,000 candles and ~10,000 fills—and provides no historical order books, global trade tape, or multi-wallet batching—builders needing deep history or scale generally choose one of four paths:

  1. Hyperliquid's raw S3 buckets (hyperliquid-archive / hl-mainnet-node-data): Requester-pays raw node dumps uploaded periodically; requires custom parsing and excludes candles.
  2. Run your own non-validator node: Captures every fill and block locally, but only going forward from the day you start and requires ongoing ops. (See How to Set Up a Hyperliquid Non-Validator Node.)
  3. Hydromancer Reservoir (free Hyperliquid historical data archive): Daily-updated Parquet datasets on AWS S3 (s3://hydromancer-reservoir, requester-pays, no API key needed) covering every fill since July 2025, 1-second candles, daily position snapshots, and 1-minute 20-level L2 order books.
  4. Managed Data API (Hydromancer): Familiar POST /info style endpoints with 1,000-wallet batching, builder endpoints (builderFills, builderLiquidations), L4 order-level streams with wallet addresses, and reconnect replay.

Official Hyperliquid API vs. Hydromancer

The two are complementary: you always use the official Hyperliquid /exchange endpoint to sign and submit orders, and pair it with a data layer once you outgrow public read limits.

Capability Official Hyperliquid API Hydromancer
Primary role Trading & single-wallet live state Production data feeds, analytics & full history
Order execution (/exchange) Yes No (pair with official /exchange)
Wallet fill history Last ~10,000 fills Full history via REST + Reservoir (S3 Parquet)
Candles Last ~5,000 candles Full history down to 1-second resolution
Order books Live L2 (20 levels/side), 1 coin/sub Live L2 & order-level L4 with wallet addresses + historical 1m L2
Multi-wallet queries 1 wallet per request Batch up to 1,000 wallets in one request
Liquidations & builder feeds Not exposed directly Dedicated live & historical liquidations and builderFills
WebSocket reconnects No replay on market channels; user channels resend recent history on reconnect Session persistence + missed-event replay
Pricing Free (IP rate-limited) Free data (Reservoir S3; you pay AWS transfer) / free access for qualifying early-stage teams / Starter from $300/mo

Teams including VALR, SEDA, HyENA, and fomo run production Hyperliquid integrations on Hydromancer. For a head-to-head benchmark of 18 real apps, see Hyperliquid vs. Hydromancer API or How to Get Hyperliquid Data.

Querying Hyperliquid Data with AI Coding Agents & DuckDB

If you are building with Claude Code, Cursor, Codex, or automated research scripts, you can give your agent accurate Hyperliquid schemas and historical datasets without manual scraping:

  • LLM-native documentation: Point coding agents directly to docs.hydromancer.xyz/llms.txt (or llms-full.txt), or append .md to any Hydromancer docs URL to fetch clean Markdown with exact request/response schemas.
  • Historical queries with DuckDB, no API key: Both humans and coding agents can query Hydromancer Reservoir's Parquet files directly from AWS S3 (ap-northeast-1, requester-pays) using SQL, with no Hydromancer API key or custom indexer. You do need AWS credentials, because requester-pays bills your AWS account for the download. If you signed in with aws login, run eval "$(aws configure export-credentials --format env)" in the same terminal first:
code
INSTALL httpfs; LOAD httpfs;
CREATE OR REPLACE SECRET (TYPE s3, PROVIDER credential_chain, REGION 'ap-northeast-1');
SET s3_requester_pays = true;

SELECT timestamp, side, price, size, address
FROM read_parquet(
  's3://hydromancer-reservoir/by_dex/hyperliquid/fills/perp/all/date=2026-09-08/fills.parquet'
)
WHERE coin = 'BTC'
ORDER BY timestamp
LIMIT 20;

See How to Query Reservoir's Hyperliquid Data for candle aggregation and historical order-book queries.

5 Common Hyperliquid API Gotchas (Verified Live)

These five bugs often break production bots, and each was confirmed against Hyperliquid's live endpoints:

1. Querying the API Wallet Address Returns an Empty Account

Passing your API wallet's address as "user" to clearinghouseState returns 0.0 equity even when your account is funded. Always query your main account address; API wallets only sign. If you only have an agent address, call {"type": "userRole", "user": "0x..."} to look up the master account.

2. Rejected Orders Still Return HTTP 200 with "status": "ok"

Top-level "status": "ok" only means the node parsed your batch—individual orders inside response.data.statuses can still fail silently:

json
{
  "statuses": [
    { "resting": { "oid": 62657813117 } },
    { "error": "Order must have minimum value of $10. asset=3" }
  ]
}
A Hyperliquid batch order response with HTTP 200 and status ok: the first order rests on the book with an order ID, the second is rejected with 'Order must have minimum value of $10'.

Always inspect every element of statuses, never just the HTTP status code.

3. Duplicate cloid Values Do Not Prevent Double Orders

If an order request times out, resending it with the same client order ID (cloid) can create two live resting orders—in our live test, Hyperliquid accepted both submissions with distinct oid values and the identical cloid. Wait a few seconds after a timeout and verify via orderStatus (exchange.info.query_order_by_cloid(main_address, Cloid.from_str(cloid)), with Cloid from hyperliquid.utils.types) before retrying.

4. Unknown Coins Return 500 null (Not a Structured Error)

Sending {"type": "l2Book", "coin": "NOTACOIN"} returned HTTP 500 with body null (and 200 null in an earlier run), whereas malformed fields or addresses return 422 Failed to deserialize. Guard against null responses instead of blindly retrying as a server outage.

5. Trailing Zeros Cause "User or API Wallet does not exist"

Hyperliquid recovers the signer address mathematically from your EIP-712 signature. Signing a price with a trailing zero ("49887.0" instead of "49887"), signing for mainnet and posting to testnet, or using an unapproved key all recover a random unknown address and return "User or API Wallet 0x... does not exist." If the address in the error isn't yours, your signing payload is wrong—not your account.

FAQ

Is the Hyperliquid API free?

Yes. Reading market and account data via POST /info, streaming via WebSockets, and trading via POST /exchange are all free within Hyperliquid's rate limits. You only pay standard exchange trading fees on executed orders.

Do I need an API key for the Hyperliquid API?

No API key is needed to read market data, order books, candles, or any public wallet's state. To place or cancel orders on POST /exchange, you must authorize an API wallet (agent wallet) at app.hyperliquid.xyz/API and sign requests with its private key.

What is a Hyperliquid API wallet?

An API wallet (also called an agent wallet) is a separate key pair approved by your main wallet to sign trading actions on its behalf for up to 180 days. It can place and cancel orders, but cannot withdraw funds.

What are the Hyperliquid API rate limits?

REST requests share a limit of 1,200 weight per minute per IP address (light calls like allMids, l2Book, and clearinghouseState cost 2; most other /info calls cost 20, or about 60 requests per minute). WebSockets are limited to 10 concurrent connections, 30 new connections per minute, 1,000 subscriptions, and 2,000 sent messages per minute per IP. Trading actions have a separate per-address limit of 10,000 actions plus 1 per $1 USDC traded.

Does Hyperliquid have a testnet API?

Yes. The testnet API is available at https://api.hyperliquid-testnet.xyz (WebSocket at wss://api.hyperliquid-testnet.xyz/ws) and mirrors mainnet behavior, though asset IDs differ (for example, BTC is asset ID 0 on mainnet and 3 on testnet).

Is there an official Hyperliquid Python SDK?

Yes. Hyperliquid maintains hyperliquid-python-sdk on GitHub (pip install hyperliquid-python-sdk), which wraps both Info and Exchange endpoints and handles EIP-712 cryptographic signing.

How far back does Hyperliquid API historical data go?

Public API history is strictly capped: candleSnapshot returns at most ~5,000 recent candles per interval (about 3.5 days of 1-minute candles), and userFillsByTime is limited to roughly the 10,000 most recent fills per wallet. fundingHistory goes further back, 500 rows per call. For complete archives, use Hyperliquid's raw S3 buckets, Hydromancer's free Reservoir S3 Parquet archive, or an indexed data API.

What is the difference between the Hyperliquid API and a Hyperliquid RPC?

The Hyperliquid API (api.hyperliquid.xyz) serves HyperCore, the high-throughput on-chain order-book exchange for perps and spot. A Hyperliquid RPC serves HyperEVM (Chain ID 999), the EVM smart-contract execution layer.

Sources & Verification Summary

All live responses, market counts (1,294 mids, 178 live main-exchange perps, 10 HIP-3 exchanges, 331 spot pairs), history caps, and error messages in this guide were verified against Hyperliquid Mainnet (POST /info) and Testnet (POST /exchange with an authorized API wallet) in October and November 2026.

Continue