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

Your requestLAYER 1 — gatewayToken? IP? Path?401 / 404 / 429empty bodyLAYER 2 — trading systemHTTP 200always"stat": "Ok""stat": "Not_Ok"An HTTP 200 is NOT success. Check the status code, then check stat in the body.Layer 1 failures have no body at all. Layer 2 failures look like successes to your HTTP client.
Figure 1. A request passes two checkpoints. Each refuses in its own way, and only one of them uses HTTP status codes to do it.
Layer 1 - gatewayLayer 2 - trading system
What it checksToken, calling IP address, path, rate limitMargin, entitlements, circuit limits, order state, instrument validity
HTTP status4xx or 5xx200 - always, even on failure
Bodyempty verifiedJSON with stat: "Not_Ok" and emsg
How you detect itresponse.status_code != 200stat / emsg in the parsed body
If you only check the statusCaught correctlysilently treated as success
Example401 Unauthorized, no body200 OK, {"stat":"Not_Ok","emsg":"Session Expired…"}
The consequence, stated plainly

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.

Note: the body is empty

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

What a rejected token actually looks like
HTTP/1.1 403 Forbidden
Server: nginx/1.20.1
Content-Length: 0

(nothing at all)
CodeMeaningBody
401The gateway rejected your credentials before the request reached the trading system.empty body
400Missing or bad request parameters or values.
403Session expired or invalidated. Must relogin.
404The requested resource was not found.empty body
405The request method is not allowed on this endpoint.
410The requested resource is gone permanently.
429Too many requests to the API (rate limiting).
500Something unexpected went wrong.
502The backend OMS is down and the API is unable to communicate with it.
503Service unavailable; the API is down.
504Gateway 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
200 OK
{
"request_time": "10:48:03 20-05-2020",
"stat": "Ok",
"norenordno": "20052000000017"
}
Error
200 OK
{
"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.

PrefixMeaningWhat to do
Session Expired :The token is no longer validClear it and re-authenticate once. Do not retry.
Invalid Input :A field is missing or unacceptableFix the request. Retrying unchanged cannot help.
Rejected :The order could not be acted onRead the order's current status. Often a lost race, not a bug.
Error Occurred :Generic, with a numeric code2 "invalid input" is usually tick or lot size. 5 "no data" usually means empty.
Server Timeout :The backend did not answerOutcome unknown. Reconcile before retrying any write.
No Data :Nothing matchedShow an empty state, not an error.
Anything elseThe published catalogue is incompleteLog 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

The order matters — status first, then body
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.
Why not test stat == "Ok"?

Because the GTT endpoints report success as "Oi created", "Oi Replacedt" and "Oi delete success" rather than "Ok". Testing for the absence of failure works everywhere; testing for a specific success string does not. More

Which failures are worth retrying

FailureRetry?Why
401, 403, Session ExpirednoRe-authenticate instead. A retry with the same credentials gets the same answer forever.
400, Invalid InputnoThe request is wrong. Fix it.
404, 405, 410noThe path or method is wrong, or the endpoint is gone.
Rejected : ORA:Order not foundnoThe order is in a state you cannot act on. Re-read its status.
429yes, with backoffBut fix the call pattern - backing off treats the symptom.
500, 502, 503yes, if it was a readTransient. For writes, reconcile first.
504, timeout, Server Timeoutreconcile firstOutcome unknown. The order may be live. Retrying blindly can double a position.
Error Occurred : 5 "no data"not an errorUsually 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.

A call failedor timed outDid it only READdata?yesRetry freelywith backoffnoReconcile FIRSTread the order bookThen decideretry or notA timeout is not a failureThe order may already be live. Retrying blindly is how you end up with two positions.
Figure 2. The decision that matters. For reads, retry. For anything that changes state, find out what actually happened before doing anything else.
A timeout is not a failure

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.

Reconcile before retrying a write
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 tag trick

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.

Exponential backoff with jitter
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.

Show this, not "order failed"
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.

Next

Esc
↑↓ navigate↵ openEsc close/ to search