On this page

Reading Infinn responses correctly takes a little more care than most APIs, for reasons set out below. None of it is hard, but all of it will bite you once if you are not expecting it.

There is no envelope

Many APIs wrap every answer in a consistent outer object. A typical enveloped API always returns {"status": ..., "data": ...}, so a client can unwrap first and interpret second.

Infinn does not. The payload is the answer, with a stat field mixed in among the data.

Request
Enveloped
{
"status": "success",
"data": {
  "user_id": "IN001",
  "broker": "EXAMPLE"
}
}
Response
Flat
{
"stat": "Ok",
"actid": "IN001",
"brkname": "VIDYA",
"exarr": ["NSE", "NFO"]
}

The practical consequence: you cannot write one generic unwrapper. Each response has to be read on its own terms, and stat has to be checked before the rest of the object is trusted.

The shape changes between success and failure

Several endpoints return a JSON array on success and a JSON object on failure. Iterating without checking gives you a crash on the error path - which is the worst possible place for one.

Request
Order Book, 200 OK
[
{ "stat": "Ok", "norenordno": "...", "status": "OPEN" },
{ "stat": "Ok", "norenordno": "...", "status": "COMPLETE" }
]
Error
Order Book, also 200 OK
{
"stat": "Not_Ok",
"emsg": "Session Expired : Invalid Session Key"
}
Check the type first

Every endpoint page states which shape it returns, under Returns in the facts panel. The book and report endpoints - order book, trade book, positions, holdings, single order history, the reports - are the array ones.

Python
data = response.json()

# Failure always arrives as an object; success here is a list.
if isinstance(data, dict):
  raise RuntimeError(data.get("emsg", "request failed"))

for order in data:
  print(order["norenordno"], order.get("status"))

Success is not always "Ok"

Nearly every endpoint reports success as stat: "Ok". The GTT endpoints do not. They return a short sentence instead.

EndpointsSuccess value of statFailure
All ordinary endpoints (60 of them)"Ok""Not_Ok" plus emsg
Place GTT Order"Oi created""Not_Ok" plus emsg
Modify GTT Order"Oi Replacedt" note the typo"Not_Ok" plus emsg
Cancel GTT Order"Oi delete success""Not_Ok" plus emsg
This is the single most dangerous quirk in the API

Code written as if (data.stat === 'Ok') will treat every successful GTT and alert call as a failure. The order was created; your code reports an error; the user tries again; you now have two GTT orders.

Note also "Oi Replacedt" - with a trailing t - from Modify GTT Order, against "Oi Replaced" from Modify Alert. Do not match these strings exactly.

Python
def succeeded(data):
  """Works across every Infinn endpoint.

  Rather than matching a success string -- which differs between the GTT,
  alert and ordinary endpoints -- test for the absence of a failure.
  """
  if isinstance(data, list):
      return True                       # an array response is a success
  if data.get("emsg"):
      return False
  return str(data.get("stat", "")).lower() != "not_ok"

Numbers arrive as strings

Prices, quantities, timestamps - all quoted.

From a real Positions Book response
{
"netqty": "0",
"netavgprc": "0.00",
"daybuyqty": "2",
"daybuyamt": "2610.00",
"lp": "0.00",
"prcftr": "1.000000"
}

So daybuyamt + daysellamt concatenates in JavaScript and raises a TypeError in Python. Convert before you calculate.

And sometimes they are not numbers at all

The published sample response for Get Order Report contains "prc": "inf", "trgprc": "-nan" and "isin": "NULL". These are C float-formatting artefacts reaching the wire.

parseFloat("inf") is NaN in JavaScript, while float("inf") is positive infinity in Python - so the same data silently produces different wrong answers in different languages. Guard every numeric parse from the report endpoints.

Python
_BAD = {"", "nan", "-nan", "inf", "-inf", "null", "none"}


def num(value, default=0.0):
  """Parses an Infinn numeric string defensively.

  Handles the documented "inf", "-nan" and "NULL" values that appear in the
  report endpoints, which float() would otherwise turn into infinity.
  """
  if value is None:
      return default
  text = str(value).strip()
  if text.lower() in _BAD:
      return default
  try:
      return float(text)
  except ValueError:
      return default


# num("1402.30") -> 1402.3     num("inf") -> 0.0     num("NULL") -> 0.0

Key casing is not consistent

The documented field tables are lower case. Several published sample responses are not. These are not transcription slips on this site - they are what the API specification shows.

EndpointDocumentedReturned in the sample
Place GTT Orderal_idAl_id
Get Pending GTT Ordersal_id, token, remarks, qty, prcAl_id, Token, Remarks, Qty, Prc
Get Top Listpc, oiPc and pc on different rows of the same array; likewise Oi and oi
Get Content ListpcPc
Get Unsettled Trading Datesrequest_timeRequest_time
Positions Bookprdprarr
Normalise once, at the boundary

