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.
"""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 dataStep 1 - Find the instrument
You need the exact tsym, and the token for getting a price. Never construct either by hand.
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'}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.
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.
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.
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.")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
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"}{
"request_time": "10:48:03 20-05-2020",
"stat": "Ok",
"norenordno": "20052000000017"
}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.")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
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
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"))If your script raises between placing and cancelling, the order is left live in the market. Wrap the experiment so the cancel always runs:
order_no, tag = place_order_safely(order)
try:
inspect(order_no)
finally:
cancel(order_no) # runs even if inspect() raisesThe whole thing
"""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()// safe_order_test.js -- place a resting order, inspect it, cancel it (Node 18+)
// infinn.js -- shared helper used by the guide scripts (Node 18+, no packages)
const BASE = process.env.INFINN_BASE || 'https://api.infinn.in';
const ACCESS_TOKEN = process.env.INFINN_ACCESS_TOKEN || 'YOUR_ACCESS_TOKEN';
const UID = process.env.INFINN_USER_ID || 'IN001';
class InfinnError extends Error {
constructor(message, status, payload) { super(message); this.status = status; this.payload = payload; }
}
// Parses a numeric string, tolerating inf / -nan / NULL.
function num(value, fallback = 0) {
if (value === null || value === undefined) return fallback;
const text = String(value).trim().toLowerCase();
if (['', 'nan', '-nan', 'inf', '-inf', 'null', 'none'].includes(text)) return fallback;
const n = Number(text);
return Number.isFinite(n) ? n : fallback;
}
// One call, checking BOTH error layers.
async function call(path, payload) {
const res = await fetch(BASE + path, {
method: 'POST',
headers: { Authorization: `Bearer ${ACCESS_TOKEN}`, 'Content-Type': 'text/plain' },
body: 'jData=' + JSON.stringify(payload),
signal: AbortSignal.timeout(15000),
});
// Layer 1: HTTP. Error responses have an empty body, so check before parsing.
if (res.status !== 200) {
throw new InfinnError(`HTTP ${res.status} -- check the token and that this machine's IP is whitelisted`, res.status);
}
const text = await res.text();
if (!text.trim()) throw new InfinnError('Empty body with HTTP 200', 200);
const data = JSON.parse(text);
// Layer 2: application. Lists are successes; objects carry stat.
if (!Array.isArray(data) && data.stat && data.stat !== 'Ok') {
throw new InfinnError(data.emsg || 'Not_Ok with no emsg', 200, data);
}
return data;
}
// Deliberately cannot fill: one share, limit price at half the market.
// INFINN_ACCESS_TOKEN=... INFINN_USER_ID=... node safe_order_test.js
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
async function findInstrument(text, exch = 'NSE') {
const result = await call('/NorenWClientAPI/SearchScrip', { uid: UID, stext: text, exch });
const wanted = `${text.toUpperCase()}-EQ`;
const hit = (result.values || []).find((row) => String(row.tsym).toUpperCase() === wanted);
if (!hit) throw new Error(`No exact match for ${wanted}; pick one explicitly`);
return hit;
}
function safeLimitPrice(quote) {
const ltp = num(quote.lp);
if (ltp <= 0) throw new Error('No last traded price -- is the market open?');
const tick = num(quote.ti, 0.05) || 0.05;
let target = ltp * 0.5;
const lc = num(quote.lc);
if (lc > 0) target = Math.max(target, lc * 1.02); // stay inside the lower circuit
// Round DOWN to a whole number of ticks, working in paise to avoid float drift.
const tickPaise = Math.round(tick * 100);
const paise = Math.floor(Math.round(target * 100) / tickPaise) * tickPaise;
return (paise / 100).toFixed(2);
}
async function main() {
const instrument = await findInstrument('RELIANCE');
const quote = await call('/NorenWClientAPI/GetQuotes', { uid: UID, exch: instrument.exch, token: instrument.token });
console.log(`${quote.tsym}: last ${quote.lp}, circuit ${quote.lc}-${quote.uc}, tick ${quote.ti}`);
const order = {
uid: UID, actid: UID, exch: instrument.exch, tsym: instrument.tsym,
qty: '1', prc: safeLimitPrice(quote),
prd: 'C', trantype: 'B', prctyp: 'LMT', ret: 'DAY',
};
const { ret, ...marginFields } = order; // margin check takes the order without ret
const margin = await call('/NorenWClientAPI/GetOrderMargin', marginFields);
if (!String(margin.remarks || '').startsWith('Order Success')) {
console.log('Margin check says this would be rejected:', margin.remarks); return;
}
console.log('Margin required:', num(margin.marginused));
const placed = await call('/NorenWClientAPI/PlaceOrder', { ...order, remarks: 'docs-safe-test' });
const orderNo = placed.norenordno;
console.log('placed:', orderNo);
try {
await sleep(1000);
const rows = await call('/NorenWClientAPI/SingleOrdStatus', { uid: UID, norenordno: orderNo, actid: UID, exch: order.exch });
const status = Array.isArray(rows) && rows.length ? rows[0] : {};
console.log('status:', status.status, 'filled:', status.fillshares || '0');
} finally {
try {
await call('/NorenWClientAPI/CancelOrder', { uid: UID, norenordno: orderNo });
console.log('cleaned up');
} catch (err) {
if (err instanceof InfinnError && /not found/i.test(err.message)) console.log('Nothing to cancel -- already final.');
else throw err;
}
}
}
main().catch((err) => { console.error(err.message); process.exit(1); });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