Installations
npm install binance
Developer Guide
Typescript
Yes
Module System
CommonJS
Node Version
22.11.0
NPM Version
10.9.0
Score
57.3
Supply Chain
74.7
Quality
91.4
Maintenance
100
Vulnerability
98.9
License
Releases
Unable to fetch releases
Contributors
Languages
TypeScript (99.36%)
JavaScript (0.64%)
Developer
Download Statistics
Total Downloads
644,643
Last Day
286
Last Week
2,188
Last Month
41,477
Last Year
138,259
GitHub Statistics
793 Stars
849 Commits
268 Forks
30 Watching
2 Branches
50 Contributors
Bundle Size
160.33 kB
Minified
39.03 kB
Minified + Gzipped
Sponsor this package
Package Meta Information
Latest Version
2.15.1
Package Id
binance@2.15.1
Unpacked Size
768.24 kB
Size
126.50 kB
File Count
76
NPM Version
10.9.0
Node Version
22.11.0
Publised On
16 Dec 2024
Total Downloads
Cumulative downloads
Total Downloads
644,643
Last day
-26.3%
286
Compared to previous day
Last week
-17.3%
2,188
Compared to previous week
Last month
328.3%
41,477
Compared to previous month
Last year
49.1%
138,259
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Dependencies
4
Dev Dependencies
11
Optional Dependencies
4
Node.js & JavaScript SDK for Binance REST APIs & WebSockets
Updated & performant JavaScript & Node.js SDK for the Binance REST APIs and WebSockets:
- Extensive integration with Binance REST APIs and WebSockets.
- TypeScript support (with type declarations for most API requests & responses).
- Supports Binance REST APIs for Binance Spot, Margin, Isolated Margin, USDM & CoinM Futures.
- Strongly typed on most requests and responses.
- Automated end-to-end tests on most API calls, ensuring no breaking changes are released.
- Extremely robust & performant JavaScript/Node.js Binance SDK with significant trading volume in production (livenet).
- Actively maintained with a modern, promise-driven interface.
- Support for seamless HMAC and RSA authentication for private Binance REST API and WebSocket calls.
- Passing a private key as a secret will automatically revert to RSA authentication.
- Supports Websockets for Binance Spot, Margin, Isolated Margin, USDM & CoinM Futures.
- Event driven messaging.
- Smart websocket persistence
- Automatically handle silent websocket disconnections through timed heartbeats, including the scheduled 24hr disconnect.
- Automatically handle listenKey persistence and expiration/refresh.
- Emit
reconnected
event when dropped connection is restored.
- Strongly typed on most websocket events, with typeguards available for TypeScript users.
- Optional:
- Automatic beautification of Websocket events (from one-letter keys to descriptive words, and strings with floats to numbers).
- Automatic beautification of REST responses (parsing numbers in strings to numbers).
- Heavy automated end-to-end testing with real API calls.
- End-to-end testing before any release.
- Real API calls in e2e tests.
- Proxy support via axios integration.
- Active community support & collaboration in telegram: Node.js Algo Traders.
Installation
npm install binance --save
Examples
Refer to the examples folder for implementation demos.
Issues & Discussion
- Issues? Check the issues tab.
- Discuss & collaborate with other node devs? Join our Node.js Algo Traders engineering community on telegram.
- Questions about Binance APIs & WebSockets? Ask in the official Binance API group on telegram.
- Follow our announcement channel for real-time updates on X/Twitter
Related projects
Check out my related JavaScript/TypeScript/Node.js projects:
- Try my REST API & WebSocket SDKs:
- Try my misc utilities:
- Check out my examples:
Documentation
Most methods accept JS objects. These can be populated using parameters specified by Binance's API documentation.
Structure
This project uses typescript. Resources are stored in 3 key structures:
- src - the whole connector written in typescript
- lib - the javascript version of the project (compiled from typescript). This should not be edited directly, as it will be overwritten with each release.
- dist - the packed bundle of the project for use in browser environments.
Usage
Create API credentials at Binance
REST API Clients
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.
Vanilla Options connectors are not yet available, though contributions are welcome!
REST Spot/Margin/etc
Start by importing the spot client. API credentials are optional, though an error is thrown when attempting any private API calls without credentials.
1const { MainClient } = require('binance'); 2 3const API_KEY = 'xxx'; 4const API_SECRET = 'yyy'; 5 6const client = new MainClient({ 7 api_key: API_KEY, 8 api_secret: API_SECRET, 9}); 10 11client 12 .getAccountTradeList({ symbol: 'BTCUSDT' }) 13 .then((result) => { 14 console.log('getAccountTradeList result: ', result); 15 }) 16 .catch((err) => { 17 console.error('getAccountTradeList error: ', err); 18 }); 19 20client 21 .getExchangeInfo() 22 .then((result) => { 23 console.log('getExchangeInfo inverse result: ', result); 24 }) 25 .catch((err) => { 26 console.error('getExchangeInfo inverse error: ', err); 27 });
See spot-client.ts for further information.
REST USD-M Futures
Start by importing the usd-m client. API credentials are optional, though an error is thrown when attempting any private API calls without credentials.
1const { USDMClient } = require('binance'); 2 3const API_KEY = 'xxx'; 4const API_SECRET = 'yyy'; 5 6const client = new USDMClient({ 7 api_key: API_KEY, 8 api_secret: API_SECRET, 9}); 10 11client 12 .getBalance() 13 .then((result) => { 14 console.log('getBalance result: ', result); 15 }) 16 .catch((err) => { 17 console.error('getBalance error: ', err); 18 }); 19 20client 21 .get24hrChangeStatististics() 22 .then((result) => { 23 console.log('get24hrChangeStatististics inverse futures result: ', result); 24 }) 25 .catch((err) => { 26 console.error('get24hrChangeStatististics inverse futures error: ', err); 27 });
See usdm-client.ts for further information.
REST COIN-M Futures
Start by importing the coin-m client. API credentials are optional, though an error is thrown when attempting any private API calls without credentials.
1const { CoinMClient } = require('binance'); 2 3const API_KEY = 'xxx'; 4const API_SECRET = 'yyy'; 5 6const client = new CoinMClient({ 7 api_key: API_KEY, 8 api_secret: API_SECRET, 9}); 10 11client 12 .getSymbolOrderBookTicker() 13 .then((result) => { 14 console.log('getSymbolOrderBookTicker result: ', result); 15 }) 16 .catch((err) => { 17 console.error('getSymbolOrderBookTicker error: ', err); 18 });
See coinm-client.ts for further information.
WebSockets
All websockets are accessible via the shared WebsocketClient
. As before, API credentials are optional unless the user data stream is required.
1const { WebsocketClient } = require('binance'); 2 3const API_KEY = 'xxx'; 4const API_SECRET = 'yyy'; 5 6// optionally override the logger 7const logger = { 8 ...DefaultLogger, 9 silly: (...params) => {}, 10}; 11 12const wsClient = new WebsocketClient( 13 { 14 api_key: key, 15 api_secret: secret, 16 beautify: true, 17 // Disable ping/pong ws heartbeat mechanism (not recommended) 18 // disableHeartbeat: true 19 }, 20 logger, 21); 22 23// receive raw events 24wsClient.on('message', (data) => { 25 console.log('raw message received ', JSON.stringify(data, null, 2)); 26}); 27 28// notification when a connection is opened 29wsClient.on('open', (data) => { 30 console.log('connection opened open:', data.wsKey, data.ws.target.url); 31}); 32 33// receive formatted events with beautified keys. Any "known" floats stored in strings as parsed as floats. 34wsClient.on('formattedMessage', (data) => { 35 console.log('formattedMessage: ', data); 36}); 37 38// read response to command sent via WS stream (e.g LIST_SUBSCRIPTIONS) 39wsClient.on('reply', (data) => { 40 console.log('log reply: ', JSON.stringify(data, null, 2)); 41}); 42 43// receive notification when a ws connection is reconnecting automatically 44wsClient.on('reconnecting', (data) => { 45 console.log('ws automatically reconnecting.... ', data?.wsKey); 46}); 47 48// receive notification that a reconnection completed successfully (e.g use REST to check for missing data) 49wsClient.on('reconnected', (data) => { 50 console.log('ws has reconnected ', data?.wsKey); 51}); 52 53// Recommended: receive error events (e.g. first reconnection failed) 54wsClient.on('error', (data) => { 55 console.log('ws saw error ', data?.wsKey); 56}); 57 58// Call methods to subcribe to as many websockets as you want. 59// Each method spawns a new connection, unless a websocket already exists for that particular request topic. 60// wsClient.subscribeSpotAggregateTrades(market); 61// wsClient.subscribeSpotTrades(market); 62// wsClient.subscribeSpotKline(market, interval); 63// wsClient.subscribeSpotSymbolMini24hrTicker(market); 64// wsClient.subscribeSpotAllMini24hrTickers(); 65// wsClient.subscribeSpotSymbol24hrTicker(market); 66// wsClient.subscribeSpotAll24hrTickers(); 67// wsClient.subscribeSpotSymbolBookTicker(market); 68// wsClient.subscribeSpotAllBookTickers(); 69// wsClient.subscribeSpotPartialBookDepth(market, 5); 70// wsClient.subscribeSpotDiffBookDepth(market); 71 72wsClient.subscribeSpotUserDataStream(); 73wsClient.subscribeMarginUserDataStream(); 74wsClient.subscribeIsolatedMarginUserDataStream('BTCUSDT'); 75 76wsClient.subscribeUsdFuturesUserDataStream(); 77 78// each method also restores the WebSocket object, which can be interacted with for more control 79// const ws1 = wsClient.subscribeSpotSymbolBookTicker(market); 80// const ws2 = wsClient.subscribeSpotAllBookTickers(); 81// const ws3 = wsClient.subscribeSpotUserDataStream(listenKey); 82 83// optionally directly open a connection to a URL. Not recommended for production use. 84// const ws4 = wsClient.connectToWsUrl(`wss://stream.binance.com:9443/ws/${listenKey}`, 'customDirectWsConnection1');
See websocket-client.ts for further information. Also see ws-userdata.ts for user data examples.
Customise Logging
Pass a custom logger which supports the log methods silly
, debug
, notice
, info
, warning
and error
, or override methods from the default logger as desired.
1const { WebsocketClient, DefaultLogger } = require('binance'); 2 3// Enable all logging on the silly level 4DefaultLogger.silly = (...params) => { 5 console.log('sillyLog: ', params); 6}; 7 8const ws = new WebsocketClient( 9 api_key: 'xxx', 10 api_secret: 'yyyy', 11 DefaultLogger 12);
Browser/Frontend Usage
Import
This is the "modern" way, allowing the package to be directly imported into frontend projects with full typescript support.
- Install these dependencies
1npm install crypto-browserify stream-browserify
- Add this to your
tsconfig.json
1{ 2 "compilerOptions": { 3 "paths": { 4 "crypto": [ 5 "./node_modules/crypto-browserify" 6 ], 7 "stream": [ 8 "./node_modules/stream-browserify" 9 ] 10}
- Declare this in the global context of your application (ex: in polyfills for angular)
1(window as any).global = window;
Webpack
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.
However, note that browser usage will lead to CORS errors due to Binance.
Contributions & Thanks
Have my projects helped you? Share the love, there are many ways you can show your thanks:
- Star & share my projects.
- Are my projects useful? Sponsor me on Github and support my effort to maintain & improve them: https://github.com/sponsors/tiagosiebler
- Have an interesting project? Get in touch & invite me to it.
- Or buy me all the coffee:
- ETH(ERC20):
0xA3Bda8BecaB4DCdA539Dc16F9C54a592553Be06C
- ETH(ERC20):
Contributions & Pull Requests
Contributions are encouraged, I will review any incoming pull requests. See the issues tab for todo items.
Star History
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
30 commit(s) and 15 issue activity found in the last 90 days -- score normalized to 10
Reason
no binaries found in the repo
Reason
license file detected
Details
- Info: project has a license file: LICENSE.md:0
- Info: FSF or OSI recognized license: MIT License: LICENSE.md:0
Reason
0 existing vulnerabilities detected
Reason
dependency not pinned by hash detected -- score normalized to 6
Details
- Warn: third-party GitHubAction not pinned by hash: .github/workflows/npmpublish.yml:18: update your workflow using https://app.stepsecurity.io/secureworkflow/tiagosiebler/binance/npmpublish.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/npmpublish.yml:27: update your workflow using https://app.stepsecurity.io/secureworkflow/tiagosiebler/binance/npmpublish.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/npmpublish.yml:29: update your workflow using https://app.stepsecurity.io/secureworkflow/tiagosiebler/binance/npmpublish.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/templates-readme.yml:18: update your workflow using https://app.stepsecurity.io/secureworkflow/tiagosiebler/binance/templates-readme.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/templates-readme.yml:20: update your workflow using https://app.stepsecurity.io/secureworkflow/tiagosiebler/binance/templates-readme.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/test.yml:15: update your workflow using https://app.stepsecurity.io/secureworkflow/tiagosiebler/binance/test.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/test.yml:17: update your workflow using https://app.stepsecurity.io/secureworkflow/tiagosiebler/binance/test.yml/master?enable=pin
- Info: 0 out of 6 GitHub-owned GitHubAction dependencies pinned
- Info: 0 out of 1 third-party GitHubAction dependencies pinned
- Info: 3 out of 3 npmCommand dependencies pinned
Reason
Found 2/6 approved changesets -- score normalized to 3
Reason
detected GitHub workflow tokens with excessive permissions
Details
- Info: topLevel 'contents' permission set to 'read': .github/workflows/npmpublish.yml:10
- Warn: topLevel 'contents' permission set to 'write': .github/workflows/templates-readme.yml:7
- Warn: no topLevel permission defined: .github/workflows/test.yml:1
- Info: no jobLevel write permissions found
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
security policy file not detected
Details
- Warn: no security policy file detected
- Warn: no security file to analyze
- Warn: no security file to analyze
- Warn: no security file to analyze
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 30 are checked with a SAST tool
Score
5.6
/10
Last Scanned on 2024-12-16
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