← All articles

Hyperliquid WebSocket API in TypeScript: trades, l2Book, userFills and reconnects

The Hyperliquid WebSocket API sends trades, order book snapshots and account fills through subscriptions. Each topic has different recovery requirements when the socket reconnects.

The examples use @siebly/hyperliquid-api.

What you need

  • Node.js 24 runs these TypeScript files directly with node file.ts.
  • @siebly/hyperliquid-api 1.0.5 from npm.
  • No API key or private key. Market data is public, and the userFills stream only needs an account address.
npm init -y
npm pkg set type=module
npm install @siebly/hyperliquid-api

For installation and REST calls, see getting started with the Hyperliquid JavaScript SDK.

How the Hyperliquid WebSocket client is organised

WebsocketClient receives subscriptions. It connects to wss://api.hyperliquid.xyz/ws on mainnet or wss://api.hyperliquid-testnet.xyz/ws with testnet: true. Override the endpoint with wsUrl. For a request with a single response, use WebsocketAPIClient as shown in the WebSocket API requests guide.

The model is small:

  • subscribe(topic) takes a topic object in Hyperliquid’s own wire format, such as { type: 'trades', coin: 'BTC' }, or an array of them. It opens the connection if needed.
  • Data arrives on the message event as the original envelope: { channel, data, wsKey }. Checking event.channel narrows event.data to the right TypeScript type.
  • Server acknowledgements arrive on response with channel: 'subscriptionResponse'.
  • Connection and server errors arrive on exception.
  • Lifecycle events are open, reconnecting, reconnected and close.

wsKey tells you which physical connection a message came from. Market data and userFills share one connection called public. Streams whose server messages do not include the user address (orderUpdates, userEvents and notification) get their own connection per account, keyed user:<address>, so messages from different accounts cannot be mixed up.

Connect and stream trades

Save this as trades.ts. It prints individual trades and stops after five messages.

import { WebsocketClient } from '@siebly/hyperliquid-api';

const ws = new WebsocketClient({
  // The default is 1,000 ms. Allow more time for slow DNS or TLS handshakes.
  connectionTimeout: 5_000,
});

ws.on('open', ({ wsKey, wsUrl }) => {
  console.log('Connected:', wsKey, wsUrl);
});

ws.on('response', (event) => {
  console.log('Ack:', JSON.stringify(event.data));
});

ws.on('exception', ({ wsKey, event }) => {
  console.error('WebSocket exception:', wsKey, event);
});

let received = 0;

ws.on('message', (event) => {
  if (event.channel !== 'trades') return;

  for (const trade of event.data) {
    const side = trade.side === 'B' ? 'buy' : 'sell';
    console.log(trade.coin, side, trade.sz, '@', trade.px, new Date(trade.time).toISOString());
  }

  received += 1;
  if (received >= 5) {
    ws.closeAll();
  }
});

await ws.subscribe({ type: 'trades', coin: 'BTC' });
console.log('Subscribe request sent');

Run node trades.ts.

Connected: public wss://api.hyperliquid.xyz/ws
Subscribe request sent
Ack: {"method":"subscribe","subscription":{"type":"trades","coin":"BTC"}}
BTC sell 0.02937 @ 60649.0 2026-11-27T00:36:54.263Z
BTC buy 0.02261 @ 60651.0 2026-11-27T00:36:54.663Z
BTC sell 0.00062 @ 60650.0 2026-11-27T00:36:55.011Z
BTC sell 0.0029 @ 60656.0 2026-11-27T00:36:57.180Z
...

You will also see lines such as [ 'Websocket connected', { category: 'hyperliquid-ws', ... } ]. That is the SDK’s default logger, which prints connection events at info level. The logging section below shows how to change it.

  • Each message is an array. event.data is Trade[], and one message can carry several trades from the same block.
  • The first trades message can include recent trades and lacks a snapshot flag. Deduplicate stored trades after subscribing or reconnecting. Hyperliquid documents (time, coin, tid) as a trade identifier.
  • side is 'B' (buy) or 'A' (sell). Prices and sizes are strings, so convert them deliberately rather than doing arithmetic on them as they arrive.
  • subscribe() resolving does not mean the server accepted the topic. It confirms the request was sent. The acknowledgement comes later on response.

