Skip to content

Order management ​

Use MainClient to place one LIMIT_MAKER order and cancel its remaining quantity. Run the private user data stream alongside these REST commands to see the order accepted, filled or cancelled.

The order script makes one REST request per command. In a persistent application, keep the user data stream connected and track orders locally. Use REST reads to initialize state, recover missed updates or resolve uncertain outcomes, not after every order.

LIMIT_MAKER is post-only: Binance rejects it if it would immediately match as a taker. An accepted resting order can still fill, including before you cancel it.

This walkthrough uses production Spot markets. The place command submits a real order. To use Spot Testnet instead, set testnet: true on both clients and use Testnet credentials.

Before placing orders, use the authenticated account read to check balances and account access.

Set up ​

Use Node.js 24 and install the binance npm package in a server-side project:

sh
npm install binance

Use production Spot API credentials with account-read and trading permissions. Keep credentials server-side and keep your system clock synchronized.

Create a local .env file, exclude it from version control, and fill in your values:

dotenv
# Illustrative values; use your own Spot credentials.
BINANCE_API_KEY=example_key
BINANCE_API_SECRET=example_secret
BINANCE_SYMBOL=BTCUSDT # Spot market
BINANCE_PRICE=60000 # Example USDT limit price; choose for the current market
BINANCE_QUANTITY=0.001 # BTC

Choose a buy price below the current best ask and a quantity that fits your Spot balance. Check the symbol's price increment, quantity increment and minimum order value using exchange information. Binance validates these rules at submission.

A custom client order ID is optional and is not needed for this example. Status and cancellation use the exchange order ID returned after placement.

Save the example ​

Save this as first-order.ts. Node.js 24 can run it directly:

ts
import { MainClient } from 'binance';

// Subscribe to account WebSocket updates before submitting orders.
// Use the status command only when those updates leave an outcome unclear.

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

function getPositiveNumberEnvVar(name: string): number {
  const value = Number(requiredEnvVar(name));
  if (!Number.isFinite(value) || value <= 0) {
    throw new Error(`${name} must be a positive number.`);
  }
  return value;
}

async function main() {
  const action = process.argv[2];
  if (!['place', 'status', 'cancel'].includes(action)) {
    throw new Error('Usage: first-order.ts place|status|cancel');
  }

  const client = new MainClient(
    {
      api_key: requiredEnvVar('BINANCE_API_KEY'),
      api_secret: requiredEnvVar('BINANCE_API_SECRET'),
    },
    { timeout: 10_000 },
  );
  const symbol = requiredEnvVar('BINANCE_SYMBOL');

  if (action === 'place') {
    const order = await client.submitNewOrder({
      symbol,
      side: 'BUY',
      type: 'LIMIT_MAKER',
      price: getPositiveNumberEnvVar('BINANCE_PRICE'),
      quantity: getPositiveNumberEnvVar('BINANCE_QUANTITY'),
    });
    console.log(
      'Submission acknowledged. Save BINANCE_ORDER_ID:',
      order.orderId,
    );
    return;
  }

  if (action === 'cancel') {
    await client.cancelOrder({
      symbol,
      orderId: getPositiveNumberEnvVar('BINANCE_ORDER_ID'),
    });
    console.log(
      'Cancellation acknowledged. Follow the account WebSocket for order updates.',
    );
    return;
  }

  const order = await client.getOrder({
    symbol,
    orderId: getPositiveNumberEnvVar('BINANCE_ORDER_ID'),
  });
  console.log({
    orderId: order.orderId,
    status: order.status,
    executedQuantity: order.executedQty,
    originalQuantity: order.origQty,
  });
}

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;
});

The example uses numeric price and quantity fields for a post-only buy order. It does not retry, poll or cancel automatically.

Place and observe the order ​

Start the private user data stream in another terminal with the same Spot account. Wait for Spot user data subscribed. before continuing. The demonstration stops after 60 seconds; keep it running while you try the commands.

Place the order:

sh
node --env-file=.env first-order.ts place

The script prints the exchange order ID. Save it in .env for status and cancellation:

dotenv
BINANCE_ORDER_ID=123456789 # Use the returned orderId

Use the same Spot account and symbol throughout.

Submission acknowledgement means Binance accepted the request, not that the order filled. A resting order normally reports NEW; an order that has traded may report PARTIALLY_FILLED or FILLED.

Follow the stream's executionReport events for the saved order ID. They report status changes and fills without additional REST requests.

Cancel remaining quantity ​

If the order still has open quantity, request cancellation using the saved BINANCE_ORDER_ID:

sh
node --env-file=.env first-order.ts cancel

Watch the private stream for the cancellation or fill. Use the same exchange order ID throughout. Expect CANCELED if cancellation wins the race with execution. FILLED means there is nothing left to cancel. A canceled order may still have a nonzero executed quantity from earlier partial fills; cancellation does not reverse those trades.

Resolve failed or interrupted requests ​

A post-only rejection can mean the price would immediately trade. Other rejections can indicate filters, funds or permissions. A timeout or lost response can also happen after Binance accepts the order. The example logs the error object and does not automatically retry writes.

Check matching private events first. If the outcome remains unclear and you have the exchange order ID, use the one-shot status command:

sh
node --env-file=.env first-order.ts status

This is a diagnostic read, not a step to repeat after every order. If neither the response nor the stream provides an ID, inspect open orders, order history and trade history for the same account and symbol before submitting again. An unavailable or not-found response does not establish whether the order was accepted. Save the confirmed order ID for subsequent status and cancellation commands.

A connection failure or process exit does not cancel an open order. Keep the saved identifiers for subsequent status and cancel commands. When using Spot Testnet, resets can remove account and order history; see Spot Testnet information.

Private order updates · Order recovery · Trading endpoints · Symbol filters

Built by Siebly. Open source SDKs for exchange APIs.