Search code examples
javascriptnode.jsgoogle-cloud-firestorewebsocketbinance

Running a function inside Websocket triggers many times


I've been trying to take advantage of the Binance Websocket to trigger buys and sells based on the live price with my own logic. I know the WebSocket is sending back live data and there might be even 5-6 or more responses at the same time, but how do I make sure I get only 1 when I close the Websockets?

I am trying to make sure it will trigger only 1 buy or 1 sell when that happens.

I am using: (works great)

'node-binance-api'

The Websocket starts from here:

binance.websockets.bookTickers('BNBBUSD', (mainTicker) => {
  var priceNow = mainTicker.bestBid;
  liveStrategy(priceNow).then(isSold => {
      // console.log('THIS IS WHEN IS CHECKED ->>>>>>');
      if (isSold == true) {
          console.log('JUST SOLD -> Setting the count to 10');
          sleep(3000).then(() => { 
              console.log("Countdown finished: ", count);
              profitCalculations(mainCurrency);
              count = 10;
          });
      }
      if (isSold == false) {
          console.log('THIS WAS A BUY ->');
          count = 10;
      }
  }).catch((isSoldErr) => {
      console.warn('Error:', isSoldErr.message);
      dumpError(isSoldErr);
  });
});

The price is being sent back into the function, this function runs continuously until a buy or a sell happens. Before triggering a buy or a sell I close the WebSocket with:

    let endpoints = binance.websockets.subscriptions();
    for ( let endpoint in endpoints ) {
        console.log("..terminating websocket: "+endpoint);
        let ws = endpoints[endpoint];
        ws.terminate();
    }

This code stops the WebSocket, but it does take about 3 seconds so I trigger the buy/sell after this like:

if (priceNow > buyPrice) {
terminateAllWebsockets();
return new Promise((resolve) => {
    sleep(5000).then(sleep => {
        marketBuyFromNoLossStrategyAmount(buySymbol,buyAmount);
        resolve(false);
    })
})

}

When it returns it basically sends back to my liveStrategy(priceNow) to trigger the profit calculations. The profitCalculations(mainCurrency); might get triggered 3-4 times or even the buy or sell. Is it something that I can do for that not to happen? So the profit or the buy & sell will trigger only once? How do I make sure that happens with my setup?

Any thoughts are most welcome!


Solution

  • The main problem was that the WebSocket was real-time and when 2 or more trades were getting executed at the same time reaching the target set in the algorithm, it would trigger multi-buy or multi-sell. Writing the data within a public variable and reading with a simple timer that executed the function every second was the best solution.