DEV Community

Tiago
Tiago

Posted on Originally published at siebly.io

Hyperliquid JavaScript QuickStart for Node.js & TypeScript

At the surface, working with Hyperliquid's interface, REST APIs & WebSockets seems more complicated than it needs to be. Hyperliquid exposes two main HTTP endpoints (Info & Exchange), plus a WebSocket feed. To call these directly in raw JS, you'll need to also manage signing, nonces, asset IDs and everything that comes with WebSocket lifecycle management (to ensure you can actually rely on them staying alive). In reality, why reinvent the wheel, it's so much simpler than that.

This quickstart guide walks you through @siebly/hyperliquid-api, an open source SDK for all the leading JavaScript (& TypeScript!) runtimes, from backend runtimes (Node.js, Nest.js, Deno, Bun, even Cloudflare Workers), to frontend frameworks (React, Vite, Next.js) and even mobile development for iOS & Android (via React Native / Expo). What a time to be alive.

The SDK itself follows the same architecture as our other exchange SDKs, building on almost a decade of extremely heavy use in production, at scale.

Key Classes

There are 3 core surfaces to integrate with HyperLiquid with this JavaScript SDK:

  • The RestClient class, which wraps around all the available REST API endpoints (public market data, account state, order management, transfers... all the REST endpoints. One fully typed function you can call for any endpoint, and under the hood it will handle authentication & the HTTP request life cycle for you, before handing back a fully typed response object.
  • The WebsocketClient class, our abstraction layer that fully manages WebSockets on demand. Subscribe to (or unsubscribe from) any supported topic, and the SDK will handle the full connection life cycle (track state on topics you've subscribed to, open connections, persist & manage connections, detect/recover/replace stale connections), while emitting rich events for any state changes (topic data, connection state transitions (reconnecting/reconnected), etc).
  • The WebsocketAPIClient class that wraps over our powerful WebsocketClient architecture to provide REST-like capabilities powered by the latency benefits of one or more persistent and fully managed WebSocket connections.

All requests and responses are fully typed (hurray for build-time checks, TypeScript absolutely recommended!). Exchange-specific semantics such as authentication are handled for you, so you can focus on integration with functionality, and not the plumbing between your machine and the exchange APIs.

Install

The package supports Node.js 22 or newer. You should always try to use Node LTS, unless you have a very good reason not to (most of you won't). The SDK is open source and published to NPM:

npm install @siebly/hyperliquid-api
Enter fullscreen mode Exit fullscreen mode

TypeScript is optional, but the type declarations make the request shapes much easier to discover in your editor.

Why not DIY?

One of the more common questions from aspiring devs (especially you vibe devs, you know who you are).

With our SDKs, you’ve got thousands of other users putting that same code through massive stress testing at scale. If there's a bug, they'll find it, and we will fix it quickly.

A reconnect bug you might hit once in six months can surface much sooner across that many connections (interesting story here with Binance's listenKey workflow for anyone interested in the comments). Once we fix it in the shared WebSocket client, everyone using that code gets the fix when they update. Suddenly a rare issue that might happen is no longer a risk. That’s a big part of why our SDKs hold up so well in production.

“Can’t I just ask my agent to build this?” Go on, try it. Ask it to stream your order updates and watch what it does. You might get a working feed in a few minutes. You might also find it fetching your entire list of open orders over REST every time the WebSocket tells you one order changed. Not obvious at the surface while you're testing your vibe spaghetti, not without thoroughly auditing what it made, or worse, finding out the hard way...

Now drop the network halfway through a reconnect and bring it back. Do your order updates start flowing again? One failed connection attempt can leave a reconnecting flag stuck on true. Every retry after that sees a reconnect already in progress and politely does nothing. If the original error got swallowed, you’ve now got a process that looks healthy, a feed that’s gone quiet and an agent saying “you’re absolutely right” before adding a second retry loop around the first one. Try the same with our SDKs. They undergo heavy testing to ensure self-healing resilience to issues. Toggle your wifi, flip around a VPN, see how WebSockets always recover and resubscribe. An event-driven system (which your system should be) needs to rely on the event source to stay alive. The SDKs manage that for you.

There are a lot of fiddly details like this. Sometimes it’s a flaw in your connection logic. Sometimes you followed a perfectly convincing example from an older version of the docs. Either can get past a quick test and turn up in production the first time the exchange has a rough afternoon. Learn from the experience of our collective user base and save your tokens (& time) for the core of your system.

Using the Hyperliquid REST APIs

To use the REST API with any of our SDKs, simply make an instance of the exported RestClient (this is a JavaScript class), and call the Promise-returning methods for the endpoint you're interested in.

Public Info methods need no credentials. Let's start by checking the exchange status, then pull mid prices and an order book:

import { RestClient } from '@siebly/hyperliquid-api';
// or use require if preferred
// const { RestClient } require('@siebly/hyperliquid-api');


const client = new RestClient();

async function main() {
  const status = await client.getExchangeStatus();
  console.log('Exchange status:', status);

  // AllMidsResponse is Record<string, string>: coin to mid price
  const mids = await client.getAllMids();
  console.log('Coins with a mid price:', Object.keys(mids).length);
  console.log('BTC mid:', mids['BTC'] ?? 'not listed');

  const book = await client.getOrderBook({
    coin: 'BTC',
    nSigFigs: 5,
  });

  if (book) {
    console.log('Best bid level:', book.levels[0][0]);
  }
}

main().catch((error) => {
  console.error('Request failed:', error);
});
Enter fullscreen mode Exit fullscreen mode

The SDK uses readable get... names rather than Hyperliquid's internal request type names, so getAllMids() maps to the allMids Info request and getOrderBook() to l2Book.

You can also read any public account by address, without a key:

const user = '0x1234567890123456789012345678901234567890';

const perpSummary = await client.getPerpAccountSummary({ user });
const spotBalances = await client.getSpotBalances({ user });
Enter fullscreen mode Exit fullscreen mode

Convenient, right?

REST API Authentication

For this part, caution is advised. API keys and private keys must be protected. While you can use the SDK in frontend environments (websites), private workflows should ideally be in trusted backend environments only. In our examples we'll use environment variables, but consider best practices around secret/credential management (tons of resources on this online).

API keys should always use the minimum possible access level. For Hyperliquid, use an API wallet, not your mai nwallet key!

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

const privateKey = process.env.HYPERLIQUID_PRIVATE_KEY;

if (!privateKey) {
  throw new Error('Set HYPERLIQUID_PRIVATE_KEY before starting.');
}

const client = new RestClient({
  privateKey,
  testnet: true,
});

const balances = await client.getBalances();
console.log('Account:', balances.user);
console.log('Spot:', balances.spot.balances);
console.log('Perpetuals:', balances.perp.assetPositions);

const openOrders = await client.getOpenOrders();
console.log('Open orders:', openOrders.length);
Enter fullscreen mode Exit fullscreen mode

Some additional notes:

  • Use testnet first. testnet: true points the client at Hyperliquid's testnet API, so you can exercise signing and order flows without touching a real account.
  • Use an API wallet, not your main wallet key. Create a dedicated API (agent) wallet from your Hyperliquid account and give the bot that key. API wallets can place and cancel orders but cannot withdraw funds, so a leaked key cannot drain the account. The SDK resolves an API wallet to its master account automatically, or you can pass accountAddress: masterAddress to skip that lookup.
  • Keep keys server-side. Never put a private key in frontend code, browser storage or a public environment variable. Especially you clauders out there! Public REST calls and public subscriptions are browser-safe; signed calls are not.
  • Custom signers. If you would rather not hand the SDK a raw key, the constructor also accepts a signer with a portable signTypedData implementation.

Using other signed API calls is as easy as the above. For example, this places a post-only limit order:

const order = await client.submitLimitOrder({
  symbol: 'BTC',
  side: 'buy',
  size: '0.001',
  price: '50000',
  timeInForce: 'GTC',
});

if (order.status === 'ok') {
  console.log(order.response.data);
}
Enter fullscreen mode Exit fullscreen mode

The SDK also exposes a convenient submitMarketOrder method, for you takers out there.

Exchange methods return an ExchangeResponse wrapper, so check status === 'ok' before reading response.data. For the full order surface, including submitOrder() with raw Hyperliquid order fields and submitMarketOrder(), see the Hyperliquid API JavaScript tutorial.

WebSockets: Subscribing to Streams

Event-driven systems are wonderful. Subscribe to state changes (account, position, balance, market data), and you'll receive an asynchronous event when something changes, something you may want to act on. An order fills, a position updates, that's a good time to update local state and upsert any related orders that your system requires (e.g. your passive limit order TP).

Do this right, and you'll only use the REST API for:

  • fetching state when your local state is dirty (first start or WS reconnected and we to make sure we're still up to date).
  • submitting commands (order management, leverage changes, any other write actions on your account)

The WebSocket stream will passively keep us informed on any changes, so we don't need to poll that regularly. If you're interested in learning more about how we do this in our systems, let us know in the comments.

The WebsocketClient is also a JavaScript class. This abstraction layer is your entry point to request the topics you want to subscribe to. It'll manage the full connection life cycle, including authentication, deduping matching topics, handling heartbeats and persisting connections. If the connection drops, heartbeats will detect this quite quickly (configurable): the SDK will emit a reconnecting event to let your system know there's a gap (aka pause/queue order placement locally), before finally emitting a reconnected event when the connection is up and running (and resubscribed), which you can use to trigger any post-reconnect checks such as:

  • query account state (positions, orders) you may have missed
  • reset/amend outdated orders on the exchange
  • resume normal workflows (incl executing queued orders if still relevant).

Usage is simple too (simple than raw WebSockets), instance the class (no keys needed for public data), register event listeners (callbacks), and subscribe to topics.

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

const ws = new WebsocketClient({ testnet: true });

ws.on('message', (event) => {
  if (event.channel === 'l2Book') {
    console.log(event.wsKey, event.data.coin, event.data.levels);
  } else if (event.channel === 'trades') {
    console.log(event.wsKey, event.data);
  }
});

ws.on('response', (event) => {
  console.log('Acknowledgement:', event.wsKey, event.channel, event.data);
});

ws.on('reconnected', ({ wsKey }) => {
  console.log('Reconnected:', wsKey);
});

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

const book = {
  type: 'l2Book',
  coin: 'BTC',
  nSigFigs: 5,
} as const;

const trades = { type: 'trades', coin: 'ETH' } as const;

await ws.subscribe([book, trades]);

// Later, when the feeds are no longer needed:
// await ws.unsubscribe([book, trades]);
// ws.closeAll();
Enter fullscreen mode Exit fullscreen mode

subscribe() resolves once the socket is open and the request has been sent. The server's acknowledgement arrives on the response event, and data arrives on message with the upstream envelope intact plus a wsKey.

Coin identifiers such as BTC, @107 or PURR/USDC pass straight through. If you want to resolve a readable alias first, there is a helper:

const coin = await ws.nameToCoin('HYPE/USDC');
await ws.subscribe({ type: 'trades', coin });
Enter fullscreen mode Exit fullscreen mode

Reconnect timing, ping interval and pong deadline are all configurable through the constructor options if the defaults do not suit your deployment.

Websocket API: Low Latency Order Placement

The WebsocketAPIClient exposes the available REST-like functionality over persisted & managed WebSockets, wrapped around the capabilities of our WebsocketClient.

It will handle the plumbing for you, including mapping your requests (which become upstream WS events) to the received responses (downstream WS events). This unique design in all our SDKs, allows you to benefit from the power of the exchange's WebSocket API, without any of the pains of managing WebSockets. It feels like a REST API.

Example time:

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

const client = new WebsocketAPIClient({ testnet: true });
const mids = await client.getAllMids();
console.log(mids);
Enter fullscreen mode Exit fullscreen mode

Fully typed, awaitable WS API commands, in just 4 lines of code.

Debugging tips

  • Pass a custom logger as the second argument to WebsocketClient to see pings, subscriptions and messages at trace level.
  • RestClient accepts Axios-compatible network options as its second argument, which lets you route requests through a local debugging proxy. Avoid logging signed /exchange bodies.
  • If Hyperliquid ships a new operation before the SDK has a typed wrapper, submitRawInfoRequest() keeps it usable in the meantime.

Next steps

Who we are

We're Siebly. You might know me, Tiago, as the lead dev behind our 10+ massively popular JavaScript SDKs with a decade of usage. Over 4.5 million npm downloads, thousands more every week.

Questions or bug reports are welcome on the GitHub issues tab. We heavily use our own SDKs in our own systems. We also actively monitor changes to the API surface of every partner exchange that we integrate with. This keeps our SDKs maintained, healthy and reliable.

What do you want to learn about next? One of our other supported exchanges, or more on algorithmic trading, or more about integrating with Hyperliquid in JavaScript? Let us know in the comments or get in touch!

Top comments (0)