Build a real-time Hyperliquid liquidation monitor
Stream every Hyperliquid liquidation over one WebSocket with GoldRush liquidationFills, then add alerts, per-coin stats, a query API and at-risk checks.
On this page
- What is a liquidation on Hyperliquid?
- Why stream liquidations from GoldRush
- Prerequisites for the liquidation monitor
- Step 1: Set up the project
- Step 2: Read a liquidation message
- Step 3: Record, de-duplicate and alert
- Step 4: Connect, subscribe and stay connected
- Step 5: Query liquidations over HTTP
- Step 6: Run the monitor
- Step 7: Flag positions close to liquidation
- Handle errors from the Hyperliquid API
- Extend the Hyperliquid liquidation monitor
- Frequently asked questions
- Next steps
A Hyperliquid liquidation monitor watches HyperCore for positions that are force-closed, records each one, and tells you when a large one happens. This guide builds one in TypeScript on the GoldRush Hyperliquid API: a single WebSocket subscription to the liquidationFills channel delivers every liquidation fill across every wallet, and one short TypeScript file turns it into a live feed, alerts, per-coin statistics and a small HTTP API you can point a dashboard at. A last step checks wallets you care about for positions close to their liquidation price.
What is a liquidation on Hyperliquid?
Every perpetual position on Hyperliquid has a maintenance margin requirement. When a trader's account value falls below it, the position is liquidated: the protocol closes it, first with market orders sent to the order book, and if that isn't possible, through a backstop liquidation in which Hyperliquid's liquidator vault takes the position over. The price at which this happens is the position's liquidation price.
Liquidations matter beyond the trader who loses the position. A cluster of long liquidations pushes the price down, which can trigger the next cluster, so traders, risk desks, market makers and analytics products all watch the liquidation feed as a signal of forced selling or buying.
Each liquidation fill on GoldRush carries:
| Field | What it tells you |
|---|---|
liquidation.liquidatedUser |
The wallet whose position was liquidated |
liquidation.method |
market (closed on the order book) or backstop |
liquidation.markPx |
The mark price at the moment of liquidation |
coin, px, sz |
The market, the fill price and the size filled |
side, dir, closedPnl |
The fill from the point of view of the wallet in the message |
hash, tid, time |
The transaction hash, the trade id and the time in milliseconds |
Why stream liquidations from GoldRush
The public Hyperliquid WebSocket has no liquidation channel. It sends fills per wallet, so finding every liquidation there means subscribing to every wallet that might be liquidated and filtering for the liquidation flag. liquidationFills is a GoldRush-native channel on the Hyperliquid WebSocket API: one subscription with no address filter, and every liquidation fill on HyperCore arrives as it happens.
- Cost. One subscription has a credit cost of 1 per minute, whatever the volume, so an always-on monitor costs 1,440 credits a day. The first minute is charged when you subscribe, and every reconnect starts a new first minute, which is why the code below backs off before reconnecting (billing details).
- Live only. The stream has no history: it sends liquidations from the moment you subscribe. For past liquidations of a wallet, query its ledger history with the Info API's
userNonFundingLedgerUpdatesover astartTime/endTimewindow: liquidations are the entries whosedelta.typeisliquidation. - Same shape as
userFills. Each fill is auserFillsfill with theliquidationobject always set, so code written for Hyperliquid fills reads it unchanged.
Prerequisites for the liquidation monitor
- Node.js 18 or later (for the built-in
fetch). - A GoldRush API key. Sign up to get one.
- Optionally, a Slack-style incoming webhook URL for alerts. Without one, alerts are printed to the console.
Keep the monitor on a server. The API key is part of the WebSocket URL, so never ship it to a browser; a browser client should use a short-lived ephemeral key minted by your backend.
Step 1: Set up the project
mkdir hyperliquid-liquidation-monitor && cd hyperliquid-liquidation-monitornpm init -ynpm pkg set type=modulenpm install ws@8.23.0npm install -D tsx@4.23.15 typescript@5.9.3 @types/ws@8.18.2 @types/node@26.6.6export GOLDRUSH_API_KEY=your_key_herenpm pkg set type=module writes "type": "module" to package.json, so tsx runs the files as ES modules and the top-level await in them works. The whole monitor is one file, monitor.ts: the code blocks in steps 1 to 5, read top to bottom, are that file, so add each one to the same file. It starts with the imports and settings:
import { appendFile, mkdir } from "node:fs/promises";import { createServer } from "node:http";import WebSocket from "ws"; const API_KEY = process.env.GOLDRUSH_API_KEY;if (!API_KEY) throw new Error("Set GOLDRUSH_API_KEY"); const WS_URL = `wss://hypercore.goldrushdata.com/ws?key=${API_KEY}`;const ALERT_USD = Number(process.env.ALERT_USD ?? 100_000); // alert on liquidations at least this largeconst WEBHOOK_URL = process.env.WEBHOOK_URL; // optional: a Slack-style incoming webhookconst PORT = Number(process.env.PORT ?? 3001);const DATA_DIR = "liquidation-data";Step 2: Read a liquidation message
After you subscribe, the server pushes messages on the liquidationFills channel. Each has a fills array of [address, fill] pairs. This is the sample message from the liquidationFills reference:
{ "channel": "liquidationFills", "fills": [ [ "0x742d35cc6634c0532925a3b844bc9e7595f7f2e2", { "coin": "ETH", "px": "2150.5", "sz": "1.5", "side": "B", "time": 1704067200000, "startPosition": "1.5", "dir": "Open Long", "closedPnl": "125.5", "hash": "0xabc...def", "oid": 12345678, "crossed": false, "fee": "2.5", "tid": 87654321, "feeToken": "USDC", "liquidation": { "liquidatedUser": "0x...", "markPx": "2148.75", "method": "market" }, "twapId": null } ] ]}The address in each pair is the wallet whose order was filled, which is not always the liquidated wallet: in the sample it is the counterparty that bought (side: "B") the position being closed. So the code works out which side was liquidated from both. If the address is the liquidated wallet, its own side says it: selling (A) closes a long. If the address is the counterparty, the liquidated wallet did the opposite. Prices and sizes arrive as decimal strings; the monitor converts them to numbers for display and statistics, and the notional is price times size in the market's quote currency (USDC for most perps).
// One fill as liquidationFills sends it: the userFills shape plus a liquidation object.type LiquidationFill = { coin: string; px: string; sz: string; side: "A" | "B"; // A = sell, B = buy, from the point of view of the wallet in the tuple time: number; dir: string; hash: string; tid: number; closedPnl: string; liquidation: { liquidatedUser: string; markPx: string; method: "market" | "backstop" };}; type LiquidationMessage = { channel: "liquidationFills"; fills: [string, LiquidationFill][] }; type Liquidation = { time: number; coin: string; liquidatedUser: string; position: "long" | "short"; px: number; sz: number; notional: number; markPx: number; method: "market" | "backstop"; hash: string; tid: number;}; function toLiquidation(address: string, fill: LiquidationFill): Liquidation { const { liquidatedUser, markPx, method } = fill.liquidation; // The tuple's address is the wallet whose order was filled. If that is the liquidated wallet, its own side // tells us the position: selling (A) closes a long. If it is the counterparty, the liquidated side is opposite. const liquidatedSold = address.toLowerCase() === liquidatedUser.toLowerCase() ? fill.side === "A" : fill.side === "B"; const px = Number(fill.px); const sz = Number(fill.sz); return { time: fill.time, coin: fill.coin, liquidatedUser, position: liquidatedSold ? "long" : "short", px, sz, notional: px * sz, markPx: Number(markPx), method, hash: fill.hash, tid: fill.tid, };}A large liquidation is often filled in several pieces, so one liquidation can arrive as several fills. The monitor treats each fill as one record. If you'd rather receive one entry per liquidation, subscribe with aggregateByTime: true, which merges partial fills of the same liquidation within a block.
Step 3: Record, de-duplicate and alert
Each liquidation is kept in memory for the API (the last 10,000), appended to a daily JSON Lines file so nothing is lost on restart, printed, and sent to your webhook when it is at least ALERT_USD in size. A set of trade ids (tid) makes sure the same trade is never counted twice.
const MAX_KEPT = 10_000;const recent: Liquidation[] = [];const seen = new Set<number>(); async function record(liq: Liquidation) { if (seen.has(liq.tid)) return; // count every trade once seen.add(liq.tid); recent.push(liq); if (recent.length > MAX_KEPT) seen.delete(recent.shift()!.tid); const day = new Date(liq.time).toISOString().slice(0, 10); await appendFile(`${DATA_DIR}/liquidations-${day}.jsonl`, JSON.stringify(liq) + "\n"); const usd = liq.notional.toLocaleString("en-US", { maximumFractionDigits: 0 }); console.log( `${new Date(liq.time).toISOString()} ${liq.coin} ${liq.position} liquidated (${liq.method}): ` + `${liq.sz} @ ${liq.px} = $${usd} | ${liq.liquidatedUser}` ); if (liq.notional >= ALERT_USD) await alert(liq, usd);} async function alert(liq: Liquidation, usd: string) { const text = `Hyperliquid: $${usd} ${liq.coin} ${liq.position} liquidated at ${liq.px} (${liq.liquidatedUser})`; if (!WEBHOOK_URL) return console.log(`ALERT ${text}`); try { await fetch(WEBHOOK_URL, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ text }), }); } catch (err) { console.error("webhook failed:", err); }} function statsByCoin(minutes: number) { const since = Date.now() - minutes * 60_000; const byCoin = new Map<string, { coin: string; count: number; longs: number; shorts: number; notional: number }>(); for (const liq of recent) { if (liq.time < since) continue; const row = byCoin.get(liq.coin) ?? { coin: liq.coin, count: 0, longs: 0, shorts: 0, notional: 0 }; row.count += 1; row.notional += liq.notional; if (liq.position === "long") row.longs += liq.notional; else row.shorts += liq.notional; byCoin.set(liq.coin, row); } return [...byCoin.values()].sort((a, b) => b.notional - a.notional);}statsByCoin adds up the liquidated notional per market over a window, split into longs and shorts, which is the number most liquidation dashboards lead with. The webhook body is {"text": ...}, the format Slack incoming webhooks accept; change it for another service.
Step 4: Connect, subscribe and stay connected
The connection sends one subscribe message with type: "liquidationFills" and no other parameters. Two details keep it healthy and cheap:
- Heartbeat. An application-level
{"method": "ping"}message every 30 seconds, as the connection guidance recommends; the server answers on thepongchannel. If nothing at all arrives between two pings, the connection is dead and is closed so it can reconnect. - Backoff. On close, reconnect after 1 second, doubling up to 30 seconds, and only reset the delay once a connection has held for a minute. Every reconnect pays a new first minute, so a client that retries every second would pay for 60 subscriptions a minute.
let backoff = 1_000; function connect() { const ws = new WebSocket(WS_URL); let alive = true; let heartbeat: NodeJS.Timeout | undefined; let stable: NodeJS.Timeout | undefined; ws.on("open", () => { console.log("connected, subscribing to liquidationFills"); ws.send(JSON.stringify({ method: "subscribe", subscription: { type: "liquidationFills" } })); // Only reset the backoff once the connection has held for a minute. stable = setTimeout(() => (backoff = 1_000), 60_000); heartbeat = setInterval(() => { if (!alive) return ws.terminate(); // nothing received since the last ping: the connection is dead alive = false; ws.send(JSON.stringify({ method: "ping" })); // application-level ping; the server replies on "pong" }, 30_000); }); ws.on("message", (raw) => { alive = true; // any message, the pong included, shows the connection is alive const msg = JSON.parse(raw.toString()); if (msg.channel !== "liquidationFills") return; for (const [address, fill] of (msg as LiquidationMessage).fills) { record(toLiquidation(address, fill)).catch((err) => console.error("record failed:", err)); } }); ws.on("close", (code) => { clearInterval(heartbeat); clearTimeout(stable); console.log(`closed (${code}), reconnecting in ${backoff / 1000}s`); setTimeout(connect, backoff); backoff = Math.min(backoff * 2, 30_000); }); ws.on("error", (err) => { console.error("socket error:", err.message); if (/\b401\b/.test(err.message)) { // The handshake was refused: the key is missing or invalid. Retrying won't help. console.error("GoldRush rejected the API key (HTTP 401). Check GOLDRUSH_API_KEY."); process.exit(1); } ws.close(); });}Messages on other channels, such as the subscription confirmation and pong, are ignored after they mark the connection alive. The handler does no slow work itself: writing to disk and calling the webhook happen in record, so the socket keeps reading while they finish.
Step 5: Query liquidations over HTTP
A small HTTP server built on Node's http module makes the data available to a dashboard, a bot or curl, with no framework:
| Route | Returns |
|---|---|
GET /liquidations/recent?limit=50 |
The latest liquidations, newest first |
GET /liquidations/large?min=250000 |
Liquidations at least min in notional (default ALERT_USD) |
GET /stats?minutes=60 |
Liquidated notional per coin over the window, longs and shorts |
GET /health |
Whether the server is up and how many records it holds |
const server = createServer((req, res) => { const url = new URL(req.url ?? "/", `http://localhost:${PORT}`); const send = (body: unknown) => { res.writeHead(200, { "Content-Type": "application/json" }); res.end(JSON.stringify(body)); }; if (url.pathname === "/liquidations/recent") { const limit = Number(url.searchParams.get("limit") ?? 50); return send(recent.slice(-limit).reverse()); } if (url.pathname === "/liquidations/large") { const min = Number(url.searchParams.get("min") ?? ALERT_USD); return send(recent.filter((l) => l.notional >= min).reverse()); } if (url.pathname === "/stats") return send(statsByCoin(Number(url.searchParams.get("minutes") ?? 60))); if (url.pathname === "/health") return send({ ok: true, kept: recent.length }); res.writeHead(404).end();}); await mkdir(DATA_DIR, { recursive: true });server.listen(PORT, () => console.log(`API on http://localhost:${PORT}`));connect();The API only reads memory, so it answers instantly, and it holds what the monitor has seen since it started. To serve more history, load the liquidation-data/*.jsonl files at startup or write the records to a database instead.
Step 6: Run the monitor
ALERT_USD=100000 npx tsx monitor.tsEach liquidation prints a line like this one, made from the sample message in step 2 (the liquidated wallet is shortened here):
2024-01-01T00:00:00.000Z ETH long liquidated (market): 1.5 @ 2150.5 = $3,226 | 0x...Then query it from another terminal:
curl "http://localhost:3001/liquidations/recent?limit=5"curl "http://localhost:3001/stats?minutes=60"How often lines appear depends on the market: in a quiet hour there may be few, and in a sharp move many arrive in the same second. To receive alerts in Slack, set WEBHOOK_URL to an incoming webhook URL before starting.
Step 7: Flag positions close to liquidation
The stream tells you about liquidations once they happen. To see one coming for wallets you care about, such as your own accounts, your users' or a list of large traders, read their positions with clearinghouseState (credit cost: 1 per call). Each open position has a liquidationPx, and positionValue divided by the size gives the price the position is valued at, so the distance between them is how far the market has to move before the position is liquidated.
Save this as at-risk.ts:
const API_KEY = process.env.GOLDRUSH_API_KEY;if (!API_KEY) throw new Error("Set GOLDRUSH_API_KEY"); const WALLETS = (process.env.WATCH_WALLETS ?? "").split(",").filter(Boolean);const WARN_PCT = Number(process.env.WARN_PCT ?? 10); // warn when price is within this % of liquidation type AssetPosition = { position: { coin: string; szi: string; positionValue: string; liquidationPx: string | null; leverage: { type: string; value: number }; };}; async function clearinghouseState(user: string): Promise<{ assetPositions: AssetPosition[] }> { const res = await fetch("https://hypercore.goldrushdata.com/info", { method: "POST", headers: { Authorization: `Bearer ${API_KEY}`, "Content-Type": "application/json" }, body: JSON.stringify({ type: "clearinghouseState", user: user.toLowerCase(), dex: "" }), }); if (!res.ok) throw new Error(`clearinghouseState ${user}: HTTP ${res.status} ${await res.text()}`); return res.json();} for (const wallet of WALLETS) { const state = await clearinghouseState(wallet); for (const { position: p } of state.assetPositions) { if (!p.liquidationPx) continue; // no liquidation price, e.g. a fully collateralised position const size = Number(p.szi); const price = Number(p.positionValue) / Math.abs(size); // the price the position is valued at const liqPx = Number(p.liquidationPx); const distancePct = (Math.abs(price - liqPx) / price) * 100; const flag = distancePct <= WARN_PCT ? "AT RISK" : "ok"; console.log( `${flag.padEnd(7)} ${wallet} ${p.coin} ${size > 0 ? "long" : "short"} ` + `${p.leverage.value}x ${p.leverage.type}: price ${price.toFixed(4)}, ` + `liquidation ${liqPx}, ${distancePct.toFixed(2)}% away` ); }}Run it with a comma-separated list of wallets:
WATCH_WALLETS=0xecb63caa47c7c4e77f60f1ce858cf28dc2b82b00 WARN_PCT=10 npx tsx at-risk.tsThe script reads only assetPositions. This is the position in the clearinghouseState reference's sample response, trimmed to that array and the fields the script uses:
{ "assetPositions": [ { "type": "oneWay", "position": { "coin": "ETH", "szi": "2.5", "leverage": { "type": "cross", "value": 5 }, "entryPx": "3400.0", "positionValue": "8500.00", "liquidationPx": "2800.5" } } ]}For that position (2.5 ETH long at 5x cross, valued at 8,500 with a liquidation price of 2,800.5), it prints:
ok 0xecb63caa47c7c4e77f60f1ce858cf28dc2b82b00 ETH long 5x cross: price 3400.0000, liquidation 2800.5, 17.63% awayEach wallet is one call. To check many wallets on a schedule, batchClearinghouseState reads up to 50 wallets in one request (credit cost: 25 per call); check each slot for an error key, since one failed wallet doesn't fail the whole response. A wallet that appears in the liquidation stream is also a good candidate to add to the watch list, since a partly liquidated account may still hold other positions.
Handle errors from the Hyperliquid API
Both scripts send your GoldRush key, and GoldRush rejects a bad key before doing any work.
The Info API (at-risk.ts). The docs show this body, with HTTP 401, for a request whose Authorization header is missing or holds an invalid key (Info API errors):
{ "error": "unauthorized" }It means the key never reached GoldRush or isn't valid: check GOLDRUSH_API_KEY and the Bearer prefix, then run the script again. The same table lists {"error":"invalid request"} (HTTP 400) for a malformed body. at-risk.ts throws with the status and the body, so you see which one it was.
The WebSocket (monitor.ts). A missing or invalid key in the URL gets HTTP 401 on the upgrade handshake, so the socket never opens and no subscription starts (WebSocket migration notes). The ws package reports it as a socket error, Unexpected server response: 401. The error handler in step 4 exits on it instead of reconnecting, since every retry would be refused the same way.
Extend the Hyperliquid liquidation monitor
- Liquidations of your own users. If you run a Hyperliquid front end with a builder code,
builderLiquidationsstreams only the liquidations whose closing order went through your builder address. - Context from the whole tape.
allFillsstreams every fill on HyperCore. Comparing liquidated volume with total volume per coin shows how much of a move is forced. - History. The stream starts when you connect. Store every record in a database, and fill in past liquidations for the wallets you track from their ledger history:
userNonFundingLedgerUpdatesentries withdelta.typeliquidation. - A dashboard. The HTTP API in step 5 is enough for a chart of
/statsand a table of/liquidations/recent. Keep the API key on the server; the browser only talks to your API.
Frequently asked questions
How do I track Hyperliquid liquidations in real time?
Subscribe to the GoldRush liquidationFills channel at wss://hypercore.goldrushdata.com/ws?key=<GOLDRUSH_API_KEY> with {"method": "subscribe", "subscription": {"type": "liquidationFills"}}. One subscription with no address filter streams every liquidation fill on HyperCore, with the liquidated wallet, the method and the mark price on every entry.
Does the public Hyperliquid WebSocket have a liquidation feed?
No. The public WebSocket sends fills per wallet, so you would have to subscribe to every wallet that might be liquidated and filter for the liquidation flag. liquidationFills is GoldRush-native and has no equivalent on wss://api.hyperliquid.xyz/ws.
How much does it cost to stream Hyperliquid liquidations?
A liquidationFills subscription has a credit cost of 1 per minute, however many liquidations it delivers, which is 1,440 credits for a full day. Billing is in whole minutes with a one-minute minimum per subscription, and a reconnect starts a new subscription, so reconnect with backoff rather than in a tight loop.
Can I get historical Hyperliquid liquidations?
Not from liquidationFills: it is live only and sends nothing from before you subscribe. Store what the stream sends, or use the decoded liquidation events in the GoldRush Streaming API for a wallet's past liquidations.
What is the difference between a market and a backstop liquidation?
A market liquidation closes the position with orders sent to the order book. A backstop liquidation happens when that isn't possible and the position is taken over by Hyperliquid's liquidator vault instead. The method field on every fill tells you which one it was.
How can I tell if a position is close to liquidation?
Read the wallet's positions with clearinghouseState and compare each position's price with its liquidationPx. The at-risk.ts script in step 7 prints the distance as a percentage and flags positions within a threshold you set.
Next steps
- Read the
liquidationFillsreference for the full field list and theaggregateByTimeoption. - See every channel on the Hyperliquid WebSocket API, including order books and wallet fills.
- Check connection limits and billing before running the monitor around the clock.
- Explore the Hyperliquid API for the Info API, the WebSocket and decoded HyperCore data in one place.