Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/tiagosiebler/bybit-api/llms.txt

Use this file to discover all available pages before exploring further.

WebsocketAPIClient wraps the lower-level WebsocketClient.sendWSAPIRequest() method with intuitive, strongly-typed methods for order management over WebSocket. Every method returns a Promise that resolves with the exchange’s typed response — making it a drop-in replacement for the REST order API with significantly lower round-trip latency.

Installation & Import

npm install bybit-api
import { WebsocketAPIClient } from 'bybit-api';

Constructor

const client = new WebsocketAPIClient(options?, logger?);
options
WSClientConfigurableOptions & Partial<WSAPIClientConfigurableOptions>
Accepts all WSClientConfigurableOptions fields (same as WebsocketClient) plus the following WebsocketAPIClient-specific option:
logger
DefaultLogger
Custom logger instance. Defaults to the SDK’s built-in console logger.

Instantiation examples

import { WebsocketAPIClient } from 'bybit-api';

const client = new WebsocketAPIClient({
  key: 'YOUR_API_KEY',
  secret: 'YOUR_API_SECRET',
});
Authentication is handled automatically. The SDK opens and authenticates the v5PrivateTrade WebSocket connection the first time you call any order method. Call client.getWSClient().connectWSAPI() beforehand to pre-warm the connection and reduce first-call latency.

Methods

getWSClient()

Returns the underlying WebsocketClient instance. Use this to attach custom event listeners, access connection state, or call subscribeV5() for market-data streams.
getWSClient(): WebsocketClient
const wsClient = client.getWSClient();

wsClient.on('update', (data) => {
  console.log('Market data:', data);
});

// You can also subscribe to public/private topics on the same client
wsClient.subscribeV5('orderbook.50.BTCUSDT', 'linear');

setTimeOffsetMs(offset)

Manually adjust the time offset (in milliseconds) used when generating request timestamps and authentication signatures. Useful when the SDK detects clock drift that prevents valid signatures.
setTimeOffsetMs(newOffset: number): void
newOffset
number
required
Time offset in milliseconds to add to Date.now() when building signed requests.

submitNewOrder(params)

Submit a new order over the WebSocket API.
submitNewOrder(
  params: OrderParamsV5,
): Promise<WSAPIResponse<OrderResultV5, 'order.create'>>
params
OrderParamsV5
required
Full order parameters. See the Types reference for the complete OrderParamsV5 interface.Key fields:
FieldTypeRequiredDescription
categoryCategoryV5'spot' | 'linear' | 'inverse' | 'option'
symbolstringTrading pair, e.g. 'BTCUSDT'
side'Buy' | 'Sell'Order side
orderType'Market' | 'Limit'Order type
qtystringOrder quantity as string
pricestringLimit price (required for Limit orders)
timeInForceOrderTimeInForceV5'GTC' | 'IOC' | 'FOK' | 'PostOnly'
orderLinkIdstringClient-defined order ID
takeProfitstringTake-profit price
stopLossstringStop-loss price
reduceOnlybooleanReduce-only flag
positionIdxnumberPosition index (hedge mode)
const response = await client.submitNewOrder({
  category: 'linear',
  symbol: 'BTCUSDT',
  side: 'Buy',
  orderType: 'Limit',
  qty: '0.01',
  price: '30000',
  timeInForce: 'GTC',
  orderLinkId: 'my-order-001',
});

console.log('Order ID:', response.data.orderId);
console.log('retCode:', response.retCode); // 0 = success

amendOrder(params)

Amend an existing open order.
amendOrder(
  params: AmendOrderParamsV5,
): Promise<WSAPIResponse<OrderResultV5, 'order.amend'>>
params
AmendOrderParamsV5
required
FieldTypeRequiredDescription
categoryCategoryV5Instrument category
symbolstringTrading pair
orderIdstringExchange order ID (orderId or orderLinkId required)
orderLinkIdstringClient order ID
qtystringNew quantity
pricestringNew price
takeProfitstringNew take-profit
stopLossstringNew stop-loss
triggerPricestringNew trigger price
const response = await client.amendOrder({
  category: 'linear',
  symbol: 'BTCUSDT',
  orderId: 'abc123',
  price: '29500',
  qty: '0.02',
});

