Binance Misc JavaScript SDK example: ws-close.ts

Binance Misc websocket close JavaScript example for the Siebly Binance SDK, covering exchange REST API and WebSocket integration, setup, and production SDK docs.

We use environment variables in our examples for API keys. It is your responsibility to manage and secure your keys appropriately.

examples/Binance/WebSockets/Misc/ws-close.ts

What this example covers

  • Binance WebSocket stream JavaScript example.
  • Uses the Siebly Binance SDK package binance instead of hand-written WebSocket plumbing.
  • Source path: Binance/WebSockets/Misc/ws-close.ts.
  • Example category: 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.
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);})(); 

Subscribe on Substack

Complete the Substack form below to join our newsletter. Substack handles all subscriber data directly.