Practise on Sandbox first

Practise first on Sandbox (UAT / Test — NOT live): https://uat.infinn.in. Then use live. Live calls hit your real account. Use 1 share, a limit price far below the market, and cancel.

Groundwork

Two helpers, used throughout. These are the versions from how responses are shaped, included here so the guide is self-contained.

infinn.py — paste this once
"""Minimal Infinn client: one call helper and one numeric parser.

The call helper checks BOTH error layers, because checking only the HTTP
status is the most common mistake made against this API.
"""
import json
import os

import requests

BASE = "https://api.infinn.in"
ACCESS_TOKEN = os.environ["INFINN_ACCESS_TOKEN"]
UID = os.environ["INFINN_USER_ID"]

_BAD_NUMBERS = {"", "nan", "-nan", "inf", "-inf", "null", "none"}


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


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):
  """Makes one Infinn call, checking both error layers."""
  response = requests.post(
      BASE + path,
      headers={
          "Authorization": f"Bearer {ACCESS_TOKEN}",
          "Content-Type": "text/plain",
      },
      data="jData=" + json.dumps(payload),
      timeout=15,
  )

  # Layer 1. A 401 has an EMPTY body, so parsing first would raise a
  # decode error that hides the real cause.
  if response.status_code != 200:
      hint = (" -- check the token AND that this machine's public IP is "
              "registered on your Infinn profile"
              if response.status_code == 401 else "")
      raise InfinnError(f"HTTP {response.status_code} from {path}{hint}",
                        status=response.status_code)

  data = response.json()

  # Layer 2. An array is always success. For objects, test for the ABSENCE
  # of failure -- the GTT endpoints report success as a sentence
  # rather than as "Ok".
  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

Step 1 - Find the instrument

You need the exact tsym, and the token for getting a price. Never construct either by hand.

Resolve a name to its identifiers
def find_instrument(text, exchange="NSE"):
  """Resolves a search string to one instrument.

  SearchScrip is the interactive lookup. For bulk work, download the
  symbol master instead -- see /concepts/instruments/.
  """
  result = call("/NorenWClientAPI/SearchScrip", {
      "uid": UID,
      "stext": text,
      "exch": exchange,
  })

  matches = result.get("values", [])
  if not matches:
      raise SystemExit(f"Nothing matched {text!r} on {exchange}")

  # SearchScrip returns everything containing the text, so "RELIANCE"
  # also matches RELCAPITAL, RELIANCEPP and so on. Prefer an exact
  # trading-symbol hit before falling back to the first result.
  wanted = f"{text.upper()}-EQ"
  for row in matches:
      if row.get("tsym", "").upper() == wanted:
          return row

  print(f"No exact match for {wanted}; candidates were:")
  for row in matches[:5]:
      print("   ", row.get("tsym"), row.get("token"))
  raise SystemExit("Pick one explicitly rather than guessing.")


instrument = find_instrument("RELIANCE")
print(instrument)
# {'exch': 'NSE', 'token': '2885', 'tsym': 'RELIANCE-EQ'}
Search is a substring match, not a lookup

Searching RELIANCE returns twelve instruments in the documented sample, including RELCAPITAL-EQ and RELINFRA-EQ. Never take values[0] on trust - match exactly, or make the user choose.

Step 2 - Get a price, and pick a safe one

We need the current price in order to choose a limit price far enough below it that the order cannot fill.

Read the market, then step well away from it
from decimal import Decimal, ROUND_DOWN


def get_quote(instrument):
  return call("/NorenWClientAPI/GetQuotes", {
      "uid": UID,
      "exch": instrument["exch"],
      "token": instrument["token"],
  })


def safe_limit_price(quote, fraction=0.5):
  """Returns a buy price far below the market, rounded to the tick size.

  At half the market price the order cannot fill, so it rests in the book
  where we can inspect and cancel it. It must still be above the lower
  circuit limit, or the exchange rejects it outright.
  """
  ltp = num(quote.get("lp"))
  if ltp <= 0:
      raise SystemExit("No last traded price available -- is the market open?")

  tick = Decimal(str(num(quote.get("ti"), 0.05) or 0.05))
  lower_circuit = num(quote.get("lc"))

  target = Decimal(str(ltp * fraction))

  # Stay just inside the lower circuit: a price below it is rejected with
  # a RED:RULE message rather than resting in the book.
  if lower_circuit > 0:
      floor = Decimal(str(lower_circuit)) * Decimal("1.02")
      target = max(target, floor)

  # Round DOWN to a tick multiple. A price that is not a multiple of the
  # tick size is rejected with the opaque "invalid input" message.
  ticks = (target / tick).to_integral_value(rounding=ROUND_DOWN)
  return str(ticks * tick)


quote = get_quote(instrument)
print(f'{quote["tsym"]}  last {quote["lp"]}  '
    f'circuit {quote["lc"]} to {quote["uc"]}  tick {quote["ti"]}')

