On this page
A correct portfolio total needs three sources and two formulas Infinn publishes but does not explain. This guide assembles all of it.
Why it takes three calls
| Source | Covers | Why you need it |
|---|---|---|
| Holdings | Shares bought on earlier days and settled into demat | This is what you own outright. It does not appear in positions. |
| Positions Book | Today's trading, and carried-forward derivatives | This is where today's profit and loss lives. It does not appear in holdings. |
| Live prices | Current value of both | Neither endpoint gives a reliable live price: holdings' lp is disabled by default, and polling positions is explicitly discouraged. |
Shares bought today sit in positions. Shares bought earlier and settled sit in holdings. A portfolio screen that reads only one of them is wrong, and which half it is missing depends on the day.
Step 1 - Holdings, and the two quantities
A holdings row has no single quantity field. The number is spread across a dozen buckets, and the two figures you want are both computed.
def holding_quantities(row):
"""Returns the valuation and saleable quantities for one holdings row.
Infinn documents both formulas. They differ by brkcolqty: pledged
shares still have value but cannot be sold, so a UI that shows one
number for both will offer to sell shares the user does not control.
"""
g = lambda field: num(row.get(field))
common = (g("btstqty") + g("holdqty") + g("unplgdqty")
+ g("benqty") - g("usedqty"))
return {
# max(), not sum() -- npoadqty and dpqty overlap.
"valuation": common + g("brkcolqty") + max(g("npoadqty"), g("dpqty")),
"saleable": common + g("dpqty"),
}
def fetch_holdings(product="C"):
"""Holdings for one product. Note that prd is required here."""
try:
rows = call("/NorenWClientAPI/Holdings",
{"uid": UID, "actid": UID, "prd": product})
except InfinnError as err:
# "no data" means no holdings, which is an empty portfolio, not a
# failure. Reported as an error, but it is not one.
if "no data" in str(err).lower():
return []
raise
if not isinstance(rows, list):
return []
out = []
for row in rows:
# exch_tsym is an ARRAY, because one holding can be listed on
# several exchanges. Take the first listing for identification.
listings = row.get("exch_tsym") or []
if not listings:
continue
primary = listings[0]
quantities = holding_quantities(row)
out.append({
"exch": primary.get("exch"),
"tsym": primary.get("tsym"),
"token": primary.get("token"),
"qty_valuation": quantities["valuation"],
"qty_saleable": quantities["saleable"],
# upldprc is roughly the cost price.
"cost_price": num(row.get("upldprc")),
"all_listings": listings,
})
return outOne holding can be listed on more than one exchange, so the instrument identity is a list of {exch, tsym, token} objects rather than three fields. Reading row["tsym"] raises a KeyError.
Step 2 - Positions, and the two P&L numbers
def fetch_positions():
try:
rows = call("/NorenWClientAPI/PositionBook",
{"uid": UID, "actid": UID})
except InfinnError as err:
if "no data" in str(err).lower():
return []
raise
return rows if isinstance(rows, list) else []
def value_position(row, live_ltp=None):
"""Values one position. Returns MTM and P&L, which are NOT the same.
Both use the documented unrealised formula
netqty x prcftr x mult x (LTP - avgprc)
but with a different avgprc: netavgprc for MTM, netupldprc for P&L
(falling back to netavgprc when netupldprc is 0).
"""
qty = num(row.get("netqty"))
mult = num(row.get("mult"), 1.0) or 1.0
prcftr = num(row.get("prcftr"), 1.0) or 1.0
ltp = num(live_ltp) if live_ltp is not None else num(row.get("lp"))
net_avg = num(row.get("netavgprc"))
net_upld = num(row.get("netupldprc"))
pnl_reference = net_upld if net_upld else net_avg # documented fallback
return {
"exch": row.get("exch"),
"tsym": row.get("tsym"),
"token": row.get("token"),
# prarr appears where the field table documents prd, in the sample
# response. Accept either.
"product": row.get("prd") or row.get("prarr"),
"net_qty": qty,
"avg_price": net_avg,
"ltp": ltp,
"realised": num(row.get("rpnl")),
"unrealised_mtm": qty * prcftr * mult * (ltp - net_avg),
"unrealised_pnl": qty * prcftr * mult * (ltp - pnl_reference),
"break_even": num(row.get("bep")),
}Leaving them out gives answers that are correct for NSE shares and wrong for currency and commodity derivatives - wrong by a factor that looks plausible enough to ship.
Step 3 - One price source for both
Holdings and positions both need a current price. Subscribe once, for the union of the two.
def subscription_key(holdings, positions):
"""Returns the 'k' string covering everything in the portfolio.
De-duplicated, because the same instrument can appear as both a
holding and a position -- you bought some earlier and some today.
"""
keys = set()
for row in holdings:
if row.get("token"):
keys.add(f'{row["exch"]}|{row["token"]}')
for row in positions:
if row.get("token"):
keys.add(f'{row["exch"]}|{row["token"]}')
return "#".join(sorted(keys)), len(keys)A 40-instrument portfolio polled once a second through Get Quotes is 40 requests every second, four times the 10-per-second budget. The same 40 cost one subscription message on the stream. The arithmetic
Putting it together
"""Live portfolio valuation.
Three REST calls at startup, then one WebSocket subscription. Every
recomputation thereafter is local and free.
pip install requests websocket-client
INFINN_ACCESS_TOKEN=... INFINN_USER_ID=... python portfolio.py
"""
import json
import threading
class Portfolio:
def __init__(self):
self.holdings = []
self.positions = []
self.prices = {} # (exch, token) -> last traded price
self._lock = threading.Lock()
# --- loading ------------------------------------------------------------
def load(self):
"""Three REST calls. Done once, at startup."""
self.holdings = fetch_holdings(product="C")
self.positions = [value_position(r) for r in fetch_positions()]
# Seed prices from the snapshots we already have, so the first
# render is not empty while waiting for the first tick.
with self._lock:
for row in self.positions:
if row.get("token") and row.get("ltp"):
self.prices[(row["exch"], row["token"])] = row["ltp"]
print(f"{len(self.holdings)} holdings, {len(self.positions)} positions")
# --- streaming ----------------------------------------------------------
def on_tick(self, row):
"""Called with a merged touchline row from the feed."""
key = (row.get("e"), row.get("tk"))
price = num(row.get("lp"))
# 0 means no price yet; 42949672.95 is the at-the-open sentinel.
if None in key or price == 0 or abs(price - 42949672.95) < 0.01:
return
with self._lock:
self.prices[key] = price
# --- valuation ----------------------------------------------------------
def value(self):
"""Returns the whole portfolio, valued at the latest prices."""
with self._lock:
prices = dict(self.prices)
holding_rows, holdings_value, holdings_cost = [], 0.0, 0.0
for row in self.holdings:
price = prices.get((row["exch"], row["token"]), row["cost_price"])
value = row["qty_valuation"] * price
cost = row["qty_valuation"] * row["cost_price"]
holdings_value += value
holdings_cost += cost
holding_rows.append({
**row,
"ltp": price,
"value": value,
"unrealised": value - cost,
})
position_rows, mtm, pnl, realised = [], 0.0, 0.0, 0.0
for row in self.positions:
price = prices.get((row["exch"], row["token"]), row["ltp"])
valued = {**row, **value_position_at(row, price)}
mtm += valued["unrealised_mtm"]
pnl += valued["unrealised_pnl"]
realised += valued["realised"]
position_rows.append(valued)
return {
"holdings": holding_rows,
"positions": position_rows,
"holdings_value": holdings_value,
"holdings_unrealised": holdings_value - holdings_cost,
"positions_mtm": mtm,
"positions_pnl": pnl,
"positions_realised": realised,
# MTM and P&L are different numbers, so both are reported
# rather than one being presented as "the" total.
"day_mtm": realised + mtm,
"day_pnl": realised + pnl,
}
def value_position_at(row, price):
"""Re-values a position at a new price, without re-reading it."""
qty = row["net_qty"]
# mult and prcftr were folded in when the row was first valued, so
# recompute from the stored average rather than re-deriving them.
delta_mtm = qty * (price - row["avg_price"])
return {
"ltp": price,
"unrealised_mtm": delta_mtm,
"unrealised_pnl": delta_mtm,
"realised": row["realised"],
}
def render(valued):
print("\033[H\033[J", end="")
print("HOLDINGS")
print(f'{"SYMBOL":<16}{"QTY":>8}{"COST":>11}{"LAST":>11}'
f'{"VALUE":>14}{"UNREALISED":>14}')
for row in valued["holdings"]:
print(f'{row["tsym"]:<16}{row["qty_valuation"]:>8,.0f}'
f'{row["cost_price"]:>11,.2f}{row["ltp"]:>11,.2f}'
f'{row["value"]:>14,.2f}{row["unrealised"]:>+14,.2f}')
print(f'{"":<16}{"":>8}{"":>11}{"":>11}'
f'{valued["holdings_value"]:>14,.2f}'
f'{valued["holdings_unrealised"]:>+14,.2f}')
if valued["positions"]:
print("\nPOSITIONS")
print(f'{"SYMBOL":<16}{"NET":>8}{"AVG":>11}{"LAST":>11}{"MTM":>14}')
for row in valued["positions"]:
print(f'{row["tsym"]:<16}{row["net_qty"]:>8,.0f}'
f'{row["avg_price"]:>11,.2f}{row["ltp"]:>11,.2f}'
f'{row["unrealised_mtm"]:>+14,.2f}')
print(f'\nDay MTM {valued["day_mtm"]:>+14,.2f}')
print(f'Day P&L {valued["day_pnl"]:>+14,.2f} '
f'(different reference price -- see /concepts/pnl/)')
def main():
portfolio = Portfolio()
portfolio.load()
key, count = subscription_key(portfolio.holdings, portfolio.positions)
if not count:
print("Nothing to value.")
return
render(portfolio.value())
# InfinnFeed is from /websocket/.
feed = InfinnFeed(
uid=UID, access_token=ACCESS_TOKEN,
on_tick=lambda row: (portfolio.on_tick(row),
render(portfolio.value())),
)
feed.subscribe(key.split("#"))
try:
feed.run_forever()
except KeyboardInterrupt:
feed.stop()
if __name__ == "__main__":
main()// portfolio.js -- value holdings and positions at their last prices (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;
}
// INFINN_ACCESS_TOKEN=... INFINN_USER_ID=... node portfolio.js
async function listOrEmpty(path, payload) {
try {
const rows = await call(path, payload);
return Array.isArray(rows) ? rows : [];
} catch (err) {
if (err instanceof InfinnError && /no data/i.test(err.message)) return [];
throw err;
}
}
async function main() {
const holdings = await listOrEmpty('/NorenWClientAPI/Holdings', { uid: UID, actid: UID, prd: 'C' });
const positions = await listOrEmpty('/NorenWClientAPI/PositionBook', { uid: UID, actid: UID });
let holdingsValue = 0;
for (const row of holdings) {
const listing = (row.exch_tsym || [])[0];
if (!listing) continue;
const qty = num(row.btstqty) + num(row.holdqty) + num(row.unplgdqty) + num(row.benqty)
- num(row.usedqty) + num(row.brkcolqty) + Math.max(num(row.npoadqty), num(row.dpqty));
const quote = await call('/NorenWClientAPI/GetQuotes', { uid: UID, exch: listing.exch, token: listing.token });
const value = qty * num(quote.lp);
holdingsValue += value;
console.log(`${listing.tsym.padEnd(16)} qty ${qty} value ${value.toFixed(2)}`);
}
let mtm = 0;
for (const row of positions) {
const qty = num(row.netqty);
const mult = num(row.mult, 1) || 1;
const prcftr = num(row.prcftr, 1) || 1;
mtm += num(row.rpnl) + qty * prcftr * mult * (num(row.lp) - num(row.netavgprc));
}
console.log(`Holdings value ${holdingsValue.toFixed(2)} | Positions MTM ${mtm.toFixed(2)}`);
}
main().catch((err) => { console.error(err.message); process.exit(1); });Cross-checking your numbers
Run this during market hours and compare the totals with what trade.infinn.in shows. If they disagree, work down this list.
| If the totals disagree | Check |
|---|---|
| Holdings value is too low | You are probably using the saleable quantity. Valuation includes brkcolqty; saleable does not. |
| Holdings value is too high | You may be summing npoadqty and dpqty. The formula uses max() of the two. |
| Derivative positions are out by a large factor | mult and prcftr are not being applied. Both are 1 for equities and not for derivatives. |
| P&L does not match the contract note | You are showing MTM. P&L uses netupldprc as its reference, not netavgprc. |
| Everything is slightly off | Charges. This valuation is gross - brokerage, STT, stamp duty and GST are not included, and Infinn publishes no endpoint for estimating them. |
| A holding is missing entirely | prd is required on the Holdings endpoint, so you only got one product. Call it per product and combine. |
What this does not do
Charges and taxes
The valuation here is gross. Brokerage, STT, stamp duty, GST and exchange charges are not included, and Infinn publishes no endpoint for calculating them - the trade report is the nearest source for realised trades. Documentation information not available for pre-trade charge estimation.
Mutual funds
The Infinn API documents no mutual fund endpoints, so fund holdings cannot be included here.
Other products
fetch_holdings requests product C only, because
prd is a required field on that endpoint. If you hold other products, call it once per product and combine.
Positions that are also holdings
The same instrument can appear in both - some bought earlier, some today. The valuation above counts them separately, which is correct for display. If you want one row per instrument, merge by token after valuing, not before.