Unable to get live data from websocket

Dear Upstox Developer Team,
I am unable to get live data from websocket.
Please help i tried from since last 5 day. Please help me i so frusted. i need code according to my code.


<?php
include '../../core/core.php';
require '../../vendor/autoload.php';

// Initialize cURL session
$curl = curl_init();


curl_setopt_array($curl, array(
    CURLOPT_URL => 'https://api.upstox.com/v2/feed/market-data-feed/authorize',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => '',
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 0,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => 'GET',
    CURLOPT_HTTPHEADER => array(
        'Accept: application/json',
        'Authorization: Bearer ' . $accessTokenUpstox
    ),
));

$jsonData = curl_exec($curl);

curl_close($curl);
$data = json_decode($jsonData, true);

// Extract the authorized redirect URI
$endpoint = $data['data']['authorizedRedirectUri'];
echo $endpoint;
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Real-time Market Data</title>
    <style>
        #status {
            font-weight: bold;
        }
        #market-data {
            white-space: pre-wrap;
            font-family: monospace;
        }
    </style>
</head>

<body>
    <h1>Real-time Market Data</h1>
    <div id="status">Not Connected</div>
    <div id="market-data"></div>

    <script src="https://cdn.jsdelivr.net/npm/protobufjs@7.3.0/dist/protobuf.min.js"></script>
    <script>
        const accessToken = "<?php echo $accessTokenUpstox; ?>";
        const wsUrl = "<?php echo $endpoint; ?>";

        let protobufRoot = null;

        // Function to establish WebSocket connection
        const connectWebSocket = async (wsUrl) => {
            return new Promise((resolve, reject) => {
                const ws = new WebSocket(wsUrl);

                ws.onopen = () => {
                    console.log("Connected");
                    document.getElementById('status').innerText = "Connected";
                    resolve(ws);

                    // Send subscription message
                    setTimeout(() => {
                        const data = {
                            guid: "someguid",
                            method: "sub",
                            data: {
                                mode: "full",
                                instrumentKeys: ["NSE_FO|56921", "NSE_FO|56922"],
                            },
                        };
                        ws.send(JSON.stringify(data));
                    }, 1000);
                };

                ws.onclose = () => {
                    console.log("Disconnected");
                    document.getElementById('status').innerText = "Disconnected";
                };

                ws.onmessage = (event) => {
                    const data = event.data;
                    console.log("Received data:", data); // Log the raw data

                    const decodedData = decodeProtobuf(data);
                    console.log("Decoded data:", decodedData); // Log decoded data
                    document.getElementById('market-data').innerText = JSON.stringify(decodedData, null, 2);
                };

                ws.onerror = (error) => {
                    console.error("Error:", error);
                    reject(error);
                };
            });
        };

        // Function to initialize protobuf
        const initProtobuf = async () => {
            protobufRoot = await protobuf.load("/MarketDataFeed.proto");
            console.log("Protobuf initialization complete");
        };

        // Function to decode protobuf message
        const decodeProtobuf = (buffer) => {
            if (!protobufRoot) {
                console.warn("Protobuf not initialized yet!");
                return null;
            }

            const FeedResponse = protobufRoot.lookupType("com.upstox.marketdatafeeder.rpc.proto.FeedResponse");
            return FeedResponse.decode(new Uint8Array(buffer));
        };

        // Initialize protobuf and establish WebSocket connection
        (async () => {
            try {
                await initProtobuf(); // Initialize protobuf
                await connectWebSocket(wsUrl); // Connect to WebSocket
            } catch (error) {
                console.error("An error occurred:", error);
            }
        })();
    </script>
</body>

</html>

This code is also same response

<?php
include '../../core/core.php';
require '../../vendor/autoload.php';

// Initialize cURL session
$curl = curl_init();


curl_setopt_array($curl, array(
    CURLOPT_URL => 'https://api.upstox.com/v2/feed/market-data-feed/authorize',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => '',
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 0,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => 'GET',
    CURLOPT_HTTPHEADER => array(
        'Accept: application/json',
        'Authorization: Bearer ' . $accessTokenUpstox
    ),
));

