Start Trading - Save 4% →

Hyperliquid Trading Bot Guide — From API Keys to Live Automation (2026)

By Concept211 (@Concept211)Updated: May 202612 min read
Table of Contents
Hyperliquid logoHyperliquid

Trading bots on Hyperliquid are not just possible — they are the backbone of the exchange's liquidity. With ~$7B in daily volume, a significant portion comes from algorithmic traders running everything from simple grid bots to sophisticated market-making systems. The platform's zero-gas execution model, sub-second fills, and official Python SDK make it one of the most bot-friendly exchanges in crypto.

This guide takes you from zero to a live trading bot. If you have already set up API access, our companion API trading guide goes deeper on endpoints and advanced order types. This article focuses on the practical: getting your first bot running safely.

Hyperliquid offers an official Python SDK, dedicated API wallets (no withdrawal permissions), 1200 requests/minute rate limits, and zero gas fees — making it one of the easiest exchanges to automate. You can go from account creation to a running bot in under 30 minutes.

Quick Answer: Does Hyperliquid Support Trading Bots?

Yes — and it actively encourages them. Hyperliquid provides:

  • Official Python SDK (hyperliquid-python-sdk) with typed wrappers for every endpoint
  • API wallets — dedicated key pairs that can trade but never withdraw
  • REST + WebSocket APIs — full market data, order management, and real-time streaming
  • Zero gas fees — every order placement, cancellation, and modification costs nothing
  • Testnet — identical API surface with free testnet USDC for development

No application process, no KYC for API access, no waiting period. Create an API wallet and you are live.

Setting Up Your API Wallet

The API wallet is a separate Ethereum key pair authorized to trade on behalf of your main wallet. It cannot withdraw funds, which limits the blast radius if the key is ever compromised.

1

Open Hyperliquid Settings

Navigate to app.hyperliquid.xyz and connect your main wallet. Click the gear icon to open Settings.

2

Navigate to the API section

In Settings, find the API tab. This is where you manage all API wallets associated with your account.

3

Generate a new API wallet

Click Generate API Wallet. A new private key is displayed — copy it immediately and store it securely. This key will not be shown again. Give the wallet a descriptive name.

4

Fund the API wallet

Transfer USDC from your main trading vault to the API wallet. Go to Portfolio > Transfer and select the API wallet as the destination. Start with a small amount for testing.

5

Store the private key securely

Save the key in an environment variable or secrets manager — never hardcode it in source files. Add .env to .gitignore to prevent accidental commits.

Warning

Never commit your API private key to version control. Use environment variables, .env files (excluded from git), or a secrets manager like AWS Secrets Manager or HashiCorp Vault. Even though the API wallet cannot withdraw funds, a compromised key could place rogue trades that drain your balance through bad fills.

You can create multiple API wallets — one per bot or strategy. Each can be revoked independently from Settings without affecting your main wallet or other API wallets.

Installing the Python SDK

The official SDK handles authentication, request signing, and type safety. It wraps both the REST and WebSocket APIs.

# Create a virtual environment (recommended)
python -m venv hyperliquid-bot
source hyperliquid-bot/bin/activate  # Linux/Mac
# hyperliquid-bot\Scripts\activate   # Windows

# Install the SDK and dependencies
pip install hyperliquid-python-sdk
pip install python-dotenv  # For loading .env files

Verify the installation:

from hyperliquid.info import Info
from hyperliquid.utils import constants

info = Info(constants.MAINNET_API_URL, skip_ws=True)
mids = info.all_mids()
print(f"BTC price: ${float(mids['BTC']):,.2f}")
print(f"ETH price: ${float(mids['ETH']):,.2f}")

If that prints current prices, your environment is set up correctly. The Info class requires no authentication — it only reads public market data.

Tip

Use testnet first. Replace constants.MAINNET_API_URL with constants.TESTNET_API_URL during development. The testnet has the same API surface and free USDC available via faucet. Switch to mainnet only after your bot logic is thoroughly tested.

Your First Bot: A Working Market Maker Example

Here is a complete, functional bot that places limit orders on both sides of the book, manages open orders, and respects basic risk limits. This is not a toy example — it is a stripped-down version of the structure I use in production.

import os
import time
from decimal import Decimal
from dotenv import load_dotenv
from eth_account import Account
from hyperliquid.info import Info
from hyperliquid.exchange import Exchange
from hyperliquid.utils import constants

load_dotenv()

