Get Live Stock Prices Using Upstox API in JavaScript
If you’re a developer or trader interested in real-time market data, the Upstox API is a powerful tool for streaming live prices, building dashboards, or creating algorithmic trading strategies. In this tutorial, I’ll show you how to use JavaScript (with React) to connect to the Upstox WebSocket, decode protobuf messages, and process live market data.
🛠️ Step 1: Load the Protobuf Schema
Upstox uses Google Protobuf for efficient real-time data transmission. Let’s start by loading the protobuf schema:
import protobuf from ‘protobufjs’;
let protobufRoot;
const initProtobuf = async () => {
protobufRoot = await protobuf.load(‘/marketDataFeed.proto’);
console.log(‘Protobuf part initialization complete’);
};
👉 Tip: Place marketDataFeed.proto in your public folder or host it securely to load it dynamically.
🛠️ Step 2: Authorize and Get WebSocket URL
Before connecting to the WebSocket, you need to authorize and get a WebSocket URL:
const getUrl = async () => {
try {
const apiUrl = ‘https://api-v2.upstox.com/feed/market-data-feed/authorize';
const headers = {
‘Content-Type’: ‘application/json’,
Authorization: ‘Bearer ‘ + authToken,
};
const response = await fetch(apiUrl, {
method: ‘GET’,
headers: headers,
});
const res = await response.json();
return res.data.authorizedRedirectUri;
} catch (error) {
console.error(‘Error fetching WebSocket URL:’, error);
}
};
🔐 Note: Replace authToken with your OAuth access token from Upstox.
🛠️ Step 3: Convert Blob to ArrayBuffer
When receiving binary data via WebSocket, you’ll get it as a Blob. Let’s convert it to an ArrayBuffer:
const blobToArrayBuffer = async (blob) => {
if (‘arrayBuffer’ in blob) return await blob.arrayBuffer();
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result);
reader.onerror = () => reject();
reader.readAsArrayBuffer(blob);
});
};
🛠️ Step 4: Decode Protobuf Messages
Next, let’s decode the protobuf data using the schema we loaded earlier:
const decodeProtobuf = (buffer) => {
if (!protobufRoot) {
console.warn(‘Protobuf not initialized!’);
return null;
}
const FeedResponse = protobufRoot.lookupType(
‘com.upstox.marketdatafeeder.rpc.proto.FeedResponse’
);
return FeedResponse.decode(buffer);
};
🛠️ Step 5: Connect to WebSocket and Subscribe
Now let’s bring it all together using a React hook (useEffect) to initialize protobuf, connect to WebSocket, and process live data:
import { useEffect, useRef } from ‘react’;
const wsRef = useRef(null);
Get Parth Vadhel’s stories in your inbox
Join Medium for free to get updates from this writer.
const UpstoxInstrumentIDs = {
BANKEX = ‘BSE_INDEX|BANKEX’,
FINNIFTY = ‘NSE_INDEX|Nifty Fin Service’,
NIFTY = ‘NSE_INDEX|Nifty 50’,
BANKNIFTY = ‘NSE_INDEX|Nifty Bank’,
SENSEX = ‘BSE_INDEX|SENSEX’,
MIDCPNIFTY = ‘NSE_INDEX|NIFTY MID SELECT’,
}
useEffect(() => {
initProtobuf();
const connectWebSocket = async () => {
try {
const wsUrl = await getUrl();
if (!wsUrl) {
console.error(‘Failed to get WebSocket URL’);
return;
}
wsRef.current = new WebSocket(wsUrl);
wsRef.current.onopen = () => {
console.log(‘Connected to Upstox WebSocket’);
const data = {
guid: ‘8096’, // Unique identifier
method: ‘sub’,
data: {
mode: ‘ltpc’, // Last traded price & close
instrumentKeys: [
`${UpstoxInstrumentIDs[instrumentName]}`,
`${VIXInstrumentIDs[‘Upstox’]}`,
],
},
};
wsRef.current.send(JSON.stringify(data));
};
wsRef.current.onmessage = async (event) => {
const arrayBuffer = await blobToArrayBuffer(event.data);
const buffer = Buffer.from(arrayBuffer);
const response = decodeProtobuf(buffer);
if (response?.feeds) {
const transformedDataArray = Object.entries(response.feeds).map(
([key, value]) => ({
ExchangeInstrumentID: key,
LastTradedPrice:
Number(value?.ltpc?.ltp) || 0,
})
);
transformedDataArray.forEach((transformedData) => {
// Update your UI or store here
console.log(transformedData);
});
}
};
wsRef.current.onclose = () => {
console.log(‘Disconnected from Upstox WebSocket’);
};
wsRef.current.onerror = (error) => {
console.error(‘WebSocket error:’, error);
};
} catch (error) {
console.error(‘WebSocket connection error:’, error);
}
};
connectWebSocket();
return () => wsRef.current?.close();
}, []);
🎯 What’s Happening Here?
✅ Initialize Protobuf
✅ Authorize and get WebSocket URL
✅ Connect and subscribe to instrument keys
✅ Decode live data using protobuf
✅ Log/transform data for your app
🖼️ Conclusion
Using Upstox’s APIs, you can stream live market data in JavaScript, decode it with protobuf, and build powerful dashboards or trading apps. With this guide, you’re well on your way to integrating real-time data into your projects.
✍️ About the Author
I’m a developer passionate about fintech and trading technologies. Follow me on Medium for more guides on building with APIs, real-time systems, and JavaScript.
📬 Email: parthvadhel1108[at]gmail[dot]com — Feel free to reach out for help or discussions!