$jsonData = curl_exec($curl);

curl_close($curl);
$data = json_decode($jsonData, true);

// Extract the authorized redirect URI
$endpoint = $data['data']['authorizedRedirectUri'];
echo $endpoint;
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Real-time Market Data</title>
    <style>
        #status {
            font-weight: bold;
        }
        #market-data {
            white-space: pre-wrap;
            font-family: monospace;
        }
    </style>
</head>

<body>
    <h1>Real-time Market Data</h1>
    <div id="status">Not Connected</div>
    <div id="market-data"></div>

    <script src="https://cdn.jsdelivr.net/npm/protobufjs@7.3.0/dist/protobuf.min.js"></script>
    <script>
        const accessToken = "<?php echo $accessTokenUpstox; ?>";
        const wsUrl = "<?php echo $endpoint; ?>&Authorization=Bearer <?php echo $accessTokenUpstox;?>&Accept=*/*";

        let protobufRoot = null;

        // Function to establish WebSocket connection
        const connectWebSocket = async (wsUrl) => {
            return new Promise((resolve, reject) => {
                const ws = new WebSocket(wsUrl);

                ws.onopen = () => {
                    console.log("Connected");
                    document.getElementById('status').innerText = "Connected";
                    resolve(ws);

                    // Send subscription message
                    setTimeout(() => {
                        const data = {
                            guid: "someguid",
                            method: "sub",
                            data: {
                                mode: "full",
                                instrumentKeys: ["NSE_FO|56921", "NSE_FO|56922"],
                            },
                        };
                        ws.send(JSON.stringify(data));
                    }, 1000);
                };

                ws.onclose = () => {
                    console.log("Disconnected");
                    document.getElementById('status').innerText = "Disconnected";
                };

                ws.onmessage = (event) => {
                    const data = event.data;
                    console.log("Received data:", data); // Log the raw data

                    const decodedData = decodeProtobuf(data);
                    console.log("Decoded data:", decodedData); // Log decoded data
                    document.getElementById('market-data').innerText = JSON.stringify(decodedData, null, 2);
                };

                ws.onerror = (error) => {
                    console.error("Error:", error);
                    reject(error);
                };
            });
        };

        // Function to initialize protobuf
        const initProtobuf = async () => {
            protobufRoot = await protobuf.load("/MarketDataFeed.proto");
            console.log("Protobuf initialization complete");
        };

        // Function to decode protobuf message
        const decodeProtobuf = (buffer) => {
            if (!protobufRoot) {
                console.warn("Protobuf not initialized yet!");
                return null;
            }

            const FeedResponse = protobufRoot.lookupType("com.upstox.marketdatafeeder.rpc.proto.FeedResponse");
            return FeedResponse.decode(new Uint8Array(buffer));
        };

        // Initialize protobuf and establish WebSocket connection
        (async () => {
            try {
                await initProtobuf(); // Initialize protobuf
                await connectWebSocket(wsUrl); // Connect to WebSocket
            } catch (error) {
                console.error("An error occurred:", error);
            }
        })();
    </script>
</body>

</html>

Hello @sonunamdev,

To connect to our WebSockets via a browser, please refer to the React WebSocket Implementation. You can adjust your code accordingly. Rest assured, the example code provided is tested and fully functional.

If you have any questions regarding the linked code, feel free to comment.

Thank you.

Why response is showing blank after server connected. Please help me according to my code :sob::cry::disappointed::sob::sob:

I have implemented running websocket data via backend server using websocket and then have HTML or frontend serve it on browser. if you need help, we can connect and I can share my code for backend serving of websocket.

my implementation is backend gets upstox data → it serves via a port → i can use that in frontend and serve in table or option chain format as needed.

Thanks Chetan Suri, It’s really helpful for me. Please contact me at WhatsApp or call : +91 9589257406