Lower-case every key as the response comes in, and work only with the normalised object thereafter. It costs a few microseconds and removes a whole category of bug.

Python
def normalise(value):
  """Lower-cases every key, recursively.

  Infinn returns Al_id, Token, Qty and Stat in some sample responses where
  the field tables document al_id, token, qty and stat. Normalising at the
  boundary means the rest of your code only deals with one spelling.
  """
  if isinstance(value, dict):
      return {k.lower(): normalise(v) for k, v in value.items()}
  if isinstance(value, list):
      return [normalise(v) for v in value]
  return value


data = normalise(response.json())

Missing fields are absent, not null

Infinn omits a field rather than returning null for it. The documented field list for Search Scrips runs to fifteen entries; its published sample response contains three.

So data["rejreason"] raises a KeyError rather than giving you None. Use .get() in Python, optional chaining in JavaScript, and never index directly into anything the field table does not mark as always present.

Where the page tells you

Response field tables on this site carry a Presence note wherever the API specification says a field is conditional - for example "Present only when the order was rejected". Fields without a note should normally be there, but defensive access still costs nothing.

Timestamps come in several formats

FieldFormatExampleSeen on
request_timeHH:MM:SS dd-mm-yyyy18:07:31 29-05-2020Most endpoints
request_timeddmmyyyyHHMMSS, no separators04062021121503Get Enabled GTTs
norentmHH:MM:SS dd-mm-yyyy19:59:32 13-12-2020Order and trade books
norentmdd-mm-yyyy HH:MM:SS - the parts reversed02-05-1975 08:48:52Get Broker Message
exch_tmdd-mm-YYYY hh:MM:SS01-01-1980 00:00:00Order and trade books
expires_inUnix timestamp in seconds, despite the name1756990407GenAcsTok
ordenttmUnix timestamp in seconds1690107153Single Order Status
lttHH:MM:SS, no date05:30:00Quotes
dob, exdDDMMYYYY or dd-MMM-yyyy01011990, 29-DEC-2026Client details; symbol master
Parse per endpoint, not globally

A single date parser applied across the whole API will fail. Two different formats appear in the same family: most endpoints return request_time as 18:07:31 29-05-2020, while Get Enabled GTTs returns 04062021121503 with no separators at all.

All times are Indian Standard Time (UTC+5:30). No timezone is included in any of them.

A reader that handles all of it

Putting the above together into one function you can paste into a project.

A defensive response reader
"""A defensive reader for Infinn API responses.

Handles, in one place, the five things that otherwise go wrong:
1. the two error layers (HTTP status, then stat in the body)
2. array-on-success / object-on-failure
3. success strings that are not "Ok" (the GTT endpoints)
4. inconsistent key casing
5. numeric strings including "inf", "-nan" and "NULL"
"""
import json

import requests

BASE = "https://api.infinn.in"
_BAD_NUMBERS = {"", "nan", "-nan", "inf", "-inf", "null", "none"}


class InfinnError(RuntimeError):
  """Raised for both transport and application failures."""

  def __init__(self, message, status=None, payload=None):
      super().__init__(message)
      self.status = status
      self.payload = payload


def _lower_keys(value):
  if isinstance(value, dict):
      return {k.lower(): _lower_keys(v) for k, v in value.items()}
  if isinstance(value, list):
      return [_lower_keys(v) for v in value]
  return value


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 _BAD_NUMBERS:
      return default
  try:
      return float(text)
  except ValueError:
      return default


def call(path, payload, access_token, timeout=10):
  """Makes one Infinn call and returns a normalised, validated payload."""
  response = requests.post(
      BASE + path,
      headers={
          "Authorization": f"Bearer {access_token}",
          "Content-Type": "text/plain",
      },
      data="jData=" + json.dumps(payload),
      timeout=timeout,
  )

  # --- Layer 1: transport ------------------------------------------------
  # 401 and 404 arrive with an EMPTY body, so parsing first would raise a
  # JSONDecodeError that hides the real cause.
  if response.status_code != 200:
      raise InfinnError(
          f"HTTP {response.status_code} from {path}"
          + (" -- check the token and that this machine's IP is registered"
             if response.status_code == 401 else ""),
          status=response.status_code,
      )

  try:
      data = _lower_keys(response.json())
  except ValueError:
      raise InfinnError(f"{path} returned a non-JSON body: {response.text[:120]!r}")

  # --- Layer 2: application ---------------------------------------------
  # An array is always a success. For objects, test for the ABSENCE of a
  # failure rather than for stat == "Ok", because the GTT and alert
  # endpoints report success as "Oi created", "Oi Replacedt" and so on.
  if isinstance(data, dict):
      if data.get("emsg"):
          raise InfinnError(data["emsg"], status=200, payload=data)
      if str(data.get("stat", "")).lower() == "not_ok":
          raise InfinnError(data.get("emsg", "request failed"),
                            status=200, payload=data)

  return data

Next

Esc
↑↓ navigate↵ openEsc close/ to search