cancelOrder(params)

Cancel an existing open order.
cancelOrder(
  params: CancelOrderParamsV5,
): Promise<WSAPIResponse<OrderResultV5, 'order.cancel'>>
params
CancelOrderParamsV5
required
FieldTypeRequiredDescription
categoryCategoryV5Instrument category
symbolstringTrading pair
orderIdstringExchange order ID (orderId or orderLinkId required)
orderLinkIdstringClient order ID
orderFilterOrderFilterV5Order filter override
const response = await client.cancelOrder({
  category: 'linear',
  symbol: 'BTCUSDT',
  orderId: 'abc123',
});

batchSubmitOrders(category, orders)

Submit multiple orders in a single WS API request.
batchSubmitOrders(
  category: 'option' | 'linear',
  orders: BatchOrderParamsV5[],
): Promise<
  WSAPIResponse<
    { list: BatchCreateOrderResultV5[] },
    'order.create-batch',
    BatchOrdersRetExtInfoV5
  >
>
category
'option' | 'linear'
required
The instrument category. Only 'option' and 'linear' are supported for batch operations.
orders
BatchOrderParamsV5[]
required
Array of order parameters. Each object matches BatchOrderParamsV5 (similar to OrderParamsV5 but without category).
const response = await client.batchSubmitOrders('linear', [
  {
    symbol: 'BTCUSDT',
    side: 'Buy',
    orderType: 'Limit',
    qty: '0.01',
    price: '29000',
    timeInForce: 'GTC',
    orderLinkId: 'batch-1',
  },
  {
    symbol: 'ETHUSDT',
    side: 'Sell',
    orderType: 'Limit',
    qty: '0.1',
    price: '2000',
    timeInForce: 'GTC',
    orderLinkId: 'batch-2',
  },
]);

for (const order of response.data.list) {
  console.log('Placed:', order.orderId, order.orderLinkId);
}

batchAmendOrder(category, orders)

Amend multiple orders in a single WS API request.
batchAmendOrder(
  category: 'option' | 'linear',
  orders: BatchAmendOrderParamsV5[],
): Promise<
  WSAPIResponse<
    { list: BatchAmendOrderResultV5[] },
    'order.amend-batch',
    BatchOrdersRetExtInfoV5
  >
>
category
'option' | 'linear'
required
Instrument category.
orders
BatchAmendOrderParamsV5[]
required
Array of amend parameters (symbol, orderId/orderLinkId, and updated fields).
await client.batchAmendOrder('linear', [
  { symbol: 'BTCUSDT', orderId: 'abc123', price: '28000' },
  { symbol: 'ETHUSDT', orderLinkId: 'batch-2', qty: '0.2' },
]);

batchCancelOrder(category, orders)

Cancel multiple orders in a single WS API request.
batchCancelOrder(
  category: 'option' | 'linear',
  orders: BatchCancelOrderParamsV5[],
): Promise<
  WSAPIResponse<
    { list: BatchCancelOrderResultV5[] },
    'order.cancel-batch',
    BatchOrdersRetExtInfoV5
  >
>
category
'option' | 'linear'
required
Instrument category.
orders
BatchCancelOrderParamsV5[]
required
Array of cancel parameters. Each requires symbol and either orderId or orderLinkId.
await client.batchCancelOrder('linear', [
  { symbol: 'BTCUSDT', orderId: 'abc123' },
  { symbol: 'ETHUSDT', orderLinkId: 'batch-2' },
]);

WSAPIResponse Structure

Every order method resolves with a WSAPIResponse<TData, TOperation> object.
interface WSAPIResponse<
  TResponseData extends object = object,
  TOperation extends WSAPIOperation = WSAPIOperation,
  TResponseExtInfo = {},
