0

I'm trying to get rid of the double quotes around the trading pair symbols I receive from a binance websocket. It sends real-time best bid and ask prices for all trading pairs on the platform. This means that it is recieving a lot of payloads very often. This is the websocket:

const WebSocket = require('ws');
ws = new WebSocket('wss://stream.binance.com:9443/ws/!bookTicker');

This chunk of code works fine as far as I know.

ws.on('open', function open() {
    ws.send(JSON.stringify({
      method: "SUBSCRIBE",
      params: ['!bookTicker'],
      id: 1
    }));
  });

This is where the problem is:

ws.on('message', function incoming(data) {
  //sets fresh_symbol to a string of the trading pair symbol
  let fresh_symbol = JSON.stringify(JSON.parse(data)['s']);
  
  //tries to filter out if fresh_symbol is undefined, doesn't work. 
  if (typeof fresh_symbol != undefined){
    console.log(fresh_symbol.replace(/['"]+/g, ''));
  }
});

The websocket constantly receives payloads (perhaps many hundred per seconds, I'm not sure but it's a lot). If I tell the code to simply console.log the fresh_symbol variable, the code outputs just fine. The problem arises when I tell the code to output the fresh_symbol string but with the double quotes on either side removed using the .replace() method. Even using that if statement to filter out when the variable is undefined, I still get a TypeError that states that:

    console.log(fresh_symbol.replace(/['"]+/g, ''));
                             ^

TypeError: Cannot read property 'replace' of undefined

I assume this has something to do with the fact that the websocket is receiving payloads so fast that the fresh_symbol variable is occasionally being overwritten when it's being accessed, but I have no idea how to remedy this problem. The code runs for a second or two, outputing the symbols in the desired format, before stopping due to an error. I'm no pro when it comes to javascript so please forgive me if anything here seems obvious.

1 Answers1

0

The error comes from the 'undefined filter':

if(typeof fresh_symbol != undefined)

should be:

if(typeof fresh_symbol != 'undefined')

since typeof returns a string of the type.