Binance TypeScript SDK example: ws-close.ts
Binance WebSocket Misc websocket close example for the Siebly Binance SDK, with TypeScript source for exchange REST API and WebSocket integration, setup, and production SDK docs.
What This Example Covers
- Binance WebSocket stream example in TypeScript.
- Uses the Siebly Binance SDK package
binanceinstead of hand-written WebSocket plumbing. - Source path:
Binance/WebSockets/Misc/ws-close.ts. - Example category: WebSocket Misc.
- Imports SDK symbols including
DefaultLogger,WebsocketClient. - Calls SDK methods such as
on(),subscribeUsdFuturesUserDataStream(),subscribe(),unsubscribeUsdFuturesUserDataStream(),unsubscribe().
How To Use This Example
- Start here for the specific request or stream pattern, then check the matching SDK guide for install, credentials, and operational notes.
- For WebSocket examples, keep reconnect, resubscribe, heartbeat, and event-handler behavior explicit in your service.
- Open the repository source when you need the latest committed version: GitHub source file.
Example Path
Binance/WebSockets/Misc/ws-close.ts
Source Link
Repository source: https://github.com/sieblyio/crypto-api-examples/blob/master/examples/Binance/WebSockets/Misc/ws-close.ts
Related SDK Docs
Example Source
import { DefaultLogger, WebsocketClient } from 'binance';
(async () => {
const key = process.env.API_KEY_COM || 'APIKEY';
const secret = process.env.API_SECRET_COM || 'APISECRET';
const logger = {
...DefaultLogger,
trace: () => {},
};
const wsClient = new WebsocketClient(
{
api_key: key,
api_secret: secret,
beautify: true,
},
logger,
);
wsClient.on('open', (data) => {
console.log('connection opened open:', data.wsKey, data.wsUrl);
});
wsClient.on('reconnecting', (data) => {
console.log('ws automatically reconnecting.... ', data?.wsKey);
});
wsClient.on('reconnected', (data) => {
console.log('ws has reconnected ', data?.wsKey);
});
wsClient.on('message', (data) => {
console.log('data received: ', data);
});
wsClient.on('response', (data) => {
console.log('response received: ', data);
});
wsClient.subscribeUsdFuturesUserDataStream();
wsClient.subscribe(
['!miniTicker@arr', 'btcusdt@avgPrice', 'btcusdt@kline_5m'],
'main',
);
setTimeout(() => {
// unsubscribe from user data stream (for usd futures)
wsClient.unsubscribeUsdFuturesUserDataStream();
// unsubscribe from individual topics on a connection, one at a time:
// wsClient.unsubscribe('!miniTicker@arr', 'main');
// arrays also supported:
wsClient.unsubscribe(['!miniTicker@arr', 'btcusdt@avgPrice'], 'main');
}, 5000);
})();