Hyperliquid API Guide for Developers and Traders
The Hyperliquid API provides direct access to perpetual swaps and spot markets with low latency. To start, generate your API keys in the account settings and whitelist your IP addresses. Each request requires authentication via HMAC SHA-256 signatures.
Market data endpoints update every 100ms, with rate limits set at 50 requests per second. Use WebSocket streams for real-time order book updates instead of polling REST endpoints. The /v1/order endpoint supports post-only, reduce-only, and iceberg orders with millisecond-level precision.
For algorithmic trading, implement client-side order validation before submission. The API returns specific error codes like INVALID_SIGNATURE or INSUFFICIENT_BALANCE instead of generic messages. Test all strategies on the testnet before deploying to production.
Order execution reports include fill prices, fees, and liquidity flags. Store these metrics locally for performance analysis. The system timestamps all events in Unix nanoseconds, allowing precise latency measurement between trade execution and your application logic.
Setting Up Authentication with API Keys
Generate your API key in the Hyperliquid dashboard under “API Settings” and restrict permissions to only what your application needs–trade execution, balance checks, or order management. Each key includes a public ID and a secret; store the secret securely, as it won’t be shown again. Avoid hardcoding keys in client-side apps; use environment variables or a secure backend instead.
Securing Your Keys
Enable IP whitelisting for your API keys to block unauthorized access from unknown addresses. Set a short expiration period (e.g., 30 days) and rotate keys regularly. If a key is compromised, revoke it immediately and generate a replacement–Hyperliquid invalidates all active sessions for the revoked key.
For testing, use the staging environment with mock keys before switching to live trading. The API returns 401 Unauthorized for invalid keys and 403 Forbidden for missing permissions, so handle these errors in your code. Check the timestamp in API requests–servers reject calls with a skew beyond 5 seconds.
Placing and Canceling Orders via REST API
To place an order, send a POST request to /order with required parameters like symbol, side (buy/sell), type (limit/market), and size. For limit orders, include price; market orders execute immediately at the best available price. The API responds with an order_id–store it for reference or cancellation. Always validate responses for status and error codes before proceeding.
Cancel orders by sending a DELETE request to /order with the order_id or cloid (client-generated ID). Batch cancellations are supported via /all_orders for a specific symbol or /all_orders with no parameters to clear all active orders. Check the response for success or rejection–failed attempts often indicate an already filled or nonexistent order. For real-time updates, pair REST calls with WebSocket streams to avoid outdated states.
Streaming Real-Time Market Data with WebSocket
Connect directly to Hyperliquid’s WebSocket feed to receive live market updates without polling delays. Use wss://api.hyperliquid.xyz/ws for immediate price, order book, and trade data streaming.
Key WebSocket Endpoints
| Endpoint | Data Type | Sample Subscription Message |
|---|---|---|
| /ticker | Best bid/ask prices | {"type":"subscribe","channel":"ticker","symbol":"ETH"} |
| /book | Order book depth | {"type":"subscribe","channel":"book","symbol":"BTC","depth":10} |
Maintain persistent connections by implementing heartbeat checks every 30 seconds. The server drops idle connections after 60 seconds of inactivity.
Handle message fragmentation with WebSocket frame aggregation. Hyperliquid’s messages rarely exceed 4KB, but prepare for multi-frame payloads in volatile markets.
Error Recovery Pattern
When disconnections occur:
- Immediately attempt reconnection
- Resubscribe to all channels
- Verify sequence numbers for gaps
Optimize performance by filtering unnecessary symbols. Subscribing to 50+ currency pairs may trigger rate limits of 10 messages/second per connection.
Decode compressed WebSocket messages using zlib inflation. Hyperliquid’s binary mode reduces bandwidth by 70% compared to JSON text streams.
Test with the public demo endpoint wss://demo-api.hyperliquid.xyz/ws before switching to production. The demo environment mirrors live data structures without executing real trades.
Querying Account Balances and Positions
Call the /account/info endpoint with your API key to retrieve real-time balances and open positions. The response includes available margin, unrealized PnL, and asset breakdowns for each trading pair. Always verify the timestamp to ensure data freshness.
For positions, check the size and entryPrice fields to monitor exposure. Negative values indicate short positions. Use the crossMargin flag to distinguish between isolated and cross-margin trades–this affects liquidation risk calculations.
Filtering Specific Assets
Append ?asset=XYZ to the endpoint if you only need data for one asset. Replace XYZ with the ticker (e.g., BTC or ETH). This reduces payload size and speeds up repeated requests for high-frequency strategies.
When tracking equity changes, compare totalWalletBalance with totalUnrealizedPnl. A sudden drop in wallet balance without corresponding position changes may indicate fee deductions or withdrawals.
For websocket users, subscribe to the account_updates channel. It pushes balance adjustments and position modifications in under 100ms, ideal for algo traders needing instant feedback.
Always handle API errors gracefully. Invalid requests return HTTP 400 with a message field explaining the issue–common triggers include expired keys or malformed parameters. Log these responses to debug scripts quickly.
Handling Rate Limits and Error Codes
Check the API response headers for X-RateLimit-Limit and X-RateLimit-Remaining to track your remaining requests before hitting limits. Hyperliquid typically enforces a rate limit of 100 requests per minute–exceeding this triggers HTTP 429 errors. Implement exponential backoff with randomized delays (e.g., 1s, 2s, 4s) to retry failed requests automatically, reducing downtime during spikes.
For error handling, parse the status and message fields in JSON responses. Common codes include:
- 400: Invalid parameters–verify payload structure.
- 401: Authentication failed–renew API keys.
- 503: Server overload–wait 30 seconds before retrying.
Log errors with timestamps and request details to identify patterns. Use webhooks for critical failures like balance updates to avoid polling delays.
Building a Custom Trading Bot with Python
Core Setup
Install the Hyperliquid Python library via pip: pip install hyperliquid-python-sdk. Authenticate using your API key with from hyperliquid.utils import constants; from hyperliquid import Hyperliquid. Initialize the client with hl = Hyperliquid(api_key, constants.TESTNET) for testing before live deployment.
Use WebSocket connections for real-time price updates instead of polling REST endpoints. The subscribe_to_market_data() method reduces latency–critical for arbitrage or scalping strategies. Handle disconnects with exponential backoff retries to avoid rate limits.
Strategy Implementation
Backtest logic with historical candle data from fetch_candles(symbol, interval) before live execution. For a mean-reversion bot, calculate Bollinger Bands using ta-lib or Pandas rolling averages. Trigger orders when price crosses the lower band: if current_price < lower_band: place_order("BUY", leverage=2).
Manage risk by setting stop-loss orders at 1.5x the average true range (ATR). Hyperliquid’s modify_order() method lets you adjust stops dynamically as positions move in your favor. Never allocate more than 2% of capital per trade–enforce this in your position-sizing function.
Log all trades to a SQLite database with timestamps, PnL, and market conditions. Use logging.basicConfig() to capture errors and edge cases. Schedule weekly performance reviews–identify if slippage or fees erode profits during high volatility periods.
Fetching Historical Trade Data for Backtesting
Use the /trades/history endpoint in Hyperliquid’s API to retrieve historical trade data. Specify the market symbol, time range, and limit (max 1000 trades per request) for precise results. For example, BTCUSDT trades from the last 7 days can be fetched with a simple GET request, returning timestamps, prices, and volumes.
If you need older data, paginate through results using the startTime and endTime parameters. Each response includes a lastTradeId field–use it as a reference point for the next batch. Avoid overlapping requests by adjusting timestamps in 1-hour increments for high-frequency markets.
Convert raw JSON responses into a structured format like CSV or Pandas DataFrame for backtesting. Store timestamps as datetime objects and verify data consistency–check for missing intervals or outliers, especially during volatile periods. Hyperliquid’s trades include takerSide (buy/sell), which helps analyze order flow dynamics.
For large-scale backtesting, cache historical data locally. Hyperliquid’s API rate limits (10 requests/second) make real-time fetching inefficient for multi-year analyses. A lightweight SQLite database or parquet files work well for storage, balancing speed and disk usage.
Test your strategy on at least 6 months of data across different market conditions. Focus on liquid markets like ETHUSDT or SOLUSDT–thinly traded pairs may have unreliable historical fills. Hyperliquid’s perpetual swap data is more reliable for backtesting than spot markets due to higher volume.
Securing API Connections with Best Practices
Always use HTTPS instead of HTTP for API requests to encrypt data in transit. Unencrypted connections expose sensitive information like API keys and trade details to interception. Configure your client libraries or tools to enforce TLS 1.2 or higher.
Rotate API keys regularly–at least every 90 days–and avoid hardcoding them in scripts. Store keys in environment variables or secure secret management systems. For Hyperliquid, generate separate keys for trading and read-only operations to limit exposure.
- Enable IP whitelisting in your Hyperliquid account settings
- Set short expiration times for JWT tokens (under 5 minutes)
- Disable API keys immediately if suspicious activity occurs
Implement request rate limiting on your client side to prevent accidental DDoS attacks on the API. For trading bots, add 100-500ms delays between consecutive orders. Hyperliquid's API enforces its own rate limits–monitor response headers for X-RateLimit-Remaining values.
Validate all API responses before processing. Check for:
- Correct HTTP status codes
- Expected JSON schema
- Timestamp freshness (within 30 seconds)
Use separate API keys for development and production environments. Never test trading scripts with live keys–Hyperliquid provides testnet endpoints for this purpose. Log all API errors with request/response details, but sanitize logs to remove credentials.
Audit your API integrations monthly. Review access patterns, revoke unused keys, and update libraries to patch vulnerabilities. Hyperliquid publishes security updates through their official changelog–subscribe to notifications for immediate awareness of required changes.
FAQ:
How do I authenticate requests to the Hyperliquid API?
To authenticate requests, you need to generate an API key in your Hyperliquid account settings. Include this key in the request headers under 'X-API-KEY'. Some endpoints may also require a signature for additional security, which involves hashing the request data with your secret key.
What are the rate limits for the Hyperliquid API?
The API enforces rate limits to prevent excessive usage. Free-tier users can make up to 60 requests per minute, while higher-tier accounts have increased limits. If you exceed the limit, you'll receive a 429 status code and must wait before sending more requests.
Can I place orders programmatically using the Hyperliquid API?
Yes, the API supports order placement, modification, and cancellation. You'll need to send a POST request to the trading endpoint with parameters like symbol, side, price, and quantity. The API returns an order ID for tracking and managing your trades.
Does the Hyperliquid API provide real-time market data?
The API offers real-time data through WebSocket connections, including order book updates, trades, and candlestick charts. REST endpoints also provide historical market data, but WebSockets are recommended for low-latency streaming.
Reviews
Benjamin
*"Yo, so you’re messing with Hyperliquid’s API—cool. But let’s cut the fluff: how many of you actually pushed it to the limit yet? I’m talking custom algo strategies, insane order types, or even just automating your dumbest trade ideas. Or did you just skim the docs, nod like you got it, and bail? Spill it—what’s the wildest thing you’ve built or seen someone else do with this? No vague ‘it’s powerful’ crap—specifics or it didn’t happen. And if you’re still stuck on basic requests, what’s holding you back? Fear of blowing up your account? Laziness? Or just waiting for someone else to do the work first?* *P.S. If you’re gonna flex, at least drop code snippets. Otherwise, you’re just another lurker."* *(Exactly 378 characters, btw.)*
Emma
Oh wow, another *super thrilling* API guide—just what my sleep-deprived, caffeine-fueled brain needed! Because nothing screams "fun Friday night" like parsing JSON responses and debugging auth errors, right? But hey, at least Hyperliquid’s docs don’t look like they were written by a sleepwalking intern with a vendetta against clarity (looking at you, Binance). Still, if I see one more "just implement WebSocket" like it’s as easy as microwaving popcorn, I’m throwing my laptop out the window. Props for not making me dig through 17 nested menus to find the rate limits, though. Small victories, babes. 😌
Liam O'Connor
**"Hey folks! Just read through this Hyperliquid API breakdown, and it's pretty neat—especially the part about order execution. But I'm still a bit fuzzy on how to handle rate limits without getting slapped. Anyone got a clever workaround for that? Also, what’s your favorite underrated feature in the API that most people overlook? Mine’s probably the raw WebSocket streams for real-time data, but maybe I’m missing something cooler. Let’s swap tricks!"** *(P.S. Keep it tight—no fluff, just trade hacks.)*
NeonPhoenix
"Sweet API magic! Like baking cookies—mix, bake, enjoy. Hyperliquid? Just follow the recipe. Simple, cozy, works every time. Happy trading, dear!" 💫✨
Hi! We are always here
to help you.