WebSocket not sending ticks for NIFTY 50 and SENSEX spot price subscription

aridg
I am trying to subscribe to NIFTY 50 and SENSEX spot prices via the websocket but it doesn't return any tick. I have provided the needed code snippet below.


import { KiteTicker } from "kiteconnect";
import { redis, connectRedis } from "./redis.js";
import fs from "fs/promises";

export async function startTicker() {
const apiKey = process.env.KITE_API_KEY!;
const accessToken = (await fs.readFile("access_token.txt", "utf-8")).trim();
const instruments = JSON.parse(
await fs.readFile("instruments.json", "utf-8")
);

await connectRedis();

const ticker = new KiteTicker({ api_key: apiKey, access_token: accessToken });
ticker.autoReconnect(true, 50, 10);
ticker.connect();

ticker.on("noreconnect", function () {
console.log("noreconnect");
});

ticker.on("reconnect", function (reconnect_interval, reconnections) {
console.log(
"Reconnecting: attempt - ",
reconnections,
" innterval - ",
reconnect_interval
);
});

// 1. Get index tokens
const indexMap = {
"NIFTY 50": instruments.find(
(i) => i.name === "NIFTY 50" && i.instrument_type === "EQ"
)!.instrument_token,
SENSEX: instruments.find(
(i) => i.name === "SENSEX" && i.instrument_type === "EQ"
)!.instrument_token,
};

const indexTokens = Object.values(indexMap);

let spotPrices: Record<number, number> = {};

ticker.on("connect", () => {
console.log("✅ KiteTicker connected");

console.log("???? Subscribing to index tokens:", indexTokens);
ticker.subscribe([...indexTokens]);
ticker.setMode(ticker.modeLTP, [...indexTokens]);
});

// if (ticker.connected()) {
// console.log("✅ Already connected, subscribing to index tokens");
// }

ticker.on("ticks", (ticks) => {
for (const t of ticks) {
if (indexTokens.includes(t.instrument_token)) {
spotPrices[t.instrument_token] = t.last_price;
// Store spot in Redis
const key = `index:${t.instrument_token}`;
redis.hSet(key, {
ltp: t.last_price.toString(),
ts: Date.now().toString(),
});
}
}
});

ticker.on("error", (err) => {
console.error("❌ Ticker error:", err);
});

ticker.on("disconnect", (reason) => {
console.warn("❗ Ticker disconnected:", reason);
});

ticker.on("close", () => {
console.warn("???? Ticker connection closed");
});
}



I have also tried directly passing 256265(NIFTY 50) and 265(SENSEX) directly to the subscribe function in an array. It doesn't return any tick.
  • Nivas
    You won't receive data if the instrument token is incorrect. I recommend fetching the correct instrument token from the instrument file and cross-verifying to ensure you're subscribing to the correct one.
Sign In or Register to comment.