Start Trading - Save 4% →

Hyperliquid API Trading Guide: Connect Bots & Automate Strategies (2026)

By Concept211 (@Concept211)Updated: April 202612 min read
Table of Contents

Hyperliquid's API gives algorithmic traders direct access to one of the highest-volume decentralized exchanges in crypto — ~$7B in daily volume, 200+ perpetual markets, and sub-second execution. Whether you are building a market-making bot, an arbitrage system, or automating a manual strategy, Hyperliquid's API provides everything you need: REST endpoints for order management, WebSocket feeds for real-time data, and an official Python SDK that handles authentication and type safety.

This guide covers the full stack — from generating your API wallet to placing your first programmatic trade.

Hyperliquid offers a REST API, WebSocket API, and official Python SDK for algorithmic trading. The API supports all order types available in the UI — including limit, market, stop-loss, take-profit, TWAP, and scaling orders — with zero gas fees on every API call.

Hyperliquid API Overview

Hyperliquid's API is split into two main endpoints, both accessed via https://api.hyperliquid.xyz:

Info API (POST /info) — Read-only. Fetch market data, account state, order status, funding rates, and historical data. No authentication required.

Exchange API (POST /exchange) — Write operations. Place orders, cancel orders, modify positions, transfer funds. Requires authentication via an API wallet signature.

Both endpoints accept JSON payloads and return JSON responses. There are no REST verbs to worry about — everything is a POST request with a type field that specifies the action.

