On this page
A working ticker, built up in five steps. The important part is step 4 - merging delta updates - which is where most clients for this feed go wrong.
Endpoints
WebSocket URL (LIVE): wss://api.infinn.in/NorenWSTP/
Use the connect message with your access token. Orders placed on live are real. Practise first on Sandbox (UAT / Test — NOT live): https://uat.infinn.in. Then use live.
What we are building
SYMBOL LAST CHG% VOLUME
RELIANCE-EQ 1402.30 +0.84 8,412,003
SBIN-EQ 812.45 -0.31 12,004,118
INFY-EQ 1536.00 +1.12 3,210,884
NIFTY INDEX 24,318.55 +0.42 -Step 1 - Open and authenticate
The handshake succeeding tells you nothing. Authentication happens in the first message, and you must wait for its acknowledgement before anything else will work.
"""Step 1: connect and authenticate.
Requires: pip install websocket-client
"""
import json
import os
import websocket # websocket-client
WS_URL = "wss://api.infinn.in/NorenWSTP/"
ACCESS_TOKEN = os.environ["INFINN_ACCESS_TOKEN"]
UID = os.environ["INFINN_USER_ID"]
def on_open(ws):
print("socket open -- this proves nothing yet; authenticating")
ws.send(json.dumps({
"t": "a",
"uid": UID,
"actid": UID,
"source": "API", # must match the source used at login
"accesstoken": ACCESS_TOKEN,
}))
def on_message(ws, raw):
msg = json.loads(raw)
if msg.get("t") == "ak":
# The documentation says "Ok or Not_Ok". The live endpoint sends
# "NOT_OK" in upper case on failure -- verified 2026-10-08. Compare
# case-insensitively or you will miss the rejection.
if str(msg.get("s", "")).lower() != "ok":
print("authentication REFUSED:", msg)
ws.close()
return
print("authenticated")
return
print(msg)
def on_close(ws, code, reason):
# 1008 PolicyViolation is what the server sends when it rejects the
# credentials. Distinguishing it prevents a reconnect loop that can
# never succeed.
if code == 1008:
print("credentials rejected (1008). Check the token and that this "
"machine's IP is registered.")
else:
print("closed:", code, reason)
websocket.WebSocketApp(
WS_URL, on_open=on_open, on_message=on_message, on_close=on_close,
).run_forever()Call User Details with the same token. An HTTP 403 there means the problem is the token or the IP, not the stream - and you get a clearer signal.
Step 2 - Resolve the instruments
Subscriptions use exchange|token, so you need numeric tokens, not trading symbols.
# Example values from the NSE symbol master.
WATCHLIST = [
("NSE", "2885"), # RELIANCE-EQ
("NSE", "3045"), # SBIN-EQ
("NSE", "1594"), # INFY-EQ
("NSE", "26000"), # Nifty 50 (an index -- value only, not tradable)
]
# Format: a pipe between exchange and token, a hash between instruments.
SUBSCRIPTION = "#".join(f"{exch}|{token}" for exch, token in WATCHLIST)
# NSE|2885#NSE|3045#NSE|1594#NSE|26000
# If you have symbols rather than tokens, resolve them first:
def resolve(symbol, exchange="NSE"):
result = call("/NorenWClientAPI/SearchScrip",
{"uid": UID, "stext": symbol, "exch": exchange})
for row in result.get("values", []):
if row["tsym"].upper() == f"{symbol.upper()}-EQ":
return row["exch"], row["token"]
raise KeyError(symbol)Tokens are stable within a trading day. Resolve your watchlist once rather than on every reconnect, and cache the result. For a large list, download the symbol master instead of calling SearchScrip repeatedly.
Step 3 - Subscribe
def on_message(ws, raw):
msg = json.loads(raw)
kind = msg.get("t")
if kind == "ak":
if str(msg.get("s", "")).lower() != "ok":
ws.close()
return
# Subscribe only AFTER the acknowledgement. Subscriptions sent
# before it are not guaranteed to be honoured.
ws.send(json.dumps({"t": "t", "k": SUBSCRIPTION}))
print(f"subscribed to {len(WATCHLIST)} instruments")
return
if kind == "tk":
# One acknowledgement arrives PER INSTRUMENT, each with a full
# snapshot. Count them: fewer than you asked for means some were
# silently dropped.
print("snapshot:", msg.get("ts"), msg.get("lp"))
elif kind == "tf":
print("update: ", msg)Step 4 - Merge the deltas
This is the step that matters. The acknowledgement carries a full snapshot; every update after it carries only what changed.
# Replaces the row. After the first update the symbol, open, high, low
# and volume are all gone, because the delta did not contain them.
state[key] = msg# Updates only the fields present in this message, leaving the rest of
# the snapshot intact.
state.setdefault(key, {}).update(msg)Your ticker works for a second and then the symbol column empties, the day's range disappears and only the price keeps moving. It looks like a rendering bug. It is a merge bug.
class TickStore:
"""Merged market state, keyed by (exchange, token).
The subscription acknowledgement (tk / dk / lk) is a complete snapshot
and replaces the entry. Feed messages (tf / df / lf) are partial and
must be merged into it.
"""
SNAPSHOTS = {"tk", "dk", "lk"}
UPDATES = {"tf", "df", "lf"}
# 2**32-1 divided by 100: the documented sentinel for an
# at-the-open price. It is not a price and must not be displayed.
ATO_SENTINEL = 42949672.95
def __init__(self):
self.rows = {}
def apply(self, msg):
"""Applies one message. Returns the merged row, or None if ignored."""
kind = msg.get("t")
if kind not in self.SNAPSHOTS and kind not in self.UPDATES:
return None
key = (msg.get("e"), msg.get("tk"))
if None in key:
return None
if kind in self.SNAPSHOTS:
self.rows[key] = dict(msg) # snapshot: replace
else:
self.rows.setdefault(key, {}).update(msg) # delta: merge
return self.rows[key]
def price(self, row):
"""Returns a displayable price, or None when there is not one."""
value = num(row.get("lp"))
if value == 0 or abs(value - self.ATO_SENTINEL) < 0.01:
return None
return valueStep 5 - Heartbeat and reconnect
The documentation says to keep the connection alive with heartbeat messages but states no required interval and no server-side timeout. Documentation information not available. Thirty seconds is well inside any plausible idle timeout and costs nothing.
import random
import threading
import time
HEARTBEAT_SECONDS = 30
def heartbeat(ws, authenticated, stopping):
"""Sends {"t":"h"} on a timer, for as long as the session is live."""
while authenticated.is_set() and not stopping.is_set():
time.sleep(HEARTBEAT_SECONDS)
try:
ws.send(json.dumps({"t": "h"}))
except Exception:
return
def run_with_reconnect(build_app, stopping):
"""Reconnects with capped exponential backoff and full jitter.
Jitter matters: without it, every client of a broker that just
restarted reconnects on the same tick and overwhelms it again.
"""
attempt = 0
while not stopping.is_set():
try:
build_app().run_forever(ping_interval=0) # we send our own
attempt = 0 # clean run resets
except Exception as err:
print("feed error:", err)
if stopping.is_set():
return
delay = min(60, 2 ** min(attempt, 6))
time.sleep(random.uniform(1, max(2, delay)))
attempt += 1
print("reconnecting")The complete ticker
"""A live Infinn price ticker.
pip install websocket-client
INFINN_ACCESS_TOKEN=... INFINN_USER_ID=... python ticker.py
Correctness notes, which are the whole point of this file:
* subscribe only after the 'ak' acknowledgement
* snapshots replace, deltas merge
* 42949672.95 is a sentinel, not a price
* compare the 'ak' status case-insensitively ("NOT_OK" on the wire)
"""
import json
import os
import random
import threading
import time
import websocket # websocket-client
WS_URL = "wss://api.infinn.in/NorenWSTP/"
ACCESS_TOKEN = os.environ["INFINN_ACCESS_TOKEN"]
UID = os.environ["INFINN_USER_ID"]
HEARTBEAT_SECONDS = 30
ATO_SENTINEL = 42949672.95
WATCHLIST = [
("NSE", "2885"), # RELIANCE-EQ
("NSE", "3045"), # SBIN-EQ
("NSE", "1594"), # INFY-EQ
("NSE", "26000"), # Nifty 50
]
SUBSCRIPTION = "#".join(f"{e}|{t}" for e, t in WATCHLIST)
rows = {}
authenticated = threading.Event()
stopping = threading.Event()
def num(value, default=0.0):
"""Parses a numeric string, tolerating Infinn's inf / -nan / NULL."""
if value is None:
return default
text = str(value).strip()
if text.lower() in {"", "nan", "-nan", "inf", "-inf", "null", "none"}:
return default
try:
return float(text)
except ValueError:
return default
def render():
"""Redraws the table. Clears the screen rather than scrolling."""
print("\033[H\033[J", end="")
print(f'{"SYMBOL":<16}{"LAST":>12}{"CHG%":>9}{"VOLUME":>14}')
for key in sorted(rows, key=lambda k: rows[k].get("ts", "")):
row = rows[key]
last = num(row.get("lp"))
# The sentinel means "no price", and 0 means we have not had one yet.
shown = "-" if (last == 0 or abs(last - ATO_SENTINEL) < 0.01) \
else f"{last:,.2f}"
change = num(row.get("pc"))
volume = num(row.get("v"))
print(f'{row.get("ts", key[1]):<16}{shown:>12}'
f'{change:>+9.2f}{(f"{volume:,.0f}" if volume else "-"):>14}')
def on_open(ws):
# Authenticate first. Nothing else is honoured until 'ak' arrives.
ws.send(json.dumps({
"t": "a", "uid": UID, "actid": UID,
"source": "API", "accesstoken": ACCESS_TOKEN,
}))
def on_message(ws, raw):
msg = json.loads(raw)
kind = msg.get("t")
if kind == "ak":
# Documented as "Not_Ok"; the wire value is "NOT_OK".
if str(msg.get("s", "")).lower() != "ok":
print("authentication refused:", msg)
ws.close()
return
authenticated.set()
ws.send(json.dumps({"t": "t", "k": SUBSCRIPTION}))
threading.Thread(target=heartbeat, args=(ws,), daemon=True).start()
return
if kind == "hk":
return
key = (msg.get("e"), msg.get("tk"))
if None in key:
return
if kind == "tk":
rows[key] = dict(msg) # snapshot: replace
elif kind == "tf":
rows.setdefault(key, {}).update(msg) # delta: MERGE
else:
return
render()
def heartbeat(ws):
while authenticated.is_set() and not stopping.is_set():
time.sleep(HEARTBEAT_SECONDS)
try:
ws.send(json.dumps({"t": "h"}))
except Exception:
return
def on_close(ws, code, reason):
authenticated.clear()
if code == 1008:
print("\ncredentials rejected (1008) -- not retrying")
stopping.set()
def main():
attempt = 0
while not stopping.is_set():
try:
websocket.WebSocketApp(
WS_URL, on_open=on_open, on_message=on_message,
on_error=lambda ws, e: print("error:", e),
on_close=on_close,
).run_forever(ping_interval=0)
attempt = 0
except Exception as err:
print("feed error:", err)
if stopping.is_set():
return
time.sleep(random.uniform(1, max(2, min(60, 2 ** min(attempt, 6)))))
attempt += 1
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
stopping.set()/**
* Browser ticker for the Infinn feed.
*
* Caveats specific to running this in a browser:
* - the access token would be visible to anyone who opens devtools, so
* this is suitable for a local tool, not for a page you ship to users
* - the browser's public IP must be the registered one
*/
const WS_URL = 'wss://api.infinn.in/NorenWSTP/';
const ATO_SENTINEL = 42949672.95;
const WATCHLIST = [
['NSE', '2885'], // RELIANCE-EQ
['NSE', '3045'], // SBIN-EQ
['NSE', '1594'], // INFY-EQ
];
const SUBSCRIPTION = WATCHLIST.map(([e, t]) => `${e}|${t}`).join('#');
const rows = new Map();
function connect(uid, accessToken, onUpdate) {
const ws = new WebSocket(WS_URL);
let heartbeat = null;
ws.addEventListener('open', () => {
ws.send(JSON.stringify({
t: 'a', uid, actid: uid, source: 'API', accesstoken: accessToken,
}));
});
ws.addEventListener('message', (event) => {
const msg = JSON.parse(event.data);
if (msg.t === 'ak') {
// Documented as "Not_Ok"; the wire value is "NOT_OK".
if (String(msg.s).toLowerCase() !== 'ok') {
console.error('authentication refused', msg);
ws.close();
return;
}
ws.send(JSON.stringify({ t: 't', k: SUBSCRIPTION }));
heartbeat = setInterval(() => ws.send(JSON.stringify({ t: 'h' })), 30000);
return;
}
if (msg.t === 'hk') return;
const key = `${msg.e}|${msg.tk}`;
if (msg.t === 'tk') {
rows.set(key, { ...msg }); // snapshot: replace
} else if (msg.t === 'tf') {
rows.set(key, { ...(rows.get(key) || {}), ...msg }); // delta: MERGE
} else {
return;
}
onUpdate(rows);
});
ws.addEventListener('close', (event) => {
clearInterval(heartbeat);
// 1008 PolicyViolation means the credentials were rejected; retrying
// cannot help.
if (event.code === 1008) {
console.error('credentials rejected -- not reconnecting');
return;
}
setTimeout(() => connect(uid, accessToken, onUpdate), 2000 + Math.random() * 3000);
});
return ws;
}
/** Returns a displayable price, or null when the feed has not given one. */
function displayPrice(row) {
const value = Number(row.lp);
if (!Number.isFinite(value) || value === 0) return null;
if (Math.abs(value - ATO_SENTINEL) < 0.01) return null; // sentinel
return value;
}A browser version
The browser has WebSocket built in, so this needs no dependencies at all. Note the caveats underneath.
/**
* Browser ticker for the Infinn feed.
*
* Caveats specific to running this in a browser:
* - the access token would be visible to anyone who opens devtools, so
* this is suitable for a local tool, not for a page you ship to users
* - the browser's public IP must be the registered one
*/
const WS_URL = 'wss://api.infinn.in/NorenWSTP/';
const ATO_SENTINEL = 42949672.95;
const WATCHLIST = [
['NSE', '2885'], // RELIANCE-EQ
['NSE', '3045'], // SBIN-EQ
['NSE', '1594'], // INFY-EQ
];
const SUBSCRIPTION = WATCHLIST.map(([e, t]) => `${e}|${t}`).join('#');
const rows = new Map();
function connect(uid, accessToken, onUpdate) {
const ws = new WebSocket(WS_URL);
let heartbeat = null;
ws.addEventListener('open', () => {
ws.send(JSON.stringify({
t: 'a', uid, actid: uid, source: 'API', accesstoken: accessToken,
}));
});
ws.addEventListener('message', (event) => {
const msg = JSON.parse(event.data);
if (msg.t === 'ak') {
// Documented as "Not_Ok"; the wire value is "NOT_OK".
if (String(msg.s).toLowerCase() !== 'ok') {
console.error('authentication refused', msg);
ws.close();
return;
}
ws.send(JSON.stringify({ t: 't', k: SUBSCRIPTION }));
heartbeat = setInterval(() => ws.send(JSON.stringify({ t: 'h' })), 30000);
return;
}
if (msg.t === 'hk') return;
const key = `${msg.e}|${msg.tk}`;
if (msg.t === 'tk') {
rows.set(key, { ...msg }); // snapshot: replace
} else if (msg.t === 'tf') {
rows.set(key, { ...(rows.get(key) || {}), ...msg }); // delta: MERGE
} else {
return;
}
onUpdate(rows);
});
ws.addEventListener('close', (event) => {
clearInterval(heartbeat);
// 1008 PolicyViolation means the credentials were rejected; retrying
// cannot help.
if (event.code === 1008) {
console.error('credentials rejected -- not reconnecting');
return;
}
setTimeout(() => connect(uid, accessToken, onUpdate), 2000 + Math.random() * 3000);
});
return ws;
}
/** Returns a displayable price, or null when the feed has not given one. */
function displayPrice(row) {
const value = Number(row.lp);
if (!Number.isFinite(value) || value === 0) return null;
if (Math.abs(value - ATO_SENTINEL) < 0.01) return null; // sentinel
return value;
}Anything in page JavaScript is visible to the user and to anyone who can read the page source. A token in a browser is a token anyone can place orders with.
For a shipped product, proxy the feed through a server you control - which also solves the registered-IP problem, since the server has the fixed address.
Choosing a feed
| Need | Feed | Per-update payload |
|---|---|---|
| A price, and nothing else, for many instruments | LTP | 4 fields |
| A watchlist or ticker row | Touchline | Up to ~19 fields |
| A depth ladder | Depth | Up to ~30 fields |
| Order status | Order updates | No subscription needed |
| Position changes | Position updates | May not be enabled on your account |