> {
  wsKey: WsKey;
  reqId: string;
  retCode: 0 | number;
  retMsg: 'OK' | string;
  op: TOperation;
  data: TResponseData;
  retExtInfo: TResponseExtInfo;
  header?: {
    'X-Bapi-Limit': string;
    'X-Bapi-Limit-Status': string;
    'X-Bapi-Limit-Reset-Timestamp': string;
    Traceid: string;
    Timenow: string;
  };
  connId: string;
}
wsKey
WsKey
The connection key that handled this request.
reqId
string
Auto-generated request ID used to correlate the response.
retCode
number
Return code. 0 indicates success. Non-zero values indicate errors — the promise rejects in this case.
retMsg
string
Human-readable message. 'OK' on success.
op
WSAPIOperation
The operation that produced this response (e.g. 'order.create').
data
object
Response payload. For single-order operations this is OrderResultV5. For batch operations it is { list: BatchCreateOrderResultV5[] } etc.
retExtInfo
object
Extended info object. Populated for batch operations with per-order status codes via BatchOrdersRetExtInfoV5.
connId
string
The WebSocket connection ID from Bybit.

Supported WS API Operations

The WSAPIOperation type and WS_API_Operations array enumerate every supported command.
// Type
export type WSAPIOperation =
  | 'order.create'
  | 'order.amend'
  | 'order.cancel'
  | 'order.create-batch'
  | 'order.amend-batch'
  | 'order.cancel-batch';

// Runtime array (useful for validation)
export const WS_API_Operations: WSAPIOperation[] = [
  'order.create',
  'order.amend',
  'order.cancel',
  'order.create-batch',
  'order.amend-batch',
  'order.cancel-batch',
];

Error Handling

When the exchange returns a non-zero retCode, the promise is rejected (not resolved). Always wrap calls in try/catch or use .catch().
try {
  const result = await client.submitNewOrder({
    category: 'linear',
    symbol: 'BTCUSDT',
    side: 'Buy',
    orderType: 'Limit',
    qty: '0.01',
    price: '1', // absurdly low — will be rejected
    timeInForce: 'GTC',
  });
} catch (err) {
  // err.retCode contains the Bybit error code
  // err.retMsg contains the error message
  console.error('Order failed:', err.retCode, err.retMsg);
}
The promise is also rejected if the WebSocket connection closes before a response is received. Implement reconnect handling in your on('exception', ...) listener.

Full End-to-End Example

import { WebsocketAPIClient } from 'bybit-api';

async function main() {
  const client = new WebsocketAPIClient({
    key: process.env.BYBIT_KEY!,
    secret: process.env.BYBIT_SECRET!,
  });

  // Optional: pre-warm connection to reduce first-order latency
  await client.getWSClient().connectWSAPI();

  // Place an order
  const order = await client.submitNewOrder({
    category: 'linear',
    symbol: 'BTCUSDT',
    side: 'Buy',
    orderType: 'Limit',
    qty: '0.01',
    price: '28000',
    timeInForce: 'GTC',
    orderLinkId: `order-${Date.now()}`,
  });

  console.log('Created:', order.data.orderId);

  // Amend it
  await client.amendOrder({
    category: 'linear',
    symbol: 'BTCUSDT',
    orderId: order.data.orderId,
    price: '27500',
  });

  console.log('Amended');

  // Cancel it
  await client.cancelOrder({
    category: 'linear',
    symbol: 'BTCUSDT',
    orderId: order.data.orderId,
  });

  console.log('Cancelled');
}

main().catch(console.error);

WebsocketClient

Lower-level WebSocket client with sendWSAPIRequest() and subscription methods.

Types Reference

OrderParamsV5, WSAPIResponse, and all related type definitions.

Enums & Constants

WSAPIOperation values and WS_API_Operations array.

RestClientV5

Full REST API reference as an alternative to WS order management.

Build docs developers (and LLMs) love