“WebSocket connection timed out after 1000 ms.”

The default connectionTimeout is 1,000 ms, including DNS and the TLS handshake. Increase it if the connection repeatedly times out before opening.

A timeout on the first connection can also end the process. When the first connection attempt fails, the subscribe() promise rejects, even though the SDK keeps the topic and carries on retrying in the background. With a top level await and no try/catch, that rejection ends the process. In a long running service, catch it, log it and let the SDK keep reconnecting.

Stream the order book with l2Book

l2Book sends a full snapshot of the top of the book in every message, not a diff, so you can replace your local copy each time. Save this as l2book.ts:

import { WebsocketClient } from '@siebly/hyperliquid-api';

const ws = new WebsocketClient({
  // The default is 1,000 ms. Allow more time for slow DNS or TLS handshakes.
  connectionTimeout: 5_000,
});

ws.on('exception', ({ wsKey, event }) => {
  console.error('WebSocket exception:', wsKey, event);
});

let updates = 0;

ws.on('message', (event) => {
  if (event.channel !== 'l2Book') return;

  const { coin, levels, time } = event.data;
  const [bids, asks] = levels;
  const bestBid = bids[0];
  const bestAsk = asks[0];

  if (!bestBid || !bestAsk) return;

  const spread = Number(bestAsk.px) - Number(bestBid.px);
  console.log(
    new Date(time).toISOString(),
    coin,
    `levels ${bids.length}/${asks.length}`,
    `bid ${bestBid.sz} @ ${bestBid.px} (${bestBid.n} orders)`,
    `ask ${bestAsk.sz} @ ${bestAsk.px} (${bestAsk.n} orders)`,
    `spread ${spread.toFixed(2)}`,
  );

  updates += 1;
  if (updates >= 5) {
    ws.closeAll();
  }
});

await ws.subscribe({ type: 'l2Book', coin: 'ETH' });
2026-11-27T00:37:26.888Z ETH levels 20/20 bid 90.4369 @ 1693.7 (23 orders) ask 779.7511 @ 1693.8 (15 orders) spread 0.10
2026-11-27T00:37:32.235Z ETH levels 20/20 bid 10.1778 @ 1693.7 (5 orders) ask 873.565 @ 1693.8 (52 orders) spread 0.10
2026-11-27T00:37:44.303Z ETH levels 20/20 bid 5.2926 @ 1694.0 (3 orders) ask 789.5964 @ 1694.1 (26 orders) spread 0.10
2026-11-27T00:37:56.565Z ETH levels 20/20 bid 143.5077 @ 1694.2 (36 orders) ask 591.4323 @ 1694.3 (7 orders) spread 0.10
2026-11-27T00:38:09.076Z ETH levels 20/20 bid 25.509 @ 1694.6 (4 orders) ask 840.8638 @ 1694.7 (26 orders) spread 0.10

levels[0] contains bids and levels[1] asks, best price first. Each level reports price (px), size (sz) and order count (n).

Set fast: true for more frequent snapshots. The SDK supports the option. Measure the update interval for the subscribed market.

await ws.subscribe({ type: 'l2Book', coin: 'BTC', fast: true });

For the full pattern, including the newer l2 diff feed and how to rebuild a local book from it, see Hyperliquid l2Book in JavaScript: slow snapshots, fast mode and l2 diffs.

The other options are nSigFigs (2 to 5) and mantissa (1, 2 or 5), which aggregate price levels. The server echoes the settings it applied in the acknowledgement, for example {"type":"l2Book","coin":"BTC","nSigFigs":null,"mantissa":null,"fast":true}, which is a quick way to confirm what you are actually receiving.

Stream user fills for an account

The userFills WebSocket stream needs an account address and nothing else, because Hyperliquid account data is public. Keep the address out of your code and pass it in as an environment variable. Save this as userfills.ts:

import { WebsocketClient } from '@siebly/hyperliquid-api';

