On this page
Infinn publishes client libraries for six environments. None is required - the API is plain HTTPS and the examples throughout this site use only each language's standard library or its most common HTTP client.
Writing the client with an AI assistant
If you are going to hand this API to a language model, hand it llms-full.txt first. It is this entire reference as one plain-text file: every endpoint, every field, every example, about 150 KB. Paste the whole thing.
This API breaks four conventions at once, and a model filling the gaps from experience gets all four wrong:
- It sends a JSON request body. The API wants
Content-Type: text/plainand a body ofjData=<json string>. - It checks only the HTTP status. Failures arrive as
200withstat: "Not_Ok"in the body. - It parses before checking. A rejected token returns
401with an empty body, so the parse throws first and the real cause never surfaces. - It assumes
stat: "Ok"means success everywhere. The GTT endpoints return a sentence instead, and have nostatfield at all.
The file opens with those four, before any endpoint, because they are what decide whether the generated client works.
llms.txt convention.Sandbox-first client with a 5-line quickstart. 0.1.2 adds option_chain() and security_info(). See Python SDK (infinn). Wheel and source are under downloads/sdk/. pip install infinn is not on PyPI yet. 0.1.1 remains in that folder for history only.
The official libraries
| Language | Repository |
|---|---|
Python (infinn SDK) | docs page + wheel 0.1.2 · downloads · also legacy InfinnOAuthApi-Py |
| .NET | hkkrfinserv/InfinnOAuthApi-dotNet |
| Java | hkkrfinserv/InfinApi-java |
| JavaScript | hkkrfinserv/InfinnOAuthApi-js |
| PHP | hkkrfinserv/InfinApi-Php |
| AmiBroker | hkkrfinserv/InfinApi-Amibroker |
This documentation does not audit the SDKs, and cannot vouch for them. If you are considering one, look at four things first:
- Recent commits. A client that has not been touched since before an API change will be missing endpoints.
- Does it cover what you need? Check specifically for
GetBasketOptSeq, which has an unusual path, and for the GTT and alert endpoints, whose success values are unusual. - How does it report errors? A client that only checks the HTTP status will report application failures as successes. That is the one thing a wrapper most needs to get right for this API.
- Does it handle the WebSocket delta merge? If it exposes raw messages and leaves merging to you, that is fine - as long as you know.
Or write the client yourself
The entire API surface is one request shape. A complete client is about sixty lines, and the examples on this site are built from exactly that.
"""A minimal, complete Infinn API client.
Every endpoint shares one request shape, so one function covers them all.
What this handles that a naive wrapper does not:
* both error layers -- HTTP status, then stat in the body
* array-on-success / object-on-failure
* the GTT endpoints, which do not return stat: "Ok"
* inconsistent key casing
* numeric strings including "inf", "-nan" and "NULL"
Requires: pip install requests
"""
import hashlib
import json
import requests
BASE = "https://api.infinn.in"
_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 _lower_keys(value):
"""Lower-cases every key, recursively. Infinn's casing is inconsistent."""
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
class Infinn:
def __init__(self, uid, access_token=None, timeout=15):
self.uid = uid
self.access_token = access_token
self.timeout = timeout
# One session reuses the TCP connection, which matters when you are
# working inside a 20-per-second budget.
self._session = requests.Session()
# --- authentication -----------------------------------------------------
@staticmethod
def checksum(app_key, secret_key, code):
"""SHA-256 of app_key + secret_key + code, concatenated, lower-case hex."""
return hashlib.sha256(
(app_key + secret_key + code).encode("utf-8")
).hexdigest()
def login(self, app_key, secret_key, code):
"""Exchanges a one-time login code for an access token."""
# Accept either the bare code or the whole redirect URL.
if "code=" in code:
code = code.split("code=", 1)[1].split("&", 1)[0]
data = self.call("/NorenWClientAPI/GenAcsTok", {
"code": code,
"checksum": self.checksum(app_key, secret_key, code),
}, authenticated=False)
self.access_token = data["access_token"]
return data
def logout(self):
result = self.call("/NorenWClientAPI/Logout", {"uid": self.uid})
self.access_token = None
return result
# --- the one request shape ----------------------------------------------
def call(self, path, payload=None, authenticated=True):
"""Makes one Infinn call. Works for every endpoint."""
headers = {"Content-Type": "text/plain"}
if authenticated:
if not self.access_token:
raise InfinnError("No access token. Call login() first.")
headers["Authorization"] = f"Bearer {self.access_token}"
response = self._session.post(
BASE + path,
headers=headers,
data="jData=" + json.dumps(payload or {}),
timeout=self.timeout,
)
# Layer 1. A 401 and a 404 both arrive with an EMPTY body, so
# parsing before checking would raise a misleading decode error.
if response.status_code != 200:
hint = ""
if response.status_code == 401:
hint = (" -- the token may be invalid, OR this machine's "
"public IP may not be the one registered on your "
"Infinn profile")
raise InfinnError(f"HTTP {response.status_code} from {path}{hint}",
status=response.status_code)
try:
data = _lower_keys(response.json())
except ValueError:
# ValidateHsToken returns plain TRUE / FALSE, not JSON.
return response.text.strip()
# Layer 2. An array is always success. For an object, test for the
# ABSENCE of failure -- the GTT endpoints report success
# as "Oi created" and similar, not 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
# --- a few conveniences -------------------------------------------------
def user_details(self):
return self.call("/NorenWClientAPI/UserDetails", {"uid": self.uid})
def limits(self, actid=None):
return self.call("/NorenWClientAPI/Limits",
{"uid": self.uid, "actid": actid or self.uid})
def order_book(self):
return self.call("/NorenWClientAPI/OrderBook", {"uid": self.uid})
def search(self, text, exchange=None):
payload = {"uid": self.uid, "stext": text}
if exchange:
payload["exch"] = exchange
return self.call("/NorenWClientAPI/SearchScrip", payload).get("values", [])
def place_order(self, **fields):
"""Places an order. Pass the jData fields as keyword arguments.
Values are stringified because Infinn expects every value as a JSON
string, including quantities and prices. Empty values are dropped,
because a required field sent empty counts as missing and an
optional one sent empty can be rejected outright -- `amo` being the
documented example.
"""
payload = {"uid": self.uid, "actid": self.uid}
payload.update({
k: str(v) for k, v in fields.items()
if v is not None and str(v) != ""
})
return self.call("/NorenWClientAPI/PlaceOrder", payload)
# --- usage -------------------------------------------------------------------
if __name__ == "__main__":
import os
client = Infinn(
uid=os.environ["INFINN_USER_ID"],
access_token=os.environ["INFINN_ACCESS_TOKEN"],
)
me = client.user_details()
print("exchanges:", me.get("exarr"))
for row in client.search("RELIANCE", "NSE")[:3]:
print(row["tsym"], row["token"])Most APIs justify an SDK by having many request shapes, pagination, retries, resource models and streaming conventions. This one has a single shape repeated 63 times.
The value an SDK could add is in the quirks - the two error layers, the GTT success strings, the key casing, the delta merge. Those are exactly the things you need to understand anyway, and sixty lines you wrote is easier to debug than a dependency you did not.
If you use an SDK, verify these
A quick test suite for any wrapper, built from the quirks documented on this site.
| Test | What a correct client does |
|---|---|
| Call an endpoint with a deliberately bad token | Raises a clear authentication error. Does not raise a JSON decode error - a 401 has an empty body. |
| Call Place GTT Order successfully | Reports success. A client testing stat == "Ok" will report this as a failure. |
| Call Order Book when it fails | Does not crash iterating. Success is an array; failure is an object. |
Read al_id from a GTT response | Finds it. The sample returns Al_id with a capital A. |
Place an order without amo | Omits the field entirely rather than sending it empty. |
Read prc from Get Order Report | Survives the value "inf". |
| Receive two WebSocket updates for one instrument | Merges them. Replacing would discard the snapshot. |