Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 55 additions & 0 deletions sdks/binance/docs/faq/does-binance-have-a-websocket-api.md
Original file line number Diff line number Diff line change
@@ -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/)
Original file line number Diff line number Diff line change
@@ -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/)
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
---
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');

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This just logs the order total without any other details? Maybe console.table or some other way log them too?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good call, it now logs symbol, side, price, quantity, total and time for each liquidation.

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.

## 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/)
62 changes: 62 additions & 0 deletions sdks/binance/docs/faq/index.md
Original file line number Diff line number Diff line change
@@ -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)
Original file line number Diff line number Diff line change
@@ -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/)
Loading