i am using websocket and applying it to backend and frontend and websocket is connected successfully but my realtime values are not changing .when i refresh page the value are change i want that when i open or render that page then it should give me live value -
const Tvniftyview = () => {
console.log("Component rendered"); // Add this line
const [livePrice, setLivePrice] = useState(null);
const [updateCount, setUpdateCount] = useState(0); // State variable to force re-render
useEffect(() => {
const ws = new WebSocket("ws://localhost:8080");
ws.onopen = () => {
console.log("Connected to WebSocket server");
};
ws.onmessage = (event) => {
const newData = JSON.parse(event.data);
console.log("Received real-time update:", newData);
const { marketQuoteData } = newData;
if (
marketQuoteData &&
marketQuoteData.data &&
marketQuoteData.data["NSE_INDEX:Nifty 50"] &&
marketQuoteData.data["NSE_INDEX:Nifty 50"].lastPrice
) {
const livePriceData =
marketQuoteData.data["NSE_INDEX:Nifty 50"].lastPrice;
console.log("Live price updated:", livePriceData);
setLivePrice(livePriceData);
setUpdateCount(prevCount => prevCount + 1); // Force re-render
}
};
ws.onerror = (error) => {
console.error("WebSocket error:", error);
};
return () => {
ws.close();
};
}, [updateCount]); // Re-run effect when updateCount changes
return (
<div className="container-fluid ps-0 pe-0">
<h1 className="text-primary text-center">Nifty Live Price</h1>
<h2 className="text-center fs-5">
{livePrice ? `Live Price: ${livePrice}` : "Fetching live price..."}
</h2>
</div>
);
};
export default Tvniftyview;
The example provided above doesnât clearly explain how you are handling the websocket data. If youâre utilizing React, I recommend reviewing our React example code and attempting to implement it.
Should you encounter any problems with this sample code, please donât hesitate to inform me.
Sample Code: Upstox NodeJS React Websocket Example
ok i will explain at server side i am using async functions and then when ws.connection is done at that time the data will ws.send the data is string format.
app.get("/getNifty", async (req, res) => {
try {
const niftysymbol = "NSE_INDEX|Nifty 50";
const niftymarketQuoteData = await getMarketQuoteData(niftysymbol, "I1");
const niftyintradayCandleData = await niftygetIntradayCandleData(
niftysymbol,
"1minute"
);
const responseData = { niftymarketQuoteData, niftyintradayCandleData };
res.status(200).json(responseData);
// wss.clients.forEach((client) => {
// if (client.readyState === WebSocket.OPEN) {
// client.send(JSON.stringify(responseData));
// }
// });
} catch (error) {
console.error(error);
res.status(500).json({ error: "Internal Server Error" });
}
});
wss.on("connection", async (ws) => {
console.log("Client connected with WebSocket at banknifty");
try {
const niftysymbol = "NSE_INDEX|Nifty 50";
const marketQuoteData = await getMarketQuoteData(niftysymbol, "I1");
const intradayCandleData = await niftygetIntradayCandleData(
niftysymbol,
"1minute"
);
const responseData = { marketQuoteData, intradayCandleData };
ws.send(JSON.stringify(responseData));
} catch (error) {
console.error("Error sending Nifty data:", error);
}
ws.on("close", () => {
console.log("Client disconnected from bank-nifty");
});
});
async function niftygetIntradayCandleData(symbol, interval) {
const niftyapiInstance = new UpstoxClient.HistoryApi(); // Make sure this instance is properly initialized with API credentials
return new Promise((resolve, reject) => {
niftyapiInstance.getIntraDayCandleData(
symbol,
interval,
apiVersion,
(error, data, response) => {
if (error) {
reject(error);
} else {
resolve(data);
}
}
);
});
}
@Pradeep_Jaiswar waiting for solution
1 Like
I have the same issue, when the trade happens through API, its giving historical values that happened hours ago instead of the current market price, this is causing the stoploss functions to not work.