Skip to main content

Hyperliquid cloid and scheduleCancel in Node.js: retry-safe orders and a dead man's switch

Safe order retries after timeouts and a scheduleCancel heartbeat with @siebly/hyperliquid-api

Updated 8 min readMarkdown

Two things go wrong for almost every automated Hyperliquid integration sooner or later. A request to place an order times out and you don't know whether the order exists, so you either resend it (and maybe double your position) or skip it (and maybe miss it). Or the process dies while orders are resting, and nobody is around to cancel them. Hyperliquid has a tool for each: the client order ID (cloid) and the scheduleCancel action, often called a dead man's switch. This guide shows both in Node.js with @siebly/hyperliquid-api.

What a Hyperliquid cloid is

A cloid is an optional ID you attach to an order when you place it. Hyperliquid's exchange endpoint docs define it as a 128-bit hex string, for example 0x1234567890abcdef1234567890abcdef: 0x followed by 32 hex characters. It's not a free-text label, so "my-order-1" won't work.

The useful part is that you choose it before the request goes out. The exchange order ID (oid) only comes back in the response, and a timed-out response is exactly when you don't have it. With a cloid you can still look the order up, cancel it, or amend it.

Generate one per order with Node's built-in crypto module:

import { randomBytes } from 'node:crypto';

function newCloid() {
  return `0x${randomBytes(16).toString('hex')}`;
}

Store the cloid (in your database, a file, wherever your process keeps state) before you send the order. If the process restarts mid-request, that saved value is how you find out what happened.

Placing an order with a cloid

In the SDK the field is called clientOrderId on the helper methods. Use a testnet API wallet while you try this out.

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

const client = new RestClient({
  privateKey: process.env.HYPERLIQUID_API_WALLET_KEY,
  accountAddress: process.env.HYPERLIQUID_ACCOUNT_ADDRESS,
  testnet: true,
});

const cloid = newCloid();

const result = await client.submitLimitOrder({
  symbol: 'BTC',
  side: 'buy',
  size: '0.001',
  price: '50000',
  postOnly: true,
  clientOrderId: cloid,
});

if (result.status === 'ok') {
  console.log(result.response.data.statuses);
  // e.g. [ { resting: { oid: 123456789 } } ] or [ { error: '...' } ]
}

Note the two levels of failure. If Hyperliquid rejects the whole action (bad signature, unknown API wallet and so on), the SDK throws a HyperliquidApiError. If the action is accepted but one order is refused (tick size, minimum notional, post-only would cross), the call succeeds and that order's entry in statuses is { error: '...' }. Check both.

Recovering from a timeout without double orders

A timeout or dropped connection is different from a rejection: the order may or may not have reached the book. Don't resend blindly. Ask Hyperliquid about the cloid first. The info endpoint accepts either an oid or a cloid for orderStatus, and the SDK passes either through getOrderStatus():

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

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

async function placeLimitOnce(cloid) {
  try {
    return await client.submitLimitOrder({
      symbol: 'BTC',
      side: 'buy',
      size: '0.001',
      price: '50000',
      postOnly: true,
      clientOrderId: cloid,
    });
  } catch (error) {
    if (error instanceof HyperliquidApiError) {
      // Hyperliquid answered and rejected the action. Nothing reached the book.
      throw error;
    }

    // Timeout or network error: outcome unknown. Look it up before resending.
    await sleep(2000);
    const status = await client.getOrderStatus({ oid: cloid });

    if (status.status === 'order') {
      console.log('Order exists:', status.order.status, 'oid', status.order.order.oid);
      return status;
    }

    // { status: 'unknownOid' }: the order was never placed. Resend with the SAME cloid.
    return placeLimitOnce(cloid);
  }
}

Two details matter here. Reuse the same cloid on the retry, never a fresh one, so a second lookup still finds a single order. And give the first request a moment to land before you query; an order that is still in flight can briefly show as unknownOid. In production you'd also cap the number of retries rather than recursing indefinitely.

When the status comes back as an order, status.order.status tells you where it ended up: open, filled, canceled, or one of the rejection reasons such as tickRejected, minTradeNtlRejected or badAloPxRejected.

Cancelling and amending by cloid

You don't need the oid for follow-up actions either. Cancel by cloid with cancelOrdersByClientOrderId():

const cancel = await client.cancelOrdersByClientOrderId({
  cancels: [{ asset: 'BTC', cloid }],
});

