binance Node.js & JavaScript SDK

repository·master·Indexed 21 days ago

https://github.com/tiagosiebler/binance

A professional, high-performance SDK for interacting with Binance REST APIs and WebSockets. It supports Spot, Margin, USDM Futures, CoinM Futures, and Portfolio Margin. The library provides specialized clients including MainClient, USDMClient, CoinMClient, PortfolioClient, WebsocketClient, and WebsocketAPIClient. Key features include TypeScript support, automatic connection recovery for WebSockets, support for HMAC, RSA, and Ed25519 authentication, and a demo trading mode for strategy testing.

Tokens
58.5K
Snippets
72
Records
137
Agent score
74%

What's inside binance

  1. Overview of Binance SDK capabilities

    master

    The binance SDK provides a professional, TypeScript-supported interface for interacting with Binance services.

    Key Features:

    • REST API Support: Covers Binance Spot, Margin, Isolated Margin, Options, USDM & CoinM Futures.
    • WebSocket Support: Event-driven messaging for all product groups (Spot, Margin, Portfolio, etc.) with smart persistence (automatic heartbeats, reconnection handling, and listenKey management).
    • Authentication: Supports HMAC, RSA, and Ed25519. Passing a private key as a secret allows the SDK to automatically detect and switch between RSA and Ed25519.
    • Data Beautification: Optional automatic parsing of WebSocket events (e.g., converting one-letter keys to descriptive words and string-based floats to numbers) and REST responses.
    • Environment Support: Works in Node.js and can be used in browser environments via the dist bundle.
  2. Project compatibility: TypeScript, ESM, and CommonJS

    master

    The Binance SDK is designed for modern development environments:

    • TypeScript: The package is TypeScript-first and includes full type declarations. It can be used in TypeScript projects or pure JavaScript projects (where types will assist your IDE).
    • Module Systems: Supports both ESM-style import and CommonJS require().
  3. Understand the Binance SDK client architecture

    master

    The SDK provides specialized clients to handle the complexity of Binance's different product groups, transport layers, and authentication requirements. Instead of a single monolithic client, the SDK uses a modular approach:

    • MainClient: Used for REST API calls across major product groups like Spot, Margin, Wallet, Convert, Earn, and Sub-Accounts.
    • WebsocketClient: Dedicated to managing streaming data (Public and Private streams).
    • WebsocketAPIClient: Used for awaitable WebSocket API commands (request/response pattern over WebSockets).

    Key Abstractions Handled by the SDK

    • Request Signing: Automatically handles HMAC, RSA, or Ed25519 signing.
    • Connectivity Management: Handles WebSocket heartbeats, healthchecks, and resubscribe behavior.
    • User Data Lifecycle: Manages listen-key refreshes and product-specific user data startup.
    • Environment Separation: Supports Live, Testnet (Spot/Futures), and Demo Trading environments.
  4. Choose between WebsocketClient and WebsocketAPIClient

    master

    The SDK distinguishes between streaming data and executing commands via WebSockets:

    • WebsocketClient: Use this for subscriptions and streaming market/user data topics.
    • WebsocketAPIClient: Use this for executing commands over Binance's WebSocket API (similar to REST API calls but over a persistent WebSocket connection).
  5. Manage Custom Client Order IDs

    master

    When placing orders, you can use custom client order IDs to track orders in your own system.

    1. Automatic/Default: Omit the ID field to let the SDK/Exchange handle it. This is the cleanest approach for most users.
    2. SDK-Generated: If you need a unique ID before the order is sent, use client.generateNewOrderId(). This ensures the ID uses the correct Binance-compatible prefix for your specific product group.
    3. Custom Suffix: If you want to include context (e.g., a strategy marker), use client.getOrderIdPrefix() to get the 10-character prefix and append your own suffix.

    Important Constraints:

    • The total length must not exceed 32 characters.
    • Use only allowed characters: [.A-Z:/a-z0-9_-].
    • For rich metadata, do not use the client order ID. Instead, use generateNewOrderId() as a primary key in your own database (e.g., Redis) to map to your metadata.
    // Option 1: Generate a valid, prefixed ID
    const newClientOrderId = client.generateNewOrderId();
    
    // Option 2: Build a custom ID with a prefix and suffix
    const prefix = client.getOrderIdPrefix();
    const suffix = `tp1_${Date.now()}`;
    const newClientOrderId = `${prefix}${suffix}`;
    
    // Validate against Binance character constraints
    const validBinanceClientOrderId = /^[.A-Z:/a-z0-9_-]{1,32}$/;
    if (!validBinanceClientOrderId.test(newClientOrderId)) {
      throw new Error(`Invalid Binance client order ID: ${newClientOrderId}`);
    }
    
    await client.submitNewOrder({
      symbol: 'BTCUSDT',
      side: 'SELL',
      type: 'LIMIT',
      quantity: 0.001,
      price: 13000,
      timeInForce: 'GTC',
      newClientOrderId,
    });
  6. How WebsocketClient and WebsocketAPIClient differ

    master

    The SDK provides two primary classes for handling WebSocket connections, depending on your use case:

    1. WebsocketClient: An all-in-one class that handles all Binance WebSocket capabilities across all subdomains. It manages subscriptions, heartbeats, and automatic connection recovery. Use this if you want to subscribe to public market data or if you need raw control over where WebSocket API commands are sent.

    2. WebsocketAPIClient: A utility class built on top of WebsocketClient designed for the WebSocket API (WSAPI). While WebSockets are inherently asynchronous, this client wraps commands in Promises, allowing you to await the result of a command (e.g., submitting an order) just like a REST API call. Use this for a more convenient integration when sending requests and commands over a persistent connection.

  7. Select WebSocket endpoints using WS_KEY_MAP

    master

    The WS_KEY_MAP object defines which Binance WebSocket endpoint family to use. Because different products (Spot, USD-M Futures, COIN-M, etc.) live on different endpoints, you must provide the correct key to .subscribe() to ensure your traffic is routed correctly. These keys also allow the SDK to track connection state and cached subscriptions per endpoint family.

    import { WS_KEY_MAP } from 'binance';
    
    // Example usage in subscribe:
    ws.subscribe(['topic'], WS_KEY_MAP.main);
  8. Choose the correct REST API Client

    master

    The SDK provides specialized REST API clients based on the specific Binance API group you need to access. Choosing the correct client ensures you have access to the relevant endpoints and subdomains.

    • MainClient: Use for most APIs, including Spot, Margin, Isolated Margin, Mining, BSwap, Fiat, Sub-account management, Staking, and more.
    • USDMClient: Use for USD-M futures APIs.
    • CoinMClient: Use for COIN-M futures APIs.
    • PortfolioClient: Use for Portfolio Margin APIs.

    Note: Vanilla Options are not currently supported.

  9. Use the WebSocket API Client for faster interactions

    master

    The WebSocketApiClient provides WebSocket-based endpoints that allow for faster interactions with the Binance API compared to standard REST requests. It maps official Exchange API endpoints to specific SDK functions, enabling low-latency execution and data retrieval via a WebSocket connection.

    Key features include:

    • Spot Trading: Order placement, cancellation, and account information.
    • Futures Trading: Position management, order modification, and account balances.
    • Market Data: Real-time order books, tickers, and klines.
    • User Data Streams: Managing subscriptions to account updates.
  10. Use the WebSocket API Client

    master

    The WebsocketAPIClient allows you to interact with Binance's WebSocket API (e.g., for submitting orders) in a way that feels similar to a REST client.

    Key features:

    • One method per command: Each available endpoint has a corresponding method.
    • Fully typed: Requests and responses are typed.
    • Automatic routing: The client handles authentication and connection persistence via the underlying WebsocketClient.
    • Async/Await: You can await responses just like an HTTP request.

    For more verbose or manual control, you can use the sendWSAPIRequest() method, though WebsocketAPIClient is generally preferred.

  11. Understand the workflow differences between REST, Streams, and WebSocket API

    master

    The SDK handles three distinct communication patterns, each with different recovery and lifecycle requirements:

    1. REST API Client Routing

    Used for standard request/response operations. The app selects a client, calls an SDK method, and the SDK handles request signing, routing, and JSON parsing.

    2. User Data Stream Recovery

    Private streams provide real-time account updates. Because streams can disconnect, you must implement a recovery pattern:

    1. Subscribe to the user data stream.
    2. Handle reconnecting events.
    3. Crucial: After a reconnect, you must backfill account state (balances, positions, orders, etc.) using the REST API to account for any events missed during the downtime.

    3. WebSocket API Command Flow

    Used for low-latency commands. The app calls an awaitable SDK method, the SDK sends the command with a request ID over the connection, and resolves the promise once the specific response event is received.

  12. Handle WebSocket reconnections and state backfilling

    master

    In production, WebSocket connections will drop. You should listen for the reconnecting and reconnected events to manage your application state:

    1. On reconnecting: Pause risky order actions.
    2. On reconnected: Perform a REST API backfill. Query the REST API for current account state, orders, fills, and positions to reconcile your internal state with the exchange's actual state.
    3. Resume: Once reconciled, resume normal processing.