Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/tiagosiebler/binance/llms.txt

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

The binance SDK is designed to get you to a working integration as quickly as possible. Public market data requires no API keys at all — you can make your first live call immediately after installation. This guide walks from install through a public REST call, an authenticated private call, and a live WebSocket stream subscription.
1
Install the package
2
npm
npm install binance
yarn
yarn add binance
pnpm
pnpm install binance
3
The package ships TypeScript declarations, an ESM build, a CommonJS build, and a pre-built browser bundle. No separate @types package is required.
4
Make your first public REST call
5
The MainClient covers Spot, Margin, Wallet, and many other APIs under Binance’s main REST API family. Public market data endpoints work without any credentials.
6
TypeScript
import { MainClient } from 'binance';

const client = new MainClient();

(async () => {
  try {
    // Fetch 24-hour ticker statistics for BTCUSDT
    const ticker = await client.get24hrChangeStatistics({
      symbol: 'BTCUSDT',
    });
    console.log('24hr ticker:', ticker);

    // Fetch statistics for multiple symbols at once
    const manyTickers = await client.get24hrChangeStatistics({
      symbols: ['BTCUSDT', 'ETHUSDT'],
    });
    console.log('Multiple tickers:', manyTickers);
  } catch (e) {
    console.error('Request failed:', e);
  }
})();
JavaScript
const { MainClient } = require('binance');

const client = new MainClient();

(async () => {
  try {
    const ticker = await client.get24hrChangeStatistics({
      symbol: 'BTCUSDT',
    });
    console.log('24hr ticker:', ticker);

    const manyTickers = await client.get24hrChangeStatistics({
      symbols: ['BTCUSDT', 'ETHUSDT'],
    });
    console.log('Multiple tickers:', manyTickers);
  } catch (e) {
    console.error('Request failed:', e);
  }
})();
7
You can also fetch all symbols at once by calling client.get24hrChangeStatistics() with no arguments.
8
Create an authenticated client
9
Private endpoints — account information, order placement, balances — require an API key and secret. Store credentials in environment variables and never hard-code them.
10
export BINANCE_API_KEY='your-api-key'
export BINANCE_API_SECRET='your-api-secret'
11
TypeScript
import { MainClient } from 'binance';

const client = new MainClient({
  api_key: process.env.BINANCE_API_KEY!,
  api_secret: process.env.BINANCE_API_SECRET!,
  // Optionally parse known float-strings to numbers in responses
  beautifyResponses: true,
});
JavaScript
const { MainClient } = require('binance');

const client = new MainClient({
  api_key: process.env.BINANCE_API_KEY,
  api_secret: process.env.BINANCE_API_SECRET,
  beautifyResponses: true,
});
12
The SDK automatically appends timestamps, computes HMAC/RSA/Ed25519 signatures, and adds the X-MBX-APIKEY header to every private request. You do not need to do any of this manually.
13
Read your account information
14
With an authenticated client, you can query account balances and permissions:
15
TypeScript
import { MainClient } from 'binance';

const client = new MainClient({
  api_key: process.env.BINANCE_API_KEY!,
  api_secret: process.env.BINANCE_API_SECRET!,
  beautifyResponses: true,
});

(async () => {
  try {
    const account = await client.getAccountInformation();
    console.log('Can trade:', account.canTrade);

    const balances = await client.getBalances();
    const usdtBalance = balances.find((b) => b.coin === 'USDT');
    console.log('USDT available:', usdtBalance?.free);
  } catch (e) {
    console.error('Request failed:', e);
  }
})();
JavaScript
const { MainClient } = require('binance');

const client = new MainClient({
  api_key: process.env.BINANCE_API_KEY,
  api_secret: process.env.BINANCE_API_SECRET,
  beautifyResponses: true,
});

