Gathering detailed insights and metrics for binance
Gathering detailed insights and metrics for binance
Gathering detailed insights and metrics for binance
Gathering detailed insights and metrics for binance
Node.js & JavaScript SDK for Binance REST APIs & WebSockets, with TypeScript & browser support, integration tests, beautification & more.
npm install binance
Typescript
Module System
Node Version
NPM Version
70.3
Supply Chain
75.3
Quality
92.9
Maintenance
100
Vulnerability
99.3
License
TypeScript (99.57%)
JavaScript (0.43%)
Total Downloads
717,496
Last Day
215
Last Week
3,314
Last Month
14,629
Last Year
166,022
MIT License
861 Stars
1,104 Commits
280 Forks
32 Watchers
2 Branches
55 Contributors
Updated on Jun 30, 2025
Minified
Minified + Gzipped
Latest Version
3.0.0
Package Id
binance@3.0.0
Unpacked Size
1.23 MB
Size
217.04 kB
File Count
121
NPM Version
10.9.0
Node Version
22.11.0
Published on
Jun 30, 2025
Cumulative downloads
Total Downloads
Last Day
7.5%
215
Compared to previous day
Last Week
-10.2%
3,314
Compared to previous week
Last Month
-14.9%
14,629
Compared to previous month
Last Year
73.5%
166,022
Compared to previous year
4
11
4
Updated & performant JavaScript & Node.js SDK for the Binance REST APIs and WebSockets:
reconnected
event when dropped connection is restored.sendWSAPIRequest()
method, or;npm install binance --save
Refer to the examples folder for implementation demos.
Check out my related JavaScript/TypeScript/Node.js projects:
Most methods accept JS objects. These can be populated using parameters specified by Binance's API documentation.
This project uses typescript. Resources are stored in 3 key structures:
Create API credentials at Binance
There are several REST API modules as there are some differences in each API group.
MainClient
for most APIs, including: spot, margin, isolated margin, mining, BLVT, BSwap, Fiat & sub-account management.USDMClient
for USD-M futures APIs.CoinMClient
for COIN-M futures APIs.PortfolioClient
for Portfolio Margin APIs.Vanilla Options is not yet available. Please get in touch if you're looking for this.
The MainClient covers all endpoints under the main "api*.binance.com" subdomains, including but not limited to endpoints in the following product groups:
Refer to the following links for a complete list of available endpoints:
Start by importing the MainClient
class. API credentials are optional, unless you plan on making private API calls. More Node.js & JavaScript examples for Binance's REST APIs & WebSockets can be found in the examples folder on GitHub.
1import { MainClient } from 'binance'; 2 3// or, if you prefer `require()`: 4// const { MainClient } = require('binance'); 5 6const API_KEY = 'xxx'; 7const API_SECRET = 'yyy'; 8 9const client = new MainClient({ 10 api_key: API_KEY, 11 api_secret: API_SECRET, 12 // Connect to testnet environment 13 // testnet: true, 14}); 15 16client 17 .getAccountTradeList({ symbol: 'BTCUSDT' }) 18 .then((result) => { 19 console.log('getAccountTradeList result: ', result); 20 }) 21 .catch((err) => { 22 console.error('getAccountTradeList error: ', err); 23 }); 24 25client 26 .getExchangeInfo() 27 .then((result) => { 28 console.log('getExchangeInfo inverse result: ', result); 29 }) 30 .catch((err) => { 31 console.error('getExchangeInfo inverse error: ', err); 32 });
See main-client.ts for further information on the available REST API endpoints for spot/margin/etc.
Start by importing the USDM client. API credentials are optional, unless you plan on making private API calls.
1import { USDMClient } from 'binance'; 2 3// or, if you prefer `require()`: 4// const { USDMClient } = require('binance'); 5 6const API_KEY = 'xxx'; 7const API_SECRET = 'yyy'; 8 9const client = new USDMClient({ 10 api_key: API_KEY, 11 api_secret: API_SECRET, 12 // Connect to testnet environment 13 // testnet: true, 14}); 15 16client 17 .getBalance() 18 .then((result) => { 19 console.log('getBalance result: ', result); 20 }) 21 .catch((err) => { 22 console.error('getBalance error: ', err); 23 }); 24 25client 26 .submitNewOrder({ 27 side: 'SELL', 28 symbol: 'BTCUSDT', 29 type: 'MARKET', 30 quantity: 0.001, 31 }) 32 .then((result) => { 33 console.log('submitNewOrder result: ', result); 34 }) 35 .catch((err) => { 36 console.error('submitNewOrder error: ', err); 37 }); 38
See usdm-client.ts for further information.
Start by importing the coin-m client. API credentials are optional, though an error is thrown when attempting any private API calls without credentials.
1import { CoinMClient } from 'binance'; 2 3// or, if you prefer `require()`: 4// const { CoinMClient } = require('binance'); 5 6const API_KEY = 'xxx'; 7const API_SECRET = 'yyy'; 8 9const client = new CoinMClient({ 10 api_key: API_KEY, 11 api_secret: API_SECRET, 12 // Connect to testnet environment 13 // testnet: true, 14}); 15 16client 17 .getSymbolOrderBookTicker() 18 .then((result) => { 19 console.log('getSymbolOrderBookTicker result: ', result); 20 }) 21 .catch((err) => { 22 console.error('getSymbolOrderBookTicker error: ', err); 23 });
See coinm-client.ts for further information.
All websockets are accessible via the shared WebsocketClient
. As before, API credentials are optional unless the user data stream is required.
The below example demonstrates connecting as a consumer, to receive WebSocket events from Binance:
1import { WebsocketClient } from 'binance'; 2 3// or, if you prefer `require()`: 4// const { WebsocketClient } = require('binance'); 5 6const API_KEY = 'xxx'; 7const API_SECRET = 'yyy'; 8 9/** 10 * The WebsocketClient will manage individual connections for you, under the hood. 11 * Just make an instance of the WS Client and subscribe to topics. It'll handle the rest. 12 */ 13const wsClient = new WebsocketClient( 14 { 15 api_key: key, 16 api_secret: secret, 17 // Optional: when enabled, the SDK will try to format incoming data into more readable objects. 18 // Beautified data is emitted via the "formattedMessage" event 19 beautify: true, 20 // Disable ping/pong ws heartbeat mechanism (not recommended) 21 // disableHeartbeat: true, 22 // Connect to testnet environment 23 // testnet: true, 24 }, 25); 26 27// receive raw events 28wsClient.on('message', (data) => { 29 console.log('raw message received ', JSON.stringify(data, null, 2)); 30}); 31 32// notification when a connection is opened 33wsClient.on('open', (data) => { 34 console.log('connection opened open:', data.wsKey, data.wsUrl); 35}); 36 37// receive formatted events with beautified keys. Any "known" floats stored in strings as parsed as floats. 38wsClient.on('formattedMessage', (data) => { 39 console.log('formattedMessage: ', data); 40}); 41 42// read response to command sent via WS stream (e.g LIST_SUBSCRIPTIONS) 43wsClient.on('response', (data) => { 44 console.log('log response: ', JSON.stringify(data, null, 2)); 45}); 46 47// receive notification when a ws connection is reconnecting automatically 48wsClient.on('reconnecting', (data) => { 49 console.log('ws automatically reconnecting.... ', data?.wsKey); 50}); 51 52// receive notification that a reconnection completed successfully (e.g use REST to check for missing data) 53wsClient.on('reconnected', (data) => { 54 console.log('ws has reconnected ', data?.wsKey); 55}); 56 57// Recommended: receive error events (e.g. first reconnection failed) 58wsClient.on('exception', (data) => { 59 console.log('ws saw error ', data?.wsKey); 60}); 61 62/** 63 * Subscribe to public topics either one at a time or many in an array 64 */ 65 66// E.g. one at a time, routed to the coinm futures websockets: 67wsClient.subscribe('btcusd@indexPrice', 'coinm'); 68wsClient.subscribe('btcusd@miniTicker', 'coinm'); 69 70// Or send many topics at once to a stream, e.g. the usdm futures stream: 71wsClient.subscribe( 72 [ 73 'btcusdt@aggTrade', 74 'btcusdt@markPrice', 75 '!ticker@arr', 76 '!miniTicker@arr', 77 ], 78 'usdm', 79); 80 81// spot & margin topics should go to "main" 82// (similar how the MainClient is for REST APIs in that product group) 83wsClient.subscribe( 84 [ 85 // All Market Rolling Window Statistics Streams 86 // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#all-market-rolling-window-statistics-streams 87 '!ticker_1h@arr', 88 // Individual Symbol Book Ticker Streams 89 // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#individual-symbol-book-ticker-streams 90 'btcusdt@bookTicker', 91 // Average Price 92 // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#average-price 93 'btcusdt@avgPrice', 94 // Partial Book Depth Streams 95 // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#partial-book-depth-streams 96 'btcusdt@depth10@100ms', 97 // Diff. Depth Stream 98 // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#diff-depth-stream 99 'btcusdt@depth', 100 ], 101 // Look at the `WS_KEY_URL_MAP` for a list of values here: 102 // https://github.com/tiagosiebler/binance/blob/master/src/util/websockets/websocket-util.ts 103 // "main" connects to wss://stream.binance.com:9443/stream 104 // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams 105 'main', 106); 107 108/** 109 * For the user data stream, these convenient subscribe methods open a dedicated 110 * connection with the listen key workflow: 111 */ 112 113wsClient.subscribeSpotUserDataStream(); 114wsClient.subscribeMarginUserDataStream(); 115wsClient.subscribeIsolatedMarginUserDataStream('BTCUSDT'); 116wsClient.subscribeUsdFuturesUserDataStream();
See websocket-client.ts for further information. Also see ws-userdata.ts for user data examples.
Some of the product groups available on Binance also support sending requests (commands) over an active WebSocket connection. This is called the WebSocket API.
Note: the WebSocket API requires the use of Ed25519 keys. HMAC & RSA keys are not supported by Binance for the WebSocket API (as of Apr 2025).
The WebSocket API is available in the WebsocketClient via the sendWSAPIRequest(wsKey, command, commandParameters)
method.
Each call to this method is wrapped in a promise, which you can async await for a response, or handle it in a raw event-driven design.
The WebSocket API is also available in a promise-wrapped REST-like format. Either, as above, await any calls to sendWSAPIRequest(...)
, or directly use the convenient WebsocketAPIClient. This class is very similar to existing REST API classes (such as the MainClient or USDMClient).
It provides one function per endpoint, feels like a REST API and will automatically route your request via an automatically persisted, authenticated and health-checked WebSocket API connection.
Below is an example showing how easy it is to use the WebSocket API without any concern for the complexity of managing WebSockets.
1import { WebsocketAPIClient } from 'binance'; 2 3// or, if you prefer `require()`: 4// const { WebsocketAPIClient } = require('binance'); 5 6/** 7 * The WS API only works with an Ed25519 API key. 8 * 9 * Check the rest-private-ed25519.md in this folder for more guidance 10 * on preparing this Ed25519 API key. 11 */ 12 13const publicKey = `-----BEGIN PUBLIC KEY----- 14MCexampleQTxwLU9o= 15-----END PUBLIC KEY----- 16`; 17 18const privateKey = `-----BEGIN PRIVATE KEY----- 19MC4CAQAexamplewqj5CzUuTy1 20-----END PRIVATE KEY----- 21`; 22 23// API Key returned by binance, generated using the publicKey (above) via Binance's website 24const apiKey = 'TQpJexamplerobdG'; 25 26// Make an instance of the WS API Client 27const wsClient = new WebsocketAPIClient({ 28 api_key: apiKey, 29 api_secret: privateKey, 30 beautify: true, 31 32 // Enforce testnet ws connections, regardless of supplied wsKey 33 // testnet: true, 34}); 35 36// Optional, if you see RECV Window errors, you can use this to manage time issues. However, make sure you sync your system clock first! 37// https://github.com/tiagosiebler/awesome-crypto-examples/wiki/Timestamp-for-this-request-is-outside-of-the-recvWindow 38// wsClient.setTimeOffsetMs(-5000); 39 40// Optional, see above. Can be used to prepare a connection before sending commands 41// await wsClient.connectWSAPI(WS_KEY_MAP.mainWSAPI); 42 43// Make WebSocket API calls, very similar to a REST API: 44 45wsClient 46 .getFuturesAccountBalanceV2({ 47 timestamp: Date.now(), 48 recvWindow: 5000, 49 }) 50 .then((result) => { 51 console.log('getFuturesAccountBalanceV2 result: ', result); 52 }) 53 .catch((err) => { 54 console.error('getFuturesAccountBalanceV2 error: ', err); 55 }); 56 57wsClient 58 .submitNewFuturesOrder('usdm', { 59 side: 'SELL', 60 symbol: 'BTCUSDT', 61 type: 'MARKET', 62 quantity: 0.001, 63 timestamp: Date.now(), 64 // recvWindow: 5000, 65 }) 66 .then((result) => { 67 console.log('getFuturesAccountBalanceV2 result: ', result); 68 }) 69 .catch((err) => { 70 console.error('getFuturesAccountBalanceV2 error: ', err); 71 });
Pass a custom logger which supports the log methods trace
, info
and error
, or override methods from the default logger as desired.
1import { WebsocketClient, DefaultLogger } from 'binance'; 2 3// or, if you prefer `require()`: 4// const { WebsocketClient, DefaultLogger } = require('binance'); 5 6// Enable all logging on the trace level (disabled by default) 7DefaultLogger.trace = (...params) => { 8 console.trace('trace: ', params); 9}; 10 11// Pass the updated logger as the 2nd parameter 12const ws = new WebsocketClient( 13 { 14 api_key: key, 15 api_secret: secret, 16 beautify: true, 17 }, 18 DefaultLogger 19); 20 21// Or, create a completely custom logger with the 3 available functions 22const customLogger = { 23 trace: (...params: LogParams): void => { 24 console.trace(new Date(), params); 25 }, 26 info: (...params: LogParams): void => { 27 console.info(new Date(), params); 28 }, 29 error: (...params: LogParams): void => { 30 console.error(new Date(), params); 31 }, 32} 33 34// Pass the custom logger as the 2nd parameter 35const ws = new WebsocketClient( 36 { 37 api_key: key, 38 api_secret: secret, 39 beautify: true, 40 }, 41 customLogger 42);
This is the "modern" way, allowing the package to be directly imported into frontend projects with full typescript support.
1npm install crypto-browserify stream-browserify
tsconfig.json
1{ 2 "compilerOptions": { 3 "paths": { 4 "crypto": [ 5 "./node_modules/crypto-browserify" 6 ], 7 "stream": [ 8 "./node_modules/stream-browserify" 9 ] 10}
1(window as any).global = window;
This is the "old" way of using this package on webpages. This will build a minified js bundle that can be pulled in using a script tag on a website.
Build a bundle using webpack:
npm install
npm build
npm pack
The bundle can be found in dist/
. Altough usage should be largely consistent, smaller differences will exist. Documentation is still TODO.
Have my projects helped you? Share the love, there are many ways you can show your thanks:
0xA3Bda8BecaB4DCdA539Dc16F9C54a592553Be06C
Contributions are encouraged, I will review any incoming pull requests. See the issues tab for todo items.
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
18 commit(s) and 13 issue activity found in the last 90 days -- score normalized to 10
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
Found 8/9 approved changesets -- score normalized to 8
Reason
3 existing vulnerabilities detected
Details
Reason
dependency not pinned by hash detected -- score normalized to 6
Details
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
Reason
security policy file not detected
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2025-06-23
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More