WebSocket API (wss://api.hyperliquid.xyz/ws) — Real-time streaming for order book updates, trade feeds, user fills, and candle data. Supports up to 10 concurrent subscriptions per connection.

Info

Testnet available. Hyperliquid runs a full testnet at https://api.hyperliquid-testnet.xyz with the same API surface. Use it to test your bot logic with fake funds before going live. Testnet USDC is available for free through the testnet faucet.

Authentication: How to Generate an API Wallet

Hyperliquid uses a dedicated "API wallet" system rather than traditional API keys. An API wallet is a separate Ethereum key pair that is authorized to trade on behalf of your main wallet — but cannot withdraw funds.

Step-by-Step Setup

  1. Navigate to app.hyperliquid.xyz and connect your main wallet
  2. Go to Settings (gear icon) → API
  3. Click Generate API Wallet
  4. The UI displays a new private key — copy and save it immediately. It will not be shown again
  5. Optionally set a descriptive name for the API wallet (e.g., "Market Making Bot")

Warning

Security best practice: Store your API wallet private key in an environment variable or a secrets manager — never hardcode it in your source code. The API wallet can place trades and cancel orders but cannot withdraw funds, which limits the damage if the key is compromised.

You can generate multiple API wallets for different bots or strategies. Each can be revoked independently from the Settings page without affecting your main wallet.

[Screenshot: Hyperliquid API wallet generation interface]

Reading Market Data (Info API)

The Info API requires no authentication and is the starting point for any bot. All requests are POST to https://api.hyperliquid.xyz/info.

Fetch All Market Metadata

import requests

url = "https://api.hyperliquid.xyz/info"

# Get all available perpetual markets
response = requests.post(url, json={"type": "meta"})
meta = response.json()

# meta["universe"] contains all listed perps with their specs
for asset in meta["universe"]:
    print(f"{asset['name']}: max leverage {asset['maxLeverage']}x")

Fetch Current Prices

# Get mid prices for all assets
response = requests.post(url, json={"type": "allMids"})
prices = response.json()
print(f"BTC: ${prices['BTC']}")
print(f"ETH: ${prices['ETH']}")

Fetch Order Book Depth

# Get L2 order book for BTC
response = requests.post(url, json={
    "type": "l2Book",
    "coin": "BTC"
})
book = response.json()
best_bid = book["levels"][0][0]  # Best bid
best_ask = book["levels"][1][0]  # Best ask
spread = float(best_ask["px"]) - float(best_bid["px"])
print(f"BTC spread: ${spread:.2f}")

Fetch Funding Rates

# Get current funding rates for all assets
response = requests.post(url, json={"type": "metaAndAssetCtxs"})
data = response.json()

for ctx in data[1]:
    if float(ctx.get("funding", 0)) != 0:
        rate = float(ctx["funding"]) * 100
        print(f"Funding: {rate:.4f}%")

For a deeper dive into how funding rates work and strategies around them, see our funding rates explained guide.

4% Off Every API Trade

The referral fee discount applies to all bot-placed orders. For high-frequency strategies, the savings compound fast.

Get Your Discount

Placing Orders (Exchange API)

The Exchange API requires signing each request with your API wallet's private key. The official Python SDK handles this automatically.

Using the Official Python SDK

Install the SDK:

pip install hyperliquid-python-sdk

Python Example: Place a Limit Order

import os
from hyperliquid.utils import constants
from hyperliquid.exchange import Exchange
from hyperliquid.info import Info
from eth_account import Account

# Load API wallet from environment variable
api_private_key = os.environ["HYPERLIQUID_API_PRIVATE_KEY"]
account = Account.from_key(api_private_key)

# Initialize SDK
info = Info(constants.MAINNET_API_URL, skip_ws=True)
exchange = Exchange(account, constants.MAINNET_API_URL)

# Fetch current BTC price
all_mids = info.all_mids()
btc_price = float(all_mids["BTC"])

# Place a limit buy order 0.5% below current price
limit_price = round(btc_price * 0.995, 1)
order_result = exchange.order(
    coin="BTC",
    is_buy=True,
    sz=0.001,          # Size in BTC
    limit_px=limit_price,
    order_type={"limit": {"tpc": "Gtc"}},  # Good-til-cancelled
)
print(f"Order placed: {order_result}")

Python Example: Place a Market Order

# Market buy 0.01 ETH
order_result = exchange.market_open(
    coin="ETH",
    is_buy=True,
    sz=0.01,
    slippage=0.01,  # 1% max slippage
)
print(f"Market order: {order_result}")

Cancel an Order

# Cancel a specific order by ID
cancel_result = exchange.cancel(
    coin="BTC",
    oid=order_result["response"]["data"]["statuses"][0]["resting"]["oid"]
)
print(f"Cancelled: {cancel_result}")

Cancel All Orders

# Cancel all open orders on BTC
open_orders = info.open_orders(account.address)
for order in open_orders:
    if order["coin"] == "BTC":
        exchange.cancel(coin="BTC", oid=order["oid"])

WebSocket: Real-Time Market Data

For strategies that need real-time data — market making, arbitrage, or signal-based execution — the WebSocket API provides streaming updates without polling.

Subscribe to Order Book Updates

import json
import websocket

def on_message(ws, message):
    data = json.loads(message)
    if data.get("channel") == "l2Book":
        book = data["data"]
        best_bid = book["levels"][0][0]["px"]
        best_ask = book["levels"][1][0]["px"]
        print(f"BTC bid: {best_bid} | ask: {best_ask}")

def on_open(ws):
    # Subscribe to BTC L2 order book
    ws.send(json.dumps({
        "method": "subscribe",
        "subscription": {"type": "l2Book", "coin": "BTC"}
    }))

ws = websocket.WebSocketApp(
    "wss://api.hyperliquid.xyz/ws",
    on_message=on_message,
    on_open=on_open,
)
ws.run_forever()

Subscribe to User Fills

def on_open(ws):
    # Subscribe to your own trade fills
    ws.send(json.dumps({
        "method": "subscribe",
        "subscription": {
            "type": "userFills",
            "user": "0xYOUR_WALLET_ADDRESS"
        }
    }))

Available WebSocket channels include: l2Book, trades, candle, userFills, userEvents, orderUpdates, and allMids.

Rate Limits and Best Practices

Hyperliquid enforces the following rate limits:

EndpointLimit
REST API (Info)~1,200 requests/min per IP
REST API (Exchange)~1,200 requests/min per IP
WebSocket10 concurrent subscriptions per connection
Order placementBurst-friendly, but sustained >1,200/min triggers throttling

How to Stay Within Limits

  • Use WebSocket for market data instead of polling the REST API. A single WebSocket subscription replaces thousands of REST requests
  • Batch operations where possible — cancel multiple orders in a single request
  • Implement exponential backoff on 429 (rate limit) responses
  • Spread requests across time rather than bursting — smooth out request patterns with a simple rate limiter

Tip

Testnet tip: The testnet at api.hyperliquid-testnet.xyz has the same API surface and rate limits. Build and test your bot there before risking real capital.

Common Errors and How to Fix Them

ErrorCauseFix
INVALID_SIGNATUREWrong API wallet key or malformed signatureVerify the private key matches your API wallet — not your main wallet
INSUFFICIENT_MARGINNot enough USDC to cover the orderDeposit more USDC or reduce position size
PRICE_OUTSIDE_BANDLimit price too far from marketBring your limit price closer to the current mid price
MAX_OPEN_ORDERSToo many resting orders (limit: 2,000)Cancel stale orders before placing new ones
429 Too Many RequestsRate limit exceededImplement backoff and reduce request frequency
UNKNOWN_COINInvalid ticker symbolCheck meta endpoint for the exact ticker name (case-sensitive)

JavaScript/TypeScript Example

For web-based bots or Node.js services, the API works the same way — POST requests with JSON payloads. Authentication requires ethers.js or a similar library for signing.

import { ethers } from "ethers";

const API_URL = "https://api.hyperliquid.xyz";

// Read-only: no auth needed
async function getMidPrices(): Promise<Record<string, string>> {
  const res = await fetch(`${API_URL}/info`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ type: "allMids" }),
  });
  return res.json();
}

