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.

Every response from the Bybit REST API includes a retCode field. A value of 0 means the request succeeded. Any other value indicates an API-level error, with additional detail in the retMsg field. Network-level failures and HTTP errors (non-2xx status codes) are surfaced as rejected promises so you can handle both layers cleanly with try/catch.

REST Error Handling Pattern

The SDK wraps axios and normalises errors. By default, a successful HTTP response (status 200) with a non-zero retCode is not thrown automatically — it is returned as a resolved value. This lets you inspect retCode on your own terms.
import { RestClientV5 } from 'bybit-api';

const client = new RestClientV5({ key: 'xxx', secret: 'yyy' });

async function placeOrder() {
  try {
    const result = await client.submitOrder({
      category: 'linear',
      symbol: 'BTCUSDT',
      orderType: 'Market',
      qty: '0.001',
      side: 'Buy',
    });

    if (result.retCode !== 0) {
      // API-level error: request reached Bybit but was rejected
      console.error(`API error ${result.retCode}: ${result.retMsg}`);
      return;
    }

    console.log('Order placed:', result.result);
  } catch (err) {
    // Network error or non-200 HTTP response
    console.error('Request failed:', err);
  }
}
Set throwExceptions: true in the client options to make the SDK automatically throw for non-zero retCode values. This simplifies handlers when you prefer a uniform try/catch flow.

Automatic Exception Throwing

const client = new RestClientV5({
  key: 'xxx',
  secret: 'yyy',
  throwExceptions: true,
});

try {
  const result = await client.submitOrder({ /* ... */ });
  console.log('Order placed:', result.result);
} catch (err) {
  // Both network errors and API errors land here
  console.error('Error:', err);
}

The API_ERROR_CODE Enum

The SDK exports API_ERROR_CODE, a typed constant map of known Bybit error codes. Using these constants prevents hard-coded magic numbers in your error handlers and enables IDE autocomplete.
import { API_ERROR_CODE } from 'bybit-api';

if (result.retCode === API_ERROR_CODE.V5_INSUFFICIENT_BALANCE) {
  console.warn('Not enough balance to execute the order.');
}

Key Error Codes

ConstantValueMeaning
SUCCESS0Request succeeded
PARAMS_MISSING_OR_WRONG10001Bad request — wrong or missing parameter values; also reused for several unchanged-state errors
INVALID_API_KEY_OR_PERMISSIONS10003API key is invalid or lacks required permissions
SIGNATURE_NOT_VALID10004Request signature could not be verified
INCORRECT_API_KEY_PERMISSIONS10005API key exists but does not have the required permission scope
INCORRECT_API_REQUEST_IP10010Request IP is not in the API key’s IP whitelist
ACCOUNT_NOT_UNIFIED10020Account must be upgraded to Unified Margin to use this endpoint
COMPLIANCE_RULES_TRIGGERED10024Compliance rules prevented this action
UNKNOWN_ERROR12000Unspecified server-side error
V5_ORDER_NOT_FOUND110001The specified order does not exist (V5 API)
V5_INSUFFICIENT_BALANCE110007Insufficient balance for the requested operation (V5 API)
V5_API_KEY_PERMISSION_DENIED10005API key permission denied (V5 API)
V5_CROSS_ISOLATED_MARGIN_NOT_CHANGED110026Margin mode was not changed because it is already set to the requested value
V5_LEVERAGE_NOT_CHANGED110043Leverage was not changed because it already matches the requested value
QTY_EXCEEDS_MAX_LIMIT130006Order quantity exceeds the maximum allowed for this contract
ORDER_COST_NOT_AVAILABLE130021Insufficient available order cost (linear)
TRANSFER_ID_EXISTS131214A transfer with this ID already exists
NOT_SUPPORTED_FOR_SUBACCOUNTS131003Operation is not supported for sub-accounts
Some error codes (such as 10001) are reused by Bybit across multiple scenarios — for example, unchanged-state errors for TP/SL, risk ID, and auto-add-margin all map to 10001. Always check retMsg alongside retCode for a precise diagnosis.

Typed Error Handling by Code