# Configuration
COIN = "ETH"
SPREAD_BPS = 15          # 15 basis points each side
ORDER_SIZE = 0.1         # ETH per side
MAX_POSITION = 0.5       # Max ETH exposure before halting
REFRESH_SECONDS = 30     # How often to refresh quotes

# Initialize SDK
private_key = os.environ["HYPERLIQUID_PRIVATE_KEY"]
account = Account.from_key(private_key)
info = Info(constants.MAINNET_API_URL, skip_ws=True)
exchange = Exchange(account, constants.MAINNET_API_URL)

def get_mid_price(coin: str) -> float:
    """Fetch current mid price for a given asset."""
    mids = info.all_mids()
    return float(mids[coin])

def get_position(coin: str) -> float:
    """Get current position size (negative = short)."""
    user_state = info.user_state(account.address)
    for position in user_state["assetPositions"]:
        if position["position"]["coin"] == coin:
            return float(position["position"]["szi"])
    return 0.0

def cancel_all_orders(coin: str):
    """Cancel all open orders for a given asset."""
    open_orders = info.open_orders(account.address)
    for order in open_orders:
        if order["coin"] == coin:
            exchange.cancel(coin, order["oid"])

def place_quotes(coin: str, mid: float, size: float):
    """Place a bid and ask around the mid price."""
    spread = mid * (SPREAD_BPS / 10000)
    bid_price = round(mid - spread, 2)
    ask_price = round(mid + spread, 2)

    # Place bid (limit buy)
    exchange.order(
        coin=coin,
        is_buy=True,
        sz=size,
        limit_px=bid_price,
        order_type={"limit": {"tpc": "Gtc"}},
    )

    # Place ask (limit sell)
    exchange.order(
        coin=coin,
        is_buy=False,
        sz=size,
        limit_px=ask_price,
        order_type={"limit": {"tpc": "Gtc"}},
    )

    print(f"Quotes placed: BID {bid_price} | ASK {ask_price} | size {size}")

def run():
    """Main loop: cancel stale quotes, check risk, place fresh quotes."""
    print(f"Starting market maker for {COIN}...")
    while True:
        try:
            # 1. Cancel existing orders
            cancel_all_orders(COIN)

            # 2. Check position risk
            position = get_position(COIN)
            if abs(position) >= MAX_POSITION:
                print(f"Position limit reached ({position}). Pausing...")
                time.sleep(REFRESH_SECONDS)
                continue

            # 3. Get current price and place new quotes
            mid = get_mid_price(COIN)
            place_quotes(COIN, mid, ORDER_SIZE)

            time.sleep(REFRESH_SECONDS)

        except Exception as e:
            print(f"Error: {e}")
            time.sleep(5)

if __name__ == "__main__":
    run()

Info

This bot is intentionally simple. A production market maker would include inventory skewing (wider spread on the side you are already exposed to), dynamic sizing based on volatility, and multi-level quote ladders. But this structure — cancel, check risk, requote — is the foundation every market-making bot is built on.

Key Patterns in This Code

  1. Cancel-before-requote: Always cancel stale orders before placing new ones. Stale orders at old prices are the fastest way to lose money.
  2. Position limits: The MAX_POSITION check prevents runaway exposure. In production, you would also track PnL and halt if drawdown exceeds a threshold.
  3. Error handling with sleep: Network errors are inevitable. Catch, log, sleep briefly, and retry. Never let an exception crash your entire bot.
  4. Good-til-cancelled (Gtc) orders: These persist until filled or explicitly cancelled — perfect for a bot that periodically refreshes quotes.

4% Off Every Bot Trade

The referral fee discount applies to all API-placed orders. For high-frequency strategies, the savings compound fast across thousands of trades.

Get Your Discount

REST API vs WebSocket: When to Use Each

Hyperliquid offers two ways to interact with market data and your account state. Each has a clear use case.