const user = process.env.HYPERLIQUID_ACCOUNT_ADDRESS;
if (!user || !/^0x[0-9a-fA-F]{40}$/.test(user)) {
  throw new Error('Set HYPERLIQUID_ACCOUNT_ADDRESS to a 0x account address.');
}

const ws = new WebsocketClient({ connectionTimeout: 5_000 });

// Hyperliquid's docs suggest (time, coin, tid) as a globally unique trade id.
const seen = new Set<string>();
const fillKey = (fill: { time: number; coin: string; tid: number }) =>
  `${fill.time}:${fill.coin}:${fill.tid}`;

ws.on('exception', ({ wsKey, event }) => {
  console.error('WebSocket exception:', wsKey, event);
});

ws.on('message', (event) => {
  if (event.channel !== 'userFills') return;

  const { isSnapshot, fills } = event.data;

  if (isSnapshot) {
    for (const fill of fills) seen.add(fillKey(fill));
    console.log(`Snapshot: ${fills.length} recent fills for ${event.data.user}`);
    // Snapshot fills are oldest first.
    const latest = fills.at(-1);
    if (latest) {
      console.log('Latest fill:', {
        coin: latest.coin,
        dir: latest.dir,
        side: latest.side,
        px: latest.px,
        sz: latest.sz,
        oid: latest.oid,
        tid: latest.tid,
        time: new Date(latest.time).toISOString(),
      });
    }
    return;
  }

  for (const fill of fills) {
    const key = fillKey(fill);
    if (seen.has(key)) continue;
    seen.add(key);
    console.log('New fill:', fill.coin, fill.dir, fill.sz, '@', fill.px, 'order', fill.oid);
  }
});

await ws.subscribe({ type: 'userFills', user });

// Stop after 30 seconds for this demo.
setTimeout(() => ws.closeAll(), 30_000);

Run HYPERLIQUID_ACCOUNT_ADDRESS=0x... node userfills.ts with the account address.

Snapshot: 30 recent fills for 0x71d0...8c26
Latest fill: {
  coin: 'ME',
  dir: 'Open Short',
  side: 'A',
  px: '0.04362',
  sz: '68.0',
  oid: 617569876210,
  tid: 70919876592520,
  time: '2026-11-27T00:47:38.917Z'
}

Example live fills:

New fill: BTC Open Long 0.00185 @ 60662.0 order 617565931711
New fill: BTC Open Long 0.00425 @ 60662.0 order 617565931711

The initial message carries isSnapshot: true. Live updates can omit the field, so test explicitly for true.

  • Snapshot fills are ordered oldest first. Use fills.at(-1) for the latest entry.
  • After a reconnect the snapshot can contain fills already stored. Deduplicate before applying them.

For the full pattern, including a fill tracker that survives reconnects without double counting, see Hyperliquid userFills in Node.js: snapshots, reconnects and missing fills.

The SDK adds aggregateByTime: false to the subscription if you leave it out. Set it to true if you want partial fills of one order in the same block combined. oid is the order id, so you can match fills to the orders you placed. For following orders as well as fills, see the docs guide on account updates over WebSocket, which pairs userFills with orderUpdates.

Heartbeats: what Hyperliquid needs and what the SDK sends

Hyperliquid’s timeouts and heartbeats page says the server closes any connection that has not sent it a message in the last 60 seconds. The keepalive is a JSON message, { "method": "ping" }, and the server replies with { "channel": "pong" }.

You do not need to send these yourself. From the SDK source and README:

  • Once a connection opens, the SDK sends {"method":"ping"} every 10,000 ms (pingInterval).
  • After each ping it waits 1,000 ms for a pong (pongTimeout). If none arrives, it logs Pong timeout - closing socket to reconnect, closes the socket and starts the reconnect process described below.
  • Pongs are handled inside the SDK. They do not appear as message events.
  • pingInterval: 0 turns pings off and pongTimeout: 0 turns off the deadline. Turning pings off on a quiet subscription brings back the 60 second server timeout, so leave them on.

To watch the heartbeat, pass a logger whose trace method prints. Trace logging is verbose (it includes every message), so this one filters it down:

