On this page
The Infinn API can refuse you in two completely different places, and the two look nothing alike. Handling only one is the most common structural bug in code written against it.
The two layers
| Layer 1 - gateway | Layer 2 - trading system | |
|---|---|---|
| What it checks | Token, calling IP address, path, rate limit | Margin, entitlements, circuit limits, order state, instrument validity |
| HTTP status | 4xx or 5xx | 200 - always, even on failure |
| Body | empty verified | JSON with stat: "Not_Ok" and emsg |
| How you detect it | response.status_code != 200 | stat / emsg in the parsed body |
| If you only check the status | Caught correctly | silently treated as success |
| Example | 401 Unauthorized, no body | 200 OK, {"stat":"Not_Ok","emsg":"Session Expired…"} |
An HTTP 200 does not mean your request succeeded.
If your code is if (response.ok) { /* done */ }, then an order rejected for insufficient margin, an expired session and a malformed symbol will all be recorded as successes.
Layer 1: the gateway
Before your request reaches anything that knows about trading, the gateway checks three things: is the token valid, is the IP registered, and is this path real. A failure here uses an ordinary HTTP status code.
Observed with a missing token, a syntactically valid but fake token, and a malformed token. All three returned HTTP 401 with Content-Length: 0. An unknown path returned HTTP 404, also with no body.
So there is no emsg to read and nothing to parse. If you call .json() on it, you get a decode error that tells you nothing about the real problem. Check the status code first. How this was verified
HTTP/1.1 403 Forbidden
Server: nginx/1.20.1
Content-Length: 0
(nothing at all)| Code | Meaning | Body |
|---|---|---|
401 | The gateway rejected your credentials before the request reached the trading system. | empty body |
400 | Missing or bad request parameters or values. | |
403 | Session expired or invalidated. Must relogin. | |
404 | The requested resource was not found. | empty body |
405 | The request method is not allowed on this endpoint. | |
410 | The requested resource is gone permanently. | |
429 | Too many requests to the API (rate limiting). | |
500 | Something unexpected went wrong. | |
502 | The backend OMS is down and the API is unable to communicate with it. | |
503 | Service unavailable; the API is down. | |
504 | Gateway timeout; the API is unreachable. |
Layer 2: the trading system
Past the gateway, your request reaches the order management system, which knows your balance, your positions and the exchange's rules. When it refuses, it does so with HTTP 200 and a message in the body.
{
"request_time": "10:48:03 20-05-2020",
"stat": "Ok",
"norenordno": "20052000000017"
}{
"stat": "Not_Ok",
"request_time": "20:40:01 19-05-2020",
"emsg": "Error Occurred : 2 \"invalid input\""
}emsg carries the reason. Most values follow a Category : detail shape, and the category is the useful part for branching.
| Prefix | Meaning | What to do |
|---|---|---|
Session Expired : | The token is no longer valid | Clear it and re-authenticate once. Do not retry. |
Invalid Input : | A field is missing or unacceptable | Fix the request. Retrying unchanged cannot help. |
Rejected : | The order could not be acted on | Read the order's current status. Often a lost race, not a bug. |
Error Occurred : | Generic, with a numeric code | 2 "invalid input" is usually tick or lot size. 5 "no data" usually means empty. |
Server Timeout : | The backend did not answer | Outcome unknown. Reconcile before retrying any write. |
No Data : | Nothing matched | Show an empty state, not an error. |
| Anything else | The published catalogue is incomplete | Log it, show the text to the user, and do not retry blindly. |
Every documented message, with its cause and fix, is on the error reference.
Checking both, in order
response = requests.post(url, headers=headers, data=body, timeout=10)
# 1. Transport. Must come first: a 401 has no body, so parsing it here
# would raise a JSONDecodeError and hide the real cause.
if response.status_code != 200:
raise InfinnError(f"HTTP {response.status_code}", status=response.status_code)
# 2. Parse. Only safe once we know there is a body.
data = response.json()
# 3. Application. An array is always success; an object may not be.
if isinstance(data, dict) and (
data.get("emsg") or str(data.get("stat", "")).lower() == "not_ok"
):
raise InfinnError(data.get("emsg", "request failed"), status=200, payload=data)
# 4. Only now is `data` trustworthy.Which failures are worth retrying
| Failure | Retry? | Why |
|---|---|---|
401, 403, Session Expired | no | Re-authenticate instead. A retry with the same credentials gets the same answer forever. |
400, Invalid Input | no | The request is wrong. Fix it. |
404, 405, 410 | no | The path or method is wrong, or the endpoint is gone. |
Rejected : ORA:Order not found | no | The order is in a state you cannot act on. Re-read its status. |
429 | yes, with backoff | But fix the call pattern - backing off treats the symptom. |
500, 502, 503 | yes, if it was a read | Transient. For writes, reconcile first. |
504, timeout, Server Timeout | reconcile first | Outcome unknown. The order may be live. Retrying blindly can double a position. |
Error Occurred : 5 "no data" | not an error | Usually an empty result. Treat as empty, not failed. |
Retrying safely
The hard case is a request that may or may not have taken effect: a timeout, a 504, a dropped connection. You do not know whether your order reached the exchange.
If PlaceOrder times out, the order may be live. Retrying blindly is how people end up with two positions and a bad afternoon.
Infinn provides no idempotency key, so the API cannot deduplicate for you. Reconciliation is your responsibility.
import time
def place_order_safely(order, access_token, tag):
"""Places an order, reconciling rather than blindly retrying on failure.
`tag` is written into the order's `remarks` field, which comes back
unchanged in the order book. That gives us a way to recognise our own
order if we never saw the response.
"""
order = dict(order, remarks=tag)
try:
result = call("/NorenWClientAPI/PlaceOrder", order, access_token)
return result["norenordno"]
except InfinnError as err:
# A clean application-level rejection means nothing was placed.
# There is no ambiguity, so there is nothing to reconcile.
if err.status == 200:
raise
# Anything else -- a timeout, a 5xx, a dropped connection -- leaves
# the outcome unknown. Look before leaping.
time.sleep(1.0)
book = call("/NorenWClientAPI/OrderBook", {"uid": order["uid"]},
access_token)
if isinstance(book, list):
for row in book:
if row.get("remarks") == tag:
# It did go through. Do NOT place it again.
return row["norenordno"]
# It genuinely did not arrive, so retrying is safe.
result = call("/NorenWClientAPI/PlaceOrder", order, access_token)
return result["norenordno"]The remarks field is free text that comes back unchanged in the order book. Writing a unique value into it on every order gives you a reliable way to recognise your own order after a lost response - which is the closest thing to an idempotency key this API offers.
Backing off
When a retry is appropriate, back off exponentially, and add jitter so that parallel workers do not all retry on the same tick.
import random
import time
def with_retries(fn, attempts=4, base=0.5, cap=8.0):
"""Retries a read-only call on transport failures only.
Application errors (HTTP 200 with stat Not_Ok) are never retried: the
trading system has given a definite answer, and asking again will get
the same one.
"""
for attempt in range(attempts):
try:
return fn()
except InfinnError as err:
# A definite rejection. Retrying cannot help.
if err.status == 200:
raise
# 401 and 403 mean re-authenticate, not wait and try again.
if err.status in (401, 403):
raise
if attempt == attempts - 1:
raise
# Full jitter: sleep for a random slice of the growing window,
# so that concurrent clients spread out instead of synchronising.
window = min(cap, base * (2 ** attempt))
time.sleep(random.uniform(0, window))What to show the user
Pass rejreason through unchanged
Infinn's risk-rule rejections are unusually specific. The documented example names the rule, the attempted price and both circuit limits. Replacing that with "Order failed" destroys the only useful information in the response.
RED:RULE:{Check circuit limit including square off order}
Current:INR 2,400.00 LowerCircuit:INR 1,590.05 UpperCircuit:INR 1,943.35
:NSE.ACC-EQ for C-IN001 [DEFAULT]Translate the ones that are opaque
Some messages help nobody. Error Occurred : 2 "invalid input"
usually means a tick-size or lot-size violation, so say that:
"The price must be a multiple of 0.10 for RELIANCE-EQ." You know
the tick size; the user does not.
Treat "no data" as empty, not broken
Error Occurred : 5 "no data" arrives when you have no
positions, or no quote exists for that token. It is reported as a failure, but
for the user it is an empty state. Show an empty table, not an error dialog.
Never show a raw 401
"HTTP 401" means nothing to a user. It means one of two things: sign in again, or this machine is not authorised. Say whichever applies.