// 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);
}
};