{"id":13633095,"url":"https://github.com/tiagosiebler/binance","last_synced_at":"2026-02-21T13:17:41.535Z","repository":{"id":37815825,"uuid":"100385838","full_name":"tiagosiebler/binance","owner":"tiagosiebler","description":"Node.js \u0026 JavaScript SDK for Binance REST APIs \u0026 WebSockets, with TypeScript \u0026 browser support, integration tests, beautification \u0026 more.","archived":false,"fork":false,"pushed_at":"2026-02-04T16:50:30.000Z","size":3857,"stargazers_count":909,"open_issues_count":14,"forks_count":288,"subscribers_count":30,"default_branch":"master","last_synced_at":"2026-02-05T03:34:19.428Z","etag":null,"topics":["api","api-client","api-wrapper","binance","binance-api","binance-api-node","binance-exchange","binance-node","binance-node-api","bitcoin","cryptocurrency","cryptocurrency-exchanges","exchange","javascript","nodejs","rest","trading","typescript","websocket"],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/package/binance","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/tiagosiebler.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null},"funding":{"github":["tiagosiebler"],"patreon":null,"open_collective":null,"ko_fi":null,"tidelift":null,"community_bridge":null,"liberapay":null,"issuehunt":null,"otechie":null,"custom":null}},"created_at":"2017-08-15T14:28:56.000Z","updated_at":"2026-02-04T16:51:53.000Z","dependencies_parsed_at":"2022-06-23T11:40:16.486Z","dependency_job_id":"4f8dae0c-8335-44c3-9937-60f83d74fddd","html_url":"https://github.com/tiagosiebler/binance","commit_stats":{"total_commits":556,"total_committers":62,"mean_commits":8.96774193548387,"dds":0.7661870503597122,"last_synced_commit":"2cc9f55095f559378d800175792dfa17144e5327"},"previous_names":["aarongarvey/binance"],"tags_count":25,"template":false,"template_full_name":null,"purl":"pkg:github/tiagosiebler/binance","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tiagosiebler%2Fbinance","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tiagosiebler%2Fbinance/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tiagosiebler%2Fbinance/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tiagosiebler%2Fbinance/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/tiagosiebler","download_url":"https://codeload.github.com/tiagosiebler/binance/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tiagosiebler%2Fbinance/sbom","scorecard":{"id":161743,"data":{"date":"2025-08-04","repo":{"name":"github.com/tiagosiebler/binance","commit":"249bafb2311e3eba941df67eb76a05a375f1b158"},"scorecard":{"version":"v5.2.1-28-gc1d103a9","commit":"c1d103a9bb9f635ec7260bf9aa0699466fa4be0e"},"score":6,"checks":[{"name":"Code-Review","score":7,"reason":"Found 5/7 approved changesets -- score normalized to 7","details":null,"documentation":{"short":"Determines if the project requires human code review before pull requests (aka merge requests) are merged.","url":"https://github.com/ossf/scorecard/blob/c1d103a9bb9f635ec7260bf9aa0699466fa4be0e/docs/checks.md#code-review"}},{"name":"Maintained","score":10,"reason":"30 commit(s) and 9 issue activity found in the last 90 days -- score normalized to 10","details":null,"documentation":{"short":"Determines if the project is \"actively maintained\".","url":"https://github.com/ossf/scorecard/blob/c1d103a9bb9f635ec7260bf9aa0699466fa4be0e/docs/checks.md#maintained"}},{"name":"Dangerous-Workflow","score":10,"reason":"no dangerous workflow patterns detected","details":null,"documentation":{"short":"Determines if the project's GitHub Action workflows avoid dangerous patterns.","url":"https://github.com/ossf/scorecard/blob/c1d103a9bb9f635ec7260bf9aa0699466fa4be0e/docs/checks.md#dangerous-workflow"}},{"name":"Packaging","score":-1,"reason":"packaging workflow not detected","details":["Warn: no GitHub/GitLab publishing workflow detected."],"documentation":{"short":"Determines if the project is published as a package that others can easily download, install, easily update, and uninstall.","url":"https://github.com/ossf/scorecard/blob/c1d103a9bb9f635ec7260bf9aa0699466fa4be0e/docs/checks.md#packaging"}},{"name":"Token-Permissions","score":0,"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"],"documentation":{"short":"Determines if the project's workflows follow the principle of least privilege.","url":"https://github.com/ossf/scorecard/blob/c1d103a9bb9f635ec7260bf9aa0699466fa4be0e/docs/checks.md#token-permissions"}},{"name":"CII-Best-Practices","score":0,"reason":"no effort to earn an OpenSSF best practices badge detected","details":null,"documentation":{"short":"Determines if the project has an OpenSSF (formerly CII) Best Practices Badge.","url":"https://github.com/ossf/scorecard/blob/c1d103a9bb9f635ec7260bf9aa0699466fa4be0e/docs/checks.md#cii-best-practices"}},{"name":"Binary-Artifacts","score":10,"reason":"no binaries found in the repo","details":null,"documentation":{"short":"Determines if the project has generated executable (binary) artifacts in the source repository.","url":"https://github.com/ossf/scorecard/blob/c1d103a9bb9f635ec7260bf9aa0699466fa4be0e/docs/checks.md#binary-artifacts"}},{"name":"License","score":10,"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"],"documentation":{"short":"Determines if the project has defined a license.","url":"https://github.com/ossf/scorecard/blob/c1d103a9bb9f635ec7260bf9aa0699466fa4be0e/docs/checks.md#license"}},{"name":"Signed-Releases","score":-1,"reason":"no releases found","details":null,"documentation":{"short":"Determines if the project cryptographically signs release artifacts.","url":"https://github.com/ossf/scorecard/blob/c1d103a9bb9f635ec7260bf9aa0699466fa4be0e/docs/checks.md#signed-releases"}},{"name":"Branch-Protection","score":-1,"reason":"internal error: error during branchesHandler.setup: internal error: githubv4.Query: Resource not accessible by integration","details":null,"documentation":{"short":"Determines if the default and release branches are protected with GitHub's branch protection settings.","url":"https://github.com/ossf/scorecard/blob/c1d103a9bb9f635ec7260bf9aa0699466fa4be0e/docs/checks.md#branch-protection"}},{"name":"Pinned-Dependencies","score":6,"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"],"documentation":{"short":"Determines if the project has declared and pinned the dependencies of its build process.","url":"https://github.com/ossf/scorecard/blob/c1d103a9bb9f635ec7260bf9aa0699466fa4be0e/docs/checks.md#pinned-dependencies"}},{"name":"Security-Policy","score":0,"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"],"documentation":{"short":"Determines if the project has published a security policy.","url":"https://github.com/ossf/scorecard/blob/c1d103a9bb9f635ec7260bf9aa0699466fa4be0e/docs/checks.md#security-policy"}},{"name":"Fuzzing","score":0,"reason":"project is not fuzzed","details":["Warn: no fuzzer integrations found"],"documentation":{"short":"Determines if the project uses fuzzing.","url":"https://github.com/ossf/scorecard/blob/c1d103a9bb9f635ec7260bf9aa0699466fa4be0e/docs/checks.md#fuzzing"}},{"name":"SAST","score":0,"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"],"documentation":{"short":"Determines if the project uses static code analysis.","url":"https://github.com/ossf/scorecard/blob/c1d103a9bb9f635ec7260bf9aa0699466fa4be0e/docs/checks.md#sast"}},{"name":"Vulnerabilities","score":10,"reason":"0 existing vulnerabilities detected","details":null,"documentation":{"short":"Determines if the project has open, known unfixed vulnerabilities.","url":"https://github.com/ossf/scorecard/blob/c1d103a9bb9f635ec7260bf9aa0699466fa4be0e/docs/checks.md#vulnerabilities"}}]},"last_synced_at":"2025-08-16T13:40:02.785Z","repository_id":37815825,"created_at":"2025-08-16T13:40:02.786Z","updated_at":"2025-08-16T13:40:02.786Z"},"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":29681508,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-02-21T12:30:22.644Z","status":"ssl_error","status_checked_at":"2026-02-21T12:29:55.402Z","response_time":107,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["api","api-client","api-wrapper","binance","binance-api","binance-api-node","binance-exchange","binance-node","binance-node-api","bitcoin","cryptocurrency","cryptocurrency-exchanges","exchange","javascript","nodejs","rest","trading","typescript","websocket"],"created_at":"2024-08-01T23:00:27.453Z","updated_at":"2026-02-21T13:17:41.503Z","avatar_url":"https://github.com/tiagosiebler.png","language":"TypeScript","funding_links":["https://github.com/sponsors/tiagosiebler"],"categories":["TypeScript","Market data libraries"],"sub_categories":[],"readme":"# Node.js \u0026 JavaScript SDK for Binance REST APIs \u0026 WebSockets\n\n[![Build \u0026 Test](https://github.com/tiagosiebler/binance/actions/workflows/test.yml/badge.svg)](https://github.com/tiagosiebler/binance/actions/workflows/test.yml)\n[![npm version](https://img.shields.io/npm/v/binance)][1]\n[![npm size](https://img.shields.io/bundlephobia/min/binance/latest)][1]\n[![users count](https://dependents.info/tiagosiebler/binance/badge?label=users)](https://dependents.info/tiagosiebler/binance)\n[![npm downloads](https://img.shields.io/npm/dt/binance)][1]\n[![last commit](https://img.shields.io/github/last-commit/tiagosiebler/binance)][1]\n[![CodeFactor](https://www.codefactor.io/repository/github/tiagosiebler/binance/badge)](https://www.codefactor.io/repository/github/tiagosiebler/binance)\n[![Telegram](https://img.shields.io/badge/chat-on%20telegram-blue.svg)](https://t.me/nodetraders)\n\n\u003cp align=\"center\"\u003e\n  \u003ca href=\"https://www.npmjs.com/package/binance\"\u003e\n    \u003cpicture\u003e\n      \u003csource media=\"(prefers-color-scheme: dark)\" srcset=\"https://github.com/tiagosiebler/binance/blob/master/docs/images/logoDarkMode2.svg?raw=true#gh-dark-mode-only\"\u003e\n      \u003cimg alt=\"SDK Logo\" src=\"https://github.com/tiagosiebler/binance/blob/master/docs/images/logoBrightMode2.svg?raw=true#gh-light-mode-only\"\u003e\n    \u003c/picture\u003e\n  \u003c/a\u003e\n\u003c/p\u003e\n\n[1]: https://www.npmjs.com/package/binance\n\nUpdated \u0026 performant JavaScript \u0026 Node.js SDK for the Binance REST APIs and WebSockets:\n\n- Professional, robust \u0026 performant Binance SDK with leading trading volume in production (livenet).\n- Extensive integration with Binance REST APIs, WebSockets \u0026 WebSocket APIs.\n- Complete TypeScript support (with type declarations for all API requests \u0026 responses).\n- Supports Binance REST APIs for Binance Spot, Margin, Isolated Margin, Options, USDM \u0026 CoinM Futures.\n  - Strongly typed requests and responses.\n  - Automated end-to-end tests on most API calls, ensuring no breaking changes are released to npm.\n- Actively maintained with a modern, promise-driven interface.\n- Support for all authentication mechanisms available on Binance:\n  - HMAC\n  - RSA\n  - Ed25519 (required for WS API).\n  - Passing a private key as a secret will automatically detect whether to switch to RSA or Ed25519 authentication.\n- Supports WebSockets for all available product groups on Binance including Spot, Margin, Isolated Margin, Portfolio, Options, USDM \u0026 CoinM Futures.\n  - Event driven messaging.\n  - Smart WebSocket persistence\n    - Automatically handle silent WebSocket disconnections through timed heartbeats, including the scheduled 24hr disconnect.\n    - Automatically handle listenKey persistence and expiration/refresh.\n    - Emit `reconnected` event when dropped connection is restored.\n  - Strongly typed on most WebSocket events, with typeguards available for TypeScript users.\n  - Optional:\n    - Automatic beautification of WebSocket events (from one-letter keys to descriptive words, and strings with floats to numbers).\n    - Automatic beautification of REST responses (parsing numbers in strings to numbers).\n- Supports WebSocket API on all available product groups, including Spot \u0026 Futures:\n  - Use the WebsocketClient's event-driven `sendWSAPIRequest()` method, or;\n  - Use the WebsocketAPIClient for a REST-like experience. Use the WebSocket API like a REST API! See [examples/ws-api-client.ts](./examples/ws-api-client.ts) for a demonstration.\n- Heavy automated end-to-end testing with real API calls.\n  - End-to-end testing before any release.\n  - Real API calls in e2e tests.\n- Proxy support via axios integration.\n- Active community support \u0026 collaboration in telegram: [Node.js Algo Traders](https://t.me/nodetraders).\n\n## Table of Contents\n\n- [Installation](#installation)\n- [Examples](#examples)\n  - [REST API Examples](./examples/REST)\n  - [WebSocket Examples](./examples/WebSockets)\n    - [WebSocket Consumers](./examples/WebSockets/)\n    - [WebSocket API](./examples/WebSockets/ws-api-client.ts)\n- [Issues \u0026 Discussion](#issues--discussion)\n- [Related Projects](#related-projects)\n- [Documentation Links](#documentation)\n- [Usage](#usage)\n  - [Demo Trading vs Testnet](#demo-trading-vs-testnet)\n  - [REST API Clients](#rest-api-clients)\n    - [REST Main Client](#rest-main-client)\n    - [REST USD-M Futures](#rest-usd-m-futures)\n    - [REST COIN-M Futures](#rest-coin-m-futures)\n    - [REST Portfolio Margin](#rest-portfolio-margin)\n  - [WebSockets](#websockets)\n    - [WebSocket Consumers](#websocket-consumers)\n    - [WebSocket API](#websocket-api)\n      - [Event Driven API](#event-driven-api)\n      - [Promise Driven API](#async-await-api)\n  - [Market Maker Endpoints](#market-maker-endpoints)\n    - [Using Market Maker Endpoints](#using-market-maker-endpoints)\n    - [Best practice](#best-practice)\n  - [Customise Logging](#customise-logging)\n  - [Frontend Usage](#browserfrontend-usage)\n    - [Import](#import)\n    - [Webpack](#webpack)\n- [LLMs \u0026 AI](#use-with-llms--ai)\n- [Contributions \u0026 Thanks](#contributions--thanks)\n\n## Installation\n\n`npm install binance --save`\n\n## Examples\n\nRefer to the [examples](./examples) folder for implementation demos.\n\n## Issues \u0026 Discussion\n\n- Issues? Check the [issues tab](https://github.com/tiagosiebler/binance/issues).\n- Discuss \u0026 collaborate with other node devs? Join our [Node.js Algo Traders](https://t.me/nodetraders) engineering community on telegram.\n- Questions about Binance APIs \u0026 WebSockets? Ask in the official [Binance API](https://t.me/binance_api_english) group on telegram.\n- Follow our announcement channel for real-time updates on [X/Twitter](https://x.com/sieblyio)\n\n\u003c!-- template_related_projects --\u003e\n\n## Related Projects\n\nCheck out my related JavaScript/TypeScript/Node.js projects:\n\n- Try our REST API \u0026 WebSocket SDKs published on npmjs:\n  - [Bybit Node.js SDK: bybit-api](https://www.npmjs.com/package/bybit-api)\n  - [Kraken Node.js SDK: @siebly/kraken-api](https://www.npmjs.com/package/coinbase-api)\n  - [OKX Node.js SDK: okx-api](https://www.npmjs.com/package/okx-api)\n  - [Binance Node.js SDK: binance](https://www.npmjs.com/package/binance)\n  - [Gate (gate.com) Node.js SDK: gateio-api](https://www.npmjs.com/package/gateio-api)\n  - [Bitget Node.js SDK: bitget-api](https://www.npmjs.com/package/bitget-api)\n  - [Kucoin Node.js SDK: kucoin-api](https://www.npmjs.com/package/kucoin-api)\n  - [Coinbase Node.js SDK: coinbase-api](https://www.npmjs.com/package/coinbase-api)\n  - [Bitmart Node.js SDK: bitmart-api](https://www.npmjs.com/package/bitmart-api)\n- Try my misc utilities:\n  - [OrderBooks Node.js: orderbooks](https://www.npmjs.com/package/orderbooks)\n  - [Crypto Exchange Account State Cache: accountstate](https://www.npmjs.com/package/accountstate)\n- Check out my examples:\n  - [awesome-crypto-examples Node.js](https://github.com/tiagosiebler/awesome-crypto-examples)\n  \u003c!-- template_related_projects_end --\u003e\n\n## Documentation\n\nMost methods accept JS objects. These can be populated using parameters specified by Binance's API documentation.\n\n- Binance API Documentation\n  - [ Spot ](https://developers.binance.com/docs/binance-spot-api-docs)\n  - [ Derivatives ](https://developers.binance.com/docs/derivatives)\n  - [ Margin ](https://developers.binance.com/docs/margin_trading)\n  - [ Wallet ](https://developers.binance.com/docs/wallet)\n- [Find all products here](https://developers.binance.com/en)\n- [REST Endpoint Function List](./docs/endpointFunctionList.md)\n- [TSDoc Documentation (autogenerated using typedoc)](https://tsdocs.dev/docs/binance)\n\n## Structure\n\nThis project uses typescript. Resources are stored in 3 key structures:\n\n- [src](./src) - the whole connector written in typescript\n- [lib](./lib) - the javascript version of the project (compiled from typescript). This should not be edited directly, as it will be overwritten with each release.\n- [dist](./dist) - the packed bundle of the project for use in browser environments.\n\n---\n\n# Usage\n\nCreate API credentials at Binance\n\n- [Livenet](https://www.binance.com/en/support/faq/360002502072?ref=IVRLUZJO)\n- [Testnet](https://testnet.binance.vision/).\n- [Testnet Futures](testnet.binancefuture.com).\n- [Demo Trading](https://www.binance.com/en/support/faq/how-to-test-my-functions-on-binance-spot-test-network-ab78f9a1b8824cf0a106b4229c76496d) - Uses real market data with simulated trading.\n\n### Demo Trading vs Testnet\n\nBinance offers two testing environments:\n\n- **Demo Trading**: Uses real market data but simulated trading. This is ideal for testing strategies since market conditions match production. Available for Spot, USD-M Futures, and COIN-M Futures.\n- **Testnet**: Separate environment with simulated market data. Market conditions are very different from real markets and not recommended for strategy testing.\n\nTo use demo trading, simply set `demoTrading: true` in the client options. See the [demo trading examples](./examples/REST/rest-spot-demo.ts) for more information.\n\n## REST API Clients\n\nThere are several REST API modules as there are some differences in each API group.\n\n1. `MainClient` for most APIs, including: spot, margin, isolated margin, mining, BLVT, BSwap, Fiat \u0026 sub-account management.\n2. `USDMClient` for USD-M futures APIs.\n3. `CoinMClient` for COIN-M futures APIs.\n4. `PortfolioClient` for Portfolio Margin APIs.\n\nVanilla Options is not yet available. Please get in touch if you're looking for this.\n\n### REST Main Client\n\nThe MainClient covers all endpoints under the main \"api\\*.binance.com\" subdomains, including but not limited to endpoints in the following product groups:\n\n- Spot\n- Cross \u0026 isolated margin\n- Convert\n- Wallet\n- Futures management (transfers \u0026 history)\n- Sub account management\n- Misc transfers\n- Auto \u0026 dual invest\n- Staking\n- Mining\n- Loans \u0026 VIP loans\n- Simple Earn\n- NFTs\n- C2C\n- Exchange Link\n- Alpha trading\n\nRefer to the following links for a complete list of available endpoints:\n\n- [Binance Node.js \u0026 JavaScript SDK Endpoint Map](https://github.com/tiagosiebler/binance/blob/master/docs/endpointFunctionList.md)\n- [Binance Spot API Docs](https://developers.binance.com/docs/binance-spot-api-docs/rest-api/general-endpoints)\n\nStart by importing the `MainClient` class. API credentials are optional, unless you plan on making private API calls. More Node.js \u0026 JavaScript examples for Binance's REST APIs \u0026 WebSockets can be found in the [examples](./examples) folder on GitHub.\n\n```javascript\nimport { MainClient } from 'binance';\n\n// or, if you prefer `require()`:\n// const { MainClient } = require('binance');\n\nconst API_KEY = 'xxx';\nconst API_SECRET = 'yyy';\n\nconst client = new MainClient({\n  api_key: API_KEY,\n  api_secret: API_SECRET,\n  // Connect to testnet environment\n  // testnet: true,\n});\n\nclient\n  .getAccountTradeList({ symbol: 'BTCUSDT' })\n  .then((result) =\u003e {\n    console.log('getAccountTradeList result: ', result);\n  })\n  .catch((err) =\u003e {\n    console.error('getAccountTradeList error: ', err);\n  });\n\nclient\n  .getExchangeInfo()\n  .then((result) =\u003e {\n    console.log('getExchangeInfo inverse result: ', result);\n  })\n  .catch((err) =\u003e {\n    console.error('getExchangeInfo inverse error: ', err);\n  });\n```\n\nSee [main-client.ts](./src/main-client.ts) for further information on the available REST API endpoints for spot/margin/etc.\n\n### REST USD-M Futures\n\nStart by importing the USDM client. API credentials are optional, unless you plan on making private API calls.\n\n```javascript\nimport { USDMClient } from 'binance';\n\n// or, if you prefer `require()`:\n// const { USDMClient } = require('binance');\n\nconst API_KEY = 'xxx';\nconst API_SECRET = 'yyy';\n\nconst client = new USDMClient({\n  api_key: API_KEY,\n  api_secret: API_SECRET,\n  // Connect to testnet environment\n  // testnet: true,\n});\n\nclient\n  .getBalance()\n  .then((result) =\u003e {\n    console.log('getBalance result: ', result);\n  })\n  .catch((err) =\u003e {\n    console.error('getBalance error: ', err);\n  });\n\nclient\n  .submitNewOrder({\n    side: 'SELL',\n    symbol: 'BTCUSDT',\n    type: 'MARKET',\n    quantity: 0.001,\n  })\n  .then((result) =\u003e {\n    console.log('submitNewOrder result: ', result);\n  })\n  .catch((err) =\u003e {\n    console.error('submitNewOrder error: ', err);\n  });\n```\n\nSee [usdm-client.ts](./src/usdm-client.ts) for further information.\n\n### REST COIN-M Futures\n\nStart by importing the coin-m client. API credentials are optional, though an error is thrown when attempting any private API calls without credentials.\n\n```javascript\nimport { CoinMClient } from 'binance';\n\n// or, if you prefer `require()`:\n// const { CoinMClient } = require('binance');\n\nconst API_KEY = 'xxx';\nconst API_SECRET = 'yyy';\n\nconst client = new CoinMClient({\n  api_key: API_KEY,\n  api_secret: API_SECRET,\n  // Connect to testnet environment\n  // testnet: true,\n});\n\nclient\n  .getSymbolOrderBookTicker()\n  .then((result) =\u003e {\n    console.log('getSymbolOrderBookTicker result: ', result);\n  })\n  .catch((err) =\u003e {\n    console.error('getSymbolOrderBookTicker error: ', err);\n  });\n```\n\nSee [coinm-client.ts](./src/coinm-client.ts) for further information.\n\n### REST Portfolio Margin\n\nStart by importing the Portfolio client. API credentials are optional, though an error is thrown when attempting any private API calls without credentials.\n\n```javascript\nimport { PortfolioClient } from 'binance';\n\n// or, if you prefer `require()`:\n// const { PortfolioClient } = require('binance');\n\nconst API_KEY = 'xxx';\nconst API_SECRET = 'yyy';\n\nconst client = new PortfolioClient({\n  api_key: API_KEY,\n  api_secret: API_SECRET,\n  // Connect to testnet environment\n  // testnet: true,\n});\n\nclient\n  .getBalance()\n  .then((result) =\u003e {\n    console.log('getBalance result: ', result);\n  })\n  .catch((err) =\u003e {\n    console.error('getBalance error: ', err);\n  });\n\nclient\n  .submitNewUMOrder({\n    side: 'SELL',\n    symbol: 'BTCUSDT',\n    type: 'MARKET',\n    quantity: 0.001,\n  })\n  .then((result) =\u003e {\n    console.log('submitNewUMOrder result: ', result);\n  })\n  .catch((err) =\u003e {\n    console.error('submitNewUMOrder error: ', err);\n  });\n```\n\nSee [portfolio-client.ts](./src/portfolio-client.ts) for further information.\n\n## WebSockets\n\n### WebSocket Consumers\n\nAll websockets are accessible via the shared `WebsocketClient`. As before, API credentials are optional unless the user data stream is required.\n\nThe below example demonstrates connecting as a consumer, to receive WebSocket events from Binance:\n\n```javascript\nimport { WebsocketClient } from 'binance';\n\n// or, if you prefer `require()`:\n// const { WebsocketClient } = require('binance');\n\nconst API_KEY = 'xxx';\nconst API_SECRET = 'yyy';\n\n/**\n * The WebsocketClient will manage individual connections for you, under the hood.\n * Just make an instance of the WS Client and subscribe to topics. It'll handle the rest.\n */\nconst wsClient = new WebsocketClient({\n  api_key: key,\n  api_secret: secret,\n  // Optional: when enabled, the SDK will try to format incoming data into more readable objects.\n  // Beautified data is emitted via the \"formattedMessage\" event\n  beautify: true,\n  // Disable ping/pong ws heartbeat mechanism (not recommended)\n  // disableHeartbeat: true,\n  // Connect to testnet environment\n  // testnet: true,\n});\n\n// receive raw events\nwsClient.on('message', (data) =\u003e {\n  console.log('raw message received ', JSON.stringify(data, null, 2));\n});\n\n// notification when a connection is opened\nwsClient.on('open', (data) =\u003e {\n  console.log('connection opened open:', data.wsKey, data.wsUrl);\n});\n\n// receive formatted events with beautified keys. Any \"known\" floats stored in strings as parsed as floats.\nwsClient.on('formattedMessage', (data) =\u003e {\n  console.log('formattedMessage: ', data);\n});\n\n// read response to command sent via WS stream (e.g LIST_SUBSCRIPTIONS)\nwsClient.on('response', (data) =\u003e {\n  console.log('log response: ', JSON.stringify(data, null, 2));\n});\n\n// receive notification when a ws connection is reconnecting automatically\nwsClient.on('reconnecting', (data) =\u003e {\n  console.log('ws automatically reconnecting.... ', data?.wsKey);\n});\n\n// receive notification that a reconnection completed successfully (e.g use REST to check for missing data)\nwsClient.on('reconnected', (data) =\u003e {\n  console.log('ws has reconnected ', data?.wsKey);\n});\n\n// Recommended: receive error events (e.g. first reconnection failed)\nwsClient.on('exception', (data) =\u003e {\n  console.log('ws saw error ', data?.wsKey);\n});\n\n/**\n * Subscribe to public topics either one at a time or many in an array\n */\n\n// E.g. one at a time, routed to the coinm futures websockets:\nwsClient.subscribe('btcusd@indexPrice', 'coinm');\nwsClient.subscribe('btcusd@miniTicker', 'coinm');\n\n// Or send many topics at once to a stream, e.g. the usdm futures stream:\nwsClient.subscribe(\n  ['btcusdt@aggTrade', 'btcusdt@markPrice', '!miniTicker@arr'],\n  'usdm',\n);\n\n// spot \u0026 margin topics should go to \"main\"\n// (similar how the MainClient is for REST APIs in that product group)\nwsClient.subscribe(\n  [\n    // All Market Rolling Window Statistics Streams\n    // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#all-market-rolling-window-statistics-streams\n    '!ticker_1h@arr',\n    // Individual Symbol Book Ticker Streams\n    // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#individual-symbol-book-ticker-streams\n    'btcusdt@bookTicker',\n    // Average Price\n    // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#average-price\n    'btcusdt@avgPrice',\n    // Partial Book Depth Streams\n    // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#partial-book-depth-streams\n    'btcusdt@depth10@100ms',\n    // Diff. Depth Stream\n    // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#diff-depth-stream\n    'btcusdt@depth',\n  ],\n  // Look at the `WS_KEY_URL_MAP` for a list of values here:\n  // https://github.com/tiagosiebler/binance/blob/master/src/util/websockets/websocket-util.ts\n  // \"main\" connects to wss://stream.binance.com:9443/stream\n  // https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams\n  'main',\n);\n\n/**\n * For the user data stream, these convenient subscribe methods open a dedicated\n * connection with the listen key workflow:\n */\n\nwsClient.subscribeSpotUserDataStream();\nwsClient.subscribeMarginUserDataStream();\nwsClient.subscribeIsolatedMarginUserDataStream('BTCUSDT');\nwsClient.subscribeUsdFuturesUserDataStream();\nwsClient.subscribePortfolioMarginUserDataStream();\n```\n\nSee [websocket-client.ts](./src/websocket-client.ts) for further information. Also see [ws-userdata.ts](./examples/ws-userdata.ts) for user data examples.\n\n#### Preserving large integers in WebSocket messages\n\nBy default, messages are parsed using `JSON.parse`, which cannot precisely represent integers larger than `Number.MAX_SAFE_INTEGER`.\nIf you need to preserve large integers (e.g., order IDs), provide a custom parser via `customParseJSONFn`.\n\nExample using RegEx below, although alternatives are possible too if desired. For more exampes check [ws-custom-parser.ts](./examples/WebSockets/ws-custom-parser.ts) in the examples folder:\n\n```ts\nimport { WebsocketClient } from 'binance';\n\n/**\n * ETHUSDT in futures can have unusually large orderId values, sent as numbers. See this thread for more details:\n * https://github.com/tiagosiebler/binance/issues/208\n *\n * If this is a problem for you, you can set a custom JSON parsing alternative using the customParseJSONFn hook injected into the WebsocketClient's constructor, as below:\n */\nconst ws = new WebsocketClient({\n  // Default behaviour, if you don't include this:\n  // customParseJSONFn: (rawEvent) =\u003e {\n  //   return JSON.parse(rawEvent);\n  // },\n\n  // Or, pre-process the raw event using RegEx, before using the same workflow:\n  customParseJSONFn: (rawEvent) =\u003e {\n    return JSON.parse(\n      rawEvent.replace(/\"orderId\":\\s*(\\d+)/g, '\"orderId\":\"$1\"'),\n    );\n  },\n\n  // Or, use a 3rd party library such as json-bigint:\n  // customParseJSONFn: (rawEvent) =\u003e {\n  //   return JSONbig({ storeAsString: true }).parse(rawEvent);\n  // },\n});\n\nws.on('message', (msg) =\u003e {\n  console.log(msg);\n});\n\n// If you prefer native BigInt, beware JSON.stringify will throw on BigInt values.\n// Use a custom replacer or JSONbig.stringify if you need to log/serialize:\n// const replacer = (_k: string, v: unknown) =\u003e typeof v === 'bigint' ? v.toString() : v;\n// console.log(JSON.stringify(msg, replacer));\n```\n\n### WebSocket API\n\nSome of the product groups available on Binance also support sending requests (commands) over an active WebSocket connection. This is called the WebSocket API.\n\nNote: the WebSocket API requires the use of Ed25519 keys. HMAC \u0026 RSA keys are not supported by Binance for the WebSocket API (as of Apr 2025).\n\n#### Event Driven API\n\nThe WebSocket API is available in the [WebsocketClient](./src/websocket-client.ts) via the `sendWSAPIRequest(wsKey, command, commandParameters)` method.\n\nEach 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.\n\n#### Async Await API\n\nThe 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).\n\nIt 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.\n\nBelow is an example showing how easy it is to use the WebSocket API without any concern for the complexity of managing WebSockets.\n\n```typescript\nimport { WebsocketAPIClient } from 'binance';\n\n// or, if you prefer `require()`:\n// const { WebsocketAPIClient } = require('binance');\n\n/**\n * The WS API only works with an Ed25519 API key.\n *\n * Check the rest-private-ed25519.md in this folder for more guidance\n * on preparing this Ed25519 API key.\n */\n\nconst publicKey = `-----BEGIN PUBLIC KEY-----\nMCexampleQTxwLU9o=\n-----END PUBLIC KEY-----\n`;\n\nconst privateKey = `-----BEGIN PRIVATE KEY-----\nMC4CAQAexamplewqj5CzUuTy1\n-----END PRIVATE KEY-----\n`;\n\n// API Key returned by binance, generated using the publicKey (above) via Binance's website\nconst apiKey = 'TQpJexamplerobdG';\n\n// Make an instance of the WS API Client\nconst wsClient = new WebsocketAPIClient({\n  api_key: apiKey,\n  api_secret: privateKey,\n  beautify: true,\n\n  // Enforce testnet ws connections, regardless of supplied wsKey\n  // testnet: true,\n});\n\n// Optional, if you see RECV Window errors, you can use this to manage time issues. However, make sure you sync your system clock first!\n// https://github.com/tiagosiebler/awesome-crypto-examples/wiki/Timestamp-for-this-request-is-outside-of-the-recvWindow\n// wsClient.setTimeOffsetMs(-5000);\n\n// Optional, see above. Can be used to prepare a connection before sending commands\n// await wsClient.connectWSAPI(WS_KEY_MAP.mainWSAPI);\n\n// Make WebSocket API calls, very similar to a REST API:\n\nwsClient\n  .getFuturesAccountBalanceV2({\n    timestamp: Date.now(),\n    recvWindow: 5000,\n  })\n  .then((result) =\u003e {\n    console.log('getFuturesAccountBalanceV2 result: ', result);\n  })\n  .catch((err) =\u003e {\n    console.error('getFuturesAccountBalanceV2 error: ', err);\n  });\n\nwsClient\n  .submitNewFuturesOrder('usdm', {\n    side: 'SELL',\n    symbol: 'BTCUSDT',\n    type: 'MARKET',\n    quantity: 0.001,\n    timestamp: Date.now(),\n    // recvWindow: 5000,\n  })\n  .then((result) =\u003e {\n    console.log('getFuturesAccountBalanceV2 result: ', result);\n  })\n  .catch((err) =\u003e {\n    console.error('getFuturesAccountBalanceV2 error: ', err);\n  });\n```\n\n---\n\n## Market Maker Endpoints\n\nBinance provides specialized market maker endpoints for qualified high-frequency trading users who have enrolled in at least one of the Futures Liquidity Provider Programs, including the USDⓈ-M Futures Maker Program, COIN-M Futures Maker Program, and USDⓈ-M Futures Taker Program.\n\nThese endpoints provide the same functionality as regular endpoints but with optimized routing for market makers. For more information about eligibility and enrollment, visit: https://www.binance.com/en/support/faq/detail/7df7f3838c3b49e692d175374c3a3283\n\n### Using Market Maker Endpoints\n\nTo use market maker endpoints, simply add the `useMMSubdomain: true` option when initializing any client (REST API clients, WebSocket clients, or WebSocket API clients):\n\n#### Market Maker REST API Clients\n\n```javascript\nimport { USDMClient, CoinMClient } from 'binance';\n\n// USD-M Futures with MM endpoints\nconst usdmClient = new USDMClient({\n  api_key: API_KEY,\n  api_secret: API_SECRET,\n  useMMSubdomain: true, // Enable market maker endpoints\n});\n\n// COIN-M Futures with MM endpoints\nconst coinmClient = new CoinMClient({\n  api_key: API_KEY,\n  api_secret: API_SECRET,\n  useMMSubdomain: true, // Enable market maker endpoints\n});\n```\n\n#### Market Maker WebSocket Clients\n\n```javascript\nimport { WebsocketClient, WebsocketAPIClient } from 'binance';\n\n// WebSocket consumer with MM endpoints\nconst wsClient = new WebsocketClient({\n  api_key: API_KEY,\n  api_secret: API_SECRET,\n  useMMSubdomain: true, // Enable market maker endpoints\n});\n\n// WebSocket API client with MM endpoints\nconst wsApiClient = new WebsocketAPIClient({\n  api_key: API_KEY,\n  api_secret: API_SECRET,\n  useMMSubdomain: true, // Enable market maker endpoints\n});\n```\n\n**Note:** Market maker endpoints are only available for futures products (USD-M and COIN-M). Spot, margin, and other product groups use the regular endpoints regardless of the `useMMSubdomain` setting. Market maker endpoints are also not available on testnet environments.\n\n### Best practice\n\nSince market maker endpoints are only available for some of the futures endpoints, you may need to use multiple client instances if your algorithm needs to use both regular and MM endpoints.\n\n```javascript\nimport { USDMClient } from 'binance';\n\n// MM client for USD-M futures\nconst futuresMMClient = new USDMClient({\n  api_key: API_KEY,\n  api_secret: API_SECRET,\n  useMMEndpoints: true, // Use MM endpoints for futures\n});\n\n// Regular client for USD-M futures\nconst futuresRegularClient = new USDMClient({\n  api_key: API_KEY,\n  api_secret: API_SECRET,\n  useMMEndpoints: false, // Use regular endpoints for futures\n});\n```\n\n## Customise Logging\n\nPass a custom logger which supports the log methods `trace`, `info` and `error`, or override methods from the default logger as desired.\n\n```javascript\nimport { WebsocketClient, DefaultLogger } from 'binance';\n\n// or, if you prefer `require()`:\n// const { WebsocketClient, DefaultLogger } = require('binance');\n\n// Enable all logging on the trace level (disabled by default)\nDefaultLogger.trace = (...params) =\u003e {\n  console.trace('trace: ', params);\n};\n\n// Pass the updated logger as the 2nd parameter\nconst ws = new WebsocketClient(\n  {\n    api_key: key,\n    api_secret: secret,\n    beautify: true,\n  },\n  DefaultLogger\n);\n\n// Or, create a completely custom logger with the 3 available functions\nconst customLogger = {\n  trace: (...params: LogParams): void =\u003e {\n    console.trace(new Date(), params);\n  },\n  info: (...params: LogParams): void =\u003e {\n    console.info(new Date(), params);\n  },\n  error: (...params: LogParams): void =\u003e {\n    console.error(new Date(), params);\n  },\n}\n\n// Pass the custom logger as the 2nd parameter\nconst ws = new WebsocketClient(\n  {\n    api_key: key,\n    api_secret: secret,\n    beautify: true,\n  },\n  customLogger\n);\n```\n\n## Browser/Frontend Usage\n\n### Import\n\nThis is the \"modern\" way, allowing the package to be directly imported into frontend projects with full typescript support.\n\n1. Install these dependencies\n   ```sh\n   npm install crypto-browserify stream-browserify\n   ```\n2. Add this to your `tsconfig.json`\n   ```json\n   {\n     \"compilerOptions\": {\n       \"paths\": {\n         \"crypto\": [\n           \"./node_modules/crypto-browserify\"\n         ],\n         \"stream\": [\n           \"./node_modules/stream-browserify\"\n         ]\n   }\n   ```\n3. Declare this in the global context of your application (ex: in polyfills for angular)\n   ```js\n   (window as any).global = window;\n   ```\n\n### Webpack\n\nThis 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.\n\nBuild a bundle using webpack:\n\n- `npm install`\n- `npm build`\n- `npm pack`\n\nThe bundle can be found in `dist/`. Altough usage should be largely consistent, smaller differences will exist. Documentation is still TODO.\n\n## Use with LLMs \u0026 AI\n\nThis SDK includes a bundled `llms.txt` file in the root of the repository. If you're developing with LLMs, use the included `llms.txt` with your LLM - it will significantly improve the LLMs understanding of how to correctly use this SDK.\n\nThis file contains AI optimised structure of all the functions in this package, and their parameters for easier use with any learning models or artificial intelligence.\n\n---\n\n\u003c!-- template_contributions --\u003e\n\n### Contributions \u0026 Thanks\n\nHave my projects helped you? Share the love, there are many ways you can show your thanks:\n\n- Star \u0026 share my projects.\n- Are my projects useful? Sponsor me on Github and support my effort to maintain \u0026 improve them: https://github.com/sponsors/tiagosiebler\n- Have an interesting project? Get in touch \u0026 invite me to it.\n- Or buy me all the coffee:\n  - ETH(ERC20): `0xA3Bda8BecaB4DCdA539Dc16F9C54a592553Be06C` \u003c!-- metamask --\u003e\n- Sign up with my referral links:\n  - OKX (receive a 20% fee discount!): https://www.okx.com/join/42013004\n  - Binance (receive a 20% fee discount!): https://accounts.binance.com/register?ref=OKFFGIJJ\n  - HyperLiquid (receive a 4% fee discount!): https://app.hyperliquid.xyz/join/SDK\n  - Gate: https://www.gate.io/signup/NODESDKS?ref_type=103\n\n\u003c!---\nold ones:\n  - BTC: `1C6GWZL1XW3jrjpPTS863XtZiXL1aTK7Jk`\n  - BTC(SegWit): `bc1ql64wr9z3khp2gy7dqlmqw7cp6h0lcusz0zjtls`\n  - ETH(ERC20): `0xe0bbbc805e0e83341fadc210d6202f4022e50992`\n  - USDT(TRC20): `TA18VUywcNEM9ahh3TTWF3sFpt9rkLnnQa\n  - gate: https://www.gate.io/signup/AVNNU1WK?ref_type=103\n\n--\u003e\n\u003c!-- template_contributions_end --\u003e\n\n### Contributions \u0026 Pull Requests\n\nContributions are encouraged, I will review any incoming pull requests. See the issues tab for todo items.\n\n## Used By\n\n[![Repository Users Preview Image](https://dependents.info/tiagosiebler/binance/image)](https://github.com/tiagosiebler/binance/network/dependents)\n\n\u003c!-- template_star_history --\u003e\n\n## Star History\n\n[![Star History Chart](https://api.star-history.com/svg?repos=tiagosiebler/bybit-api,tiagosiebler/okx-api,tiagosiebler/binance,tiagosiebler/bitget-api,tiagosiebler/bitmart-api,tiagosiebler/gateio-api,tiagosiebler/kucoin-api,tiagosiebler/coinbase-api,tiagosiebler/orderbooks,tiagosiebler/accountstate,tiagosiebler/awesome-crypto-examples\u0026type=Date)](https://star-history.com/#tiagosiebler/bybit-api\u0026tiagosiebler/okx-api\u0026tiagosiebler/binance\u0026tiagosiebler/bitget-api\u0026tiagosiebler/bitmart-api\u0026tiagosiebler/gateio-api\u0026tiagosiebler/kucoin-api\u0026tiagosiebler/coinbase-api\u0026tiagosiebler/orderbooks\u0026tiagosiebler/accountstate\u0026tiagosiebler/awesome-crypto-examples\u0026Date)\n\n\u003c!-- template_star_history_end --\u003e\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftiagosiebler%2Fbinance","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftiagosiebler%2Fbinance","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftiagosiebler%2Fbinance/lists"}