Hyperliquid JavaScript SDK example: ws-api-client.ts

Hyperliquid websocket API client JavaScript example. Read the source code, review its SDK calls, and browse related exchange integration examples.

This example uses @siebly/hyperliquid-api, the JavaScript and TypeScript SDK for Hyperliquid. Install it with npm install @siebly/hyperliquid-api.

We use environment variables in our examples for API keys. It is your responsibility to manage and secure your keys appropriately.

examples/Hyperliquid/Websocket/WS-API/ws-api-client.ts

What this example covers

  • Hyperliquid WebSocket API request/response JavaScript example.
  • Uses the Siebly Hyperliquid SDK package @siebly/hyperliquid-api instead of hand-written WebSocket plumbing.
  • Source path: Hyperliquid/Websocket/WS-API/ws-api-client.ts.
  • Imports SDK symbols including DefaultLogger, WebsocketAPIClient.
  • Calls SDK methods such as on(), connect(), getAllMids(), getOrderBook(), submitLimitOrder(), cancelOrders(), close().

How to use this example

  • Start here for the specific request or stream pattern, then check the matching SDK guide for install, credentials, and operational notes.
  • For WebSocket examples, keep reconnect, resubscribe, heartbeat, and event-handler behavior explicit in your service.
  • Open the repository source when you need the latest committed version: GitHub source file.
import {  DefaultLogger,  type ExchangeResponse,  type OrderResponseData,  WebsocketAPIClient,} from '@siebly/hyperliquid-api'; // or// import { DefaultLogger, WebsocketAPIClient } from '@siebly/hyperliquid-api'; /** * WebsocketAPIClient has the same Info and Exchange methods as RestClient, but * sends them over Hyperliquid's correlated WebSocket POST protocol. * * Public example: * npx tsx examples/Websocket/WS-API/ws-api-client.ts * * Private example: * HYPERLIQUID_PRIVATE_KEY='0xabc' npx tsx examples/Websocket/WS-API/ws-api-client.ts */const logger = {  ...DefaultLogger,  // trace: (...params: unknown[]) => console.log(new Date(), 'trace', ...params),}; const privateKey = process.env.HYPERLIQUID_PRIVATE_KEY; const wsClient = new WebsocketAPIClient(  {    ...(privateKey === undefined ? {} : { privateKey }),    // testnet: true,  },  logger,); wsClient.on('open', (data) => {  console.log('ws connection opened:', data.wsKey);}); wsClient.on('reconnecting', ({ wsKey }) => {  console.log('ws automatically reconnecting.... ', wsKey);}); wsClient.on('reconnected', (data) => {  console.log('ws has reconnected ', data?.wsKey);}); wsClient.on('exception', ({ event, data, wsKey }) => {  console.error('ws exception:', wsKey, event ?? data);}); function firstRestingOid(  result: ExchangeResponse<OrderResponseData>,): number | undefined {  if (result.status !== 'ok') {    return undefined;  }  const status = result.response.data?.statuses[0];  return status && 'resting' in status ? status.resting.oid : undefined;} async function main() {  try {    // Optional: open the WS API connection early so the first call is not a    // cold start. connect() happens automatically on the first request.    // await wsClient.connect();     const mids = await wsClient.getAllMids();    console.log('BTC mid:', mids.BTC);     const book = await wsClient.getOrderBook({ coin: 'ETH' });    console.log('ETH best bid:', book?.levels[0]?.[0]);     if (!privateKey) {      console.log(        'Set HYPERLIQUID_PRIVATE_KEY to also submit a limit over the WS API.',      );      return;    }     const result = await wsClient.submitLimitOrder({      price: '1100',      side: 'buy',      size: '0.01',      symbol: 'ETH',    });    console.log('WS API limit order:', JSON.stringify(result, null, 2));     const oid = firstRestingOid(result);    if (oid !== undefined) {      console.log(        'cancel:',        await wsClient.cancelOrders({          cancels: [{ a: 'ETH', o: oid }],        }),      );    }  } catch (e) {    console.error('WS API request failed: ', e);  } finally {    wsClient.close();  }} main(); 

Subscribe on Substack

Complete the Substack form below to join our newsletter. Substack handles all subscriber data directly.