Binance SDK Quickstart: Install, Connect, and Trade
Install the binance npm package, fetch live Spot market data, authenticate, place a test order, and subscribe to a WebSocket stream in under 5 minutes.
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.
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.
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,});
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:
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); }})();
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 openedwsClient.on('open', (data) => { console.log('Connected:', data.wsKey, data.wsUrl);});// Raw streaming datawsClient.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 RESTwsClient.on('reconnecting', (data) => { console.log('Reconnecting...', data?.wsKey);});wsClient.on('reconnected', (data) => { console.log('Reconnected:', data?.wsKey);});// Always handle errorswsClient.on('exception', (data) => { console.error('WebSocket error:', data?.wsKey);});// Subscribe to Spot market topics — WS_KEY_MAP.main routes to the Spot/Margin stream endpointwsClient.subscribe( ['btcusdt@trade', 'btcusdt@bookTicker', 'btcusdt@depth10@100ms'], WS_KEY_MAP.main,);
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'.