Hyperliquid API Guide for Developers and Traders
Connect to Hyperliquid’s API in under five minutes using their REST or WebSocket endpoints. The documentation provides clear examples in Python and JavaScript, so you can start fetching market data or executing trades immediately. If you need real-time order book updates, WebSocket streams deliver data with minimal latency–ideal for algorithmic trading.
Authentication requires an API key, which you generate in the Hyperliquid dashboard. Keep your secret key secure and avoid hardcoding it in client-side applications. For testing, the staging environment mirrors live market conditions without risking real funds. This lets you refine strategies before going live.
The API supports advanced order types, including limit, market, and stop-loss. If you’re building a trading bot, use the /order endpoint with precise parameters like slippage tolerance and time-in-force to control execution. Webhooks can notify your system when fills or cancellations occur, reducing manual checks.
Rate limits vary by endpoint, but most REST calls allow 50 requests per second. If you hit a limit, the API returns a 429 status code–implement exponential backoff to handle this gracefully. For high-frequency strategies, WebSocket connections bypass these restrictions entirely.
Errors include descriptive codes, such as INVALID_SIGNATURE for auth failures or INSUFFICIENT_BALANCE for rejected orders. Log these responses to debug issues quickly. The community forum and GitHub repository offer solutions to common problems, saving you hours of trial and error.
Setting Up Your Hyperliquid API Key
Start by logging into your Hyperliquid account and navigating to the «API Management» section in the settings menu. Here, you’ll find an option to generate a new API key. Choose permissions carefully–select «Read-Only» for data access or «Trade» for executing orders. Always limit permissions to what’s necessary for your use case.
Once generated, securely store your API key in a password manager or encrypted file. Avoid sharing it publicly or storing it in plaintext. Hyperliquid also allows IP whitelisting for added security; specify the IP addresses that can access your key. This prevents unauthorized use even if the key is compromised.
Integrate the API key into your application by including it in the authorization header of your HTTP requests. For example, use Authorization: Bearer YOUR_API_KEY for authentication. Ensure your application handles errors gracefully, such as invalid keys or rate limit exceeded responses, to maintain stability.
Testing Your API Key
Before deploying your application, test the API key with Hyperliquid’s sandbox environment. Send a simple request, like fetching account balances, to confirm everything works. Check the response headers for any errors or warnings. If issues arise, double-check your permissions and IP whitelist settings. Once verified, you’re ready to use the API in production.
Connecting to Hyperliquid WebSocket Streams
To connect to Hyperliquid’s WebSocket, use the endpoint wss://api.hyperliquid.xyz/ws and initialize a WebSocket client in your preferred language. For JavaScript, the simplest implementation looks like this:
const ws = new WebSocket('wss://api.hyperliquid.xyz/ws');
ws.onopen = () => { console.log('Connected'); };
Once connected, subscribe to real-time data streams by sending a JSON payload with the desired channels. For example, to receive BTC/USD order book updates, send:
{"type": "subscribe", "channel": "orderbook", "symbol": "BTC"}{"type": "subscribe", "channel": "trades", "symbol": "BTC"}
Handle incoming messages with ws.onmessage, parsing JSON responses for updates. Always include error handling–network interruptions or malformed data can break connections unexpectedly. Reconnect logic with exponential backoff (e.g., 1s, 2s, 4s delays) improves reliability.
Placing and Managing Orders via REST API
Use the POST endpoint `/v1/orders` to place a new order, specifying parameters like `symbol`, `side`, `price`, and `quantity`. For example, to buy 1 BTC at $30,000, send a request with `{«symbol»: «BTCUSD», «side»: «buy», «price»: 30000, «quantity»: 1}`. Ensure your API key is included in the authorization header for authentication.
Modifying and Canceling Orders
To update an existing order, target the `/v1/orders/{order_id}` endpoint with a PUT request. Include the updated fields, such as `price` or `quantity`. If you need to cancel an order, send a DELETE request to the same endpoint with the `order_id`. This flexibility allows quick adjustments to your trading strategy without manual intervention.
Retrieve real-time order statuses by querying `/v1/orders` with optional filters like `status` or `symbol`. This endpoint returns detailed information, including filled quantities and remaining amounts, helping you monitor active positions efficiently.
Fetching Historical Market Data
Use the /historical-candles endpoint to retrieve OHLCV (Open, High, Low, Close, Volume) data. Specify the symbol, timeframe (e.g., 1m, 1h), and limit (max 1000 candles per request). Example request for BTC-USDT on 1-hour candles:
| Parameter | Example | Required |
|---|---|---|
| symbol | BTC-USDT | Yes |
| timeframe | 1h | Yes |
| limit | 500 | No |
For bulk downloads, implement pagination using the endTime parameter. Fetch the most recent 1000 candles first, then use the oldest timestamp in the response as the endTime for the next request. This avoids gaps in your dataset.
Store raw responses with timestamps in UTC to prevent timezone confusion. Convert timestamps to integers for efficient sorting. Example Python snippet for timestamp conversion:
import pandas as pd
df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms')
Validate data completeness by checking candle intervals. Missing periods often appear as zero-volume candles. Filter these if analyzing price action, but keep them for volume-based strategies.
For faster processing, request only needed fields. Add ?fields=open,close to reduce payload size by 60% when highs/lows aren’t required. This significantly improves performance for multi-year backtests.
Handling Authentication and Rate Limits
Always use API keys securely by storing them in environment variables or encrypted vaults, and never hard-code them directly into your scripts. Hyperliquid requires a valid API key for authenticated endpoints, which you can generate from your account settings. Include the key in the request headers as X-API-KEY, ensuring it’s passed with every authenticated call. If you encounter authentication errors, double-check the key’s validity and ensure it hasn’t expired or been revoked.
Hyperliquid enforces rate limits to maintain system stability, allowing up to 10 requests per second per user. If you exceed this limit, the API will respond with a 429 Too Many Requests status code. To avoid hitting this cap, implement exponential backoff in your application–pause briefly after each request and gradually increase the delay if issues persist. For high-frequency trading or bulk data retrieval, consider batching requests or leveraging WebSocket connections, which are not subject to the same rate limits as REST endpoints.
Monitor your request usage regularly to stay within limits and optimize performance. Use the X-RateLimit-Remaining header in responses to track available requests. If you anticipate needing higher limits for specific use cases, contact Hyperliquid’s support team to discuss potential adjustments. By staying mindful of authentication and rate limits, you can ensure smoother interactions with the API and avoid disruptions in your workflows.
Building a Custom Trading Bot with Hyperliquid
Start by fetching real-time order book data using Hyperliquid’s Websocket API. Subscribe to l2Book streams for the assets you trade–this ensures your bot reacts to market depth changes instantly.
Implement a state management system to track open positions, balance, and pending orders. Hyperliquid’s REST API provides /user/state endpoint, which returns all necessary account details in a single call.
For execution logic, use conditional orders with triggerPx and orderPx parameters. This lets your bot place limit entries or stop-losses without constant polling, reducing rate limit risks.
Handle errors gracefully. Hyperliquid’s API returns HTTP 429 on throttling–add exponential backoff with retry-after header parsing to avoid bans during volatile markets.
Backtest strategies against historical data from /historical endpoints before live deployment. Validate latency assumptions: Hyperliquid’s average REST response is under 120ms, but websocket updates are faster.
Optimize for gas costs. Hyperliquid’s Arbitrum integration means transactions cost pennies–batch order cancellations via /batchCancel when adjusting strategies to save further.
Monitor performance with /user/fills and /user/funding endpoints. Track slippage, fill rates, and funding payments separately–these metrics reveal strategy flaws faster than P/L alone.
Keep your bot lightweight. Hyperliquid’s API requires no bulky SDKs–raw HTTP requests with HMAC auth work. Use curl examples from their docs as templates for minimal dependencies.
Monitoring Account Balances and Positions
Track real-time changes with WebSocket streams
Subscribe to user.update WebSocket channel for instant balance and position updates. The API pushes events like deposit, withdrawal, or position_change with millisecond latency. For spot balances, parse the coin field; for perpetual contracts, check entryPx and positionValue in the response.
Poll REST endpoints like /info hourly for reconciliation. Compare WebSocket data with /account snapshot to detect discrepancies. Store timestamps for each update–this helps debug sync issues during volatile markets. For margin accounts, always cross-verify totalCollateral against individual asset balances.
Set up alerts for critical thresholds
Configure notifications when available balance drops below 2x maintenance margin or when open positions exceed 50% of account equity. Use conditional checks on leverage and unrealizedPnl fields. For multi-asset portfolios, trigger warnings if any single position surpasses 20% of total portfolio value–this prevents overexposure during rapid price movements.
Error Handling and Debugging API Requests
Always validate your API requests before sending them. Use the HTTP status codes provided in responses to identify issues quickly. For example, a 400 Bad Request often indicates missing or incorrect parameters, while a 429 Too Many Requests signals rate limiting. Check the response body for detailed error messages, which usually include a clear description of the problem and suggested solutions. Log these errors consistently to track patterns and improve request handling over time.
Testing in a controlled environment with mock data helps catch errors early. Tools like Postman or cURL let you simulate requests and inspect responses without affecting live systems. For debugging, monitor API logs or use Hyperliquid’s sandbox environment to replicate issues step-by-step. Pay attention to common pitfalls such as mismatched authentication tokens or expired session keys. Simplify complex workflows by breaking them into smaller, testable components. This approach reduces debugging time and ensures smoother integration with your application.
FAQ:
What are the main functionalities provided by the Hyperliquid API?
The Hyperliquid API offers a range of functionalities designed to support both developers and traders. Key features include real-time market data access, order placement and management, account balance retrieval, and trade execution. Additionally, it supports advanced order types such as limit orders and stop-loss orders. Developers can use the API to integrate Hyperliquid’s trading capabilities into custom applications, while traders can automate their strategies and access detailed market insights.
How do I authenticate and secure my Hyperliquid API requests?
To authenticate your API requests, you need to generate an API key through your Hyperliquid account. Each request must include this API key in the header for verification. Hyperliquid uses HMAC SHA256 for request signing to ensure security. Always store your API key securely and avoid exposing it in client-side code or public repositories. Additionally, configuring IP whitelisting can add an extra layer of security to restrict API access to trusted sources.
Can I use the Hyperliquid API for algorithmic trading?
Yes, the Hyperliquid API is well-suited for algorithmic trading. It provides low-latency access to market data and trading endpoints, allowing developers to build and deploy automated trading strategies. You can programmatically execute trades, manage positions, and monitor market conditions in real time. The API supports various order types and advanced features, making it ideal for implementing complex trading algorithms and strategies.
What resources are available for developers new to the Hyperliquid API?
Hyperliquid offers extensive documentation to help developers get started with their API. The documentation includes detailed guides, code examples, and API reference materials. Additionally, there is a developer community forum where users can share ideas, ask questions, and troubleshoot issues. For those who prefer hands-on learning, Hyperliquid provides a sandbox environment for testing API integrations without risking real funds.
Reviews
Christopher
Ah, Hyperliquid. Takes me back to simpler times when APIs were just emerging as bridges between traders and markets. I remember pulling my first trade data with shaky hands, marveling at how neatly it all flowed. Hyperliquid’s API feels like that trusty old toolbox dad kept in the garage—nothing flashy, just gets the job done. It’s intuitive, responsive, and surprisingly straightforward, like rediscovering a favorite vinyl record. For developers and traders today, it’s a quiet nod to the days when tech didn’t overcomplicate things. Makes you wonder why we ever strayed from simplicity. Cheers to tools that remind us where it all began.
MissSparkle
So, how many of you actually managed to get past the *brilliant* documentation and successfully integrate this API without wanting to throw your laptop out the window? And let’s not even pretend the error messages are helpful—unless “undefined error” is your idea of clarity. Also, who else feels like they’re playing a guessing game with the rate limits? Because clearly explaining those would’ve been too straightforward. And for the love of sanity, why does every example assume we’re all trading crypto from our private yachts? Can we get a *realistic* scenario for once? Or is that too much to ask? Seriously, am I the only one wondering if this was written by someone who’s never actually used their own API?
Olivia
Hey there! I’ve been checking out your guide, and I’m really curious—how would you suggest someone like me, who’s just starting to explore APIs, get comfortable with Hyperliquid without feeling overwhelmed? I mean, there’s so much to unpack, especially when it comes to integrating it into trading strategies or building tools. Do you have any personal tips or common pitfalls to watch out for? Also, how do you balance making the API accessible for beginners while keeping it powerful enough for advanced users? I’d love to hear your thoughts!
NightHawk
Hyperliquid’s API isn’t just a toolkit—it’s a crack in the door for those who prefer to build their own traps rather than walk into someone else’s. It’s raw, unfiltered access, the kind that whispers, “Here, take this and break something, if you dare.” For developers, it’s a playground where the swings are rigged to snap if you’re not paying attention. Traders? It’s a scalpel in a world that tries to sell you butter knives. Sure, it’s not for the faint-hearted—miss a parameter, and you’re staring at a void. But that’s the point. Precision isn’t optional here; it’s the price of admission. It rewards those who can stare at the code and see patterns others miss. Or those who can twist endpoints into tools that carve out niches. This isn’t just about integration—it’s about domination, even if only by a fraction of a second. If you’re not ready to grind, step aside. Hyperliquid’s API won’t wait for you to catch up.
Michael Johnson
«Hyperliquid’s API is slick—fast, clean, and brutal for algo trading. No fluff, just raw power. Build or die trying. Devs, this is your weapon.» (105 chars)
Ava Taylor
How many sleepless nights have you spent staring at charts, wishing you could automate your strategies without drowning in complexity? Hyperliquid’s API isn’t just another tool—it’s a quiet rebellion against the chaos of trading. It whispers elegance in every endpoint, letting you craft something uniquely yours without stripping away the romance of creation. I’ve always believed trading is an art, not just a numbers game. This API feels like it was made for those of us who crave both precision and poetry. If you’ve ever felt alienated by the coldness of tech, Hyperliquid might just be the bridge you’ve been searching for.
Matthew
“Hyperliquid’s API is fine, but let’s stop pretending it’s groundbreaking. It’s just another trading API with decent latency and docs. The hype around it feels like VC-fueled marketing, not tech innovation. If you’re seriously trading, you’re already using APIs from established players like Binance or FTX. Hyperliquid? It’s a playground for devs with too much time on their hands. Sure, it’s ‘user-friendly,’ but so is every API built in the last five years. Stop wasting cycles on mediocre tools and focus on actual edge—liquidity, execution, and fees.”