On this page
Login fails? Check your IP first

If GenAcsTok returns stat: "Not_Ok", the most common cause is that the computer you are using is not on the whitelist. Open api.ipify.org on that computer and make sure the number shown is the Primary IP in trade.infinn.in → top-right profile icon → Generate Key (API Key panel). Only then check the API key, secret and code.

Work down this list in order. It is ordered by how often each cause turns out to be the real one, so stopping early is normal.

Before anything else, print the status code and the raw body

Most time lost to this API is lost by debugging the wrong layer. Two lines of output tell you which one you are in.

The only diagnostic you need to start
print("status:", response.status_code)
print("body:  ", repr(response.text))     # repr, so an empty body is visible

An empty body means layer 1 - the gateway. A body containing stat means layer 2 - the trading system. They have completely different causes. Why

If the body is empty

  1. Check the status code401 is authentication or IP. 404 is the path. 429 is the rate limit. 405 means you used GET. Each has an entry with its causes.
  2. If 401 — check your public IP before your tokenThis is the single most common cause of a stalled first integration, and almost nobody checks it first. Does this match your profile?Copycurl -s https://api.ipify.org; echo Compare the output against the Primary IP Address in trade.infinn.in → Profile → Generate Key. If they differ, no token will work from this machine. How to update it
  3. If 401 — then check the header itselfIt must be exactly Authorization: Bearer <token>: the word Bearer, one space, then the token. Common mistakes are omitting Bearer, using Token instead, or including the angle brackets from the documentation. Also check you are sending the access token (64 hex characters, no dashes) and not the login code (36 characters, with dashes).
  4. If 401 — then get a fresh tokenRe-run the login flow. Remember the login code is single-use: if token generation itself failed, you need a new code, not a retry of the old one.
  5. If 404 — check the path character by characterPaths are case-sensitive. /NorenWClientAPI/OrderBook works; /norenwclientapi/orderbook does not. Every endpoint uses /NorenWClientAPI/.
  6. If 429 — stop and look at your call patternBacking off treats the symptom. Count your calls per second against the limit of 20 per second and 200 per minute. If a loop is involved, the answer is the WebSocket feed, not a longer sleep. The arithmetic

If the body contains stat: "Not_Ok"

  1. Read emsg, and look it upEvery documented message has an entry on the error reference with its cause and fix. The part before the colon tells you the category.
  2. If "Invalid Input : Missing ..." — the message names the fieldsIt lists exactly what is absent. Check them against the endpoint page's parameter table; required fields carry a red required badge. Note that sending a required field as an empty string counts as missing.
  3. If "Error Occurred : 2 \"invalid input\"" — check tick size and lot sizeThis generic message is usually one of two specific things: a price that is not a multiple of the tick size, or a quantity that is not a multiple of the lot size. Both values are in the symbol master. RELIANCE-EQ ticks in 0.10, so 1402.33 is rejected and 1402.30 is fine. There is a validator you can paste in.
  4. If "Session Expired" — re-authenticate, do not retryThe token is gone. Retrying will produce the same answer indefinitely. Clear the stored token and run the login flow once. Handling this cleanly
  5. If "Error Occurred : 5 \"no data\"" — you may not have an errorThis usually means the result is empty: no positions, no quote for that token, no holdings for that product. Show an empty state rather than an error. If you did expect data, check that exch and token identify the instrument you had in mind - a token from the wrong exchange returns no data rather than an error.
  6. If "Rejected : ORA:Order not found" — check the order's statusOnly OPEN and TRIGGER_PENDING orders can be modified or cancelled. Read the current status with Single Order Status. If it has filled, this is not a bug - the order did what you asked before you changed your mind.

If the call succeeds but the result is wrong

Numbers are concatenating instead of adding

Infinn sends numbers as JSON strings. "1000" + "500" is "1000500". Convert before calculating, and guard against the "inf", "-nan" and "NULL" values that appear in the report endpoints. Parser

A field I expected is missing

Infinn omits fields rather than returning null. The documented field list for Search Scrips has fifteen entries; its sample response has three. Use .get(), not direct indexing.

My key lookup returns nothing although the field is clearly there

Capitalisation. Several sample responses return Al_id, Token, Qty, Prc, Pc and even Stat where the field tables document lower case. Normalise keys on the way in

A successful GTT or alert call is reported as a failure

Your success test is stat === "Ok". The GTT and alert endpoints return "Oi created", "Oi Replacedt" and "Oi delete success" instead. Test for the absence of emsg. More

Iterating the response crashes on the error path

Several endpoints return an array on success and an object on failure. Your loop works until the first error. Check the type first. How

The order placed but my code thinks it did not

Check whether you are treating a timeout as a failure. A timed-out PlaceOrder may well have succeeded. Reconcile against the order book. Retrying safely

MTM and P&L do not match the terminal

