From 312c6d629f5926e0354292a6690c879436782e02 Mon Sep 17 00:00:00 2001 From: harbourlark Date: Wed, 2 Dec 2026 01:59:40 +0000 Subject: [PATCH 1/2] docs(binance): add a frequently asked questions hub and five question pages --- .../faq/does-binance-have-a-websocket-api.md | 55 +++++++++++++++ ...-a-binance-api-key-and-use-it-in-nodejs.md | 69 +++++++++++++++++++ ...-binance-futures-liquidations-in-nodejs.md | 66 ++++++++++++++++++ sdks/binance/docs/faq/index.md | 62 +++++++++++++++++ ...a-binance-sdk-for-typescript-and-nodejs.md | 42 +++++++++++ .../faq/why-does-binance-return-error-2015.md | 60 ++++++++++++++++ sdks/binance/docs/guides/api-key.md | 2 + sdks/binance/docs/guides/errors.md | 2 + sdks/binance/docs/guides/futures-api.md | 2 + sdks/binance/docs/guides/troubleshooting.md | 2 +- sdks/binance/docs/guides/websocket-api.md | 2 + sdks/binance/docs/guides/websockets.md | 2 + sdks/binance/docs/index.md | 2 + .../binance/examples/check-key-permissions.ts | 31 +++++++++ sdks/binance/examples/liquidations-stream.ts | 30 ++++++++ sdks/binance/examples/websocket-api-price.ts | 15 ++++ shared/config.mjs | 8 +++ 17 files changed, 451 insertions(+), 1 deletion(-) create mode 100644 sdks/binance/docs/faq/does-binance-have-a-websocket-api.md create mode 100644 sdks/binance/docs/faq/how-do-i-get-a-binance-api-key-and-use-it-in-nodejs.md create mode 100644 sdks/binance/docs/faq/how-do-i-get-binance-futures-liquidations-in-nodejs.md create mode 100644 sdks/binance/docs/faq/index.md create mode 100644 sdks/binance/docs/faq/is-there-a-binance-sdk-for-typescript-and-nodejs.md create mode 100644 sdks/binance/docs/faq/why-does-binance-return-error-2015.md create mode 100644 sdks/binance/examples/check-key-permissions.ts create mode 100644 sdks/binance/examples/liquidations-stream.ts create mode 100644 sdks/binance/examples/websocket-api-price.ts diff --git a/sdks/binance/docs/faq/does-binance-have-a-websocket-api.md b/sdks/binance/docs/faq/does-binance-have-a-websocket-api.md new file mode 100644 index 00000000..2e772e9c --- /dev/null +++ b/sdks/binance/docs/faq/does-binance-have-a-websocket-api.md @@ -0,0 +1,55 @@ +--- +title: "Does Binance have a WebSocket API?" +titleTemplate: ":title | Binance SDK FAQ | Siebly Docs" +description: "Yes. Binance offers WebSocket Streams for live data and a WebSocket API for request and response calls. See how to use both from JavaScript and TypeScript with the binance SDK." +sidebar: false +prev: false +next: false +faq: + - q: "Does Binance have a WebSocket API?" + a: "Yes. Binance has two WebSocket interfaces. WebSocket Streams push live market and account data, and the WebSocket API sends request and response calls, such as placing and querying orders, over a persistent connection. The binance SDK covers both, with WebsocketClient for streams and WebsocketAPIClient for the WebSocket API." +--- + +# Does Binance have a WebSocket API? + +Yes. Binance has two WebSocket interfaces. **WebSocket Streams** push live market and account data to you. The **WebSocket API** sends request and response calls, such as placing and querying orders, over one persistent connection. The [`binance`](https://www.npmjs.com/package/binance) SDK covers both, with `WebsocketClient` for streams and `WebsocketAPIClient` for the WebSocket API. + +## Which one to use + +| | WebSocket Streams | WebSocket API | +| --- | --- | --- | +| Direction | Binance pushes updates to you | You send a request and receive one response | +| Typical use | Live prices, order books, trades, account updates | Prices, order placement and account queries without a new HTTP request each time | +| SDK client | `WebsocketClient` | `WebsocketAPIClient` | +| Guide | [WebSocket streams](/guides/websockets) | [WebSocket API requests](/guides/websocket-api) | + +Use streams for anything continuous. Use the WebSocket API when you want REST-style calls on a connection that is already open. + +## Subscribe to live prices + +Streams need no API key for public data. This example prints BTCUSDT Spot ticker updates for 30 seconds and then closes the connection: + +<<< @/../examples/stream.ts + +## Make a WebSocket API request + +`WebsocketAPIClient` has one method for each supported WebSocket API operation. It opens and looks after the connection, so a call reads like a REST call. This public price request needs no key: + +<<< @/../examples/websocket-api-price.ts + +For account calls, pass `api_key` and `api_secret` to the client. Binance supports HMAC, RSA and Ed25519 keys on the WebSocket API. An Ed25519 key lets the connection log on once and skip signing each request. See [API key setup](/guides/api-key#ed25519-keys). + +## Connection details + +- Binance serves the Spot WebSocket API at `wss://ws-api.binance.com:443/ws-api/v3` and the Spot Testnet at `wss://ws-api.testnet.binance.vision/ws-api/v3`. The SDK picks the address for you. +- Binance closes each connection after 24 hours. The SDK reconnects and restores your subscriptions. See [recover after a disconnect](/guides/websockets#recover-after-a-disconnect). +- A WebSocket API response confirms one request. Follow orders and fills with the [private account stream](/guides/private-streams). + +## Related guides + +- [Binance WebSocket streams in the SDK](/guides/websockets) +- [Binance WebSocket API in the SDK](/guides/websocket-api) +- [Private account updates](/guides/private-streams) +- [WebsocketClient reference](/api/classes/WebsocketClient) and [WebsocketAPIClient reference](/api/classes/WebsocketAPIClient) +- Binance's own reference: [WebSocket API](https://developers.binance.com/docs/binance-spot-api-docs/websocket-api) and [WebSocket Streams](https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams) +- [More Binance SDK questions](/faq/) diff --git a/sdks/binance/docs/faq/how-do-i-get-a-binance-api-key-and-use-it-in-nodejs.md b/sdks/binance/docs/faq/how-do-i-get-a-binance-api-key-and-use-it-in-nodejs.md new file mode 100644 index 00000000..4a70aba8 --- /dev/null +++ b/sdks/binance/docs/faq/how-do-i-get-a-binance-api-key-and-use-it-in-nodejs.md @@ -0,0 +1,69 @@ +--- +title: "How do I get a Binance API key and use it in Node.js?" +titleTemplate: ":title | Binance SDK FAQ | Siebly Docs" +description: "Create a Binance API key, set its permissions and IP restrictions, then use it from Node.js with the binance SDK. Includes a short TypeScript check that the key works." +sidebar: false +prev: false +next: false +faq: + - q: "How do I get a Binance API key and use it in Node.js?" + a: "Create the key in your Binance account under API Management, store the key and secret in environment variables, and pass them to MainClient from the binance SDK. A call to getAccountInformation() confirms that the key works. Public market data needs no key." +--- + +# How do I get a Binance API key and use it in Node.js? + +Create the key in your Binance account under API Management, store the key and secret in environment variables, and pass them to `MainClient` from the [`binance`](https://www.npmjs.com/package/binance) SDK. A call to `getAccountInformation()` confirms that the key works. Public market data needs no key at all. + +## Create the key + +1. Log in to Binance and open Profile, then Account, then API Management. +2. Choose Create API and pick a key type. A system-generated key uses HMAC and gives you a key and a secret. A self-generated key uses Ed25519 or RSA, and you register a public key that you generate yourself. +3. Name the key and confirm with your two-factor device or passkey. +4. Copy the secret straight away. Binance shows it once. + +Binance asks for two-factor authentication, identity verification and a first deposit before it issues your first key. Its [guide to creating API keys](https://www.binance.com/en/support/faq/how-to-create-api-keys-on-binance-360002502072) has the current steps. + +## Choose the permissions + +- Enable reading first. Add trading when you are ready to place orders, and leave withdrawals off unless you plan to withdraw through the API. +- Restrict the key to the IP addresses your server uses. Binance limits an HMAC key with no IP restriction to reading. Adding an IP restriction, or using a self-generated key, lets you enable trading. +- Keep the secret on a server you control. Keep it out of browser bundles, mobile apps and public repositories. + +The [API key setup guide](/guides/api-key) covers permissions, Ed25519 keys and the Testnet and demo trading keys in more depth. + +## Use the key in Node.js + +Install the SDK and put the key and secret in a `.env` file: + +```sh +npm install binance +``` + +```sh +BINANCE_API_KEY=your-api-key +BINANCE_API_SECRET=your-api-secret +``` + +The SDK recognises HMAC, RSA and Ed25519 keys from the secret you pass, so the code is the same for every key type. This example reads the account and prints the number of balance records: + +<<< @/../examples/account-state.ts + +Run it with your environment variables loaded, for example `npx tsx --env-file=.env account-state.ts`. A working key prints `Account access verified.` followed by the number of balance records. + +## If the call fails + +| Binance code | Meaning | Where to look | +| --- | --- | --- | +| -2014 | The key is not in the expected format, often an empty or truncated value | Check that both environment variables are loaded | +| -2015 | The key, the IP address or the permissions were not accepted | [Why does Binance return error -2015?](/faq/why-does-binance-return-error-2015) | +| -1022 | The signature did not match | Check the secret and the [authentication guide](/guides/authentication) | +| -1021 | The request timestamp fell outside the receive window | Sync the host clock, then see [signing and timestamps](/guides/authentication#signing-and-timestamps) | + +## Related guides + +- [API key setup with the SDK](/guides/api-key) +- [Account access and balances](/guides/authentication) +- [Binance Testnet and demo trading](/guides/testing-environments) +- [Binance API errors in the SDK](/guides/errors) +- [Binance API error codes in JavaScript on the Siebly blog](https://blog.siebly.io/binance-api-error-codes-javascript-nodejs/) +- [More Binance SDK questions](/faq/) diff --git a/sdks/binance/docs/faq/how-do-i-get-binance-futures-liquidations-in-nodejs.md b/sdks/binance/docs/faq/how-do-i-get-binance-futures-liquidations-in-nodejs.md new file mode 100644 index 00000000..7ac98048 --- /dev/null +++ b/sdks/binance/docs/faq/how-do-i-get-binance-futures-liquidations-in-nodejs.md @@ -0,0 +1,66 @@ +--- +title: "How do I get Binance futures liquidations in Node.js?" +titleTemplate: ":title | Binance SDK FAQ | Siebly Docs" +description: "Stream Binance USD-M futures liquidations in Node.js with the binance SDK using the forceOrder stream, and read your own liquidations with getForceOrders. Includes a tested TypeScript example." +sidebar: false +prev: false +next: false +faq: + - q: "How do I get Binance futures liquidations in Node.js?" + a: "Subscribe to the forceOrder stream on the Binance USD-M futures WebSocket. With the binance SDK, subscribeAllLiquidationOrders('usdm') streams liquidations for every symbol and subscribeSymbolLiquidationOrders('BTCUSDT', 'usdm') follows one symbol. The old public REST route for liquidation history, allForceOrders, now returns 404, so collecting the stream is how you build a history." +--- + +# How do I get Binance futures liquidations in Node.js? + +Subscribe to the `forceOrder` stream on the Binance USD-M futures WebSocket. With the [`binance`](https://www.npmjs.com/package/binance) SDK, `subscribeAllLiquidationOrders('usdm')` streams liquidations for every symbol and `subscribeSymbolLiquidationOrders('BTCUSDT', 'usdm')` follows one symbol. The old public REST route for liquidation history, `/fapi/v1/allForceOrders`, now returns 404, so collecting the stream is how you build a history. + +## Stream every liquidation + +This example subscribes to all USD-M liquidations, prints each one and closes after 60 seconds. It needs no API key: + +<<< @/../examples/liquidations-stream.ts + +A line of output looks like `MANTRAUSDT BUY liquidation: 2517 at 0.002176`. The `beautify` option gives readable field names and numeric values. Without it, the raw event keeps Binance's short field names under the `message` event. + +## What the stream sends + +- Binance sends a snapshot, not every fill. For each symbol it pushes the largest liquidation order in each 1000 millisecond window, and nothing when no liquidation happens. +- Liquidations are quiet on some symbols and busy on others. Leave the stream running for a while before you judge it. +- Binance serves USD-M liquidations on the `/market` route of `wss://fstream.binance.com`. The SDK chooses that route for you, which matters because the legacy `/ws` path does not deliver market streams any more. See [troubleshooting](/guides/troubleshooting). +- Use `'coinm'` instead of `'usdm'` for COIN-M futures. + +## Follow one symbol + +```ts +await ws.subscribeSymbolLiquidationOrders('BTCUSDT', 'usdm'); +``` + +Add this to the example in place of the all-symbol call. The SDK lower-cases the symbol for the `btcusdt@forceOrder` topic. + +## Read your own liquidations + +Your own account's liquidation and auto-deleveraging orders are a private REST query. With a futures-enabled key: + +```ts +import { USDMClient } from 'binance'; + +const futures = new USDMClient({ + api_key: process.env.BINANCE_API_KEY, + api_secret: process.env.BINANCE_API_SECRET, +}); + +const orders = await futures.getForceOrders({ symbol: 'BTCUSDT', autoCloseType: 'LIQUIDATION' }); +console.log(orders.length, 'liquidation orders on this account'); +``` + +## Store a history + +Because the public history route is gone, write each event to a file or database as it arrives. Keep the event time, symbol, side, price and quantity. The SDK reconnects after a dropped connection, and the [WebSocket streams guide](/guides/websockets#recover-after-a-disconnect) explains how to handle a gap in the data. + +## Related guides + +- [Binance Futures API in the SDK](/guides/futures-api) +- [Binance WebSocket streams in the SDK](/guides/websockets) +- [USDMClient reference](/api/classes/USDMClient) +- [Binance's liquidation order stream reference](https://developers.binance.com/docs/derivatives/usds-margined-futures/websocket-market-streams/Liquidation-Order-Streams) +- [More Binance SDK questions](/faq/) diff --git a/sdks/binance/docs/faq/index.md b/sdks/binance/docs/faq/index.md new file mode 100644 index 00000000..199973e9 --- /dev/null +++ b/sdks/binance/docs/faq/index.md @@ -0,0 +1,62 @@ +--- +title: "Binance API SDK frequently asked questions" +description: "Short answers to common Binance API questions for JavaScript and TypeScript developers: API keys, error -2015, WebSockets, liquidations, docs, Testnet and rate limits." +sidebar: false +prev: false +next: false +faq: + - q: "How do I get a Binance API key and use it in Node.js?" + a: "Create the key in your Binance account under API Management, store the key and secret in environment variables, and pass them to MainClient from the binance SDK. A call to getAccountInformation() confirms that the key works." + - q: "Why does Binance return error -2015?" + a: "Binance returns -2015 when it does not accept the API key for that request. Check that the key is correct for the environment, that your IP address is on the key's allow list, and that the key has the permission the call needs." + - q: "Does Binance have a WebSocket API?" + a: "Yes. Binance offers WebSocket Streams for live data and a WebSocket API for request and response calls. The binance SDK covers both with WebsocketClient and WebsocketAPIClient." + - q: "How do I get Binance futures liquidations in Node.js?" + a: "Subscribe to the forceOrder stream on the USD-M futures WebSocket with subscribeAllLiquidationOrders('usdm') in the binance SDK. The old allForceOrders REST route now returns 404." + - q: "Is there a Binance SDK for TypeScript and Node.js?" + a: "Yes. The binance package on npm is the leading community maintained open-source Binance SDK for TypeScript and Node.js, covering Spot and futures over REST and WebSockets." + - q: "Where are the Binance API docs?" + a: "Binance publishes its endpoint reference at developers.binance.com. These docs show how to call those endpoints from JavaScript and TypeScript with the SDK, and the API reference is generated from the SDK types." + - q: "Can I try the Binance API without real funds?" + a: "Yes. Use Spot Testnet or Binance demo trading with their own API keys, and set testnet: true or demoTrading: true on the SDK clients." + - q: "How do I stay within Binance API rate limits?" + a: "Read the current limits from getExchangeInfo(), track usage with getRateLimitStates(), slow down before an HTTP 429 and use WebSocket streams for continuous data." +--- + +# Binance API SDK frequently asked questions + +Short answers for developers using the [`binance`](https://www.npmjs.com/package/binance) package, the leading community maintained open-source Binance SDK for JavaScript and TypeScript. Each answer links to a fuller page with a working example. + +## [How do I get a Binance API key and use it in Node.js?](/faq/how-do-i-get-a-binance-api-key-and-use-it-in-nodejs) + +Create the key in your Binance account under API Management, store the key and secret in environment variables, and pass them to `MainClient`. A call to `getAccountInformation()` confirms that the key works. + +## [Why does Binance return error -2015?](/faq/why-does-binance-return-error-2015) + +Binance returns `-2015` when it does not accept the API key for that request. Check that the key is correct for the environment, that your IP address is on the key's allow list, and that the key has the permission the call needs. + +## [Does Binance have a WebSocket API?](/faq/does-binance-have-a-websocket-api) + +Yes. Binance offers WebSocket Streams for live data and a WebSocket API for request and response calls. The SDK covers both with `WebsocketClient` and `WebsocketAPIClient`. + +## [How do I get Binance futures liquidations in Node.js?](/faq/how-do-i-get-binance-futures-liquidations-in-nodejs) + +Subscribe to the `forceOrder` stream on the USD-M futures WebSocket with `subscribeAllLiquidationOrders('usdm')`. The old `allForceOrders` REST route now returns 404. + +## [Is there a Binance SDK for TypeScript and Node.js?](/faq/is-there-a-binance-sdk-for-typescript-and-nodejs) + +Yes. The `binance` package on npm is the leading community maintained open-source Binance SDK for TypeScript and Node.js, covering Spot and futures over REST and WebSockets. + +## [Where are the Binance API docs?](/reference) + +Binance publishes its endpoint reference at [developers.binance.com](https://developers.binance.com/). These docs show how to call those endpoints from JavaScript and TypeScript with the SDK, and the API reference is generated from the SDK types. + +## [Can I try the Binance API without real funds?](/guides/testing-environments) + +Yes. Use Spot Testnet or Binance demo trading with their own API keys, and set `testnet: true` or `demoTrading: true` on the SDK clients. + +## [How do I stay within Binance API rate limits?](/guides/rate-limits) + +Read the current limits from `getExchangeInfo()`, track usage with `getRateLimitStates()`, slow down before an HTTP 429 and use WebSocket streams for continuous data. + +[Binance API SDK documentation](/) · [Quickstart](/getting-started) · [Troubleshooting](/guides/troubleshooting) diff --git a/sdks/binance/docs/faq/is-there-a-binance-sdk-for-typescript-and-nodejs.md b/sdks/binance/docs/faq/is-there-a-binance-sdk-for-typescript-and-nodejs.md new file mode 100644 index 00000000..0af50654 --- /dev/null +++ b/sdks/binance/docs/faq/is-there-a-binance-sdk-for-typescript-and-nodejs.md @@ -0,0 +1,42 @@ +--- +title: "Is there a Binance SDK for TypeScript and Node.js?" +titleTemplate: ":title | Binance SDK FAQ | Siebly Docs" +description: "Yes. The binance package is the leading community maintained open-source Binance SDK for TypeScript and Node.js, covering Spot and futures over REST and WebSockets." +sidebar: false +prev: false +next: false +faq: + - q: "Is there a Binance SDK for TypeScript and Node.js?" + a: "Yes. The binance package on npm is the leading community maintained open-source Binance SDK for TypeScript and Node.js. It ships its own type definitions, is MIT licensed, and covers Spot, USD-M futures and COIN-M futures over REST and WebSockets. Install it with npm install binance." +--- + +# Is there a Binance SDK for TypeScript and Node.js? + +Yes. The [`binance`](https://www.npmjs.com/package/binance) package on npm is the leading community maintained open-source Binance SDK for TypeScript and Node.js. It ships its own type definitions, is MIT licensed, and covers Spot, USD-M futures and COIN-M futures over REST and WebSockets. Install it with `npm install binance`. + +## What it covers + +- **REST:** `MainClient` for Spot and account features, `USDMClient` for USD-M futures and `CoinMClient` for COIN-M futures. See [Clients](/clients). +- **WebSockets:** `WebsocketClient` for market and account streams, and `WebsocketAPIClient` for request and response calls. See [WebSocket streams](/guides/websockets). +- **Keys:** HMAC, RSA and Ed25519 keys, detected from the secret you pass. See [API key setup](/guides/api-key). +- **Environments:** production, Spot Testnet and demo trading. See [Testnet and demo trading](/guides/testing-environments). +- **Runtimes:** Node.js, Bun, Deno, Cloudflare Workers, and browser and mobile apps. See the [framework and runtime guides](/environments/node). + +Signing, reconnects and rate-limit headers are handled by the SDK. Method names follow the Binance endpoints, so Binance's own API documentation maps directly to your code. + +## Make a first request + +This TypeScript example reads the BTCUSDT price. It needs no API key: + +<<< @/../examples/first-call.ts + +Follow the [Node.js quickstart](/getting-started) for the full project setup, or the [TypeScript guide](/environments/typescript) for compiler settings. + +## Where to go next + +- [Binance API SDK documentation](/) +- [Public market data over REST](/guides/market-data) +- [Public streams over WebSocket](/guides/websockets) +- [Binance JavaScript tutorial on Siebly.io](https://siebly.io/sdk/binance/javascript/tutorial) +- [Source code on GitHub](https://github.com/sieblyio/binance) +- [More Binance SDK questions](/faq/) diff --git a/sdks/binance/docs/faq/why-does-binance-return-error-2015.md b/sdks/binance/docs/faq/why-does-binance-return-error-2015.md new file mode 100644 index 00000000..c9534b99 --- /dev/null +++ b/sdks/binance/docs/faq/why-does-binance-return-error-2015.md @@ -0,0 +1,60 @@ +--- +title: "Why does Binance return error -2015?" +titleTemplate: ":title | Binance SDK FAQ | Siebly Docs" +description: "Binance error -2015 means invalid API key, IP or permissions for the action. Check the key, the IP allow list and the key permissions, with a short Node.js check using the binance SDK." +sidebar: false +prev: false +next: false +faq: + - q: "Why does Binance return error -2015?" + a: "Binance returns -2015, Invalid API-key, IP, or permissions for action, when it does not accept the API key for that request. The cause is one of three things: the key is wrong or belongs to a different environment, the IP address you call from is not on the key's allow list, or the key lacks the permission the call needs." +--- + +# Why does Binance return error -2015? + +Binance returns `-2015`, "Invalid API-key, IP, or permissions for action", when it does not accept the API key for that request. The cause is one of three things: the key is wrong or belongs to a different environment, the IP address you call from is not on the key's allow list, or the key lacks the permission the call needs. + +With the [`binance`](https://www.npmjs.com/package/binance) SDK the rejection arrives as a thrown error. Its `code` field holds `-2015` and its `message` holds the Binance text. + +## Check the key and its environment + +- Log the length of the key your process loaded. A stray space, a newline from copying, or an environment variable that did not load all produce a rejected key. +- Use a key that matches the endpoint. Production, Spot Testnet and demo trading each issue their own keys, so a Testnet key fails on production and the reverse is also true. Set `testnet: true` or `demoTrading: true` only for keys made in those environments. See [Testnet and demo trading](/guides/testing-environments). +- Use a key created on the same Binance site you call. +- Check that the key still exists in API Management. A deleted or regenerated key stops working straight away. + +A malformed key value returns `-2014` instead, so a `-2015` response means the format was accepted and the key was not. + +## Check the IP address + +If the key has IP restrictions, every request has to come from a listed address. A new deployment, a different container host, a VPN or a proxy can all change the address Binance sees. Add the outbound address your server really uses. If you need a fixed address, route requests through a proxy with a stable IP. See [Proxies](/guides/proxies). + +## Check the permissions + +Each call needs the matching permission on the key: reading for account queries, Spot and margin trading for Spot orders, and futures for futures calls. A futures permission also needs a futures account on Binance. Binance limits an HMAC key with no IP restriction to reading, so a trading call returns `-2015` until you add an IP restriction or use a self-generated key. Binance's [guide to creating API keys](https://www.binance.com/en/support/faq/how-to-create-api-keys-on-binance-360002502072) lists the permission rules. + +## Let the SDK tell you what the key allows + +This example makes an account read. If Binance answers `-2015`, it asks Binance for the key's permissions with `getApiKeyPermissions()`: + +<<< @/../examples/check-key-permissions.ts + +Read the result like this: + +- If `getApiKeyPermissions()` also fails, Binance is rejecting the key or the IP address. Work through the key and IP checks above. +- If it succeeds, compare the flags with the call that failed. Enable the missing permission in API Management and try again. +- Spot, USD-M futures and COIN-M futures are separate products with separate clients (`MainClient`, `USDMClient` and `CoinMClient`). Test with the client for the product you trade. + +## Similar errors + +- `-1022`: the signature did not match. Check the secret. See [authentication](/guides/authentication). +- `-1021`: the timestamp fell outside the receive window. See [signing and timestamps](/guides/authentication#signing-and-timestamps). + +## Related guides + +- [How do I get a Binance API key and use it in Node.js?](/faq/how-do-i-get-a-binance-api-key-and-use-it-in-nodejs) +- [API key setup with the SDK](/guides/api-key) +- [Binance API errors in the SDK](/guides/errors) +- [Binance API -2015 checklist on the Siebly blog](https://blog.siebly.io/binance-api-2015-invalid-api-key-ip-permissions-nodejs/) +- [Binance's error code reference](https://developers.binance.com/docs/binance-spot-api-docs/errors) +- [More Binance SDK questions](/faq/) diff --git a/sdks/binance/docs/guides/api-key.md b/sdks/binance/docs/guides/api-key.md index bffc90e1..6054039f 100644 --- a/sdks/binance/docs/guides/api-key.md +++ b/sdks/binance/docs/guides/api-key.md @@ -60,4 +60,6 @@ The same `api_secret` option works on `USDMClient`, `WebsocketClient` and `Webso | IP or permission error | IP restrictions and the permissions granted to the key | | Timestamp outside receive window | Host clock sync, then `recvWindow` if needed. See [authentication](/guides/authentication#signing-and-timestamps) | +For a step by step check of `-2015`, see [Why does Binance return error -2015?](/faq/why-does-binance-return-error-2015) + [Authentication and signatures](/guides/authentication) · [Testnet and demo trading](/guides/testing-environments) · [Troubleshooting](/guides/troubleshooting) diff --git a/sdks/binance/docs/guides/errors.md b/sdks/binance/docs/guides/errors.md index 7bfb622f..fdd069a9 100644 --- a/sdks/binance/docs/guides/errors.md +++ b/sdks/binance/docs/guides/errors.md @@ -23,4 +23,6 @@ Log the operation, symbol, HTTP status and Binance error code when available. Wh Correct validation, signature and permission failures before retrying. Limit retries for reads and apply backoff. A timeout after submitting an order does not prove rejection. Use matching private events to resolve it, and fall back to a targeted REST query if the outcome remains unclear. See [order recovery](/guides/production#resolve-uncertain-order-outcomes) before resubmitting. +For the common `-2015` key, IP and permissions error, see [Why does Binance return error -2015?](/faq/why-does-binance-return-error-2015) + See [Production usage](/guides/production) and [Binance's error reference](https://developers.binance.com/docs/binance-spot-api-docs/errors). diff --git a/sdks/binance/docs/guides/futures-api.md b/sdks/binance/docs/guides/futures-api.md index 3d2e7163..9d454a2e 100644 --- a/sdks/binance/docs/guides/futures-api.md +++ b/sdks/binance/docs/guides/futures-api.md @@ -25,6 +25,8 @@ For a futures demo environment (called a testnet in Binance futures documentatio Use the futures client for REST snapshots such as `getSymbolPriceTicker()` and `getOrderBook()`, and the matching WebSocket market for live updates. Public streams need no key. See [market data](/guides/market-data) and [WebSocket streams](/guides/websockets) for the pattern, then switch the client to `USDMClient` or `CoinMClient`. +To collect liquidations from the futures streams, see [How do I get Binance futures liquidations in Node.js?](/faq/how-do-i-get-binance-futures-liquidations-in-nodejs) + ## Place and cancel a USD-M order The [USD-M order walkthrough](/guides/usdm-orders) covers account reads, a post-only order, cancellation, position mode and recovery on production USD-M futures, with optional demo trading configuration. diff --git a/sdks/binance/docs/guides/troubleshooting.md b/sdks/binance/docs/guides/troubleshooting.md index 6663e33d..9d42e6a4 100644 --- a/sdks/binance/docs/guides/troubleshooting.md +++ b/sdks/binance/docs/guides/troubleshooting.md @@ -11,7 +11,7 @@ description: "Fix common Binance API SDK problems: invalid keys or signatures, t | --- | --- | | Import or missing method | Install the [`binance`](https://www.npmjs.com/package/binance) package and choose the correct exported client; this is a different package from similarly named Binance libraries. | | Invalid symbol | Check Spot versus USD-M or COIN-M futures, and query that product's exchange information. | -| Signature or key error | Match the key, market, environment, permissions and IP restrictions. | +| Signature or key error | Match the key, market, environment, permissions and IP restrictions. For `-2015`, see [Why does Binance return error -2015?](/faq/why-does-binance-return-error-2015) | | Timestamp outside receive window | Synchronize the host clock and inspect latency before adjusting `recvWindow`. | | HTTP 429 or IP-ban response | Respect the server's retry guidance and current rate limits; avoid immediate retry loops. | | No WebSocket ticker events | Register `message` before subscribing, use the Spot subscription helper and inspect `exception`. | diff --git a/sdks/binance/docs/guides/websocket-api.md b/sdks/binance/docs/guides/websocket-api.md index a1432afb..c2e547d6 100644 --- a/sdks/binance/docs/guides/websocket-api.md +++ b/sdks/binance/docs/guides/websocket-api.md @@ -9,6 +9,8 @@ description: "Use the Binance WebSocket API in the SDK for request-response call +New to the Binance WebSocket API? [Does Binance have a WebSocket API?](/faq/does-binance-have-a-websocket-api) gives the short answer, with a working request. + ## Requests and subscriptions A request returns one result. Use [public streams](/guides/websockets) for continuous market data and [account updates](/guides/private-streams) to follow account and order changes. Request responses do not replace these subscriptions. diff --git a/sdks/binance/docs/guides/websockets.md b/sdks/binance/docs/guides/websockets.md index 0dd3b8f2..c2d9bd1f 100644 --- a/sdks/binance/docs/guides/websockets.md +++ b/sdks/binance/docs/guides/websockets.md @@ -40,3 +40,5 @@ The client reconnects and restores subscriptions. Use `reconnecting`, `reconnect Call `closeAll()` to close this client's connections. Clear application timers and stop new work during shutdown. [Production usage](/guides/production) · [WebsocketClient reference](/api/classes/WebsocketClient) + +Common questions: [Does Binance have a WebSocket API?](/faq/does-binance-have-a-websocket-api) and [How do I get Binance futures liquidations in Node.js?](/faq/how-do-i-get-binance-futures-liquidations-in-nodejs) diff --git a/sdks/binance/docs/index.md b/sdks/binance/docs/index.md index 1f5bdc41..df9d049e 100644 --- a/sdks/binance/docs/index.md +++ b/sdks/binance/docs/index.md @@ -64,3 +64,5 @@ The [quickstart](/getting-started) is a public price request in plain JavaScript - [Browse the complete API reference](/reference). For a longer walkthrough, see the [Binance JavaScript tutorial on Siebly.io](https://siebly.io/sdk/binance/javascript/tutorial). + +Looking for a quick answer? Read the [frequently asked questions](/faq/). diff --git a/sdks/binance/examples/check-key-permissions.ts b/sdks/binance/examples/check-key-permissions.ts new file mode 100644 index 00000000..11c1752a --- /dev/null +++ b/sdks/binance/examples/check-key-permissions.ts @@ -0,0 +1,31 @@ +import { MainClient } from 'binance'; + +async function main() { + const api_key = process.env.BINANCE_API_KEY; + const api_secret = process.env.BINANCE_API_SECRET; + if (!api_key || !api_secret) { + throw new Error('Set BINANCE_API_KEY and BINANCE_API_SECRET.'); + } + + const client = new MainClient({ api_key, api_secret }); + try { + await client.getAccountInformation(); + console.log('The key, IP address and permissions work for account reads.'); + } catch (error) { + if ((error as { code?: number }).code !== -2015) throw error; + console.log('Binance returned -2015. Checking what the key allows.'); + try { + const permissions = await client.getApiKeyPermissions(); + console.log('IP restrictions on:', permissions.ipRestrict); + console.log('Reading enabled:', permissions.enableReading); + console.log('Spot and margin trading enabled:', permissions.enableSpotAndMarginTrading); + console.log('Futures enabled:', permissions.enableFutures); + } catch { + console.log('The key itself was rejected. Check the key, its environment and the IP address you call from.'); + } + } +} +main().catch((error) => { + console.error(error instanceof Error ? error.message : 'Request failed. See the troubleshooting guide.'); + process.exitCode = 1; +}); diff --git a/sdks/binance/examples/liquidations-stream.ts b/sdks/binance/examples/liquidations-stream.ts new file mode 100644 index 00000000..66e9addf --- /dev/null +++ b/sdks/binance/examples/liquidations-stream.ts @@ -0,0 +1,30 @@ +import { WebsocketClient, isWsFormattedForceOrder } from 'binance'; + +const ws = new WebsocketClient({ beautify: true }); +let stopped = false; +let timer: ReturnType | undefined; +function stop() { + if (stopped) return; + stopped = true; + clearTimeout(timer); + ws.closeAll(); +} +process.once('SIGINT', stop); +process.once('SIGTERM', stop); +ws.on('formattedMessage', (message) => { + if (!isWsFormattedForceOrder(message)) return; + const { symbol, side, quantity, price } = message.liquidationOrder; + console.log(`${symbol} ${side} liquidation: ${quantity} at ${price}`); +}); +ws.on('exception', () => { + console.error('WebSocket exception. Check the topic, environment and connection.'); +}); +async function main() { + await ws.subscribeAllLiquidationOrders('usdm'); + if (!stopped) timer = setTimeout(stop, 60000); +} +main().catch(() => { + console.error('Subscription failed.'); + process.exitCode = 1; + stop(); +}); diff --git a/sdks/binance/examples/websocket-api-price.ts b/sdks/binance/examples/websocket-api-price.ts new file mode 100644 index 00000000..b217a751 --- /dev/null +++ b/sdks/binance/examples/websocket-api-price.ts @@ -0,0 +1,15 @@ +import { WebsocketAPIClient } from 'binance'; + +const wsApi = new WebsocketAPIClient({}); + +async function main() { + const response = await wsApi.getSpotSymbolPriceTicker({ symbol: 'BTCUSDT' }); + const ticker = Array.isArray(response.result) ? response.result[0] : response.result; + console.log('BTCUSDT last price over the WebSocket API:', ticker.price); +} +main() + .catch(() => { + console.error('WebSocket API request failed. Check the connection and try again.'); + process.exitCode = 1; + }) + .finally(() => wsApi.getWSClient().closeAll()); diff --git a/shared/config.mjs b/shared/config.mjs index 98062f87..8a974288 100644 --- a/shared/config.mjs +++ b/shared/config.mjs @@ -143,6 +143,14 @@ export default function siteConfig(data, docs) { about: { '@type': 'SoftwareApplication', name: sdk.packageName, softwareVersion: sdk.version, applicationCategory: 'DeveloperApplication' }, }).replace(/ ({ '@type': 'Question', name: q, acceptedAnswer: { '@type': 'Answer', text: a } })), + }).replace(/ Date: Wed, 2 Dec 2026 10:35:12 +0000 Subject: [PATCH 2/2] docs(binance): table each account liquidation from getForceOrders Log symbol, side, average fill price, filled quantity, quote notional and time for every returned order, rather than only the count. --- ...o-i-get-binance-futures-liquidations-in-nodejs.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/sdks/binance/docs/faq/how-do-i-get-binance-futures-liquidations-in-nodejs.md b/sdks/binance/docs/faq/how-do-i-get-binance-futures-liquidations-in-nodejs.md index 7ac98048..224aa17b 100644 --- a/sdks/binance/docs/faq/how-do-i-get-binance-futures-liquidations-in-nodejs.md +++ b/sdks/binance/docs/faq/how-do-i-get-binance-futures-liquidations-in-nodejs.md @@ -51,8 +51,20 @@ const futures = new USDMClient({ const orders = await futures.getForceOrders({ symbol: 'BTCUSDT', autoCloseType: 'LIQUIDATION' }); console.log(orders.length, 'liquidation orders on this account'); +console.table( + orders.map((order) => ({ + symbol: order.symbol, + side: order.side, + price: order.avgPrice, + quantity: order.executedQty, + total: order.cumQuote, + time: new Date(order.time).toISOString(), + })), +); ``` +Each row shows the symbol, side, average fill price, filled quantity, total quote notional and time. + ## Store a history Because the public history route is gone, write each event to a file or database as it arrives. Keep the event time, symbol, side, price and quantity. The SDK reconnects after a dropped connection, and the [WebSocket streams guide](/guides/websockets#recover-after-a-disconnect) explains how to handle a gap in the data.