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 ordersPolled every secondAgainst the budget of at most 20 per second and 200 per minute
11 request/secondfine
33 requests/second30% gone before any order
1010 requests/secondhalf the budget
2020 requests/secondat the limit; more fails
Any number, on the order-update feed0 requeststhe answer

These docs assume read-only calls count towards the same limit as orders, which is the safe choice.

Order updates

Order updates come only over the WebSocket (om messages). INFINN does not offer webhooks or postbacks.

And polling still misses things

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

Your clientwss://api.infinn.in/NorenWSTP/open the socket{"t":"a", ... "accesstoken": "..."}{"t":"ak","s":"Ok"}authenticated — now you may subscribe{"t":"t","k":"NSE|2885#NSE|3045"}{"t":"tk", ...} × one per tokenfull snapshot{"t":"tf","tk":"2885","lp":"1402.30"}delta — merge it, do not replace{"t":"h"} every ~30s{"t":"hk","ft":"..."}
Figure 1. Seed once over REST, then follow the stream. Order updates need no subscription message: they begin arriving as soon as the connection is authenticated.
  1. Read the order book onceOrder Book gives you every order placed today and its current state. That is your starting picture.
  2. Connect and authenticate the streamOrder updates are pushed automatically once ak arrives - unlike price feeds, there is no subscribe message for them.
  3. Merge each update into local stateAn om message describes one event on one order. Merge it into the stored row rather than replacing the row.
  4. 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

Normalise at the boundary

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.

ConceptOn the WebSocketOver REST
Productpcodeprd
Event / report typereporttyperpt
Message typemsgtypemsgtyp
Contract tokentktoken
Exchangeeexch
Trading symboltstsym

The tracker

order_tracker.py
"""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 = previous

Wiring it to the feed

Putting it together
"""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()
InfinnFeed needs one small addition

The client on the WebSocket overview page has no on_authenticated hook. Add one line to its _on_message, just after self._authenticated.set():

Python
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.

Place and wait, without a single poll
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 final

Reconnects, and why re-seeding matters

The stream has no replay

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 reconnectWhy
Re-read the order bookThe stream replays nothing. Anything that happened while you were away is gone.
Resubscribe to every price feedSubscriptions belong to the connection, not the account.
Restart the heartbeatThe old timer was tied to the closed socket.
Do not retry after close code 1008PolicyViolation means the credentials were rejected. Retrying cannot succeed; re-authenticate instead.
Back off with jitterWithout jitter, every client of a broker that just restarted reconnects on the same tick.

What this does not cover

Positions need their own treatment

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

Next

Esc
↑↓ navigate↵ openEsc close/ to search