Getting websocket message [] data

Hi ,
Is this correct way to extract data from websocket ? it returns data.
Below passed data object is correct?

import { Buffer } from ‘buffer’;
const data = {
guid: ‘someguid’,
method: ‘sub’,
data: {
mode: ‘full’,
instrumentKeys: [‘NSE_EQ|INE002A01018’],
},
};
ws.send(Buffer.from(JSON.stringify(data)));

if it is wrong please help me out.

@svishwakarma123

To begin with market updates using WebSockets in Node.js, you can refer to the example provided in the following GitHub link:

Upstox Node.js WebSocket Market Data Example

This should guide you through the setup and usage.

Thanks!

@shanmu I have already gone through that sample link. Can you help me understand why I get empty array data in response?

@svishwakarma123

It appears that the websocket sample is functioning correctly with the instrument key you provided. Could you please post your entire code snippet here? This will allow us to review it more thoroughly.

Thank you!

// Import required modules
import {ApiClient, WebsocketApi} from ‘upstox-js-sdk’;
import {Buffer} from ‘buffer’;

// Initialize the protobuf part and establish the WebSocket connection
export const callWebSocket = async token => {
// Initialize global variables
let defaultClient = ApiClient.instance;
let apiVersion = ‘2.0’;
let OAUTH2 = defaultClient.authentications[‘OAUTH2’];
OAUTH2.accessToken = token; // Replace “ACCESS_TOKEN” with your actual token

// Function to authorize the market data feed
const getMarketFeedUrl = async () => {
return new Promise((resolve, reject) => {
let apiInstance = new WebsocketApi(); // Create new Websocket API instance
// Call the getMarketDataFeedAuthorize function from the API
apiInstance.getMarketDataFeedAuthorize(
apiVersion,
(error, data, response) => {
if (error) reject(error); // If there’s an error, reject the promise
else resolve(data.data.authorizedRedirectUri); // Else, resolve the promise with the authorized URL
},
);
});
};

// Function to establish WebSocket connection
const connectWebSocket = async wsUrl => {
return new Promise((resolve, reject) => {
const ws = new WebSocket(wsUrl, {
headers: {
‘Api-Version’: apiVersion,
Authorization: 'Bearer ’ + OAUTH2.accessToken,
},
followRedirects: false,
});

  console.log('websocket objecct', ws);

  ws.onopen = () => {
    console.log('WebSocket connection opened');
    resolve(ws); // Resolve the promise once connected

    // Set a timeout to send a subscription message after 1 second
    setTimeout(() => {
      const data = {
        guid: 'someguid',
        method: 'sub',
        data: {
          mode: 'full',
          instrumentKeys: ['NSE_EQ|INE002A01018'],
        },
      };
      // console.log("sending data", Buffer.from(JSON.stringify(data)))
      ws.send(Buffer.from(JSON.stringify(data)));
    }, 1000);
  };

  ws.onmessage = event => {
    console.log('WebSocket message received:', JSON.stringify(event));
  };

  ws.onerror = error => {
    reject(error);
    console.error('WebSocket error:', error);
  };

  ws.onclose = event => {
    console.log('WebSocket connection closed:', event.code, event.reason);
  };
});

};

try {
const wsUrl = await getMarketFeedUrl(); // Get the market feed URL
const ws = await connectWebSocket(wsUrl); // Connect to the WebSocket
} catch (error) {
console.log(‘in catch error’, error);
}
};

@svishwakarma123 Have you get the solution for this ?