Hyperliquid API Guide for Traders
How to connect to Hyperliquid's API — WebSocket setup, order placement, position management, and building your first trading bot.
Hyperliquid's API is the reason algorithmic traders migrate from centralized exchanges. No VIP tier required to access WebSocket feeds. No rate-limit walls at standard volumes. Maker rebates that pay you -0.02% per fill. And a non-custodial architecture that means your bot controls capital without trusting an exchange with it.
This guide covers the practical aspects of Hyperliquid's API — authentication, data feeds, order management, and the patterns that production trading bots use. It's written for traders who want to automate perpetual futures strategies, not for protocol developers.
API Architecture Overview
Hyperliquid exposes two primary interfaces:
REST API — For order placement, cancellation, account queries, and historical data. Synchronous request-response. Rate-limited at 100 requests/second.
WebSocket API — For real-time market data, order updates, and fill notifications. Persistent connection. No meaningful rate limit on subscriptions. This is where your bot lives during active trading.
Both connect to the Hyperliquid L1 blockchain. Every order you submit through the API is an on-chain transaction — signed by your wallet (or API wallet) and settled by the HyperBFT consensus. The API abstracts the blockchain mechanics, so you interact with it like any exchange API.
Base URLs:
- Mainnet REST: https://api.hyperliquid.xyz
- Mainnet WebSocket: wss://api.hyperliquid.xyz/ws
- Testnet: Available for paper trading with identical endpoints on a test domain
Authentication and API Wallets
Hyperliquid uses wallet-based authentication. There are two approaches:
Direct Wallet Signing
Your bot signs every API request with your primary wallet's private key. This works but exposes your main key to the trading server.
API Wallet (Recommended)
Generate a dedicated API wallet through the Hyperliquid interface. This creates a secondary key pair with trading permissions but no withdrawal access.
Security model: The API wallet can place orders, cancel orders, and query positions. It cannot withdraw funds from the smart contract. If the API key is compromised, an attacker can trade but cannot steal your collateral.
Setup flow:
- Connect your primary wallet to Hyperliquid
- Navigate to API settings
- Generate an API wallet (returns an address + private key)
- Approve the API wallet from your primary wallet (on-chain transaction)
- Use the API wallet's private key in your bot
Every API request is signed using EIP-712 typed data signing. The Python and TypeScript community libraries handle signature generation — you provide the private key, and the library handles the rest.
WebSocket Data Feeds
The WebSocket connection is the backbone of any real-time trading bot. Hyperliquid supports multiple subscription channels:
Order Book (L2)
{
"method": "subscribe",
"subscription": {
"type": "l2Book",
"coin": "BTC"
}
}Returns the full order book snapshot on subscribe, then incremental updates. The book data includes price levels and aggregate size at each level. Typical update frequency: every 100-200ms during active trading.
Use case: Market-making bots that need to know the current best bid/ask and depth at each level. Grid bots that adjust order placement based on book shape.
Trades
{
"method": "subscribe",
"subscription": {
"type": "trades",
"coin": "BTC"
}
}Real-time trade feed with price, size, side, and timestamp. Every fill on the book generates a trade message.
Use case: Volume analysis, trade flow detection, and TWAP/VWAP execution algorithms that need to track executed volume.
User Fills
{
"method": "subscribe",
"subscription": {
"type": "userFills",
"user": "0xYourAddress"
}
}Notifications when your orders fill. Includes fill price, size, fee, and order ID.
Use case: Position tracking, fill confirmation, and P&L calculation in real-time.
Candles (OHLCV)
{
"method": "subscribe",
"subscription": {
"type": "candle",
"coin": "BTC",
"interval": "1m"
}
}Candlestick data at various intervals (1m, 5m, 15m, 1h, 4h, 1d). Updates as the current candle forms.
Use case: Technical analysis signals, trend detection, and volatility estimation.
WebSocket Connection Management
Latency: Typical round-trip latency is 50-100ms for WebSocket messages. This is competitive with centralized exchanges and sufficient for all but the lowest-latency HFT strategies.
Reconnection: WebSocket connections can drop during network issues or Hyperliquid maintenance. Your bot must handle reconnection gracefully:
- Detect disconnect (missing heartbeat or connection error)
- Cancel all open orders (if possible via REST)
- Reconnect with exponential backoff
- Re-subscribe to all channels
- Re-sync position state before resuming trading
Heartbeat: Send periodic pings to keep the connection alive. Most libraries handle this automatically.
Order Placement via REST
Order Types
Limit order:
{
"type": "order",
"orders": [{
"a": 0,
"b": true,
"p": "68000",
"s": "0.1",
"r": false,
"t": {"limit": {"tif": "Gtc"}}
}],
"grouping": "na"
}Where a is the asset index (0 = BTC), b is buy side (true = long), p is price, s is size, r is reduce-only, and t specifies the order type.
Time-in-force options:
- Gtc — Good till cancelled. Sits on the book until filled or cancelled.
- Ioc — Immediate or cancel. Fills what it can, cancels the rest.
- Alo — Add liquidity only (post-only). Rejected if it would immediately fill. Guarantees maker execution and the -0.02% rebate.
Market order: Use Ioc with a price far from current market. The order sweeps the book and fills at available prices.
Batch Orders
Submit multiple orders in a single API call:
{
"type": "order",
"orders": [
{"a": 0, "b": true, "p": "67500", "s": "0.05", "r": false, "t": {"limit": {"tif": "Gtc"}}},
{"a": 0, "b": true, "p": "67000", "s": "0.05", "r": false, "t": {"limit": {"tif": "Gtc"}}},
{"a": 0, "b": false, "p": "68500", "s": "0.05", "r": false, "t": {"limit": {"tif": "Gtc"}}},
{"a": 0, "b": false, "p": "69000", "s": "0.05", "r": false, "t": {"limit": {"tif": "Gtc"}}}
],
"grouping": "na"
}This places 4 orders in 1 request. Essential for grid bots and market makers that manage multiple price levels. Reduces latency and API call count.
Cancel Orders
Cancel by order ID (returned on placement) or cancel all orders for an asset:
{
"type": "cancel",
"cancels": [{"a": 0, "o": 12345}]
}Batch cancellation works the same way — pass multiple cancel objects in the array. Critical for risk management: your bot should cancel all open orders before disconnecting or during unexpected market events.
Position and Account Queries
Current Positions
Query via the info endpoint to get all open positions, margin used, liquidation prices, and unrealized P&L:
{
"type": "clearinghouseState",
"user": "0xYourAddress"
}Returns position details including entry price, size, leverage, margin allocated, and liquidation price. Your bot should poll this periodically (every 5-10 seconds) to maintain accurate state, supplemented by real-time fill updates from the WebSocket.
Funding Rate Data
{
"type": "metaAndAssetCtxs"
}Returns current funding rates for all assets, along with mark price, index price, open interest, and 24-hour volume. This is the primary data source for funding rate arbitrage bots.
For historical funding data, query the info endpoint with time range parameters. Historical funding is essential for backtesting carry strategies.
Rate Limits and Optimization
REST: 100 requests/second. For most strategies, this is generous. A market-making bot updating 10 price levels every second uses 10 req/s (or 1 with batch orders). A grid bot rebalancing every minute uses <2 req/s.
WebSocket: No explicit rate limit on subscriptions. You can subscribe to order books for 20+ coins simultaneously. The constraint is processing speed on your end, not the API.
Optimization patterns:
- Use batch orders to reduce request count (20 orders in 1 call vs. 20 calls)
- Use Alo (post-only) to guarantee maker fills and avoid taker fees
- Cache the order book locally from WebSocket updates instead of polling REST
- Subscribe only to the channels you need — unnecessary subscriptions waste bandwidth and processing time
Common Integration Patterns
Python (using hyperliquid-python-sdk)
The community Python SDK wraps the REST and WebSocket APIs. Install via pip, initialize with your API wallet key, and start placing orders. The SDK handles EIP-712 signing, WebSocket management, and response parsing.
Typical bot loop:
- Initialize WebSocket connection and subscribe to L2 book, user fills
- On each book update: calculate target quotes based on strategy
- Cancel stale orders via REST batch cancel
- Place new orders via REST batch order
- On each fill: update position state, adjust risk parameters
- Every 30 seconds: poll clearinghouse state for full position sync
TypeScript (using hyperliquid-ts)
Similar structure to Python. The TypeScript SDK uses ethers.js for wallet signing. WebSocket handling uses the standard ws library. Suitable for Node.js bots and serverless deployments.
Testnet and Paper Trading
Hyperliquid provides a testnet environment with identical API endpoints. Test your bot with paper money before deploying real capital.
Testnet limitations: Lower liquidity, wider spreads, and fewer participants mean fills behave differently than mainnet. Test execution logic on testnet, but validate P&L assumptions on mainnet with small capital.
FAQ
Is the Hyperliquid API free to use?
Yes. API access is free with no subscription tiers. The only costs are trading fees (maker rebates of -0.02%, taker fees of 0.05% at standard). No VIP volume requirements to access WebSocket feeds or batch orders.
What programming languages are supported?
Officially, the API is language-agnostic (REST + WebSocket). Community SDKs exist for Python and TypeScript. Any language that can make HTTP requests and handle WebSocket connections works. Python is the most popular for trading bots; TypeScript for web-based integrations.
How do I handle API wallet security?
Store your API wallet private key in environment variables or a secrets manager — never in source code. The API wallet cannot withdraw funds, limiting blast radius if compromised. Rotate keys periodically. Consider running your bot on a dedicated server (not your personal machine) with firewall rules limiting outbound connections to Hyperliquid endpoints only.
What happens if my bot crashes during an open position?
Your positions and open orders remain on Hyperliquid. Positions don't auto-close when your bot disconnects. Open limit orders stay active until filled or cancelled. Build a startup routine that checks existing positions and orders before placing new ones. Implement a dead-man's switch: if the bot hasn't sent an order update in N minutes, cancel all orders via a separate monitoring process.
Can I run multiple bots on the same account?
Yes, but coordination is critical. Multiple bots placing orders from the same account need shared state management to avoid conflicting positions or exceeding margin limits. Alternatively, use separate API wallets (sub-accounts) for each bot to isolate their activity.
Beyond DIY: The Agent Approach
Building a production trading bot requires API integration, strategy logic, risk management, monitoring, alerting, and ongoing maintenance. Most traders underestimate the engineering overhead — a working bot prototype is 10% of the effort; keeping it reliable in production is the other 90%.
Deploy strategies on Hyperliquid with the agent: the AI trading agent handles the full stack — API connectivity, position management, risk controls, and strategy execution — without custom code or infrastructure. Connect wallet, define parameters, and trade.
Related: Hyperliquid trading bot for strategy-level bot guidance. Hyperliquid overview for platform fundamentals. Hyperliquid review for an honest assessment.