bybit-api Node.js SDK

repository·master·Indexed 43 days ago

https://github.com/tiagosiebler/bybit-api

A professional Node.js, JavaScript, and TypeScript SDK for Bybit's REST and WebSocket APIs. Version 4.7.6 features support for V5 APIs, automatic HMAC & RSA authentication, and robust WebSocket management with automatic heartbeats and reconnection. It includes specialized clients like RestClientV5, WebsocketClient for real-time data, and WebsocketAPIClient for promise-driven WebSocket requests.

Tokens
38K
Snippets
76
Records
101
Agent score
53%

What's inside bybit-api

  1. Overview of the bybit-api SDK

    master

    The bybit-api is a professional Node.js, JavaScript, and TypeScript SDK for Bybit's REST and WebSocket APIs.

    Key Features:

    • High Rate Limits: Automatically subject to higher rate limits (up to 400 requests per second) than standard VIP tiers.
    • Low Minimum Notional: Supports placing orders with a notional value as low as $1 (undocumented benefit).
    • Authentication: Automatic support for HMAC & RSA authentication.
    • WebSocket Robustness: Includes smart persistence, automatic heartbeats to handle silent disconnections, automatic authentication, and automatic reconnection/resubscription workflows.
    • TypeScript Support: Thorough type declarations for most API requests and responses.
    • Proxy Support: Integrated via axios.
  2. Identify available REST and WebSocket clients

    master

    The SDK provides two primary types of clients for interacting with Bybit:

    1. REST Clients: Used for standard request-response API calls. These are organized by API version (e.g., rest-client-v5.ts).
    2. WebSocket API Clients: Used for real-time data streaming and persistent connections (websocket-api-client.ts).

    You can find the implementation details for these clients in the src/ folder and practical usage patterns in the examples/ folder.

  3. Overview of the Bybit SDK Surface

    master

    The Bybit SDK provides complete coverage for the Bybit API through three primary client types, each suited for different workflows:

    • RestClientV5: The current client for all REST API calls across market, trade, position, account, and asset APIs.
    • WebsocketClient: Used for subscribing to public market data streams (e.g., order books, tickers, klines) and private account streams (e.g., order, execution, position, and wallet updates).
    • WebsocketAPIClient: Used for awaitable WebSocket API commands (e.g., sending signed orders via WebSocket).
    • SpotClientV3: Provided for legacy compatibility only; do not use for new integrations.

    When building integrations, you should choose the surface that matches your specific workflow (e.g., using RestClientV5 for broad coverage or WebsocketAPIClient for low-latency command execution).

  4. How WebSocket API integration works

    master

    The SDK offers two distinct design patterns for using the WebSocket API (sending commands via WebSockets instead of REST):

    1. Asynchronous Promise-driven responses:

      • Use the WebsocketAPIClient.
      • Call functions and await the responses directly, similar to a REST API.
      • Best for developers who want a familiar REST-like experience over WebSockets.
    2. Asynchronous Event-driven responses:

      • Use the WebsocketClient.
      • Send commands using the sendWSAPIRequest(...) method.
      • Listen for responses and errors by subscribing to the response and error events emitted by the client's event emitter.
      • Best for developers who prefer a raw, event-driven architecture.
  5. How Bybit API Category Routing Works

    master

    The Bybit API often routes requests based on a category value. Instead of using separate clients for different products, the SDK uses a single client (like RestClientV5) where the product family is specified via a category parameter.

    To ensure robust code, make the category value a first-class part of your request building, logging, testing, and reconciliation logic. Supported categories include:

    • category: 'spot': Spot market data and spot order workflows.
    • category: 'linear': USDT and USDC linear contracts (perpetual and futures).
    • category: 'inverse': Inverse perpetual and inverse futures contracts.
    • category: 'option': Options market data, orders, positions, and greeks.
    // Example of category-based routing concept
    const category = 'linear';
    // Use this category in your request parameters
  6. Choose the correct SDK client for your use case

    master

    The SDK provides different client surfaces depending on whether you need request/response patterns, real-time streams, or command-based WebSocket interactions.

    Use caseSDK surfaceDescription
    REST APIRestClientV5Best for request/response calls, public/private reads, order management, and reconciliation. Handles signing, routing, and rate-limiting.
    Public/Private StreamsWebsocketClientUse subscribeV5(...) for real-time market data (order books, trades) or account events (executions, positions). Handles heartbeats and reconnects.
    WebSocket API CommandsWebsocketAPIClientBest for awaitable commands (create, amend, cancel orders) over a persistent WebSocket connection. Handles request/response matching.
    Legacy SpotSpotClientV3For legacy Spot V3 endpoints. Note: New integrations should use RestClientV5.
  7. Understanding WebSocket API Command Flows

    master

    When using the WebsocketAPIClient, it is critical to distinguish between a command acknowledgement and a trade execution/fill.

    An acknowledgement from the WebSocket API means the command was accepted by the server, but it does not mean the order has been filled or the state has changed.

    Correct Workflow:

    1. Connect using connectWSAPI().
    2. Authenticate (e.g., v5PrivateTrade).
    3. Await a command like submitNewOrder().
    4. Receive the command acknowledgement.
    5. Track the order/execution state via private WebSocket streams or reconcile with the REST API to confirm the final outcome.
  8. Understand the different client types

    master

    The SDK provides different clients depending on your interaction needs:

    • RestClientV5: The primary client for all new Bybit API work (REST). Use this for market data, account info, and order management.
    • WebsocketClient: Used for subscribing to and streaming real-time market or account data topics.
    • WebsocketAPIClient: Used for sending commands (request/response pattern) over a persistent WebSocket connection.
    • SpotClientV3: Provided for legacy compatibility; not recommended for new integrations.
  9. Balance load across multiple WebSocket connections

    master

    By default, a WebsocketClient prepares one connection per API group. All topics subscribed to on that specific client instance will share the same connection.

    To reduce throughput on a single connection and spread the load, create multiple instances of WebsocketClient and divide your subscribed topics into separate groups.

    Warning: Do not subscribe to the same topics on multiple clients, or you will receive duplicate messages.

    const wsClientGroup1 = new WebsocketClient();
    const wsClientGroup2 = new WebsocketClient();
    
    // Divide topics between group 1 and group 2
    wsClientGroup1.subscribeV5('topic.one', 'linear');
    wsClientGroup2.subscribeV5('topic.two', 'linear');
  10. Use the event-driven approach with WebsocketClient

    master

    If you prefer an event-driven model over promises, you can use the base WebsocketClient. In this mode, you 'fire and forget' requests and handle asynchronous replies via event handlers.

    • Use client.sendWSAPIRequest(wsKey, operation, params) to send requests.
    • Listen for replies using client.on('response', cb).
    • Listen for errors using client.on('exception', cb).

    See examples/ws-api-raw-events.ts for a full implementation example.

  11. Optimize LLM development with llms.txt

    master
    The SDK includes an llms.txt file in the root directory. When developing with AI coding agents or LLMs, provide this file to the model. It contains an AI-optimized structure of all functions and parameters, which significantly improves the model's ability to correctly use the SDK.
  12. Understand the REST client function mapping

    master

    Each REST client in the bybit-api SDK is a JavaScript class where individual methods are mapped directly to the exchange's API endpoints.

    To find the correct method for a specific task, you can cross-reference the Bybit API documentation with the SDK's endpoint maps. The SDK provides a mapping that includes:

    • Function name: The exact method name to call on the client instance.
    • AUTH: A boolean indicating if the method requires API keys (authentication is handled automatically by the SDK if keys are provided during initialization).
    • HTTP Method: The underlying HTTP verb (e.g., GET, POST) used for the request.
    • Endpoint: The specific URL path used to reach the exchange's API.

    All REST clients are located in the src/ directory of the repository.