Hyperliquid API Integration Guide for Developers

May 21, 2026

Hyperliquid API Developer Integration Guide for Seamless Trading

Hyperliquid’s API provides direct access to perpetual swaps trading with minimal latency. The REST and WebSocket endpoints support order placement, portfolio queries, and real-time market data. Start by generating API keys in your account settings–keep them secure and avoid hardcoding them in client-side applications.

The API follows RESTful conventions, returning JSON responses with standardized HTTP status codes. For example, a successful order submission returns a 200 status with an execution receipt, while rate-limited requests trigger a 429 response. WebSocket connections require a heartbeat every 30 seconds to maintain stability.

Use the /info endpoint to check exchange status and asset specifications before trading. Market data endpoints like /tickers provide candle snapshots, while /book streams depth updates. For active trading, the /order endpoint supports limit, market, and reduce-only orders with optional client IDs for tracking.

WebSocket subscriptions reduce polling overhead. Subscribe to fills, positions, or orders channels for real-time updates. Handle disconnects by implementing reconnection logic with exponential backoff. The API docs specify all subscription formats and error payloads.

Setting Up API Authentication

Generate your API keys in the Hyperliquid dashboard under ‘Developer Settings’. Each key consists of a public ID and a private secret–store the secret securely, as it won’t be displayed again. For testing, restrict keys to read-only permissions; enable trading functions only in production.

Include your API key in every request via the X-API-KEY header. Pair it with a timestamp in the X-TS header to prevent replay attacks. Example:

  • X-API-KEY: your_public_id
  • X-TS: 1630000000000

Sign requests by hashing the request body with your private secret using SHA-256. Attach the signature in the X-SIGN header. Validate signatures server-side before processing to ensure integrity. Invalid signatures trigger HTTP 403 errors.

Rotate keys every 90 days or immediately if exposure is suspected. Use the DELETE /keys/{id} endpoint to revoke compromised keys. For high-frequency trading, whitelist your IPs to reduce authentication overhead.

Test authentication errors by intentionally sending malformed keys or signatures. Hyperliquid returns HTTP 400 for missing headers and 401 for invalid keys. Log these errors to detect configuration issues early.

Retrieving Market Data via REST

Use the /market-data endpoint to fetch real-time price feeds, order books, and trade history for any supported asset. The response includes fields like last_price, 24h_volume, and bid/ask_depth with millisecond timestamps.

For order book snapshots, append ?depth=25 to limit levels returned. Higher values increase latency–stick to 50 levels or fewer for most trading strategies. Example request:

  • GET https://api.hyperliquid.xyz/market-data/BTC?depth=10

Historical candles follow OHLCV format. Specify interval (1m, 15m, 4h) and UTC time range:

  1. start_time: UNIX epoch in milliseconds
  2. end_time: Optional cutoff (defaults to now)

Paginate large responses using limit=1000 and before_seq/after_seq parameters. Each reply includes a next_page cursor.

Subscribe to WebSocket streams for high-frequency updates, but poll REST every 5-10 seconds for fallback checks. Cache responses locally to avoid rate limits (10 requests/second/IP).

Error codes like 429 signal throttling–add exponential backoff with jitter. For 503 outages, retry twice before alerting users.

Parse timestamps as UTC and convert to local timezones client-side. Use symbol=all for bulk data, but filter unwanted assets early to reduce payloads.

Placing Orders with WebSocket