(async () => {
  try {
    const account = await client.getAccountInformation();
    console.log('Can trade:', account.canTrade);

    const balances = await client.getBalances();
    const usdtBalance = balances.find((b) => b.coin === 'USDT');
    console.log('USDT available:', usdtBalance?.free);
  } catch (e) {
    console.error('Request failed:', e);
  }
})();
16
Validate and place a Spot order
17
Use testNewOrder() to validate a request against the matching engine without placing a live order. Switch to submitNewOrder() only when you’re ready to trade.
18
The example below mirrors the real example from the SDK’s examples/Rest/Spot/rest-spot-private-trade.ts file: it checks available USDT balance, fetches the current price, calculates a buy amount, and validates the order request before submitting.
19
TypeScript
import {
  MainClient,
  NewSpotOrderParams,
  OrderResponseFull,
  SymbolPrice,
} from 'binance';

const client = new MainClient({
  api_key: process.env.BINANCE_API_KEY!,
  api_secret: process.env.BINANCE_API_SECRET!,
  beautifyResponses: true,
});

const symbol = 'BTCUSDT';
const assetDecimalPlaces = 4;

function trimToDecimalPlaces(number: number, precision: number): number {
  const array: any[] = number.toString().split('.');
  array.push(array.pop().substring(0, precision));
  return parseFloat(array.join('.'));
}

(async () => {
  try {
    // Check available USDT balance
    const balance = await client.getBalances();
    const usdtBal = balance.find((b) => b.coin === 'USDT');
    if (!usdtBal?.free) {
      return console.error('No USDT balance available');
    }

    // Get the current BTC price
    const btcTicker = (await client.getSymbolPriceTicker({
      symbol,
    })) as SymbolPrice;
    const lastPrice = btcTicker?.price;
    if (!lastPrice) return console.error('No price returned');

    // Calculate buy quantity (50% of available USDT)
    const buyAmountUsdt = Number(usdtBal.free) * 0.5;
    const buyAmountBtc = trimToDecimalPlaces(
      buyAmountUsdt / Number(lastPrice),
      assetDecimalPlaces,
    );

    const orderRequest: NewSpotOrderParams = {
      symbol,
      side: 'BUY',
      type: 'MARKET',
      quantity: buyAmountBtc,
      newOrderRespType: 'FULL',
    };

    // Validate without placing (remove testNewOrder to place a real order)
    await client.testNewOrder(orderRequest);
    console.log('Order validated successfully:', orderRequest);

    // Uncomment to place the actual order:
    // const result = await client.submitNewOrder(orderRequest) as OrderResponseFull;
    // console.log('Order placed:', result);
  } catch (e) {
    console.error('Error:', e);
  }
})();
JavaScript
const { MainClient } = require('binance');

const client = new MainClient({
  api_key: process.env.BINANCE_API_KEY,
  api_secret: process.env.BINANCE_API_SECRET,
  beautifyResponses: true,
});

(async () => {
  try {
    const balance = await client.getBalances();
    const usdtBal = balance.find((b) => b.coin === 'USDT');
    if (!usdtBal?.free) return console.error('No USDT balance');

    const btcTicker = await client.getSymbolPriceTicker({ symbol: 'BTCUSDT' });
    const lastPrice = btcTicker?.price;
    if (!lastPrice) return console.error('No price returned');

    const buyAmountBtc = parseFloat(
      ((Number(usdtBal.free) * 0.5) / Number(lastPrice)).toFixed(4),
    );

    const orderRequest = {
      symbol: 'BTCUSDT',
      side: 'BUY',
      type: 'MARKET',
      quantity: buyAmountBtc,
      newOrderRespType: 'FULL',
    };

    await client.testNewOrder(orderRequest);
    console.log('Order validated:', orderRequest);

    // Uncomment to place a real order:
    // const result = await client.submitNewOrder(orderRequest);
    // console.log('Order placed:', result);
  } catch (e) {
    console.error('Error:', e);
  }
})();
20
submitNewOrder() places a live order against real funds. Always test with testNewOrder() first and consider using demoTrading: true for strategy validation before going live.
21
Subscribe to a WebSocket stream
22
The WebsocketClient manages all WebSocket connections — heartbeats, reconnection, and resubscription are handled automatically. Listen for events via the on() API.
23
TypeScript
import { WebsocketClient, WS_KEY_MAP } from 'binance';

