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.
{
"status": "success",
"data": {
"user_id": "IN001",
"broker": "EXAMPLE"
}
}{
"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.
[
{ "stat": "Ok", "norenordno": "...", "status": "OPEN" },
{ "stat": "Ok", "norenordno": "...", "status": "COMPLETE" }
]{
"stat": "Not_Ok",
"emsg": "Session Expired : Invalid Session Key"
}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.
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"))const data = await response.json();
// Failure always arrives as an object; success here is an array.
if (!Array.isArray(data)) {
throw new Error(data.emsg || 'request failed');
}
for (const order of data) {
console.log(order.norenordno, order.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.
| Endpoints | Success value of stat | Failure |
|---|---|---|
| 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 |
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.
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"/**
* Works across every Infinn endpoint.
* Tests for the absence of a failure rather than matching a success string,
* because the success string differs between endpoint families.
*/
function succeeded(data) {
if (Array.isArray(data)) return true; // an array means success
if (data.emsg) return false;
return String(data.stat ?? '').toLowerCase() !== 'not_ok';
}Numbers arrive as strings
Prices, quantities, timestamps - all quoted.
{
"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.
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.
_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.0const BAD = new Set(['', 'nan', '-nan', 'inf', '-inf', 'null', 'none']);
/**
* Parses an Infinn numeric string defensively. Handles the documented
* "inf", "-nan" and "NULL" values returned by the report endpoints.
*/
function num(value, fallback = 0) {
if (value === null || value === undefined) return fallback;
const text = String(value).trim();
if (BAD.has(text.toLowerCase())) return fallback;
const parsed = Number(text);
return Number.isFinite(parsed) ? parsed : fallback;
}
// num('1402.30') -> 1402.3 num('inf') -> 0 num('NULL') -> 0Key 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.
| Endpoint | Documented | Returned in the sample |
|---|---|---|
| Place GTT Order | al_id | Al_id |
| Get Pending GTT Orders | al_id, token, remarks, qty, prc | Al_id, Token, Remarks, Qty, Prc |
| Get Top List | pc, oi | Pc and pc on different rows of the same array; likewise Oi and oi |
| Get Content List | pc | Pc |
| Get Unsettled Trading Dates | request_time | Request_time |
| Positions Book | prd | prarr |
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.
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())/**
* Lower-cases every key, recursively.
* Infinn returns Al_id, Token, Qty and Stat in some responses where the
* field tables document al_id, token, qty and stat.
*/
function normalise(value) {
if (Array.isArray(value)) return value.map(normalise);
if (value && typeof value === 'object') {
return Object.fromEntries(
Object.entries(value).map(([k, v]) => [k.toLowerCase(), normalise(v)]),
);
}
return value;
}
const data = normalise(await 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.
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
| Field | Format | Example | Seen on |
|---|---|---|---|
request_time | HH:MM:SS dd-mm-yyyy | 18:07:31 29-05-2020 | Most endpoints |
request_time | ddmmyyyyHHMMSS, no separators | 04062021121503 | Get Enabled GTTs |
norentm | HH:MM:SS dd-mm-yyyy | 19:59:32 13-12-2020 | Order and trade books |
norentm | dd-mm-yyyy HH:MM:SS - the parts reversed | 02-05-1975 08:48:52 | Get Broker Message |
exch_tm | dd-mm-YYYY hh:MM:SS | 01-01-1980 00:00:00 | Order and trade books |
expires_in | Unix timestamp in seconds, despite the name | 1756990407 | GenAcsTok |
ordenttm | Unix timestamp in seconds | 1690107153 | Single Order Status |
ltt | HH:MM:SS, no date | 05:30:00 | Quotes |
dob, exd | DDMMYYYY or dd-MMM-yyyy | 01011990, 29-DEC-2026 | Client details; symbol master |
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 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