price = safe_limit_price(quote)
print("We will bid:", price, "-- far below the market, so it cannot fill")

Step 3 - Validate before you send

Two local checks prevent most rejections, and give a clear message instead of an opaque one.

Lot size and tick size, locally
def validate_order(order, quote):
  """Raises with a readable message rather than letting the API reject it."""
  problems = []

  lot = int(num(quote.get("ls"), 1) or 1)
  qty = int(order["qty"])
  if lot > 1 and qty % lot != 0:
      problems.append(f"qty {qty} is not a multiple of the lot size {lot}")

  # Decimal, not float: 1402.30 % 0.10 in binary floating point is not
  # zero, which would reject perfectly valid prices.
  tick = Decimal(str(num(quote.get("ti"), 0) or 0))
  prc = Decimal(str(order["prc"]))
  if tick > 0 and prc % tick != 0:
      problems.append(f"price {prc} is not a multiple of the tick size {tick}")

  lc, uc = num(quote.get("lc")), num(quote.get("uc"))
  if lc and float(prc) < lc:
      problems.append(f"price {prc} is below the lower circuit {lc}")
  if uc and float(prc) > uc:
      problems.append(f"price {prc} is above the upper circuit {uc}")

  if problems:
      raise SystemExit("Order would be rejected: " + "; ".join(problems))


order = {
  "uid": UID,
  "actid": UID,
  "exch": instrument["exch"],
  "tsym": instrument["tsym"],
  "qty": "1",                  # ONE share
  "prc": price,                # far below the market
  "prd": "C",                  # delivery
  "trantype": "B",             # buy
  "prctyp": "LMT",             # limit -- never MKT while learning
  "ret": "DAY",
  "remarks": "docs-safe-test",  # our own tag, comes back in the order book
}

validate_order(order, quote)
print("Local validation passed.")

Step 4 - Ask whether it would pass

Order Margin is a dry run. Note carefully that marginused means two different things depending on the verdict.

A dry run before committing
def check_margin(order):
  """Returns (will_pass, caption, amount) for a proposed order."""
  response = call("/NorenWClientAPI/GetOrderMargin", {
      k: v for k, v in order.items()
      # The margin endpoint takes the order fields but not these.
      if k not in ("ret", "remarks")
  })

  remarks = str(response.get("remarks", ""))
  amount = num(response.get("marginused"))
  cash = num(response.get("cash"))

  if remarks.startswith("Order Success"):
      # Here marginused is the margin that WOULD BE USED.
      return True, "Margin required", amount, cash

  if remarks == "Insufficient Balance":
      # Here the SAME FIELD is the shortfall still needed. Infinn's own
      # documentation says to caption it "Shortfall margin".
      return False, "Shortfall margin", amount, cash

  # Other documented verdicts all mean rejection.
  return False, remarks or "would be rejected", amount, cash


will_pass, caption, amount, cash = check_margin(order)
print(f"{caption}: {amount:,.2f}   (cash available {cash:,.2f})")

if not will_pass:
  raise SystemExit("Margin check says this would be rejected. Stopping.")
The same field, two opposite meanings

On "Order Success", marginused is what the order would consume. On "Insufficient Balance", it is the extra amount you still need.

Branch on remarks before labelling the number, or you will display a figure that means the opposite of its caption.

Step 5 - Place it

Request
HTTP
POST /NorenWClientAPI/PlaceOrder HTTP/1.1
Host: api.infinn.in
Authorization: Bearer YOUR_ACCESS_TOKEN
Content-Type: text/plain

jData={"uid":"IN001","actid":"IN001","exch":"NSE",
"tsym":"RELIANCE-EQ","qty":"1","prc":"700","prd":"C","trantype":"B",
"prctyp":"LMT","ret":"DAY","remarks":"docs-safe-test"}
Response
200 OK
{
"request_time": "10:48:03 20-05-2020",
"stat": "Ok",
"norenordno": "20052000000017"
}
Place, with the reconciliation that makes a retry safe
import time
import uuid


def place_order_safely(order):
  """Places an order, reconciling rather than retrying on an unclear failure.

  The `remarks` tag is the key: it comes back unchanged in the order book,
  so if we never see the response we can still recognise our own order.
  There is no idempotency key in this API, so this is the closest we get.
  """
  tag = f"docs-{uuid.uuid4().hex[:8]}"
  order = dict(order, remarks=tag)

  try:
      result = call("/NorenWClientAPI/PlaceOrder", order)
      return result["norenordno"], tag

  except InfinnError as err:
      # A clean application-level rejection: nothing was placed, so there
      # is nothing ambiguous and nothing to reconcile.
      if err.status == 200:
          raise

      # A timeout or a 5xx leaves the outcome UNKNOWN. The order may be
      # live. Look before leaping.
      print(f"Unclear failure ({err}). Checking the order book.")
      time.sleep(1.0)

      book = call("/NorenWClientAPI/OrderBook", {"uid": UID})
      if isinstance(book, list):
          for row in book:
              if row.get("remarks") == tag:
                  print("It did go through. Not placing it again.")
                  return row["norenordno"], tag

      print("It did not arrive. Retrying is safe.")
      result = call("/NorenWClientAPI/PlaceOrder", order)
      return result["norenordno"], tag


