node-binance-api

repository·master·Indexed 23 days ago

https://github.com/ccxt/node-binance-api

A typed, safe SDK for interacting with Binance's REST APIs and WebSockets. It provides complete API coverage for Spot, Margin, Futures, and Delivery trading, including advanced features such as candlestick streaming, market depth, and proxy support. The library supports modern JavaScript/TypeScript with async/await and includes capabilities for managing orders, account balances, and real-time market data.

Tokens
18.6K
Snippets
32
Records
106
Agent score
82%

What's inside node-binance-api

  1. Features of node-binance-api

    master

    The library provides a comprehensive SDK for Binance REST APIs and WebSockets with the following capabilities:

    • API Support: Spot, Margin, Futures, and Delivery API (including algoOrder service).
    • Trading Modes: Demo trading support and Testnet support (note: Testnet is deprecated).
    • Connectivity: Proxy support for both REST and WebSockets (including WS-API), customizable HTTP headers, and overridable hostnames (e.g., .us, .jp).
    • Security & Reliability: RSA/ECDSA support, automatic RecvWindow and timestamp generation, and WebSocket handling with automatic reconnection.
    • Flexibility: Ability to call any endpoint even if not explicitly supported by the library, customizable request parameters, and a verbose mode for debugging HTTP requests/responses.
  2. Use different asynchronous syntax patterns

    master

    The library supports three primary asynchronous patterns:

    1. Callbacks: Pass a function as the last argument.
    2. Promises: If no callback is provided, the method returns a Promise.
    3. Async/Await: Use await with the returned Promise.

    All patterns handle errors via the standard callback (error, response) or Promise .catch()/try-catch blocks.

    // 1. Callback
    const callback = binance.prices("NEOBTC", (error, response) => {
      if (error) {
        console.error(error)
      } else {
        console.log(response)
      }
    })
    
    // 2. Classic Promise
    const classicPromise = binance.prices("NEOBTC")
      .then(response => console.log(response))
      .catch(error => console.error(error))
    
    // 3. Async/Await
    const asyncAwait = (async _ => {
      try {
        const response = await binance.prices("NEOBTC")
        console.log(response)
      } catch (error) {
        console.error(error)
      }
    })()
  3. Get started with node-binance-api (ESM)

    master

    If you are using ECMAScript Modules (ESM), import the Binance class and use async/await to interact with the exchange. The library is fully typed and supports modern JavaScript syntax.

    import Binance from 'node-binance-api';
    async function run() {
        const exchange = new Binance();
        const res = await exchange.futuresTime();
        console.log( res );
    }
  4. Get started with node-binance-api (CJS)

    master

    If you are using CommonJS (CJS), require the Binance module. You can pass a configuration object to the constructor to provide your API credentials and enable testnet/sandbox mode.

    const Binance = require('node-binance-api');
    const binance = new Binance({
      APIKEY: '<key>',
      APISECRET: '<secret>',
      test: true, // if you want to use the sandbox/testnet
    });
  5. Configure Proxy Support

    master

    The standard REST API honors the https_proxy or socks_proxy environment variables.

    Note: The proxy package does not support DNS names; use the proxy IP address. For WebSockets, currently only the socks_proxy method is functional.

    Linux/Windows Setup: Set the environment variable before running your application.

    Linux:

    export https_proxy=http://ip:port
    # For WebSockets:
    export socks_proxy=socks://ip:port

    Windows:

    set https_proxy=http://ip:port
    # For WebSockets:
    set socks_proxy=socks://ip:port
  6. Upgrading to v1.0.0+

    master

    The library underwent a major refactor for version 1.0.0 to use modern, typed JavaScript/TypeScript with async/await. If you are upgrading from 0.0.X, be aware of the following breaking changes:

    • Callbacks Removed: REST methods no longer accept callbacks as parameters; they now return Promises.
    • Signature Changes: Method signatures have been adapted to receive request values (like symbol, orderId, etc.) directly.
  7. Understand WebSocket method interfaces

    master

    The IWebsocketsMethods interface defines the available streaming endpoints. Methods typically follow these patterns:

    • User Data Streams: userData, userMarginData, userFutureData, and userDeliveryData provide real-time updates on account balances, orders, and executions.
    • Market Data Streams:
      • depth / depthCache / depthCacheStaggered: Order book updates.
      • aggTrades / trades: Trade history.
      • candlesticks / futuresCandlesticks / deliveryCandlesticks: OHLCV data.
      • futuresTicker / deliveryTicker: Ticker updates.
    • Termination: Use terminate(endpoint), futuresTerminate(endpoint, reconnect), or deliveryTerminate(endpoint, reconnect) to close specific streams.
  8. How Futures WebSocket subscriptions manage connectivity

    master

    The library manages WebSocket connectivity for Futures and Delivery streams through several internal mechanisms:

    1. Heartbeats: A shared interval tick runs futuresSocketHeartbeat (or deliverySocketHeartbeat) to monitor all active subscriptions. It sends a ping to active sockets. If a socket does not respond (is not isAlive), it is considered a 'zombie' and is terminated.
    2. Automatic Reconnection: If this.Options.reconnect is enabled, the library attempts to call the reconnect() function provided during the socket's close event.
    3. Proxy Support: Both Futures and Delivery subscriptions automatically detect and use configured HTTPS or SOCKS proxies via HttpsProxyAgent or SocksProxyAgent if available.
  9. Configure Proxy Support

    master

    If the exchange is unavailable in your location or you need to bypass rate limits, you can configure one of three proxy types on the client instance:

    1. httpsProxy: A standard HTTP(S) proxy. Requests are tunneled through the proxy server.
    2. proxyUrl: Prepends a URL to API requests (useful for redirection or bypassing CORS).
    3. socksProxy: A SOCKS proxy.

    Note: The examples use client, ensure you apply these to your initialized Binance instance.

    client.httpsProxy = 'http://1.2.3.4:8080/';
    client.proxyUrl = 'YOUR_PROXY_URL';
    client.socksProxy = 'socks5://1.2.3.4:8080/';
  10. Manage Order Book Depth Cache

    master

    The library maintains a local cache of the order book (depth) to allow for efficient querying of bids and asks.

    Accessing the Cache

    • getDepthCache(symbol): Returns the current cached bids and asks for a specific symbol. Returns empty objects if no cache exists.
    • depthVolume(symbol): Calculates the total buy/sell volume from the current depth cache. Returns an object containing bids (base volume), asks (base volume), bidQty (total quantity), and askQty (total quantity).

    Synchronization

    The depthHandler manages the synchronization between the WebSocket stream and the local cache. It validates updateId sequences to ensure the cache is not out of sync. If a gap is detected between the snapshot and the stream, or if the updateId sequence is broken, an error is thrown, indicating the connection must be re-established.