if (cancel.status === 'ok') {
  console.log(cancel.response.data.statuses); // [ 'success' ] or [ { error: '...' } ]
}

The SDK resolves 'BTC' to the numeric asset ID for you, so you don't have to look up the index in meta first.

Amending works the same way: Hyperliquid's modify action takes either an oid or a cloid. A modify cancels the old order and places a new one with a new oid, so keeping the same cloid on the replacement keeps your bookkeeping simple:

await client.modifyOrder({
  oid: cloid,
  order: {
    a: 'BTC',
    b: true,
    p: '49500',
    s: '0.001',
    r: false,
    t: { limit: { tif: 'Alo' } },
    c: cloid,
  },
});

scheduleCancel: a dead man's switch for open orders

The scheduleCancel action tells Hyperliquid to cancel all of your open orders at a time you choose. You keep pushing that time forward while your process is healthy. If the process crashes, hangs or loses its network, the refreshes stop, the deadline passes, and the exchange cancels the orders for you.

The rules, from the exchange endpoint docs:

  • The time is a millisecond timestamp and must be at least 5 seconds in the future.

  • Sending the action without a time removes the scheduled cancel.

  • Each time the deadline is actually reached and orders are cancelled, a trigger count goes up. The maximum is 10 triggers per day, reset at 00:00 UTC.

  • Orders cancelled this way show the status scheduledCancel in orderStatus, so you can tell them apart from your own cancels.

In the SDK the method is setCancelAllAfter():

const WINDOW_MS = 60_000;  // cancel everything 60 s after the last heartbeat
const REFRESH_MS = 20_000; // heartbeat every 20 s

function startDeadMansSwitch() {
  const refresh = async () => {
    try {
      await client.setCancelAllAfter({ time: Date.now() + WINDOW_MS });
    } catch (error) {
      console.error('scheduleCancel refresh failed:', error);
    }
  };

  void refresh();
  const timer = setInterval(refresh, REFRESH_MS);

  return async function stop(clearSchedule) {
    clearInterval(timer);
    if (clearSchedule) {
      await client.setCancelAllAfter(); // no time: remove the scheduled cancel
    }
  };
}

const stop = startDeadMansSwitch();

process.on('SIGTERM', async () => {
  // Planned handover to a new process: keep the orders, drop the deadline.
  await stop(true);
  process.exit(0);
});

Choosing the window

  • Refresh well inside the window. With a 60-second window and a 20-second refresh, one slow or failed refresh doesn't cancel anything; a process that stays stuck for a minute does.

  • Every refresh is a signed exchange action and counts towards your address's request budget like any other action, so a refresh every 15 to 30 seconds is plenty. Refreshing every second buys nothing.

  • The 10-per-day limit only counts deadlines that actually fire. Refreshing doesn't use it up, but a flapping process that keeps letting the deadline lapse will.

  • Decide what a clean shutdown means for you. If you want orders gone when the process stops, simply stop refreshing and let the deadline fire (or cancel explicitly). If a new process is taking over the same orders, clear the schedule as above and have the new process start its own heartbeat.

  • The cancel applies to all open orders on the account the action is signed for (pass vaultAddress in the client options for a subaccount or vault). If several processes trade the same account, any one of them letting its deadline lapse cancels everyone's orders, so give one process clear ownership of the switch.

Putting the two together

A practical pattern for a long-running Node.js process:

  • On start-up, begin the dead man's switch before placing any order.

  • For every order, generate and save a cloid, then place it.

  • On any timeout, look the cloid up with getOrderStatus() and resend with the same cloid only on unknownOid.

  • Cancel and amend by cloid, so your state never depends on having seen a response.

  • After a restart, read your saved cloids and query each one before you rebuild. Any that show scheduledCancel were cancelled by the switch while the process was down; compare the rest with getOpenOrders().

Further reading

The Hyperliquid JavaScript tutorial covers API wallet setup, account state, orders and WebSockets end to end, and the Hyperliquid SDK docs list every REST and WebSocket method. If your API wallet suddenly stops signing, see Hyperliquid API wallet expiry, pruning and rotation in Node.js. The SDK is open source under the MIT licence, from the same maintainers as the binance, bybit-api and okx-api packages, with over 4.5 million npm downloads across 10+ SDKs.


Originally published on the Siebly blog. The SDK is open source on GitHub, and the orders guide in the docs covers placing, amending and cancelling orders.

No comments yet. Be the first to comment.