order_no, tag = place_order_safely(order)
print("Order number:", order_no)
print("NOTE: this means ACCEPTED, not filled.")
An order number is an acknowledgement

stat: "Ok" and a norenordno mean Infinn took the order. The exchange may still reject it, and an accepted order may sit unfilled all day. Step 6 is not optional.

Step 6 - Read it back

Confirm what actually happened
def order_status(order_no):
  """Returns the current state of one order."""
  rows = call("/NorenWClientAPI/SingleOrdStatus", {
      "uid": UID,
      "norenordno": order_no,
      "actid": UID,
      "exch": instrument["exch"],
  })
  # Documented as an array of exactly one element, deliberately, so that
  # code written against SingleOrdHist can switch to this endpoint.
  return rows[0] if isinstance(rows, list) and rows else {}


time.sleep(1.0)        # give the exchange a moment to acknowledge
status = order_status(order_no)

# Status casing is inconsistent in the documentation -- "Open" and "REJECT"
# both appear where the annexure says OPEN and REJECTED.
state = str(status.get("status", "")).upper()

print(f'status      {status.get("status")}')
print(f'filled      {status.get("fillshares", "0")} of {status.get("qty")}')
print(f'price       {status.get("prc")}')

if state.startswith("REJECT"):
  # rejreason is unusually informative here -- show it unchanged.
  print("rejected:", status.get("rejreason"))
elif state == "OPEN":
  print("Resting in the order book, as intended. Nothing has traded.")
elif state == "COMPLETE":
  print("WARNING: this filled. The limit price was not far enough from "
        "the market. You now hold a position.")

Step 7 - Cancel it

Clean up
def cancel(order_no):
  """Cancels an order, treating 'already gone' as success."""
  try:
      result = call("/NorenWClientAPI/CancelOrder", {
          "norenordno": order_no,
          "uid": UID,
      })
      # Note: cancel returns the order number in `result`, not in
      # `norenordno` as PlaceOrder does.
      return result.get("result", order_no)

  except InfinnError as err:
      # "not found to Cancel" means it already filled, was already
      # cancelled, or was rejected. For a cleanup routine that is a
      # success, not a failure.
      if "not found" in str(err).lower():
          print("Nothing to cancel -- the order is already in a final state.")
          return None
      raise


if state == "OPEN":
  cancelled = cancel(order_no)
  print("Cancelled:", cancelled)

  time.sleep(1.0)
  print("Final status:", order_status(order_no).get("status"))
Use try/finally in anything long-running

If your script raises between placing and cancelling, the order is left live in the market. Wrap the experiment so the cancel always runs:

Python
order_no, tag = place_order_safely(order)
try:
  inspect(order_no)
finally:
  cancel(order_no)      # runs even if inspect() raises

The whole thing

safe_order_test.py — the complete script
"""Place a resting order, inspect it, cancel it.

Deliberately cannot fill: one share, limit price at half the market. This is
how to learn this API's order flow. Practise first on Sandbox (UAT / Test — NOT live): https://uat.infinn.in. Then use live.

INFINN_ACCESS_TOKEN=... INFINN_USER_ID=... python safe_order_test.py
"""
import time
import uuid

# ... the helpers from the steps above ...


def main():
  instrument = find_instrument("RELIANCE")
  quote = get_quote(instrument)

  print(f'{quote["tsym"]}: last {quote["lp"]}, '
        f'circuit {quote["lc"]}-{quote["uc"]}, tick {quote["ti"]}')

  order = {
      "uid": UID, "actid": UID,
      "exch": instrument["exch"], "tsym": instrument["tsym"],
      "qty": "1",
      "prc": safe_limit_price(quote),
      "prd": "C", "trantype": "B", "prctyp": "LMT", "ret": "DAY",
  }

  validate_order(order, quote)

  will_pass, caption, amount, cash = check_margin(order)
  print(f"{caption}: {amount:,.2f} (cash {cash:,.2f})")
  if not will_pass:
      return

  order_no, tag = place_order_safely(order)
  print("placed:", order_no)

  try:
      time.sleep(1.0)
      status = order_status(order_no)
      print("status:", status.get("status"),
            "filled:", status.get("fillshares", "0"))
      if str(status.get("status", "")).upper().startswith("REJECT"):
          print("rejected:", status.get("rejreason"))
  finally:
      # Always clean up, even if the inspection above raised.
      cancel(order_no)
      print("cleaned up")


if __name__ == "__main__":
  main()
Executability

This script is syntactically valid and was checked as part of the build, but it cannot be executed here: it needs a live access token and must run from a registered IP address. Run it yourself, during market hours, with your own credentials. What was and was not verified

Esc
↑↓ navigate↵ openEsc close/ to search