import { DefaultLogger, WebsocketClient } from '@siebly/hyperliquid-api';

const logger = {
  ...DefaultLogger,
  trace: (message: unknown) => {
    if (/ping|PONG|Subscribing/.test(String(message))) {
      console.debug(new Date().toISOString(), message);
    }
  },
};

const ws = new WebsocketClient({ connectionTimeout: 5_000 }, logger);

Example output over 25 seconds:

2026-11-27T00:46:03.864Z Subscribing to 3 "public" topics in 3 batches.
2026-11-27T00:46:03.865Z Enabled ping timer
2026-11-27T00:46:13.865Z Sending ping
2026-11-27T00:46:14.289Z Received PONG event
2026-11-27T00:46:23.865Z Sending ping
2026-11-27T00:46:24.280Z Received PONG event

Increase pongTimeout if healthy connections repeatedly close while waiting for a pong.

Reconnects: what the SDK does for you

Automatic reconnection is on by default (autoReconnect: true). When a connection drops, times out or misses a pong, the SDK:

  1. Emits reconnecting with { attempt, delay, cause }.
  2. Waits, starting at 500 ms (reconnectTimeout) and doubling after each failed attempt up to 10,000 ms (maxReconnectTimeout).
  3. Opens a new socket and resends every topic it has cached for that connection.
  4. Emits reconnected, and resets the backoff once the socket has opened.

What the SDK does not do

A reconnect restores your subscriptions. It does not replay what was sent while you were disconnected. The SDK README is explicit that interrupted WebSocket API requests are rejected rather than replayed, and the reconnected event means the socket is back, not that your data is complete. For trades and the book, that usually does not matter: the next l2Book message is a full snapshot, and the first trades message after resubscribing carries a batch of recent trades. For fills, a gap can matter.

Backfill fills after a reconnect

The userFills snapshot you get after reconnecting may cover the gap, but you cannot rely on its size. A simple pattern is to record the time of the last fill you processed, and on reconnected ask the REST API for everything since then. Save this as fills-reconcile.ts:

import { RestClient, WebsocketClient, type UserFill } from '@siebly/hyperliquid-api';

const user = process.env.HYPERLIQUID_ACCOUNT_ADDRESS;
if (!user || !/^0x[0-9a-fA-F]{40}$/.test(user)) {
  throw new Error('Set HYPERLIQUID_ACCOUNT_ADDRESS to a 0x account address.');
}

const rest = new RestClient();
const ws = new WebsocketClient({ connectionTimeout: 5_000 });

const seen = new Set<string>();
let lastFillTime = 0;

function applyFill(fill: UserFill, source: string) {
  const key = `${fill.time}:${fill.coin}:${fill.tid}`;
  if (seen.has(key)) return;
  seen.add(key);
  lastFillTime = Math.max(lastFillTime, fill.time);
  console.log(source, fill.coin, fill.dir, fill.sz, '@', fill.px, 'order', fill.oid);
}

ws.on('reconnecting', ({ wsKey }) => {
  console.log('Disconnected, SDK will retry:', wsKey);
});

ws.on('reconnected', async () => {
  // The SDK has resubscribed. Fetch anything that happened during the gap.
  if (!lastFillTime) return;
  try {
    const missed = await rest.getUserFillsByTime({ user, startTime: lastFillTime });
    console.log(`REST backfill returned ${missed.length} fills since ${new Date(lastFillTime).toISOString()}`);
    for (const fill of missed) applyFill(fill, 'backfill');
  } catch (error) {
    console.error('Backfill failed, retry before trusting local state:', error);
  }
});

ws.on('exception', ({ wsKey, event, data }) => {
  console.error('WebSocket exception:', wsKey, event ?? data);
});

ws.on('message', (event) => {
  if (event.channel !== 'userFills') return;
  const source = event.data.isSnapshot ? 'snapshot' : 'live';
  for (const fill of event.data.fills) applyFill(fill, source);
});

await ws.subscribe({ type: 'userFills', user });

The backfill start time is inclusive. Deduplicate the boundary fill and any overlap with the snapshot. getUserFillsByTime() returns at most 2,000 fills per call. See the production guide for order recovery and WebSocket reconnects and backfill for pagination and reconnects.

