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>