Skip to content

Subscribe to private account updates ​

Use WebsocketClient to receive private account updates, including orders, executions, positions and wallet changes. It supports Mainnet, Testnet and demo trading with credentials and topics supported by the selected environment.

This example uses Mainnet and the order.linear topic. It prints order changes for 60 seconds without placing or cancelling orders.

Configure the connection ​

Mainnet is the default. For Testnet or demo trading, configure the stream and order clients for the same environment and use matching credentials; see configuration for the options and supported features.

To run this example, use Node.js 24 with the bybit-api npm package installed. Create a private .env file with Bybit Mainnet credentials and permission to read your orders:

dotenv
# Use your own Bybit Mainnet credentials.
BYBIT_API_KEY=example_key
BYBIT_API_SECRET=example_secret

Keep .env server-side and excluded from version control. Leave BYBITTRACE unset to avoid logging signed requests. The SDK signs the WebSocket authentication request.

Save the following as private-stream.ts:

ts
import { WebsocketClient } from 'bybit-api';

function main() {
  if (process.env.BYBITTRACE) {
    throw new Error('Unset BYBITTRACE to keep signed requests out of logs.');
  }
  const key = process.env.BYBIT_API_KEY;
  const secret = process.env.BYBIT_API_SECRET;
  if (!key || !secret) {
    throw new Error('Set BYBIT_API_KEY and BYBIT_API_SECRET.');
  }

  const ws = new WebsocketClient({
    key,
    secret,
  });
  let stopped = false;

  function stop() {
    if (stopped) {
      return;
    }
    stopped = true;
    clearTimeout(timer);
    process.removeListener('SIGINT', stop);
    process.removeListener('SIGTERM', stop);
    ws.closeAll(true);
    console.log('Private stream closed. This does not cancel orders.');
  }

  // Stop after 60 seconds, including connection and authentication.
  const timer = setTimeout(stop, 60_000);
  process.once('SIGINT', stop);
  process.once('SIGTERM', stop);

  // Install listeners before initiating the subscription.
  ws.on('authenticated', () => {
    console.log('Private stream authenticated.');
  });
  ws.on('response', (message) => {
    if (stopped) {
      return;
    }
    if (message.op === 'subscribe' && message.success === true) {
      console.log('Subscribed to order.linear. Waiting for order changes.');
    } else {
      console.log('Private stream response:', message);
    }
  });
  ws.on('update', (message) => {
    if (stopped) {
      return;
    }
    if (message.topic === 'order.linear' && Array.isArray(message.data)) {
      for (const order of message.data) {
        console.log({
          orderId: order.orderId,
          symbol: order.symbol,
          orderStatus: order.orderStatus,
          cumExecQty: order.cumExecQty,
          leavesQty: order.leavesQty,
        });
      }
    } else {
      console.log('Private stream update:', message);
    }
  });
  // The SDK reconnects, authenticates and restores subscriptions automatically.
  ws.on('exception', (error) => {
    console.error('Private stream error:', error);
  });
  ws.on('reconnect', (event) => {
    console.log('Reconnecting:', event);
  });
  ws.on('reconnected', (event) => {
    console.log('Reconnected:', event);
    // If missed events leave state unresolved, use a targeted REST recovery query.
    // Do not query after each order event or submission.
  });
  ws.on('close', (event) => {
    console.log('Connection closed:', event);
  });

  try {
    // The response event above confirms subscription, not this promise alone.
    void Promise.all(ws.subscribeV5('order.linear', 'linear')).catch(
      (error) => {
        console.error('Private subscription failed:', error);
      },
    );
  } catch (error) {
    console.error('Could not start the private stream:', error);
  }
}

try {
  main();
} catch (error) {
  console.error(error);
  process.exitCode = 1;
}

Run it:

sh
node --env-file=.env private-stream.ts

Observe an order ​

Wait for Private stream authenticated. and Subscribed to order.linear. before starting the order example in another terminal using the same account. Authentication alone does not confirm a subscription.

Each update prints the exchange order ID, symbol, status, cumulative executed quantity and remaining quantity. Match orderId to the ID returned by the order example. Stream and subscription errors are logged with their error objects.

Bybit's order.linear stream emits changes, not an initial snapshot of all orders. Use REST once at startup to load existing state, accounting for events that arrive during that read. Then apply stream updates locally instead of querying REST after each submission or cancellation. A quiet stream can simply mean no orders have changed. See Account State for the startup, event-driven update and recovery pattern.

This example subscribes only to orders. Subscribe to the execution, position and wallet topics your application needs as well; an order update alone does not provide all account state. See account state.

For supported derivatives categories, position updates can trigger SL/TP placement or adjustment when a position opens or increases. Compare the previous and current position size, keyed by account, category, symbol and positionIdx; a position message alone does not establish a new fill. Use a throttled debounce with a maximum wait to combine partial-fill bursts without postponing the follow-up indefinitely.

The subscription uses the category-specific order.linear topic. To consume all supported categories, use order instead; do not combine it with category-specific order topics in the same subscription request. See Bybit's private order stream.

Handle disconnects and shutdown ​

The example runs for 60 seconds, including connection and authentication time. Its timer and Ctrl+C handler close the socket and clear the timer; network errors do not trigger shutdown.

The SDK reconnects, authenticates and restores subscriptions automatically. The example logs reconnect, reconnected, close and error events without interrupting that recovery. A reconnected event confirms the connection is open; the subsequent subscription response confirms order.linear is subscribed again.

Reconnection does not replay missed order events. Reconcile orders with REST after a gap, then continue processing updates. Closing the stream does not cancel open orders.

Bybit can emit two Filled order updates when a fill races with a cancellation. Track cumulative execution by order ID, or use execution records for individual fills.

WebSockets · Order management · Production guidance

Built by Siebly. Open source SDKs for exchange APIs.