'how to stop a stream api in callback nodejs

hi i'm using binance api, it has a stream function like below which i don't know how to stop it after the if statement is true.

binance.websockets.bookTickers("BNBUSDT", (res) => {
  if (res.bestAsk > 250) {
    // i want to finish this stream here
  }
});

running result is something like this:

  {
  updateId: 4510982,
  symbol: 'BNBUSDT',
  bestBid: '276.10010000',
  bestBidQty: '0.24000000',
  bestAsk: '277.77770000',
  bestAskQty: '0.99000000'
}
(always running - infinite loop)

thanks.



Solution 1:[1]

From the context I see that you're using binance-node-api.

Unfortunately their code doesn't have a method for unsubscribing from a specific websocket stream.

  1. The bookTickets stream is created on line 5755. If its handler were saved to a (accessible) variable somewhere, you could call its method .close() to close the stream. But...
  2. On line 5756 only its name is returned and the stream handler is not saved to any variable. So outside of the bookTickers function, there's currently no way to close the stream.

Easiest way is to start ignoring the the stream as soon as you don't need the data. The disadvantage is of course that you're wasting resources on something you don't need, and opening your app to more potential malfunctions (what if the stream throws an error or causes memory leak?).

const Binance = require('node-binance-api');
const binance = new Binance();

let isTickersProcessed = false;

const websocket = binance.websockets.bookTickers("BNBUSDT", (res) => {
    if (isTickersProcessed) {
        return;
    }

    if (res.bestAsk > 250) {
        console.log(res);
        isTickersProcessed = true;
    }
});

Or to use a different wrapper module that gives you more control over the streams. Or connect directly using websocket.

Solution 2:[2]

This is how you can terminate all socket connections:

let endpoints = binance.websockets.subscriptions();
  for (let endpoint in endpoints) {
    console.log(endpoint);
    binance.websockets.terminate(endpoint)
  }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Petr Hejda
Solution 2 Viktor Bokhan