javascriptwebsocketblobextract

How to extract blob data from websocket response


I'm trying to get market data from bingx websocket API but once my connection stablished i recieve blob data and i dont know how can i read candlestick data from that blob response with javascript does any one know how can i extract data?

here is my Js code :

var ws = new WebSocket('wss://open-ws-swap.bingbon.pro/ws');

    ws.onopen = (event) => {
        const msg = {
            id: "548",
            reqType:"sub",
            dataType: "market.kline.BTC-USDT.1min",
        }
        ws.send(JSON.stringify(msg));
        console.log('connection stablished!')
    }


    // Listen for messages
    ws.onmessage = function(event) {
        console.log(event.data);
    }

    ws.onclose = function(event) {
        console.log(event)
    };

    ws.onerror = function(error) {
        console.log(error);
    };

And here is the result in console:

enter image description here

I tried this answer bot not working: text


Solution

  • From the docs ->

    All response data from Websocket server are compressed into GZIP format. Clients have to decompress them for further use

    So using this information we can use DecompressionStream -> https://developer.mozilla.org/en-US/docs/Web/API/DecompressionStream to uncompress the data, and then use TextDecoder to convert that into to text, finally JSON.parse to convert into an object.

    Finally you will want to watch for the Ping message, as the API will disconnect if you don't send a Pong.

    eg.

    var ws = new WebSocket('wss://open-ws-swap.bingbon.pro/ws');
    
    
    async function decompressBlob(blob) {
      const ds = new DecompressionStream("gzip");
      const decompressedStream = blob.stream().pipeThrough(ds);
      return await new Response(decompressedStream).blob();
    }
    
    
    
    
    ws.onopen = (event) => {
       const msg = {
          id: "548",
          reqType:"sub",
          dataType: "market.kline.BTC-USDT.1min",
       }
       ws.send(JSON.stringify(msg));
       console.log('connection stablished!')
    }
    
    // Listen for messages
    ws.onmessage = async function(event) {
       const data = await decompressBlob(event.data);
       const txt = new TextDecoder().decode(await data.arrayBuffer());
       if (txt === 'Ping') {
         //this keeps the api open
         ws.send('Pong');
       } else {
         console.log(JSON.parse(txt));
       }
    }
    
    ws.onclose = function(event) {
       console.log(event)
    };
    
    ws.onerror = function(error) {
       console.log(error);
    };