Hyperliquid API Features and Step-by-Step Integration Guide
The Hyperliquid API provides direct access to perpetual swaps and spot markets with low latency. Developers can build trading bots, analytics tools, or custom dashboards by leveraging WebSocket streams and REST endpoints. The API supports order placement, portfolio tracking, and real-time market data without rate limits on private endpoints.
Authentication uses HMAC signatures with API keys for secure requests. Each key requires specific permissions, reducing risk if credentials are exposed. The documentation includes code samples in Python and JavaScript to help you start quickly.
WebSocket connections deliver updates on order books, trades, and account balances. For example, subscribing to l2Book streams provides level 2 market depth with millisecond latency. REST endpoints handle historical data queries, such as retrieving candle sticks or past trades.
Error responses follow consistent formatting with HTTP status codes and actionable messages. Testing in the staging environment before going live helps identify issues early. The API’s design prioritizes simplicity–common tasks like placing a limit order need fewer than five parameters.
Setting Up Authentication with API Keys
To authenticate with Hyperliquid’s API, generate an API key in the account settings under the “API Access” tab. The key consists of a public ID and a secret–store the secret securely, as it won’t be displayed again. For security, restrict the key’s permissions to only necessary endpoints, like trade execution or data queries, and set an IP whitelist if available.
When making requests, include the API key in the request header as X-API-KEY: [your-public-id]. For signed endpoints, create a HMAC-SHA256 signature using your secret, timestamp, and request parameters, then pass it in the X-SIGNATURE header. Rotate keys every 90 days and avoid hardcoding them in client-side applications.
Retrieving Market Data via REST Endpoints
Use the /marketdata endpoint to fetch real-time price feeds, order book snapshots, and 24h trading volume. For static pairs like BTC-USDT, append ?symbol=BTCUSDT to filter results, reducing payload size by ~40% compared to full-market requests.
Optimizing Data Requests
Batch queries for multiple symbols with a comma-separated list (?symbols=BTCUSDT,ETHUSDT) to minimize API calls. Set limit=100 for order book depth–the maximum supported without websockets–and cache responses client-side for 2-5 seconds to avoid rate limits.
For historical candles, add interval=1m|5m|1h and startTime/endTime as UNIX timestamps. Pagination isn’t native–manually track timestamps for sequential queries beyond the 500-candle default cutoff.
Placing and Managing Orders with WebSocket
Use the order WebSocket command to submit new orders with minimal latency. Specify required parameters like symbol, side, price, and quantity, and include optional flags such as postOnly or reduceOnly for advanced execution control. The API confirms successful placement with an orderAck event containing the order ID, which you should store for later updates or cancellations.
To modify or cancel orders in real time, send a modify or cancel command with the relevant order ID. Track execution status via WebSocket streams–fill events confirm partial/completed trades, while reject messages highlight errors. For bulk operations, structure requests like this:
| Command | Parameters | Response Event |
|---|---|---|
batchCancel |
orderIds: ["id1","id2"] |
batchCancelAck |
batchOrder |
orders: [{symbol: "BTC", side: "Buy", ...}] |
batchOrderAck |
Handling Rate Limits and Error Responses
Check API rate limits in Hyperliquid’s documentation before making requests. Each endpoint has specific thresholds, and exceeding them triggers temporary blocks. Store these values in your code to avoid unexpected interruptions.
Implement an exponential backoff strategy if you hit a rate limit. Start with a 1-second delay, doubling it after each failed attempt. Cap the delay at 32 seconds to prevent excessive waiting. The formula looks like delay = min(2^(attempts-1), 32) seconds.
Parse HTTP status codes first when handling errors. Status 429 means too many requests – wait before retrying. Status 4xx indicates client-side issues; verify your request parameters. Status 5xx requires checking Hyperliquid’s status page for service outages.
Log full error responses including timestamps and request IDs. Hyperliquid often includes detailed error messages with actionable feedback. For example, a malformed order might return “INVALID_SYMBOL: ETHUSD” instead of a generic error.
Create a retry loop for timeout errors (status 503 or 504). Use a maximum of 3 retries with increasing intervals. Skip retries for authentication errors (status 401/403) since they won’t resolve without credential updates.
Monitor your remaining rate limit using response headers like X-RateLimit-Remaining. Some endpoints return this as a percentage while others show absolute counts. Adjust your request frequency dynamically based on these values.
Working with Custom User Data Streams
To filter market data without polling multiple endpoints, use stream_user_data() with specific channel parameters. For example, specify type: 'fills' or type: 'orders' to receive real-time updates only for trade executions or open orders, reducing unnecessary network traffic.
Setting Up Listeners
Configure WebSocket listeners using the on_message callback to process incoming events. Handle errors with on_error to avoid silent failures:
- Parse JSON responses immediately to check for
status: 'error'. - Reconnect automatically if the stream closes unexpectedly (code 1006).
For position updates, combine stream_user_data() with REST API snapshots. Fetch initial positions via /positions, then sync changes through the stream–this avoids gaps during connection drops. Store timestamps locally to detect missed events.
Optimizing Performance
- Throttle high-frequency streams (e.g., balance updates) with
throttle_ms: 1000. - Use diff-based updates for large datasets like order books instead of full snapshots.
Test streams in sandbox mode first by appending ?env=test to URLs. Monitor CPU usage when processing 10+ streams concurrently–consider batching events if latency exceeds 50ms.
Implementing Webhook Notions for Trades
Set up a secure endpoint on your server to receive trade notifications via Hyperliquid’s API. The endpoint must handle POST requests with JSON payloads containing trade execution details such as symbol, price, size, and timestamp.
Register your webhook URL in the Hyper liquid dashboard under API settings. Use the webhook_url parameter with a valid HTTPS endpoint to ensure encrypted data transmission.
Test your webhook with mock trade events before going live. Hyper liquid’s sandbox environment lets you simulate order fills without risking real funds.
Process incoming webhook data in near real-time. Parse the JSON response to extract trade execution details, then trigger downstream actions like portfolio rebalancing or database logging.
Implement error handling for failed deliveries. If your endpoint returns HTTP status codes outside 2xx range, Hyper liquid’s API will retry failed notifications up to three times.
Monitor webhook activity through network logs and API response metrics. Track delivery times to identify potential bottlenecks in your notification pipeline.
Scale your webhook infrastructure to handle peak trading volumes. Consider asynchronous processing for high-frequency trading scenarios where milliseconds matter.
Keep your authentication tokens secure. Rotate API keys periodically and never hardcode credentials in client-side applications.
Querying Historical Price Data for Analysis
Use the Hyperliquid API’s `/historical-prices` endpoint to retrieve specific price data by specifying a trading pair, time range, and granularity. For example, request minute-level data for ETH/USD over the last 24 hours by setting `pair=ETHUSD`, `start_time=1672531200`, `end_time=1672617600`, and `interval=1m`.
Filter the response to focus on relevant fields like `timestamp`, `open`, `high`, `low`, `close`, and `volume`. This minimizes unnecessary data processing and ensures faster analysis. Extract these fields using built-in JSON parsing tools in your preferred programming language.
For large datasets, paginate your requests using the `limit` and `offset` parameters. Set `limit=1000` to retrieve 1000 records per request and adjust `offset` to fetch subsequent batches. This prevents API rate limits and optimizes performance.
Cache retrieved data locally to avoid redundant API calls. Store the data in a database or file system for quick access during repeated analysis. Tools like SQLite or CSV files work well for smaller datasets.
Handling Missing Data
Check for gaps in the returned data by comparing timestamps. If missing intervals are detected, query the API again with adjusted time ranges or smaller intervals. Use interpolation techniques if gaps are unavoidable.
Validate the accuracy of retrieved data by comparing it with alternative sources or cross-checking with the Hyperliquid UI. This ensures consistency and reliability for your analysis.
For automated workflows, integrate error handling to manage API rate limits, timeouts, or unexpected responses. Implement retries with exponential backoff to maintain smooth operation.
Testing Strategies in the Sandbox Environment
Begin by simulating low-volume trades to validate order execution and latency metrics. Use the Hyperliquid API’s mock endpoints to test limit, market, and stop orders without risking real funds. Monitor response times for different order types to ensure they meet your application’s performance thresholds. Incorporate edge cases, such as placing orders during high volatility scenarios, to identify potential bottlenecks.
Leverage the sandbox’s ability to reset your account state, allowing you to test specific workflows repeatedly. For example:
- Simulate account margin changes to verify liquidations work as expected.
- Test portfolio rebalancing logic with multiple positions.
- Validate error handling by intentionally submitting malformed requests or exceeding rate limits.
This approach ensures a smooth transition to live trading while minimizing unexpected issues.
Full description
What are the key features of the Hyperliquid API?
The Hyperliquid API provides real-time market data, order execution, and portfolio management tools. It supports REST and WebSocket connections, allowing users to fetch prices, submit trades, and monitor positions. Key features include low-latency updates, historical data access, and customizable order types like limit and market orders.
How do I authenticate requests with the Hyperliquid API?
Authentication requires an API key, which you generate in your account settings. Each request must include this key in the header. For sensitive actions like trading, additional signature verification is needed using your secret key. Always keep your secret key private and avoid hardcoding it in client-side applications.
Can I test the Hyperliquid API without risking real funds?
Yes, Hyperliquid offers a sandbox environment with simulated trading. You can use testnet API endpoints to practice integration, place mock orders, and check responses. This helps verify your code works correctly before switching to the live API.
What are common issues when integrating the Hyperliquid API?
Frequent problems include incorrect timestamp formats, expired API keys, and rate limit breaches. Double-check request parameters and ensure your system clock is synchronized. If WebSocket connections drop, implement reconnection logic. The API documentation lists error codes and troubleshooting steps for each scenario.
Video:
William Foster
“Hey there! Just tried out the Hyperliquid API and it’s way smoother than I expected. The docs are clear, and setting up trades feels like chatting with an old friend—no weird surprises. Love how it handles orders without fuss. If you’re into coding and trading, this one’s a no-brainer. Cheers!” (284 chars)
Isabella Brooks
### Critical Commentary: The Hyperliquid API guide lacks depth in explaining key trade-offs between speed and security, which is critical for any real-world implementation. The endpoints are listed, but there’s no meaningful discussion on rate limits, error handling, or latency under load—basic concerns for developers. The authentication section is oversimplified, ignoring common pitfalls like key rotation or IP whitelisting. The examples provided feel disconnected from practical use cases. Instead of demonstrating how to handle partial fills or slippage in orders, the focus is on trivial requests. Real trading strategies require more than basic REST calls—where’s the guidance on websocket stability or order book synchronization? Documentation isn’t just about listing features; it’s about clarifying limitations. If the API can’t handle certain market conditions or has quirks in cancellation logic, that needs upfront transparency. Right now, it reads like a promotional pamphlet, not a technical resource. Lastly, the absence of community feedback or versioning details raises red flags. APIs evolve, but without clear deprecation policies or changelogs, integrations break silently. This isn’t a guide—it’s a placeholder.
VelvetShadow
*”Ah, the Hyperliquid API—because manually tracking trades is so last decade. Elegant, ruthless, and just cryptic enough to make you feel like a hacker (until you accidentally liquidate yourself). Bravo.”* (184 chars)
LunaWhisper
The Hyperliquid API offers functionality that aligns well with scalable automation needs, though its documentation could benefit from more granular examples for edge cases. The setup process is straightforward, assuming familiarity with WebSocket and REST protocols, but those new to trading APIs might find the initial configuration mildly cumbersome. Its real-time data streaming is reliable, though latency-sensitive applications may require additional optimization. The platform’s modular design allows for customization, but this flexibility comes with the trade-off of requiring a deeper understanding of its architecture. For developers with mid-to-advanced experience, it’s a solid tool, but beginners might need supplemental resources to fully leverage its potential.
Robert Hughes
**”So, the API lets users swap assets, query data, and place orders—got it. But why should anyone trust Hyperliquid’s infra more than, say, a random dev’s weekend project? The docs mention low latency and ‘sovereign’ logic, but where’s the proof it won’t fold under load or leak keys like a sieve? Also, ‘gasless trades’ sound neat until you dig into the L1 settlement—what’s the actual cost of that abstraction? And why no war stories? Show me a bot that survived more than three market cycles using this, or admit it’s just another ‘smooth UX until it breaks’ pipe dream.”** *(297 symbols, direct, no fluff, with sarcasm—just how you wanted.)*
Leave a Reply