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

> Complete guide to Hyperliquid's API for algorithmic trading. REST & WebSocket endpoints, Python SDK, API key setup, code examples, and rate limits.

*Source: https://hyperliquidguide.com/guides/trading/api-trading-guide*

Hyperliquid's API gives algorithmic traders direct access to one of the highest-volume decentralized exchanges in crypto — [live data] in daily volume, [live data] perpetual markets, and sub-second execution. Whether you are building a market-making bot, an arbitrage system, or [automating a manual strategy](/guides/trading/trading-bot-setup-guide), 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.

> **Key takeaway:** 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 Documentation: Where to Find It and What It Covers

The official Hyperliquid API documentation is available at [docs.hyperliquid.xyz/for-developers](https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api). The API covers REST endpoints for order placement, account management, and market data, plus WebSocket subscriptions for real-time feeds.

| Endpoint | URL | What It Does |
|----------|-----|--------------|
| REST API | `https://api.hyperliquid.xyz` | Order placement, account data, market info |
| WebSocket | `wss://api.hyperliquid.xyz/ws` | Real-time fills, order book, funding rates |
| Info Endpoint | `/info` (POST) | Read-only market and account queries (no auth) |
| Exchange Endpoint | `/exchange` (POST) | Write operations: orders, cancels, transfers (signed) |

**Authentication model.** Hyperliquid uses an API wallet system rather than traditional API key/secret pairs. You generate a separate keypair from your main wallet inside the Hyperliquid UI (Settings → API), and that API wallet signs L1 actions on behalf of your main account. The API wallet can place and cancel orders but cannot withdraw funds, which limits the blast radius if the key leaks. Every write request to `/exchange` carries an EIP-712-style signature produced by the API wallet's private key — the official Python SDK handles this signing automatically when you pass the private key during initialization. This separation is the most common confusion point for developers coming from CEX APIs; the [for-developers documentation](https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers) covers the signature format in full.

## 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.

> **Note:** **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](https://app.hyperliquid.xyz/join/Concept211)** 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

```python

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

```python
# 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

```python
# 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

```python
# 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](/guides/trading/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](https://app.hyperliquid.xyz/join/Concept211)

## 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:

```bash
pip install hyperliquid-python-sdk
```

### Python Example: Place a Limit Order

```python

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

```python
# 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

```python
# 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

```python
# 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

```python

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

```python
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:

| Endpoint | Limit |
|----------|-------|
| REST API (Info) | ~1,200 requests/min per IP |
| REST API (Exchange) | ~1,200 requests/min per IP |
| WebSocket | 10 concurrent subscriptions per connection |
| Order placement | Burst-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

| Error | Cause | Fix |
|-------|-------|-----|
| `INVALID_SIGNATURE` | Wrong API wallet key or malformed signature | Verify the private key matches your API wallet — not your main wallet |
| `INSUFFICIENT_MARGIN` | Not enough USDC to cover the order | Deposit more USDC or reduce position size |
| `PRICE_OUTSIDE_BAND` | Limit price too far from market | Bring your limit price closer to the current mid price |
| `MAX_OPEN_ORDERS` | Too many resting orders (limit: 2,000) | Cancel stale orders before placing new ones |
| `429 Too Many Requests` | Rate limit exceeded | Implement backoff and reduce request frequency |
| `UNKNOWN_COIN` | Invalid ticker symbol | Check `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.

```typescript

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

// Read-only: no auth needed
async function getMidPrices(): Promise> {
 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](https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api) 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](/referral) 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](https://app.hyperliquid.xyz/join/Concept211) 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](https://app.hyperliquid.xyz/join/Concept211)

## Resources and Further Reading

- **[Hyperliquid API Documentation](https://hyperliquid.gitbook.io/hyperliquid-docs/for-developers/api)** — Official API reference with endpoint specifications
- **[hyperliquid-python-sdk on GitHub](https://github.com/hyperliquid-dex/hyperliquid-python-sdk)** — Official Python SDK source code and examples
- **[Trading Strategies Guide](/guides/trading/hyperliquid-trading-strategies)** — Which automated strategies to run, risk controls, and 24/7 operations
- **[Funding Rates Explained](/guides/trading/funding-rates-explained)** — Understanding funding mechanics for bot strategies
- **[Order Types Guide](/guides/trading/order-types-guide)** — All available order types including TWAP and scaling orders
- **[Fee Structure](/guides/fees/fees-explained)** — Complete fee breakdown for calculating bot economics
- **[Trading Tools](/guides/trading/hyperliquid-trading-tools)** — Third-party dashboards and analytics platforms

## 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](https://github.com/hyperliquid-dex/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](/referral) 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.