// Example usage
const prices = await getMidPrices();
console.log(`BTC: $${prices.BTC}`);
console.log(`ETH: $${prices.ETH}`);

For full order placement in TypeScript, you will need to implement the EIP-712 signing scheme that Hyperliquid uses. The Python SDK handles this automatically — for TypeScript, refer to Hyperliquid's official API documentation for the signing specification.

API Key Security Best Practices

Your API wallet's private key is the single most sensitive piece of your bot infrastructure. Follow these practices:

  • Environment variables only. Never commit private keys to version control. Use .env files locally and secret managers (AWS Secrets Manager, GCP Secret Manager) in production
  • Separate wallets. Use different API wallets for different bots. If one is compromised, revoke it without affecting others
  • Minimal funds. Keep only the capital your bot needs in the trading account. The API wallet cannot withdraw funds, but a compromised key could still make unfavorable trades
  • Monitor actively. Set up alerts for unexpected trades or position changes. The WebSocket userEvents channel is useful for this
  • Rotate keys periodically. Generate a new API wallet and update your bot, then revoke the old one from the Settings page

Referral Code for Bot Developers

The 4% referral fee discount applies to all trades on your account, including those placed via the API. For algorithmic strategies that execute hundreds or thousands of trades per day, the 4% reduction compounds into significant savings.

Example: A bot trading $1M in daily taker volume at base tier:

  • Without referral: $1,000,000 × 0.045% = $450/day in fees
  • With referral: $1,000,000 × 0.0432% = $432/day in fees
  • Annual savings: ~$6,570

The referral code must be applied at account creation — before you start building. Sign up through our referral link first, then generate your API wallet.

Build on Hyperliquid with Lower Fees

The 4% referral discount applies to every API trade. For high-frequency strategies, that's thousands saved per year.

Claim Your Discount

Resources and Further Reading

Frequently Asked Questions

Does Hyperliquid have a trading API?

Yes. Hyperliquid provides a full REST API and WebSocket API for programmatic trading. The API supports market data retrieval, order placement, position management, and account information. An official Python SDK (hyperliquid-python-sdk) is available via pip.

Is there a Hyperliquid Python SDK?

Yes. The official Hyperliquid Python SDK is available on PyPI and GitHub. It provides typed wrappers for all API endpoints, handles EIP-712 authentication, and supports both mainnet and testnet environments. Install with pip install hyperliquid-python-sdk.

What are Hyperliquid's API rate limits?

Hyperliquid allows approximately 1,200 requests per minute for REST API calls. WebSocket connections support up to 10 concurrent subscriptions per connection. Rate limits are enforced per IP address. Use WebSocket feeds instead of polling to stay well within limits.

Does the 4% referral discount apply to bot trades?

Yes. The referral fee discount applies to all trades on your account, whether placed manually through the UI or programmatically via the API. For high-frequency bots, the 4% reduction can save thousands of dollars annually.

What is the difference between mainnet and testnet?

The testnet at api.hyperliquid-testnet.xyz has the same API surface, order types, and rate limits as mainnet. The only difference is that testnet uses fake USDC (available from a faucet) and trades do not involve real funds. Always test your bot on testnet first.

Frequently Asked Questions

Yes. Hyperliquid provides a full REST API and WebSocket API for programmatic trading. The API supports market data retrieval, order placement, position management, and account information. An official Python SDK is available via pip.

Yes. The official Hyperliquid Python SDK (hyperliquid-python-sdk) is available on PyPI and GitHub. It provides typed wrappers for all API endpoints, handles authentication, and supports both mainnet and testnet environments.

Hyperliquid allows approximately 1,200 requests per minute for REST API calls. WebSocket connections support up to 10 concurrent subscriptions per connection. Rate limits are enforced per IP address, not per API key.

Yes. The referral fee discount applies to all trades on your account, whether placed manually through the UI or programmatically via the API. For high-frequency bots, the 4% reduction can save significant amounts over time.

Hyperliquid's API endpoints are publicly accessible. The geo-restriction applies only to the frontend web interface, not to the API. Many traders use VPNs as standard privacy tools when interacting with any DeFi protocol's infrastructure.

Disclaimer: This content is for informational purposes only and does not constitute financial advice. Trading perpetual futures involves substantial risk of loss. Past performance is not indicative of future results. Always do your own research before trading. This site contains referral links - see our disclosure for details.

Ready to Start Trading?

Join Hyperliquid with our referral link and get a 4% lifetime fee discount. No KYC, no email - just connect your wallet and trade.

Start Trading - Save 4%