Invalid subscriptions: silent disconnects and reconnect loops

Hyperliquid treats a bad coin name and a malformed WebSocket request differently, and only one of them tells you what went wrong.

Unknown coin: the server closes the connection with no message

An invalid coin subscription can close the socket with code 1006 before a subscription acknowledgement arrives.

Through the SDK this becomes a loop. The bad topic is cached, so every reconnect resends it, the server drops the connection again, and the backoff never grows because each attempt does open successfully. Good subscriptions on the same connection are interrupted every time. Here is BTC and BTC-PERP subscribed together:

 1530 response {"method":"subscribe","subscription":{"type":"trades","coin":"BTC"}}
 1709 reconnecting {"attempt":1,"delay":500,"cause":{}}
 3646 reconnected
 4116 response {"method":"subscribe","subscription":{"type":"trades","coin":"BTC"}}
 4308 reconnecting {"attempt":1,"delay":500,"cause":{}}
 6135 reconnected
 6566 response {"method":"subscribe","subscription":{"type":"trades","coin":"BTC"}}
 6788 reconnecting {"attempt":1,"delay":500,"cause":{}}
 7116 unsubscribing BTC-PERP
 8775 reconnected
 9201 response {"method":"subscribe","subscription":{"type":"trades","coin":"BTC"}}

Remove a bad topic with unsubscribe() to stop the SDK restoring it on reconnect. Repeated connection attempts count toward the limit in Hyperliquid’s rate limits page.

The fix is to check names before subscribing. nameToCoin() looks the name up in Hyperliquid’s asset metadata (one REST call, then cached), throws for unknown names, and also converts readable spot names to the ids the WebSocket expects:

import { WebsocketClient } from '@siebly/hyperliquid-api';

const ws = new WebsocketClient({ connectionTimeout: 5_000 });

ws.on('message', (event) => {
  if (event.channel === 'trades') {
    console.log('trades for', event.data[0]?.coin, 'count', event.data.length);
  }
});

async function subscribeTrades(name: string) {
  let coin: string;
  try {
    // Checks the name against Hyperliquid's asset metadata (one REST call, then cached).
    coin = await ws.nameToCoin(name);
  } catch (error) {
    console.error(`Not subscribing to ${name}:`, (error as Error).message);
    return;
  }
  await ws.subscribe({ type: 'trades', coin });
  console.log(`Subscribed to trades for ${name} as ${coin}`);
}

for (const name of ['BTC', 'HYPE/USDC', 'BTC-PERP']) {
  await subscribeTrades(name);
}

setTimeout(() => ws.closeAll(), 5_000);
Subscribed to trades for BTC as BTC
Subscribed to trades for HYPE/USDC as @107
Not subscribing to BTC-PERP: Unknown Hyperliquid asset "BTC-PERP". Call refreshAssetMetadata() after a new listing.
trades for BTC count 30
trades for @107 count 30

Perpetuals use the bare coin name (BTC, ETH). Spot pairs use either a native name such as PURR/USDC or an @ index such as @107, and the trades for HYPE/USDC arrive with coin: '@107'. Names are case sensitive.

Malformed request: an error you can see

A request the server cannot parse, such as a bad address or an unknown subscription type, gets an explicit error and the connection stays open. Subscribing to userFills with user: '0x123' through the SDK emits this exception event:

{"channel":"error","data":"Error parsing JSON into valid websocket request: {\"method\":\"subscribe\",\"subscription\":{\"type\":\"userFills\",\"user\":\"0x123\",\"aggregateByTime\":false}}","wsKey":"public"}

That is why the user fills example checks the address with a regular expression before subscribing.

Subscribe to trades, books and fills on one connection

This is the full script: three streams on one connection, every lifecycle event logged, optional heartbeat tracing with DEBUG_WS=1, and a clean shutdown on Ctrl+C. Save it as stream.ts and run HYPERLIQUID_ACCOUNT_ADDRESS=0x... node stream.ts.

import { DefaultLogger, WebsocketClient } from '@siebly/hyperliquid-api';

