WebSocket API Basic Information
- The API requires a user's API Key. For instructions on creating an API Key, refer to here.
- Base URL: wss://api.binance.com/sapi/wss
- Each connection to the base URL is valid for up to 24 hours. Please handle reconnections appropriately.
- WebSocket clients should actively send PING messages every 30 seconds.
- If the WebSocket server does not receive a PING message within one minute, the connection will be closed.
- It is recommended to use an empty payload for these PING messages.
- Signature payload must be generated by taking all request params except for the signature and sorting them by name in alphabetical order.
- All timestamps are in milliseconds in UTC, unless noted otherwise.
- All field names and values are case-sensitive, unless noted otherwise.
WebSocket Connection Limits
- The WebSocket server accepts a maximum of 5 messages per second. Messages include:
- PING frames
- PONG frames
- JSON-formatted messages (e.g., subscription or unsubscription requests).
- If a user exceeds this limit, the connection will be terminated. Repeated disconnections may result in IP blocking by the server.
WebSocket API Request Format
Connection URL:
wss://api.binance.com/sapi/wss?random={{random}}&topic={{topic}}&recvWindow={{recvWindow}}×tamp={{timestamp}}&signature={{signature}}
Replace {{xxx}}
with the corresponding values.
- Format Example:
wss://api.binance.com/sapi/wss?random=56724ac693184379ae23ffe5e910063c&topic=topic1&recvWindow=30000×tamp=1753244327210&signature=341098eff29e3ef395ed4ea85035bd7fe9e9356d2b0d4f1f97655c74516a2d65
- Parameter Details:
random
: A random string or number (recommended length ≤32) to ensure signature randomness and validity.- Example:
random=56724ac693184379ae23ffe5e910063
- Example:
topic
: Supports subscribing to one or multiple topics, separated by a vertical bar|
.- Example:
topic=topic1|topic2
- Example:
recvWindow
: Allowed latency window (in milliseconds). Maximum value: 60000 ms.- Example:
recvWindow=30000
- Example:
timestamp
: Current timestamp in milliseconds.- Example:
timestamp=1753244327210
- Example:
signature
: Signature of the current request.
WebSocket API Authentication
The user's API Key must be included in the WebSocket request header as the X-MBX-APIKEY
field to authenticate the connection.
Time Security
- A
SIGNED
endpoint also requires a parameter,timestamp
, to be sent which should be the millisecond timestamp of when the request was created and sent. - An additional parameter,
recvWindow
, may be sent to specify the number of milliseconds aftertimestamp
the request is valid for.
Signature Generation
Here is a step-by-step example of how to send a vaild signed payload from the
Linux command line using echo
, openssl
, and curl
.
Key | Value |
---|---|
apiKey | vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A |
secretKey | NhqPtmdSJYdKjVHjA7PZj4Mge3R5YNiP1e3UZjInClVN65XAbvqqM6A7H5fATj0j |
Signature Payload: Concatenate all parameters in the connection URL (excluding signature
):
random={{random}}&topic={{topic}}&recvWindow={{recvWindow}}×tamp={{timestamp}}
Example:
HMAC SHA256 signature:
$ echo -n "random=56724ac693184379ae23ffe5e910063c&topic=topic1&recvWindow=30000×tamp=1753244327210" | openssl dgst -sha256 -hmac "Avqz4IQjoZSJOowMFSo3QZEd4ovfwLH7Kie8ZliTtP8ktDnqcX8bpCP7WluFtrfn"
SHA2-256(stdin)= 8346d214e0da7165a0093043395f67e08c63f61b5d6e25779d513c11450e691b
Real-Time Subscription/Unsubscription
After establishing the connection, you can subscribe to or unsubscribe from channels by sending JSON messages via WebSocket (supports multiple channels separated by |
). Example:
Subscription
Request
{
"command": "SUBSCRIBE",
"value": "topic1"
}
Response
{
"type": "COMMAND",
"data": "SUCCESS",
"subType": "SUBSCRIBE",
"code": "00000000"
}
Unsubscription
Request
{
"command": "UNSUBSCRIBE",
"value": "topic1"
}
Response
{
"type": "COMMAND",
"data": "SUCCESS",
"subType": "UNSUBSCRIBE",
"code": "00000000"
}
WebSocket API Coding Example
JS script
const WebSocket = require('ws');
const CryptoJS = require('crypto-js');
const uri = 'wss://api.binance.com/sapi/wss?random=56724ac693184379ae23ffe5e910063c&topic=topic1&recvWindow=30000×tamp=${timestamp}&signature=${signature}';
const binance_api_key = "Replace with your API Key";
const binance_api_secret = "Load your Secret Key"; // Load private key
const ts = Date.now();
let paramsObject = {};
const queryString = uri.substring(uri.indexOf('?') + 1);
const parameters = queryString.split('&')
.filter(param => param.includes('='))
.map(param => {
const [key, value] = param.split('=');
return {key, value};
});
parameters.map((param) => {
if (param.key !== 'signature' &&
param.key !== 'timestamp') {
paramsObject[param.key] = param.value;
}
})
Object.assign(paramsObject, {'timestamp': ts});
const tmp = Object.keys(paramsObject).map((key) => {
return `${key}=${paramsObject[key]}`;
}).join('&');
const signature = CryptoJS.HmacSHA256(tmp, binance_api_secret).toString();
Object.assign(paramsObject, {'signature': signature});
const result = Object.keys(paramsObject).map((key) => {
return `${key}=${paramsObject[key]}`;
}).join('&');
const baseUri = uri.substring(0, uri.indexOf("?"))
console.log("final uri: " + baseUri + '?' + result)
const ws = new WebSocket(baseUri + '?' + result, [], {
headers: {
"X-MBX-APIKEY": binance_api_key
}
});
ws.on('open', function open() {
console.log('Connected to the server');
});
ws.on('message', function incoming(data) {
console.log(`Data from server: ${data}`);
});
ws.on('close', function close() {
console.log('Disconnected from server');
});
ws.on('error', function error(err) {
console.error(`Error: ${err.message}`);
});
// TODO setup your ping and reconnect logic