Building a Hyperliquid Liquidation Bot on the Clearinghouse
A hyperliquid liquidation bot watches margin ratios over websocket, front-runs forced closes, and captures the spread that would otherwise feed the HLP backstop.
Hyperliquid's clearinghouse liquidates a position the moment its account value drops below the maintenance margin, and when that happens the position gets handed to the HLP vault at the mark price. That handoff is the whole opportunity. If you can see the account approaching its liquidation price before the clearinghouse acts, you can position ahead of the forced flow and capture part of the move that HLP would otherwise absorb. A hyperliquid liquidation bot is really two problems stitched together: reconstructing every account's margin ratio in real time, and firing an order in the sub-second window before liquidation prints.
What the clearinghouse actually does
Hyperliquid runs a cross and isolated margin system where maintenance margin is a flat fraction of the max leverage tier. For a 20x asset, maintenance margin is half the initial — so 2.5%. An account gets liquidated when its account value falls below maintenance_margin_required across all its positions. There's no partial deleveraging ladder like some CEXes run; below the line, the position transfers to HLP at the mark, and HLP takes over the risk (and usually the profit) of unwinding it.
That design is why the HLP vault strategy is worth understanding in its own right before you build against it — you're effectively competing with the backstop for the same fill. HLP is the counterparty of last resort. Your job is to be the counterparty of first resort, one block earlier.
The key number you're chasing is the liquidation price for each open position. For a long, it's roughly:
liq_price = entry_price * (1 - 1/leverage + maintenance_margin_fraction)
isolated margin makes this clean because the position stands alone. Cross margin is messier: the liquidation price of any single position depends on the unrealized PnL of every other position in the account, so you have to recompute the whole account's margin whenever any mark moves.
Getting the data: info endpoint plus websocket
You need two feeds and you need to keep them consistent.
The info endpoint (POST https://api.hyperliquid.xyz/info) gives you the snapshot. clearinghouseState for a given address returns every position, its entry, leverage, and the account's margin summary. That's your seed state. But polling it per-account doesn't scale — you can't hammer the info endpoint for ten thousand addresses.
The websocket (wss://api.hyperliquid.xyz/ws) is where the real work happens. Subscribe to:
allMids— mark price updates for every asset, which is what actually moves accounts toward liquidation.webData2for accounts you're tracking, which pushes position and margin changes.activeAssetCtxfor funding and open-interest context.
The trick is you don't monitor "every account." You build a watchlist. Walk the leaderboard and large-fill events, pull clearinghouseState for accounts holding meaningful size, compute their liquidation prices, and keep only the ones sitting within a few percent of the current mark. That set is small — usually a few hundred addresses in a volatile market — and you refresh liquidation prices locally on every allMids tick instead of re-polling.
Here's the core margin check in Python, using the official SDK's info client for the seed and raw mark updates after:
from hyperliquid.info import Info
from hyperliquid.utils import constants
info = Info(constants.MAINNET_API_URL, skip_ws=False)
def liq_distance(state, marks):
acct_value = float(state["marginSummary"]["accountValue"])
maint = float(state["marginSummary"]["totalMntNtlPos"]) * 0.025
# cross-margin: one number for the whole account
buffer = acct_value - maint
nearest = min(
abs(marks[p["position"]["coin"]] - float(p["position"]["liquidationPx"]))
/ marks[p["position"]["coin"]]
for p in state["assetPositions"]
)
return buffer, nearest
# fire when the account is within 40 bps of its liquidation price
def on_mark_update(marks, watched):
for addr, state in watched.items():
buffer, nearest = liq_distance(state, marks)
if nearest < 0.004 and buffer < threshold:
queue_entry(addr, state)
liquidationPx comes straight off each position in clearinghouseState, which saves you re-deriving the cross-margin formula by hand. Recompute it whenever the account's positions change, not on every tick — the field only moves when size or collateral changes, not when the mark does.
Front-running the forced flow
Seeing the liquidation coming is the easy half. Profiting is where the tradeoffs bite.
When a large long gets liquidated, HLP effectively becomes a forced seller into the book. The mark ticks down, the position transfers, and there's often a brief dislocation as the book absorbs it. Your bot wants to be short into that flow and cover as the dislocation reverts. So the entry logic is: when a big account crosses your 40-bps threshold on the wrong side, pre-position against its direction and set a tight take-profit near the expected reversion.
Two things determine whether this is actually profitable:
- Notional size of the doomed position relative to book depth. A $50k liquidation on a deep BTC book barely moves anything and won't cover your fees. A $2M liquidation on a thin altcoin perp is where the edge lives. Filter aggressively on
sz * markversus the current L2 book depth. - Your fill latency. You're racing the clearinghouse and every other bot doing the same read. Colocate near the API, keep a warm signed-order pipeline, and use
Iocorders so you don't sit resting in the book when the move doesn't come.
The failure mode nobody warns you about: false positives from a single stale mark. allMids can print a wick that recovers next block, and if you fired on it you're now long a reverting position with no liquidation to bail you out. Require the threshold breach to persist across two consecutive updates, and cross-check against the activeAssetCtx oracle price before committing size.
Execution and infrastructure
Everything runs off signed actions against the exchange endpoint, and getting the signing, nonce handling, and rate limits right is its own project — the Python and Rust API guide covers the exact request shapes. For a liquidation bot specifically, Rust earns its keep: the websocket decode, margin recompute, and order signing all sit on the hot path, and shaving 20ms off that loop is the difference between the fill and the reject.
A few hard-won defaults:
- Run the monitor and the executor as separate processes so a slow disk write in logging never stalls order submission.
- Cap per-account exposure. One dislocation that doesn't revert can eat a week of small wins.
- Watch funding while you hold — a position you entered for a 30-second liquidation play can flip into a funding drag if the reversion stalls. The mechanics overlap heavily with funding-rate strategies against CEX venues.
Most of the operational polish — watchlist decay, latency budgets, kill switches on drawdown — is the same discipline you'd put into any Hyperliquid perpetuals bot, and the monitoring layer benefits enormously from a real trading dashboard so you can see near-liquidation accounts building up before the market does.
Liquidation flow is one of the few genuinely structural edges on Hyperliquid, but it's latency-sensitive and unforgiving of sloppy state management. If you'd rather have that clearinghouse-monitoring stack built and tuned by people who've run it in production, our Hyperliquid liquidation bot service is where to start.
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