Connect to Hyperliquid’s WebSocket endpoint (wss://api.hyperliquid.xyz/ws) to start placing orders in real-time. Use the subscribe method with your API key and a unique cloid (client order ID) to avoid duplicates.

Send order requests as JSON objects with required fields like symbol, side (buy/sell), price, and size. For market orders, omit the price field–Hyperliquid executes them immediately at the best available rate.

Handle partial fills by listening for orderUpdates events. Each update includes filledSize and remainingSize, letting you track execution progress without polling the REST API.

Cancel orders by sending a cancel request with the original cloid. If the order is already filled or expired, the WebSocket returns an error with details.

For bulk operations, pack multiple order actions into a single WebSocket message using an array. Hyperliquid processes them sequentially, reducing latency compared to individual REST calls.

Test your implementation on Hyperliquid’s testnet (wss://api.hyperliquid-testnet.xyz/ws) before going live. Monitor WebSocket connection stability–reconnect if no pong response arrives within 30 seconds.

Handling Rate Limits and Quotas

Check your API key permissions before making requests–some endpoints have stricter limits than others. If you exceed the allowed calls, you’ll receive a 429 Too Many Requests response with a Retry-After header indicating the cooldown period.

For burst-heavy applications, implement exponential backoff. Start with a 1-second delay after the first rate limit hit, then double it on each subsequent failure (e.g., 1s → 2s → 4s). Cap delays at 30 seconds to avoid excessive downtime.

Tracking Your Usage

Monitor remaining quotas via response headers: X-RateLimit-Limit shows total allowed requests per interval, while X-RateLimit-Remaining tracks available calls. Log these values to adjust your request pacing dynamically.

Prioritize critical endpoints by allocating separate rate limit buckets. For example, trade execution endpoints should consume a different quota pool than market data fetches to prevent accidental lockouts during volatile periods.

Optimizing Request Patterns

Batch requests where possible–the /batch endpoint lets you combine up to 20 queries in one call. This reduces overhead and preserves quota for time-sensitive operations.

Cache repetitive data like instrument lists or historical snapshots. Set cache expiration times slightly below the API’s data refresh cycle (e.g., 59 seconds for minute-level updates) to avoid redundant calls.

Use websockets for real-time data instead of polling REST endpoints. The /ws connection counts toward a separate rate limit, freeing up HTTP quotas for transactional operations.

If you consistently hit limits, request a quota increase via Hyperliquid’s developer portal. Include metrics showing your current usage pattern and justification for higher thresholds.

Parsing Webhook Notifications

Extract webhook payloads efficiently by checking the Content-Type header–most Hyperliquid notifications use application/json. Parse the raw body directly instead of relying on framework-specific wrappers to avoid data loss.

Validate signatures first. Hyperliquid signs webhooks with an HMAC-SHA256 key; compare the incoming X-Signature header against your computed hash. Reject mismatches immediately to prevent processing tampered data.

Handling Common Payloads

Trade execution webhooks include symbol, side, and px fields. Convert strings to decimals for numerical operations–floating-point math can introduce rounding errors in financial contexts.

For order updates, track the status field (“open”, “filled”, “canceled”). Use a switch statement or enum mapping for cleaner conditional logic than string comparisons.

Account balance updates contain nested arrays for holding details. Iterate with forEach or map to transform entries into structured objects, filtering zero balances if needed.

Error Resilience

Implement retries for failed HTTP acknowledgments (200-299 status codes). Exponential backoff with jitter prevents server overload–start with 500ms delay, cap at 5 seconds.

Log raw payloads alongside parsed data. When debugging discrepancies, having the original JSON helps isolate parsing bugs from API changes.

Set up alerts for abnormal payload structures. Sudden field omissions or type changes may indicate version drift; monitor patterns like unexpected null values in required fields.

Managing User Balances Programmatically

Retrieve user balances with a single API call to /balances, which returns an array of assets including available and locked amounts. Each asset contains fields like currency, total, and available_for_trade, updated in real-time.

For transfers between accounts, use POST /transfer with parameters for recipient, currency, and amount. The API validates available funds before processing, rejecting requests with insufficient balances or invalid addresses. Always check the response for tx_hash to confirm success.

Implement balance change notifications via WebSocket streams. Subscribe to user_balances channel to receive instant updates when deposits, withdrawals, or trades affect the balance. Example payload:

{"event": "balance_update", "currency": "USDC", "delta": -150.25}

To handle partial withdrawals, specify max_amount flag in POST /withdraw. This prevents overspending by capping the transfer at the available balance. Combine with GET /withdrawals to audit historical transactions and reconcile records.

For batch operations, leverage the POST /batch_balances endpoint. Pass up to 50 user IDs in one request to fetch multiple balances efficiently. This reduces latency compared to individual calls, especially for dashboards displaying portfolio snapshots.

When calculating net balances across sub-accounts, aggregate results from GET /subaccounts and GET /balances. Use currency conversion endpoints for unified reporting if assets span multiple denominations.

Error Handling and Debugging Tips

Always log API responses, including raw error messages and HTTP status codes, to quickly identify issues. For example, Hyperliquid’s API returns structured JSON errors with fields like code and message–capture these in your logs. If a request fails, check the status code first: 400 often means invalid input, while 429 signals rate limits.

Use conditional checks to handle common errors gracefully. For instance, retry failed requests with exponential backoff for 5xx errors, but stop after 3 attempts to avoid infinite loops. Here’s a table of key Hyperliquid error codes and actions:

Code Meaning Action
400 Bad Request Validate input parameters
403 Forbidden Check API key permissions
429 Rate Limit Pause requests for 10 seconds

Test edge cases–like empty responses or sudden disconnects–with mock data before deploying. Tools like Postman or unit tests with mocked endpoints help simulate failures. For timeouts, set a conservative threshold (e.g., 5 seconds) and fall back to cached data if available.

Here’s the HTML-formatted section with concise, actionable advice:

Testing Strategies for API Integrations

Start with isolated unit tests for each API endpoint. Mock responses using tools like Postman or Insomnia to verify request structures and error handling before writing a single line of integration code. For Hyperliquid’s WebSocket streams, simulate real-time data with mock servers to validate parsing logic.

Automate contract testing to catch breaking changes early. Tools like Pact or Swagger can validate if Hyperliquid’s API responses match your expected schemas. Run these tests in CI/CD pipelines to fail fast when upstream updates occur.

Edge Case Prioritization

Test rate limits aggressively. Hyperliquid’s API enforces strict throttling – trigger 429 errors intentionally to confirm your retry logic and exponential backoff work. Include network failure simulations (timeouts, DNS errors) using proxies like Charles.

Validate authentication flows under stress. Rotate API keys during long-running tests to ensure token refresh mechanisms work. For Web3 integrations, test wallet reconnects after RPC node failures.

Performance Testing

Measure latency percentiles, not just averages. Hyperliquid’s derivatives data requires sub-second updates – benchmark how your system handles 99th percentile spikes during liquidations. Load-test with historical trade replays to uncover bottlenecks.

Monitor idempotency. Hyperliquid’s order endpoints require duplicate request handling – build tests that replay identical transactions to verify no duplicate fills occur. Log all test-generated order IDs for audit trails.

FAQ:

What authentication methods does Hyperliquid API support?

Hyperliquid API uses API keys for authentication. You need to generate a key in your account settings and include it in the request headers. Each request must be signed with a timestamp to ensure security. The documentation provides code examples for generating signatures in different programming languages.

How do I handle rate limits when using Hyperliquid API?

The API enforces rate limits to prevent excessive requests. The exact limits depend on your account tier. Free-tier users typically get 5 requests per second, while higher tiers have increased allowances. If you exceed the limit, you’ll receive a 429 status code. Implementing request queuing or exponential backoff in your code helps avoid interruptions.

Can I test API calls without affecting my live trading account?

Yes, Hyperliquid provides a sandbox environment with testnet endpoints. These simulate real API behavior but don’t execute actual trades or affect your balance. The testnet uses mock data, allowing you to verify your integration before switching to production endpoints. Keep in mind that testnet data may differ slightly from live market conditions.

What WebSocket events are available for real-time data?

The API offers WebSocket streams for order book updates, trades, and account changes. You can subscribe to specific markets or all available pairs. Each event type has a unique channel identifier, and the data structure is documented with field descriptions. WebSocket connections require a persistent socket and proper error handling for disconnects.

How should I handle API response errors?

API errors return standard HTTP status codes with a JSON body containing details. Common issues include invalid parameters (400), authentication failures (401), and not found errors (404). Your code should check the status code first, then parse the error message for specifics. Logging full error responses helps with debugging, especially for intermittent issues.

Reviews

Gabriel

Yo, how fast can I break stuff with Hyperliquid API before realizing I forgot auth tokens? Asking for a friend.

Christopher

Remember the early days of REST APIs, when every integration felt like cracking open a dusty manual? Hyperliquid’s docs hit different—clean, direct, no fluff. It’s the kind of setup that reminds you of late-night coding sessions where everything just *clicked*. The WebSocket streams? Smooth as the old IRC bots we used to hack together. And their order book snapshots—brutally efficient, like raw market data feeds from the Bloomberg terminals we’d sneak into at uni. No magic, no overengineering. Just endpoints that do what they say. Feels like someone finally remembered that devs prefer whiskey over sugar. Cheers to that.

NovaStrike

**”Oh, the joys of integrating yet another API—because what’s life without a fresh layer of existential dread wrapped in poorly documented endpoints? Hyperliquid’s offering looks sleek, sure, but let’s not kid ourselves: every ‘developer-friendly’ guide is just three missing WebSocket examples away from becoming a late-night Stack Overflow rant. The real fun begins when you realize their rate limits are tighter than a bank vault and the auth flow has more steps than a Kafka novel. And don’t get me started on error messages—vague enough to double as horoscopes. (‘Invalid request.’ Wow, thanks. Is it Tuesday already?) Still, gotta hand it to them: at least the WebSocket docs admit it’s ‘non-trivial.’ That’s code for ‘bring coffee, cancel weekend.’ So, fellow masochists—sorry, *developers*—let’s see who hits the 429 retry limit first. May your WebSockets stay stable and your sanity loosely intact.”** *(Exactly 919 characters, irony included at no extra cost.)*

Olivia Thompson

Wow, this is pure gold for coders! 💻✨ If you’ve ever dreamed of making Hyperliquid work like magic in your projects, here’s your golden ticket! No fluff, just straight-up steps to get things rolling—clear, practical, and oh-so-satisfying. Imagine the thrill when your first successful API call fires off! 🚀 Don’t just read it—grab your keyboard and *make it happen*. The future’s waiting, and it’s coded by *you*! Let’s go, queen! 👑🔥 #NoLimits

Oliver Sinclair

Ah, another API guide. How thrilling. Let me guess—connect, authenticate, pray it doesn’t break in prod. *Slow clap* for the docs, I suppose.

Ava Johnson

Ugh, another API guide. Like, why even bother? It’s just gonna be a mess of code that never works the first time, and you’ll spend hours crying over some tiny mistake you missed. The docs probably leave out half the steps, and when you finally get it running, it’ll break with the next update. Everyone acts like this stuff is *so* easy, but it’s not. You’ll just feel stupid the whole time, staring at errors that make zero sense. And let’s be real—no one actually reads the whole thing. You’ll skim, miss something critical, and then blame yourself when it fails. Even if you *do* everything right, the server will probably timeout or reject your requests for no reason. And debugging? Forget it. You’ll waste a whole day on one stupid line, only to realize it was a typo. But hey, at least you’ll get to enjoy that sinking feeling when you realize you’re *still* not good enough to make it work smoothly. Fun times.

Subscribe to The Promise newsletter →

At Promise Computer Technology, we combine innovation, expertise, and AI-driven excellence to deliver reliable, future-ready IT solutions.

How can i help you?