They are different numbers computed against different reference prices - netavgprc for MTM, netupldprc for P&L. Also check you are applying mult and prcftr, which are both 1 for equities and not for derivatives. The formulas

If the WebSocket is not working

  1. Test the token over REST firstCall User Details with the same token. If that returns an HTTP 403, the problem is the token or the IP, not the stream - and you have a much clearer error message to work with.
  2. Check what came back from the connect taskYou should receive {"t":"ak","s":"Ok"}. If you receive {"t":"ak","s":"NOT_OK"} followed by a close with code 1008, the credentials were refused. Note the live value is NOT_OK in upper case, while the documentation says Not_Ok. If your check is s === 'Not_Ok' it will not match either value reliably - compare case-insensitively.
  3. Make sure you subscribed after the acknowledgementSubscriptions sent before ak arrives are not guaranteed to be honoured. Queue them and flush the queue when ak reports success.
  4. Count your acknowledgementsOne tk, dk or lk should arrive per token you subscribed to. Fewer means some were silently dropped - usually because you exceeded the feed's undocumented subscription ceiling.
  5. Check the subscription key formatexchange|token, joined with #. A pipe between exchange and token; a hash between instruments. So NSE|2885#NSE|3045. A trading symbol where a numeric token belongs produces silence, not an error.
  6. Send a heartbeat{"t":"h"} should produce {"t":"hk"} promptly. If it does not, the connection is dead even though the socket may still report itself open. Reconnect and resubscribe.
  7. Check the market is openA silent feed outside trading hours is a silent market, not a bug.

A diagnostic script

Checks the four things that account for most failures, in order, and tells you which one is wrong.

Run this before debugging anything else
"""Infinn connectivity diagnostic.

Checks, in order: outbound network, your public IP, the token over REST, and
the WebSocket handshake. Each step explains what a failure means rather than
just reporting it.

INFINN_ACCESS_TOKEN=... INFINN_USER_ID=... python diagnose.py
"""
import json
import os
import sys

import requests

TOKEN = os.environ.get("INFINN_ACCESS_TOKEN", "")
UID = os.environ.get("INFINN_USER_ID", "")
BASE = "https://api.infinn.in"


def step(n, label):
  print(f"\n[{n}] {label}")


def main():
  if not TOKEN or not UID:
      sys.exit("Set INFINN_ACCESS_TOKEN and INFINN_USER_ID first.")

  # --- 1. Can we reach anything at all? ---------------------------------
  step(1, "Outbound connectivity")
  try:
      requests.get("https://api.ipify.org", timeout=10).raise_for_status()
      print("    ok")
  except Exception as err:
      sys.exit(f"    FAILED: no outbound HTTPS. {err}")

  # --- 2. What IP does the world see? -----------------------------------
  step(2, "Public IP address")
  ip = requests.get("https://api.ipify.org", timeout=10).text.strip()
  print(f"    this machine appears as {ip}")
  print("    -> this MUST match Primary IP Address on your Infinn profile")

  # --- 3. Is the host reachable, and is the token accepted? -------------
  step(3, "REST call with your token")
  response = requests.post(
      f"{BASE}/NorenWClientAPI/UserDetails",
      headers={"Authorization": f"Bearer {TOKEN}",
               "Content-Type": "text/plain"},
      data="jData=" + json.dumps({"uid": UID}),
      timeout=15,
  )
  print(f"    HTTP {response.status_code}, body {len(response.content)} bytes")

  if response.status_code == 401:
      sys.exit("    FAILED: 401 with an empty body. Either the token is "
               f"invalid, or {ip} is not the registered IP. Check the IP "
               "first -- a new token will not help if the address is wrong.")
  if response.status_code != 200:
      sys.exit(f"    FAILED: unexpected status {response.status_code}. "
               "See /errors/ for this code.")

  data = response.json()
  if data.get("stat") != "Ok":
      sys.exit(f"    FAILED at the application layer: {data.get('emsg')}")

  print(f"    ok -- account {data.get('actid')}, "
        f"exchanges {', '.join(data.get('exarr', []))}")

  # --- 4. Does the stream accept the same token? ------------------------
  step(4, "WebSocket handshake")
  try:
      import websocket
  except ImportError:
      print("    skipped (pip install websocket-client to test this)")
      return

  ws = websocket.create_connection("wss://api.infinn.in/NorenWSTP/",
                                   timeout=15)
  ws.send(json.dumps({"t": "a", "uid": UID, "actid": UID,
                      "source": "API", "accesstoken": TOKEN}))
  reply = json.loads(ws.recv())
  ws.close()

  # The documentation says "Not_Ok"; the live feed sends "NOT_OK".
  if str(reply.get("s", "")).lower() == "ok":
      print("    ok -- stream authenticated")
  else:
      sys.exit(f"    FAILED: stream refused the token: {reply}")

  print("\nAll checks passed.")


if __name__ == "__main__":
  main()

Still stuck

Esc
↑↓ navigate↵ openEsc close/ to search