REST API (POST https://api.hyperliquid.xyz/info)

  • Best for: Order placement, account state checks, periodic price polling
  • Latency: 50-150ms per request depending on location
  • Rate limit: ~1200 requests/minute
  • Authentication: Required only for the Exchange endpoint (order placement)

Use REST when your bot operates on 1-second or longer intervals. A grid bot that rebalances every 30 seconds, a funding rate arbitrage bot that checks rates hourly, or a portfolio rebalancing script all fit comfortably within REST.

WebSocket (wss://api.hyperliquid.xyz/ws)

  • Best for: Real-time order book updates, trade feed, fill notifications
  • Latency: Sub-10ms push updates
  • Rate limit: No limit on incoming data; up to 10 concurrent subscriptions
  • Authentication: Required for user-specific channels (fills, order updates)

Use WebSocket when your bot needs to react to market changes in real time. Market makers, latency-sensitive arbitrage bots, and any strategy that triggers on price movement should stream data via WebSocket.

import json
import websocket

def on_message(ws, message):
    data = json.loads(message)
    # Process real-time order book updates
    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: {best_bid} / {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()

Hybrid pattern (recommended): Stream market data via WebSocket for real-time awareness, then use REST for order placement. This gives you the best of both worlds — fast reactions without burning through rate limits on data polling.

Rate Limits and Best Practices

Hyperliquid's rate limits are generous compared to centralized exchanges, but you can still hit them with a poorly designed bot.

EndpointLimitReset
REST (Info + Exchange)~1200 req/minRolling window
WebSocket subscriptions10 per connectionN/A
Order placementPart of the 1200/min poolRolling window

Staying Within Limits

  • Batch where possible: The SDK supports batch order placement — send 5 orders in one request instead of 5 separate requests.
  • Use WebSocket for reads: Every price check via REST costs a request. Stream prices via WebSocket and you free up your entire REST budget for order operations.
  • Implement exponential backoff: If you get a 429 response, wait 1s, then 2s, then 4s before retrying. Never hammer a rate-limited endpoint.
  • Cache market metadata: Asset specs (tick sizes, max leverage) change rarely. Fetch once at startup, not on every loop iteration.
# Batch order placement — single request, multiple orders
order_requests = [
    {"coin": "BTC", "is_buy": True, "sz": 0.001, "limit_px": 67000.0,
     "order_type": {"limit": {"tpc": "Gtc"}}},
    {"coin": "BTC", "is_buy": False, "sz": 0.001, "limit_px": 68000.0,
     "order_type": {"limit": {"tpc": "Gtc"}}},
    {"coin": "ETH", "is_buy": True, "sz": 0.05, "limit_px": 3400.0,
     "order_type": {"limit": {"tpc": "Gtc"}}},
]
results = exchange.bulk_orders(order_requests)

Tip

Pro tip: Run your bot on a VPS geographically close to Hyperliquid's infrastructure (Tokyo or Singapore) to minimize latency. The difference between 50ms and 200ms round-trip can matter for competitive strategies.

Risk Management for Automated Trading

Bots can lose money much faster than humans because they execute without hesitation. Every bot needs built-in safety rails.

Non-Negotiable Safeguards

  1. Maximum position size — Hard cap on how much exposure the bot can accumulate in any single asset.
  2. Daily loss limit — If the bot loses more than X USDC in a day, it shuts down. No exceptions.
  3. Kill switch — A way to instantly cancel all orders and flatten positions. Test it regularly.
  4. Stale order detection — Orders more than N seconds old at a price that has moved significantly should be cancelled immediately.
  5. Connection monitoring — If the WebSocket disconnects or REST calls fail 3 times in a row, cancel all open orders before reconnecting.
# Simple daily loss limit implementation
class RiskManager:
    def __init__(self, max_daily_loss: float):
        self.max_daily_loss = max_daily_loss
        self.starting_equity = None
        self.halted = False

    def check(self, current_equity: float) -> bool:
        """Returns True if bot should continue, False if halted."""
        if self.starting_equity is None:
            self.starting_equity = current_equity
            return True

        daily_pnl = current_equity - self.starting_equity
        if daily_pnl <= -self.max_daily_loss:
            self.halted = True
            print(f"RISK HALT: Daily loss {daily_pnl:.2f} exceeds limit")
            return False
        return True

# Usage in your main loop
risk = RiskManager(max_daily_loss=100.0)  # Halt after $100 loss

# Inside run():
user_state = info.user_state(account.address)
equity = float(user_state["marginSummary"]["accountValue"])
if not risk.check(equity):
    cancel_all_orders(COIN)
    break

Warning

Start small. Fund your API wallet with the minimum amount needed for testing — $50-100 is plenty for a single-asset bot. Scale up only after the bot has run profitably for at least a week. Understand your fee structure so you can calculate whether your strategy is profitable after costs.

Leverage Considerations

If your bot uses leverage, the risk multiplies proportionally. A 10x leveraged bot with a $100 loss limit can be liquidated in a 10% move. Keep leverage low (2-3x max) for automated strategies unless you have sophisticated hedging in place.

Common Bot Strategies on Hyperliquid

Here is a brief overview of strategies that work well on Hyperliquid's infrastructure. Each deserves its own deep dive, but this gives you a starting point.

Grid Trading

Place buy orders below the current price and sell orders above it at fixed intervals. When a buy fills, place a new sell above it (and vice versa). Profits from range-bound markets.

Why it works on Hyperliquid: Zero gas means you can maintain dense grids (20-50 levels) without execution costs eating into profits. The only cost is the taker/maker fee.

Funding Rate Arbitrage

When funding rates are elevated, go short on Hyperliquid (collecting funding) and long spot elsewhere (or vice versa). The delta-neutral position earns the funding rate as yield.

Why it works on Hyperliquid: Hourly funding settlement means you collect 3x more frequently than Binance (every 8 hours). Rates on altcoin perps can exceed 0.1% per 8 hours during momentum periods.

Market Making

Continuously quote both sides of the order book, earning the bid-ask spread on each round trip. Requires inventory management and dynamic spread adjustment.

Why it works on Hyperliquid: Maker rebates (0.015% on perps) mean you are paid to provide liquidity. Combined with the 4% referral discount, effective fees are extremely low.

Momentum/Breakout

Monitor price action for breakouts above resistance or below support, then enter a position in the breakout direction with a tight stop-loss.

Why it works on Hyperliquid: WebSocket price feeds give you sub-second reaction time. The wide selection of 200+ perp markets means there are always assets moving.

Start Trading on Hyperliquid

Create your account, deposit USDC, and start building bots with a 4% lifetime fee discount.

Join Hyperliquid

From a Developer Who Has Built Bots Since 2016

I have been writing trading bots since 2016 — starting with basic arbitrage scripts on Poloniex and Bittrex, evolving through the ICO boom, the DeFi summer, and now on-chain perpetuals. I have seen every flavor of exchange API: REST-only nightmares with 10-second rate limits, WebSocket feeds that drop messages under load, authentication schemes that require a PhD in cryptography.

Hyperliquid is, genuinely, one of the best API experiences I have encountered across centralized and decentralized exchanges. Here is why:

The API wallet system is brilliant. Separating trading permissions from withdrawal permissions at the protocol level means you can run a bot on a cloud server without ever exposing funds to full theft. On CEXs, a leaked API key with trading permissions has historically been enough to drain accounts via market manipulation.

Zero gas execution changes everything. On other DEXs (dYdX v3 had this partially, but v4 moved on-chain), every order costs gas. This makes high-frequency strategies impossible or uneconomical. On Hyperliquid, you can place and cancel 1200 orders per minute at zero cost beyond the trading fee on fills.

The SDK is maintained and typed. It sounds basic, but the number of exchanges shipping broken or undocumented SDKs is staggering. The hyperliquid-python-sdk has type hints, handles retry logic, and matches the API surface one-to-one.

My honest advice after a decade of bot development:

  1. Start with the simplest possible strategy — a grid bot or a single-pair market maker. Get the infrastructure right (deployment, monitoring, alerting) before adding strategy complexity.
  2. Paper trade for at least a week using testnet before going live. Bugs in bot logic cost real money, and they always appear in production conditions you did not simulate.
  3. Monitor obsessively for the first month. Set up Telegram alerts for fills, position changes, and errors. You want to know within seconds if something goes wrong.
  4. Accept that most bot strategies have a shelf life. Markets change, edges decay, and competition increases. The skill is not writing one perfect bot — it is continuously adapting.

If you need USDC on Hyperliquid to fund your bot, our deposit guide covers every method from CEX withdrawals to cross-chain bridging.

Info

Need the full API reference? Our comprehensive API trading guide covers every endpoint, all order types (including TWAP, scaling orders, and trigger orders), and advanced authentication patterns. Use it as a companion reference alongside this practical setup guide.

Get 4% Fee Discount on All Bot Trades

Frequently Asked Questions

Yes. Hyperliquid provides a full REST API and WebSocket feed for automated trading. You can use the official hyperliquid-python-sdk to place orders, manage positions, and stream real-time market data. No special API key application is needed — create an API wallet directly in the Hyperliquid UI.

In the Hyperliquid app, go to Settings > API Wallets > Create. This generates a separate wallet with its own private key that can only trade — it cannot withdraw funds. Transfer some USDC from your main vault to the API wallet to fund bot trading.

The official SDK is Python (hyperliquid-python-sdk on PyPI). Community SDKs exist for TypeScript/JavaScript, Rust, and Go. Python is recommended for beginners due to the official SDK's comprehensive documentation and examples.

Hyperliquid allows up to 1200 requests per minute for REST API calls. WebSocket connections support unlimited incoming data. For high-frequency strategies, use WebSocket for market data and REST for order placement to stay within limits.

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%