On this page
Polling order status does not scale and is unnecessary. One REST call establishes the picture; the WebSocket keeps it current.
Why not just poll
| Open orders | Polled every second | Against the budget of at most 20 per second and 200 per minute |
|---|---|---|
| 1 | 1 request/second | fine |
| 3 | 3 requests/second | 30% gone before any order |
| 10 | 10 requests/second | half the budget |
| 20 | 20 requests/second | at the limit; more fails |
| Any number, on the order-update feed | 0 requests | the answer |
These docs assume read-only calls count towards the same limit as orders, which is the safe choice.
Order updates come only over the WebSocket (om messages). INFINN does not offer webhooks or postbacks.
Between two polls an order can fill, be rejected and be replaced. A poll shows you the end state and tells you nothing about the path - which is exactly what you need when something went wrong.
The pattern
- Read the order book onceOrder Book gives you every order placed today and its current state. That is your starting picture.
- Connect and authenticate the streamOrder updates are pushed automatically once
akarrives - unlike price feeds, there is no subscribe message for them. - Merge each update into local stateAn
ommessage describes one event on one order. Merge it into the stored row rather than replacing the row. - Re-seed after every reconnectThe stream has no replay. Anything that happened while you were disconnected is gone, so read the order book again before trusting your state.
The field names differ between the two sources
The stream calls the product pcode; the order book calls it prd. The stream calls the event reporttype; the order book calls it rpt.
If you merge both into one model without mapping, you end up with rows that have prd sometimes and pcode other times.
| Concept | On the WebSocket | Over REST |
|---|---|---|
| Product | pcode | prd |
| Event / report type | reporttype | rpt |
| Message type | msgtype | msgtyp |
| Contract token | tk | token |
| Exchange | e | exch |
| Trading symbol | ts | tsym |
The tracker
"""Track every order for a session, with no polling.
Combines one Order Book call with the WebSocket order feed. Handles the
three things that make this non-trivial:
* the stream and REST use different names for the same fields
* updates are partial, so they must be merged rather than assigned
* the stream has no replay, so a reconnect must re-seed from REST
"""
import json
import logging
import threading
log = logging.getLogger("orders")
# Statuses after which nothing further will happen. Both spellings of
# "rejected" appear in the documentation, in different cases.
TERMINAL = {"complete", "canceled", "cancelled", "rejected", "reject"}
# The stream's names for fields the REST endpoints call something else.
STREAM_TO_REST = {"pcode": "prd", "reporttype": "rpt"}
class OrderTracker:
def __init__(self, on_change=None):
self.orders = {}
self.on_change = on_change or (lambda order, event: None)
self._lock = threading.Lock()
# --- seeding ------------------------------------------------------------
def seed(self, rows):
"""Replaces local state from an Order Book response.
Called at startup and after every reconnect. Replacing rather than
merging is correct here: the order book is authoritative, and a
stale local row could otherwise survive indefinitely.
"""
if not isinstance(rows, list):
log.warning("order book returned %s, not a list", type(rows).__name__)
return
with self._lock:
self.orders = {
r["norenordno"]: dict(r)
for r in rows if r.get("norenordno")
}
log.info("seeded %d orders (%d still open)",
len(self.orders), len(self.open_orders()))
# --- streaming ----------------------------------------------------------
def on_message(self, message):
"""Handles one WebSocket message. Ignores anything that is not 'om'."""
if message.get("t") != "om":
return
ordno = message.get("norenordno")
if not ordno:
return
# Rename the stream-only field names so downstream code sees one
# vocabulary regardless of where a row came from.
patch = {STREAM_TO_REST.get(k, k): v for k, v in message.items()}
event = patch.get("rpt", "")
with self._lock:
row = self.orders.setdefault(ordno, {})
# MERGE. An update carries only the fields that changed; an
# assignment would discard everything the order book gave us.
row.update(patch)
snapshot = dict(row)
log.info("%s %s %s filled %s/%s",
ordno, snapshot.get("status"), event,
snapshot.get("fillshares", "0"), snapshot.get("qty"))
if event == "Rejected" and snapshot.get("rejreason"):
# Unusually informative -- surface it unchanged.
log.warning("rejected: %s", snapshot["rejreason"])
self.on_change(snapshot, event)
# --- queries ------------------------------------------------------------
def open_orders(self):
with self._lock:
return [dict(o) for o in self.orders.values()
if str(o.get("status", "")).lower() not in TERMINAL]
def get(self, ordno):
with self._lock:
row = self.orders.get(ordno)
return dict(row) if row else None
def filled(self, ordno):
"""Returns (filled, total) for one order."""
row = self.get(ordno) or {}
return (int(num(row.get("fillshares"))), int(num(row.get("qty"))))
def wait_for_terminal(self, ordno, timeout=60):
"""Blocks until an order reaches a final state, or the timeout.
Uses an event rather than a sleep loop, so it reacts the moment the
stream reports the change.
"""
done = threading.Event()
previous = self.on_change
def watch(order, event):
previous(order, event)
if (order.get("norenordno") == ordno
and str(order.get("status", "")).lower() in TERMINAL):
done.set()
self.on_change = watch
try:
# It may already be terminal -- check before waiting.
row = self.get(ordno)
if row and str(row.get("status", "")).lower() in TERMINAL:
return row
done.wait(timeout)
return self.get(ordno)
finally:
self.on_change = previousWiring it to the feed
"""Run the tracker against the live feed.
Re-seeding on every reconnect is the part that is easy to leave out and
expensive to leave out: without it, any order event that occurred during a
network blip is simply never seen.
"""
import logging
import time
def main():
logging.basicConfig(level=logging.INFO,
format="%(asctime)s %(levelname)-7s %(message)s")
tracker = OrderTracker(on_change=react)
# 1. Establish the starting picture.
tracker.seed(call("/NorenWClientAPI/OrderBook", {"uid": UID}))
# 2. Follow the stream. InfinnFeed is from /websocket/.
feed = InfinnFeed(uid=UID, access_token=ACCESS_TOKEN,
on_order=tracker.on_message)
# 3. Re-seed whenever the connection comes back, because the stream
# replays nothing.
def on_reconnect():
log.info("reconnected -- re-seeding from the order book")
tracker.seed(call("/NorenWClientAPI/OrderBook", {"uid": UID}))
feed.on_authenticated = on_reconnect
try:
feed.run_forever()
except KeyboardInterrupt:
feed.stop()
def react(order, event):
"""Your own logic. Called on every order event."""
if event == "Fill":
filled, total = int(num(order.get("fillshares"))), int(num(order.get("qty")))
if filled >= total:
print(f'FILLED {order["tsym"]} {filled} @ {order.get("avgprc")}')
else:
print(f'PARTIAL {order["tsym"]} {filled}/{total} '
f'@ {order.get("avgprc")}')
elif event == "Rejected":
print(f'REJECTED {order.get("tsym")}: {order.get("rejreason")}')
elif event in ("Canceled", "CanAck"):
print(f'CANCELLED {order.get("tsym")}')
if __name__ == "__main__":
main()// order_tracker.js -- seed from the order book, then follow the WebSocket order feed
// infinn.js -- shared helper used by the guide scripts (Node 18+, no packages)
const BASE = process.env.INFINN_BASE || 'https://api.infinn.in';
const ACCESS_TOKEN = process.env.INFINN_ACCESS_TOKEN || 'YOUR_ACCESS_TOKEN';
const UID = process.env.INFINN_USER_ID || 'IN001';
class InfinnError extends Error {
constructor(message, status, payload) { super(message); this.status = status; this.payload = payload; }
}
// Parses a numeric string, tolerating inf / -nan / NULL.
function num(value, fallback = 0) {
if (value === null || value === undefined) return fallback;
const text = String(value).trim().toLowerCase();
if (['', 'nan', '-nan', 'inf', '-inf', 'null', 'none'].includes(text)) return fallback;
const n = Number(text);
return Number.isFinite(n) ? n : fallback;
}
// One call, checking BOTH error layers.
async function call(path, payload) {
const res = await fetch(BASE + path, {
method: 'POST',
headers: { Authorization: `Bearer ${ACCESS_TOKEN}`, 'Content-Type': 'text/plain' },
body: 'jData=' + JSON.stringify(payload),
signal: AbortSignal.timeout(15000),
});
// Layer 1: HTTP. Error responses have an empty body, so check before parsing.
if (res.status !== 200) {
throw new InfinnError(`HTTP ${res.status} -- check the token and that this machine's IP is whitelisted`, res.status);
}
const text = await res.text();
if (!text.trim()) throw new InfinnError('Empty body with HTTP 200', 200);
const data = JSON.parse(text);
// Layer 2: application. Lists are successes; objects carry stat.
if (!Array.isArray(data) && data.stat && data.stat !== 'Ok') {
throw new InfinnError(data.emsg || 'Not_Ok with no emsg', 200, data);
}
return data;
}
// npm install ws
// INFINN_ACCESS_TOKEN=... INFINN_USER_ID=... node order_tracker.js
const WebSocket = require('ws');
const WS_URL = process.env.INFINN_WS || 'wss://api.infinn.in/NorenWSTP/';
const orders = new Map();
async function seed() {
const rows = await call('/NorenWClientAPI/OrderBook', { uid: UID }).catch(() => []);
orders.clear();
for (const r of Array.isArray(rows) ? rows : []) if (r.norenordno) orders.set(r.norenordno, { ...r });
console.log(`seeded ${orders.size} orders`);
}
function connect() {
const ws = new WebSocket(WS_URL);
ws.on('open', () => ws.send(JSON.stringify({ t: 'a', uid: UID, actid: UID, source: 'API', accesstoken: ACCESS_TOKEN })));
ws.on('message', async (raw) => {
const msg = JSON.parse(raw);
if (msg.t === 'ak') {
if (String(msg.s).toLowerCase() !== 'ok') { console.error('refused', msg); ws.close(); return; }
await seed(); // re-seed on every (re)connect; order updates then arrive automatically
return;
}
if (msg.t === 'om' && msg.norenordno) {
const merged = { ...(orders.get(msg.norenordno) || {}), ...msg }; // updates are partial: merge
orders.set(msg.norenordno, merged);
console.log(`${merged.tsym || ''} ${merged.status || ''} ${merged.reporttype || ''}`);
}
});
ws.on('close', () => setTimeout(connect, 2000 + Math.random() * 3000)); // reconnect with jitter
}
connect();The client on the WebSocket overview page has no on_authenticated hook. Add one line to its _on_message, just after self._authenticated.set():
if getattr(self, "on_authenticated", None):
self.on_authenticated()That is what lets the tracker re-seed on every reconnect rather than only at startup.
Waiting for one order
A common need: place an order and continue once it resolves. Done on the stream this costs nothing and reacts immediately.
def place_and_wait(order, timeout=60):
"""Places an order and returns its final state.
Reacts the instant the stream reports a change, rather than discovering
it up to one poll-interval late.
"""
result = call("/NorenWClientAPI/PlaceOrder", order)
ordno = result["norenordno"]
print("placed", ordno, "-- waiting")
final = tracker.wait_for_terminal(ordno, timeout=timeout)
if final is None:
# The stream told us nothing in time. Fall back to one REST read
# rather than assuming either outcome.
print("no update within the timeout; checking over REST")
rows = call("/NorenWClientAPI/SingleOrdStatus", {
"uid": UID, "norenordno": ordno,
"actid": UID, "exch": order["exch"],
})
final = rows[0] if isinstance(rows, list) and rows else {}
return finalReconnects, and why re-seeding matters
Nothing that happened while you were disconnected is redelivered. A fill during a thirty-second network blip produces no message you will ever see.
So a reconnect is not just "resume listening" - it is "re-read the truth, then resume listening". The order book is cheap and authoritative; call it every time.
| On reconnect | Why |
|---|---|
| Re-read the order book | The stream replays nothing. Anything that happened while you were away is gone. |
| Resubscribe to every price feed | Subscriptions belong to the connection, not the account. |
| Restart the heartbeat | The old timer was tied to the closed socket. |
| Do not retry after close code 1008 | PolicyViolation means the credentials were rejected. Retrying cannot succeed; re-authenticate instead. |
| Back off with jitter | Without jitter, every client of a broker that just restarted reconnects on the same tick. |
What this does not cover
Order updates tell you about orders. They do not maintain your position - for that, either subscribe to position updates (which may not be enabled on your account) or recompute from fills plus a positions book reading. Portfolio valuation