Skip to content

Order management ​

Use RestClientV5 to place one BTCUSDT perpetual limit order and cancel any unfilled quantity. Run the private order stream alongside these REST commands to follow its status.

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

This walkthrough uses Mainnet, the SDK default. The place command submits a live order that can fill and affect your balance. To use Testnet or demo trading instead, select that environment explicitly in both the REST and WebSocket clients and use matching credentials; see configuration.

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

Before you start ​

  • Use Node.js 24 and install the bybit-api npm package with npm install bybit-api.
  • Use Bybit Mainnet credentials with derivatives trading and account-read permissions, and sufficient account margin for the order.
  • Use a Unified Trading Account with BTCUSDT in one-way position mode (positionIdx: 0). The example does not change your account's position mode or leverage.
  • Use a private .env file excluded from version control for local development, and a secure server-side environment for deployment. Leave BYBITTRACE unset to avoid logging signed requests.

A PostOnly order is cancelled if it would immediately take liquidity. A resting order can fill before cancellation. Cancelling the remaining quantity does not close a position created by a fill.

Configure the order ​

Create a .env file:

dotenv
# Use your own Bybit Mainnet credentials.
BYBIT_API_KEY=example_key
BYBIT_API_SECRET=example_secret
BYBIT_LIMIT_PRICE=60000 # Illustrative USDT price; choose for the current market.
BYBIT_ORDER_QTY=0.001 # Illustrative BTC quantity; current symbol filters apply.

Set the buy price below the current BTCUSDT best bid and specify quantity in BTC. Use decimal strings that satisfy the current price increments, quantity increments and minimum order value from getInstrumentsInfo(). This example sends your values unchanged; Bybit validates them, account margin and dynamic price limits. Prices can move before submission.

Place and observe the order ​

Save this as first-order.ts:

ts
import { RestClientV5 } from 'bybit-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}.`);
  }
  return value;
}

async function printOrderStatus(client: RestClientV5, orderId: string) {
  const query = { category: 'linear' as const, symbol: 'BTCUSDT', orderId };
  // Realtime results include recent closed orders.
  const activeResponse = await client.getActiveOrders(query);
  const order = activeResponse.result.list.find(
    (item) => item.orderId === orderId,
  );
  if (!order) {
    throw new Error(
      'Order not found. Check order history before placing another order.',
    );
  }
  console.log({
    orderId,
    orderStatus: order.orderStatus,
    cumExecQty: order.cumExecQty,
    leavesQty: order.leavesQty,
  });
}

async function main() {
  if (process.env.BYBITTRACE) {
    throw new Error('Unset BYBITTRACE to keep signed requests out of logs.');
  }
  const action = process.argv[2];
  if (!['place', 'status', 'cancel'].includes(action)) {
    throw new Error('Usage: first-order.ts place|status|cancel');
  }

  const client = new RestClientV5(
    {
      key: requiredEnvVar('BYBIT_API_KEY'),
      secret: requiredEnvVar('BYBIT_API_SECRET'),
      throwExceptions: true,
    },
    { timeout: 10_000 },
  );
  const market = { category: 'linear' as const, symbol: 'BTCUSDT' };

  if (action === 'place') {
    const response = await client.submitOrder({
      ...market,
      side: 'Buy',
      orderType: 'Limit',
      price: requiredEnvVar('BYBIT_LIMIT_PRICE'),
      qty: requiredEnvVar('BYBIT_ORDER_QTY'),
      timeInForce: 'PostOnly',
      positionIdx: 0,
    });
    console.log('Order ID:', response.result.orderId);
    console.log(
      'Save this as BYBIT_ORDER_ID. Follow the private WebSocket for order updates.',
    );
    return;
  }

  // Status and cancellation use the ID returned by submitOrder().
  const orderId = requiredEnvVar('BYBIT_ORDER_ID');
  if (action === 'cancel') {
    await client.cancelOrder({ ...market, orderId });
    console.log(
      'Cancellation acknowledged. Follow the private WebSocket for order updates.',
    );
    return;
  }

  await printOrderStatus(client, orderId);
}

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

Start the private order stream in another terminal using the same account. Wait for Private stream authenticated. and Subscribed to order.linear. before continuing. Keep the stream running while you try the commands; the demonstration stops after 60 seconds.

Place the order:

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

The response supplies orderId. Copy the ID printed by the script into .env before running status or cancel:

dotenv
BYBIT_ORDER_ID=a1b2c3d4-5678-4abc-9def-0123456789ab # Use the returned orderId.

Follow the stream's matching orderId updates. Inspect orderStatus, cumExecQty and leavesQty as they change.

Cancel remaining quantity ​

A New or PartiallyFilled order can have remaining quantity to cancel:

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

Submission and cancellation responses acknowledge requests. Follow the private stream to see the resulting order state; cancellation can race with a fill. cumExecQty includes earlier fills even when the final status is Cancelled; resulting positions are separate from the remaining order quantity.

See Bybit's create-order and cancel-order documentation. Use the execution and position topics as well when your application needs fills and position changes, rather than repeatedly querying them through REST.

Recover an interrupted request ​

A timeout or lost response can happen after Bybit accepts a request. The example does not retry submissions or cancellations automatically.

Check matching private events first. If the outcome is still unclear, make one getActiveOrders() request with the saved orderId and the same account. The example exposes this recovery step through status:

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

Use this for diagnosis or recovery, not after every order. Despite its name, the method also returns recent closed orders. If no ID is available, use realtime orders, order history, executions and positions for BTCUSDT to resolve the request using its time, side, price and quantity. Avoid resubmitting until the outcome is resolved.

For older records, or closed orders no longer available after a service restart, use getHistoricOrders(). Set orderStatus: 'Cancelled' when looking for a cancelled order, and check the endpoint's retention rules. Fully cancelled, rejected and deactivated orders have a shorter history window than orders with fills.

An empty result is inconclusive, and history can lag behind order updates. See open and closed orders.

Stopping the process or closing a WebSocket does not cancel an open order.

Authentication · Private order stream · Error handling

Built by Siebly. Open source SDKs for exchange APIs.