How to Build a Liquidation Bot on Hyperliquid in 2024
Hyperliquid's on-chain perpetuals engine triggers liquidations at predictable price levels, creating reliable MEV for well-positioned bots. This tutorial covers liquidation mechanics, risk engine timing, and the exact API calls needed to capture positions profitably.
Hyperliquid runs one of the few fully on-chain perpetuals engines with publicly readable risk state — every open position, margin level, and liquidation threshold is visible in real time. That transparency is the edge. Unlike opaque CEX liquidation queues or Solana programs where you need to simulate in-flight transactions, Hyperliquid gives you deterministic liquidation prices you can derive from first principles and act on the moment the engine does. If you've built liquidation or backrun bots before, this is the cleanest target you'll find in 2024.
How the Liquidation Engine Actually Works
Hyperliquid uses a cross-margin risk engine at the account level, not per-position. A user's margin ratio is calculated across their entire portfolio: total unrealized PnL plus available balance, divided by the sum of maintenance margin requirements across all open positions.
The liquidation price for an isolated long on a single asset simplifies to:
liq_price = entry_price * (1 - (initial_margin_ratio - maintenance_margin_ratio))
For cross-margin accounts you need to account for portfolio-level equity, which means reading all open positions and their unrealized PnL before computing the effective trigger. The key public endpoint is POST /info with type clearinghouseState — this returns the full account snapshot including marginSummary, crossMaintenanceMarginUsed, and per-position unrealizedPnl.
Once marginSummary.accountValue drops below crossMaintenanceMarginUsed, the account is eligible for liquidation. The engine checks this on every trade that affects any position in that account and on every oracle price update — roughly every 0.5–1 second.
Reading the Liquidation Queue in Real Time
The fastest path to upcoming liquidations is the WebSocket feed. Subscribe to allMids for oracle price updates and trades for fill events, then maintain your own local state of at-risk accounts derived from the REST snapshot you pull at startup.
import asyncio, json, websockets
async def subscribe():
async with websockets.connect("wss://api.hyperliquid.xyz/ws") as ws:
await ws.send(json.dumps({
"method": "subscribe",
"subscription": {"type": "allMids"}
}))
async for msg in ws:
data = json.loads(msg)
# update your local price map, recheck margin ratios
process_price_update(data)
Maintain a heap keyed on each account's distance-to-liquidation in percentage terms. When an oracle update crosses a threshold — say, any account within 2% of liquidation — pull a fresh clearinghouseState snapshot to confirm the margin ratio before committing.
Capturing the Liquidation
When the engine liquidates an account, it transfers the position to the insurance fund at the bankruptcy price and simultaneously opens a taker order on the book at or better than the liquidation price. Your job is to be the resting maker on the other side of that taker fill.
The tightest execution path is a limit order placed slightly inside the mark price before the liquidation triggers. You're not racing to submit after the liquidation — you're pre-positioning:
- Identify accounts within 1.5% of liquidation using your local state.
- Place a maker limit order at
liq_price + (0.5 * tick_size)for a position size proportional to the at-risk account's open notional. - If the account's margin ratio recovers, cancel via the REST cancel endpoint and move on.
Order placement uses POST /exchange with action type order. Authentication requires an EIP-712 signature over the order struct using your wallet's private key — the official Python SDK (hyperliquid-python-sdk) handles this cleanly, and it's worth using rather than rolling the signing yourself.
Sizing and Risk Management
The tempting failure mode here is position sizing against accounts that are large relative to your capital. A $2M BTC-PERP position liquidating against a $50k bot account is not a good trade regardless of the execution quality.
Practical limits to enforce:
- Cap each liquidation capture to 5–10% of your available margin, not the full liquidated notional.
- Track your net delta exposure across all open liquidation captures — you can end up with correlated directional risk fast in volatile sessions.
- Set a hard stop on daily liquidation volume: the engine's mark price can gap significantly during cascade events, and your fills at the liquidation price can be underwater before you unwind.
The insurance fund backstop protects the protocol, not your PnL. You are still taking on delta that you need to close.
Latency and Co-location
Hyperliquid's validators run in a known region. From a co-located server in the same AWS region (us-east-1 as of late 2024), WebSocket round-trips to api.hyperliquid.xyz run 4–8ms. From Europe or Asia, add 80–150ms — enough to meaningfully degrade your fill rate on fast-moving liquidations.
The REST snapshot for clearinghouseState on a large account with many positions takes 20–60ms depending on response size. Pre-cache snapshots on accounts already near the liquidation threshold; don't fetch cold on every price tick.
You don't need sub-millisecond latency here the way you do in Solana MEV — Hyperliquid processes blocks at roughly 0.5-second intervals, and your maker orders are already on the book. But regional co-location still matters when competing with other bots for the same liquidation flow.
What This Looks Like in Production
A production setup runs three concurrent processes: the WebSocket listener updating a shared price state, a risk calculator iterating the at-risk heap every 200ms, and an order manager handling placement and cancellation with exponential backoff on 429s. The risk calculator is the hot path — profile it carefully before deploying at scale.
Accounts that repeatedly approach liquidation thresholds without triggering are often hedged or managed programmatically. Track their behavior over multiple sessions; chasing them wastes order slots and creates noise in your cancel rate, which can affect API rate limits.
If you want a production-grade liquidation bot without building and operating the infrastructure yourself, reach out to TierZero — we design and run these systems across Hyperliquid, Solana, and Polymarket for clients who need the edge without the operational overhead.
Need a bot like this built?
We design, build and run trading bots on Solana, Hyperliquid and Polymarket.
Start a projectMore from the blog
Public vs Paid RPC: How to Run a Fair Benchmark
A fair comparison of public and paid RPC endpoints must account for quotas, workload, freshness and support guarantees.
Read articleRPC Benchmark Percentiles Explained: p50, p95 and p99
Why averages hide the latency spikes that break trading bots, wallets and production blockchain applications.
Read articleHyperliquid REST vs WebSocket Benchmark: What to Measure
A benchmark plan for Hyperliquid market data that separates request latency from streaming freshness and recovery.
Read article