const user = process.env.HYPERLIQUID_ACCOUNT_ADDRESS;
if (!user || !/^0x[0-9a-fA-F]{40}$/.test(user)) {
  throw new Error('Set HYPERLIQUID_ACCOUNT_ADDRESS to a 0x account address.');
}

// Trace output is verbose (every message). Keep only heartbeat and subscribe lines.
const logger = {
  ...DefaultLogger,
  trace: (message: unknown) => {
    if (process.env.DEBUG_WS && /ping|PONG|Subscribing/.test(String(message))) {
      console.debug(new Date().toISOString(), message);
    }
  },
};

const ws = new WebsocketClient(
  {
    connectionTimeout: 5_000, // default 1,000 ms
    pingInterval: 10_000, // default 10,000 ms
    pongTimeout: 1_000, // default 1,000 ms
    reconnectTimeout: 500, // first retry delay, default 500 ms
    maxReconnectTimeout: 10_000, // backoff cap, default 10,000 ms
  },
  logger,
);

let stale = false;

ws.on('open', ({ wsKey }) => console.log('open', wsKey));

ws.on('reconnecting', ({ wsKey, event }) => {
  stale = true;
  console.log('reconnecting', wsKey, event);
});

ws.on('reconnected', ({ wsKey }) => {
  // Topics are already being resubscribed by the SDK at this point.
  console.log('reconnected', wsKey, 'state was stale:', stale);
  stale = false;
});

ws.on('close', ({ wsKey }) => console.log('closed', wsKey));

ws.on('response', (event) => {
  if (event.channel === 'subscriptionResponse') {
    console.log('ack', event.data.method, JSON.stringify(event.data.subscription));
  }
});

ws.on('exception', ({ wsKey, event, data }) => {
  console.error('exception', wsKey, event ?? data);
});

ws.on('message', (event) => {
  switch (event.channel) {
    case 'trades':
      console.log('trades', event.data.length, 'last px', event.data.at(-1)?.px);
      break;
    case 'l2Book': {
      const [bids, asks] = event.data.levels;
      console.log('l2Book', event.data.coin, bids[0]?.px, asks[0]?.px);
      break;
    }
    case 'userFills':
      console.log('userFills', event.data.isSnapshot ? 'snapshot' : 'update', event.data.fills.length);
      break;
  }
});

await ws.subscribe([
  { type: 'trades', coin: 'BTC' },
  { type: 'l2Book', coin: 'BTC', fast: true },
  { type: 'userFills', user },
]);

function stop() {
  ws.closeAll();
}
process.once('SIGINT', stop);
process.once('SIGTERM', stop);
open public
ack subscribe {"type":"trades","coin":"BTC"}
ack subscribe {"type":"l2Book","coin":"BTC","nSigFigs":null,"mantissa":null,"fast":true}
ack subscribe {"type":"userFills","user":"0x71d0...8c26","aggregateByTime":false}
userFills snapshot 30
userFills update 1
userFills update 1
closed public

That is the log with the frequent trades and l2Book lines and the heartbeat trace filtered out. The first market data lines look like this:

trades 30 last px 60725.0
trades 2 last px 60716.0
l2Book BTC 60718.0 60719.0
l2Book BTC 60714.0 60715.0

closeAll() rejects anything pending, clears the timers and cached topics, and the close event confirms when each socket has actually closed. Call close('public') instead to close one connection.

Hyperliquid WebSocket limits to keep in mind

From Hyperliquid’s rate limits page, per IP address:

  • 10 WebSocket connections
  • 30 new WebSocket connections per minute
  • 1,000 WebSocket subscriptions
  • 10 unique users across user specific subscriptions
  • 2,000 messages sent to Hyperliquid per minute across all connections

One WebsocketClient also caps itself at 10 connections. The SDK source throws This client already manages the maximum of 10 WebSocket connections. if you go beyond that, which in practice means more than nine accounts on orderUpdates or userEvents alongside the public connection.

Further reading

The Hyperliquid SDK is one of Siebly’s open source exchange SDKs, which have over 4.8 million npm downloads across 10+ SDKs.