Combining API_ERROR_CODE with a switch statement keeps error handling readable and exhaustive:
import { RestClientV5, API_ERROR_CODE } from 'bybit-api';

const client = new RestClientV5({ key: 'xxx', secret: 'yyy' });

async function getBalance() {
  try {
    const res = await client.getWalletBalance({ accountType: 'UNIFIED' });

    switch (res.retCode) {
      case API_ERROR_CODE.SUCCESS:
        return res.result;

      case API_ERROR_CODE.INVALID_API_KEY_OR_PERMISSIONS:
        throw new Error('Check your API key and its permission settings.');

      case API_ERROR_CODE.INCORRECT_API_REQUEST_IP:
        throw new Error('Your IP is not whitelisted for this API key.');

      case API_ERROR_CODE.ACCOUNT_NOT_UNIFIED:
        throw new Error('Upgrade your account to Unified Margin to use this endpoint.');

      default:
        throw new Error(`Unexpected API error ${res.retCode}: ${res.retMsg}`);
    }
  } catch (networkErr) {
    console.error('Network or HTTP error:', networkErr);
    throw networkErr;
  }
}

WebSocket Error Events

The WebsocketClient emits an exception event whenever a connection-level or subscription-level error occurs. Always register a listener for this event to prevent unhandled error crashes.
import { WebsocketClient } from 'bybit-api';

const ws = new WebsocketClient({ key: 'xxx', secret: 'yyy' });

// Always listen for exceptions
ws.on('exception', (err) => {
  console.error('WebSocket exception:', err);
});

// Other lifecycle events
ws.on('open', ({ wsKey }) => {
  console.log('Connection opened:', wsKey);
});

ws.on('reconnect', ({ wsKey }) => {
  console.log('Reconnecting:', wsKey);
});

ws.on('reconnected', ({ wsKey }) => {
  console.log('Reconnected:', wsKey);
});

ws.subscribeV5(['position', 'order', 'wallet'], 'linear');
Failing to listen to the exception event on a WebsocketClient will cause unhandled error events that crash Node.js processes using the default EventEmitter behaviour.

Debugging Raw HTTP Requests

Set the BYBITTRACE environment variable to any truthy value to log the full HTTP response — including request URL, method, headers, and body — to the console for every API call. This is useful when diagnosing signature failures or unexpected parameter serialisation.
BYBITTRACE=true node your-script.js
This activates an axios response interceptor inside the SDK that prints structured output for every response:
2024-01-15T10:30:00.000Z Response: {
  request: { url: '...', method: 'POST', data: '...', headers: {...}, params: {...} },
  response: { status: 200, statusText: 'OK', headers: {...}, data: {...} }
}
BYBITTRACE is intended for local debugging only. Do not enable it in production — it will print API keys, signatures, and potentially sensitive response data to stdout.

Common Errors and Fixes

Signature Not Valid (10004)

The HMAC or RSA signature could not be verified. Common causes:
  • Wrong API secret — double-check you are using the secret that matches your key
  • System clock skew — enable enable_time_sync: true or set syncTimeBeforePrivateRequests: true
  • Proxy latency pushing timestamps outside the recv_window — increase recv_window to 10000 or more

IP Not Whitelisted (10010)

Your API key has an IP restriction and the request is coming from an unlisted address. Either add your IP in the Bybit API management panel, or create a key without IP restriction for dynamic-IP environments.

Incorrect Permissions (10003 / 10005)

The API key does not have the required permission scope for the endpoint. Check the key’s read/trade/transfer permissions on the Bybit API management page and ensure they match what the endpoint requires.

Recv Window Too Small

The timestamp on the request arrived outside the acceptable window on the server. Increase recv_window (e.g. 10000 ms) and consider enabling time synchronisation.

Account Not Unified (10020)

The endpoint requires a Unified Margin or Unified Trading account. Upgrade your account in the Bybit dashboard before calling V5 endpoints that require unified margin.

Configuration

Set recv window, throwExceptions, and other client options

Logging

Enable trace logging and HTTP request debugging

Build docs developers (and LLMs) love