const wsClient = new WebsocketClient({
  // Optional: enable beautified events via the 'formattedMessage' event
  beautify: true,
});

// Notification when a connection is opened
wsClient.on('open', (data) => {
  console.log('Connected:', data.wsKey, data.wsUrl);
});

// Raw streaming data
wsClient.on('message', (data) => {
  console.log('Raw message:', JSON.stringify(data, null, 2));
});

// Beautified data (when beautify: true)
wsClient.on('formattedMessage', (data) => {
  console.log('Formatted message:', data);
});

// Reconnection events — use 'reconnected' to reconcile state via REST
wsClient.on('reconnecting', (data) => {
  console.log('Reconnecting...', data?.wsKey);
});
wsClient.on('reconnected', (data) => {
  console.log('Reconnected:', data?.wsKey);
});

// Always handle errors
wsClient.on('exception', (data) => {
  console.error('WebSocket error:', data?.wsKey);
});

// Subscribe to Spot market topics — WS_KEY_MAP.main routes to the Spot/Margin stream endpoint
wsClient.subscribe(
  ['btcusdt@trade', 'btcusdt@bookTicker', 'btcusdt@depth10@100ms'],
  WS_KEY_MAP.main,
);
JavaScript
const { WebsocketClient, WS_KEY_MAP } = require('binance');

const wsClient = new WebsocketClient({ beautify: true });

wsClient.on('open', (data) => {
  console.log('Connected:', data.wsKey, data.wsUrl);
});

wsClient.on('formattedMessage', (data) => {
  console.log('Formatted message:', data);
});

wsClient.on('reconnecting', (data) => {
  console.log('Reconnecting...', data?.wsKey);
});
wsClient.on('reconnected', (data) => {
  console.log('Reconnected:', data?.wsKey);
});
wsClient.on('exception', (data) => {
  console.error('WebSocket error:', data?.wsKey);
});

// Subscribe Spot topics — WS_KEY_MAP.main routes to the Spot/Margin stream endpoint
wsClient.subscribe(
  ['btcusdt@trade', 'btcusdt@bookTicker', 'btcusdt@depth10@100ms'],
  WS_KEY_MAP.main,
);
24
The second argument to subscribe() is a WS_KEY_MAP key that routes the connection to the correct Binance endpoint family. Use WS_KEY_MAP.main for Spot and Margin, WS_KEY_MAP.usdm (auto-routed alias) or WS_KEY_MAP.usdmMarket / WS_KEY_MAP.usdmPublic for USD-M Futures, and WS_KEY_MAP.coinm for COIN-M Futures. Import WS_KEY_MAP from 'binance'.

Which client should I use?

MainClient

Spot trading, margin, wallet, convert, earn, sub-accounts, and all api/ or sapi/ endpoints.

USDMClient

USD-M Futures. Any endpoint under the fapi/ path.

CoinMClient

COIN-M Futures. Any endpoint under the dapi/ path.

PortfolioClient

Portfolio Margin accounts. Any endpoint under the papi/ path.

WebsocketClient

Public market data streams and private user data streams (listen-key flow for Futures).

WebsocketAPIClient

Promise-based commands over Binance’s WebSocket API — lower overhead than REST for order placement.

Testing environments

Binance provides two testing environments that can be activated with a single constructor option:
// Demo trading: real market data, simulated fills — best for strategy testing
const demoClient = new USDMClient({
  api_key: process.env.BINANCE_API_KEY!,
  api_secret: process.env.BINANCE_API_SECRET!,
  demoTrading: true,
});

// Testnet: separate credentials, simulated market data
const testnetClient = new USDMClient({
  api_key: process.env.BINANCE_TESTNET_KEY!,
  api_secret: process.env.BINANCE_TESTNET_SECRET!,
  testnet: true,
});
Demo trading and testnet credentials are separate from each other and from live credentials. Never mix them in the same client instance.

Build docs developers (and LLMs) love