Skip to content

Order management ​

Place a BTC perpetual limit order with RestClient and cancel any remaining quantity. Run the account stream alongside these REST commands to follow order updates and fills.

The example uses separate commands to place, cancel and check an order. In a persistent application, keep the account stream connected and track orders and fills locally. Use REST reads for startup, recovery and unresolved requests rather than after every order.

This walkthrough uses Mainnet. The place command submits a real order. To use Testnet instead, set testnet: true on the REST and WebSocket clients and use the corresponding account and signer.

A post-only order is rejected if it would immediately take liquidity. Once resting, it can fill before cancellation. Cancelling an order does not reverse fills or close an existing position.

Before placing orders, use the account read example to inspect positions. Keep account reads, order requests and subscriptions on the same network.

Set up ​

Use Node.js 24, a funded Hyperliquid account and an API wallet authorized for that account. See API wallets and account addresses.

Install the @siebly/hyperliquid-api npm package:

sh
npm install @siebly/hyperliquid-api

Create a private .env file and add it to .gitignore:

dotenv
HYPERLIQUID_ACCOUNT_ADDRESS=0x1111111111111111111111111111111111111111 # Example managed account
HYPERLIQUID_PRIVATE_KEY=0x2222222222222222222222222222222222222222222222222222222222222222 # Public example key; use your API wallet key
HYPERLIQUID_ORDER_SIZE=0.001 # BTC; illustrative size
HYPERLIQUID_LIMIT_PRICE=60000 # USD; adjust for the current market

The address and key above are illustrative. Use the authorized API wallet's key and the account it manages. Signing runs locally in Node.js.

Set a size in BTC and a buy price below the current BTC best bid. The example passes both values as decimal strings; the exchange applies its current tick and lot size rules.

Save the example ​

Save the following as orders.mts. Node.js 24 runs this TypeScript file directly.

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

// Subscribe to the matching account WebSocket stream before submitting orders.
// Use its order and fill updates for ongoing state. The explicit status command
// is a one-shot diagnostic for unresolved state, not a post-submit/cancel step.

function requiredEnvVar(name: string): string {
  const value = process.env[name];
  if (!value) {
    throw new Error(`Set ${name} in your .env file.`);
  }
  return value;
}

function createClient(action: string): RestClient {
  const accountAddress = requiredEnvVar('HYPERLIQUID_ACCOUNT_ADDRESS');
  // Status queries do not require a signing key.
  const privateKey =
    action === 'status' ? undefined : requiredEnvVar('HYPERLIQUID_PRIVATE_KEY');
  return new RestClient(
    { accountAddress, privateKey },
    { timeout: 10_000 },
  );
}

async function placeOrder(client: RestClient) {
  const result = await client.submitLimitOrder({
    symbol: 'BTC',
    side: 'buy',
    price: requiredEnvVar('HYPERLIQUID_LIMIT_PRICE'),
    size: requiredEnvVar('HYPERLIQUID_ORDER_SIZE'),
    postOnly: true,
  });

  // Check the individual order result, not just the HTTP response.
  if (result.status !== 'ok') {
    console.error(result);
    throw new Error('Order was not accepted.');
  }
  const order = result.response.data.statuses[0];
  if (!order || 'error' in order) {
    console.error(result);
    throw new Error('Order was rejected.');
  }
  const orderId = 'resting' in order ? order.resting.oid : order.filled.oid;
  console.log('Order result:', 'resting' in order ? 'resting' : 'filled');
  console.log('HYPERLIQUID_ORDER_ID=' + orderId);
}

async function main() {
  const action = process.argv[2];
  if (!['place', 'status', 'cancel'].includes(action)) {
    throw new Error('Usage: orders.mts place|status|cancel');
  }
  const client = createClient(action);

  if (action === 'place') {
    await placeOrder(client);
    return;
  }

  const orderId = Number(requiredEnvVar('HYPERLIQUID_ORDER_ID'));
  if (!Number.isSafeInteger(orderId) || orderId <= 0) {
    throw new Error(
      'HYPERLIQUID_ORDER_ID must be the numeric ID returned by the exchange.',
    );
  }
  if (action === 'status') {
    const status = await client.getOrderStatus({ oid: orderId });
    if (status.status === 'unknownOid') {
      console.log('Order not found for this account and order ID.');
      process.exitCode = 1;
      return;
    }
    console.log(
      'Order ID:',
      status.order.order.oid,
      'Status:',
      status.order.status,
    );
    return;
  }

  const result = await client.cancelOrders({
    cancels: [{ a: 'BTC', o: orderId }],
  });
  if (
    result.status !== 'ok' ||
    result.response.data.statuses[0] !== 'success'
  ) {
    console.error(result);
    throw new Error(
      'Cancellation was not confirmed. The order may already have filled; check received account WebSocket updates.',
    );
  }
  console.log(
    'Cancellation accepted. Follow the account WebSocket for order updates.',
  );
}

main().catch((error: unknown) => {
  console.error(error);
  console.error(
    'Use account WebSocket updates to resolve the outcome. If still unknown, make a targeted REST query before deciding whether to retry.',
  );
  process.exitCode = 1;
});

Place the order ​

Start the account order stream in another terminal for the same account. Wait for the server subscription acknowledgements for orderUpdates and userFills. Keep it running while you try the commands; the demonstration stops after 60 seconds.

sh
node --env-file=.env orders.mts place

The script submits one order and prints its exchange-assigned numeric ID. Save the printed HYPERLIQUID_ORDER_ID line in .env for the following commands, for example:

dotenv
HYPERLIQUID_ORDER_ID=123456789 # Use the ID returned by your order

postOnly: true selects the exchange's ALO order type. A successful response contains an individual result: resting, filled or error. The script checks that result rather than treating a fulfilled request as proof of acceptance.

Follow matching orderUpdates and userFills events as the order changes. The submission response can contain useful immediate results, while the stream continues to report later changes.

Cancel remaining quantity ​

If the order still has open quantity, request cancellation:

sh
node --env-file=.env orders.mts cancel

Watch the stream for the resulting order update or fill. Cancellation can race with execution, so the final status may be filled. The command does not query REST before or after cancelling.

Recover an interrupted request ​

A timeout can occur after the exchange accepts a request. Check matching orderUpdates and userFills events first. If the outcome is still unclear, use the one-shot status command:

sh
node --env-file=.env orders.mts status

This calls getOrderStatus() with the saved ID and account address, without a signing key. Use it for diagnosis or recovery, not after every submission. If no ID is available, inspect the account's open orders, order history and fills to resolve the outcome before resubmitting. The example does not retry writes.

unknownOid means no order was found for that account and ID. Check order and fill history to resolve an uncertain submission. Closing the script or a WebSocket does not cancel an open order.

Account order updates · Order results · Production usage

Built by Siebly. Open source SDKs for exchange APIs.