update ws realtime pricing

This commit is contained in:
MuslemRahimi 2024-10-16 23:27:12 +02:00
parent f00a28ab05
commit 15d39e7a25

View File

@ -114,6 +114,22 @@ const WebSocket = require("ws");
let isSend = false; let isSend = false;
let sendInterval; let sendInterval;
function formatTimestampNewYork(timestamp) {
const d = new Date(timestamp / 1e6);
return new Intl.DateTimeFormat("en-US", {
timeZone: "America/New_York",
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
hour12: false,
})
.format(d)
.replace(/(\d+)\/(\d+)\/(\d+),/, "$3-$1-$2")
.replace(",", "");
}
fastify.register(async function (fastify) { fastify.register(async function (fastify) {
fastify.get("/realtime-data", { websocket: true }, (connection, req) => { fastify.get("/realtime-data", { websocket: true }, (connection, req) => {
// Send a welcome message to the client // Send a welcome message to the client
@ -172,11 +188,15 @@ fastify.register(async function (fastify) {
try { try {
const jsonData = JSON.parse(stringData); const jsonData = JSON.parse(stringData);
console.log(jsonData);
// Check if bpData is a number, not equal to zero, and jsonData properties are not null/undefined // Check if bpData is a number, not equal to zero, and jsonData properties are not null/undefined
if ( if (
jsonData?.bp != null && jsonData?.bp != null &&
jsonData?.ap != null && jsonData?.ap != null &&
jsonData?.lp != null && jsonData?.lp != null &&
jsonData?.t != null &&
["Q", "T"]?.includes(jsonData?.type) &&
connection.socket.readyState === WebSocket.OPEN && connection.socket.readyState === WebSocket.OPEN &&
!isSend !isSend
) { ) {
@ -185,12 +205,14 @@ fastify.register(async function (fastify) {
bp: jsonData.bp?.toFixed(2), bp: jsonData.bp?.toFixed(2),
ap: jsonData.ap?.toFixed(2), ap: jsonData.ap?.toFixed(2),
lp: jsonData.lp?.toFixed(2), lp: jsonData.lp?.toFixed(2),
type: jsonData.type,
time: formatTimestampNewYork(jsonData?.t),
}) })
); );
isSend = true; isSend = true;
setTimeout(() => { setTimeout(() => {
isSend = false; isSend = false;
}, 2000); }, 4000);
} }
} catch (error) { } catch (error) {
console.error("Error parsing JSON:", error); console.error("Error parsing JSON:", error);