On this page
Infinn documents several formulas but does not explain them, and two of them use the same field name to mean different things. This page works through all of it.
Available margin: how much can I still trade with?
There is no "available balance" field. You compute it from Limits, using the formula Infinn publishes.
total credits = cash + payin + payout + daycash + unclearedcash
+ brkcollamt + collateral + aux_brkcollamt
available margin = total credits − marginused
utilisation = marginusedcollateral and aux_brkcollamt appear in the published formula but have no entry in the documented response field list, and neither appears in the sample payload. Documentation information not available.
Treat them as absent-and-zero unless your own live response contains them. The code below does exactly that.
| Field | Part of | Meaning |
|---|---|---|
cash | Credits | Cash margin available |
payin | Credits | Transferred in today |
payout | Credits | Requested for withdrawal today |
daycash | Credits | Broker-added leverage or adjustment |
unclearedcash | Credits | Pay-ins not yet settled, e.g. by cheque |
brkcollamt | Credits | Pre-valued collateral |
collateral | Credits | in the formula, not in the field table |
aux_brkcollamt | Credits | in the formula, not in the field table |
marginused | Utilisation | Total margin or funds used today |
urmtom | Neither | Unrealised MTM. In the sample response, absent from the field tables. |
grexpo | Neither | Gross exposure. In the sample response only; see Known limitations. |
"""Compute available margin from a Limits response.
Two fields in Infinn's published formula -- collateral and aux_brkcollamt --
are not in the documented field list and do not appear in the sample
response. They are summed here if present and treated as zero if not, which
matches the formula without assuming fields that may never arrive.
"""
CREDIT_FIELDS = (
"cash", # cash margin available
"payin", # transferred in today
"payout", # requested for withdrawal today
"daycash", # broker-added leverage or adjustment
"unclearedcash", # pay-ins not yet settled
"brkcollamt", # pre-valued collateral
"collateral", # in the formula, absent from the field table
"aux_brkcollamt", # in the formula, absent from the field table
)
def margin_summary(limits):
"""Returns total credits, margin used and what remains."""
total_credits = sum(num(limits.get(f)) for f in CREDIT_FIELDS)
used = num(limits.get("marginused"))
return {
"total_credits": total_credits,
"margin_used": used,
"available": total_credits - used,
# Guard the division: a fresh account has zero credits.
"utilisation_pct": (used / total_credits * 100) if total_credits else 0.0,
}
# Using the documented sample response:
# cash 1500000000000000.00, everything else 0, marginused 3945540.00
# -> available = 1499999996054460.00Mark-to-market and profit: the same formula, two reference prices
This is the part that trips people up. Infinn documents one unrealised formula and then says to feed it a different average price depending on which number you want.
ActualUnrealizedMtoM = netqty × prcftr × mult × (LTP − avgprc)
for MTM: avgprc = netavgprc
for P&L: avgprc = netupldprc,
and if netupldprc is 0, fall back to netavgprc| Mark-to-market | Profit & loss | |
|---|---|---|
| Reference price | netavgprc | netupldprc, falling back to netavgprc when 0 |
| Measures | Movement since you traded | Movement since the position was carried in |
| Realised part | rpnl | ActualBookedPNL, the documented recomputation |
| Total | rpnl + unrealised | ActualBookedPNL + unrealised |
| Differs when | - | The position was carried forward, so netupldprc is not zero |
They differ for any carried-forward position, because netupldprc is the price the position was carried in at, not the price you traded at today. Showing MTM under a "Profit" heading will not match the user's contract note.
The multipliers
Two fields scale the result, and leaving them out gives answers that are right for equities and wrong for everything else.
| Field | Meaning | Equities | Derivatives |
|---|---|---|---|
mult | Contract price multiplier, used for order-value maths | 1 | Varies by contract |
prcftr | Price factor, documented as gnpn/(gdpd) and shown as ((GN / GD) * (PN/PD)) | 1.000000 | Varies by contract |
For an NSE equity both are 1 and the formula collapses to the obvious one. For a currency future they are not, and omitting them produces a number that is wrong by a factor of a thousand - which looks plausible enough to ship.
Realised profit, properly
Infinn documents a fuller calculation for booked profit that accounts for carried-forward quantity at its upload price, rather than at today's traded price.
NetBuyQty = daybuyqty + cfbuyqty
NetSellQty = daysellqty + cfsellqty
ActualSellAvgPrice = ((daysellamt / mult) + (upldprc × prcftr × cfsellqty))
/ NetSellQty … or 0 if NetSellQty is 0
ActualBuyAvgPrice = ((daybuyamt / mult) + (upldprc × prcftr × cfbuyqty))
/ NetBuyQty … or 0 if NetBuyQty is 0
if netqty > 0: ActualBookedPNL = (SellAvg − BuyAvg) × NetSellQty × mult
else: ActualBookedPNL = (SellAvg − BuyAvg) × NetBuyQty × mult
MTM = rpnl + ActualUnrealizedMtoM
PnL = ActualBookedPNL + ActualUnrealizedMtoMAll of it, in one function
"""Value a position exactly as Infinn documents it.
Takes one row from the Positions Book and, optionally, a live last traded
price from the WebSocket feed. Returns both MTM and P&L, which are
different numbers computed against different reference prices.
"""
def value_position(row, live_ltp=None):
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
# Prefer the live price; fall back to the snapshot's own lp.
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"))
# --- Unrealised, twice, against two different reference prices --------
unrealised_mtm = qty * prcftr * mult * (ltp - net_avg)
# The documented fallback: netupldprc of 0 means "use netavgprc".
pnl_reference = net_upld if net_upld else net_avg
unrealised_pnl = qty * prcftr * mult * (ltp - pnl_reference)
# --- Realised, from the day and carry-forward components ---------------
net_buy_qty = num(row.get("daybuyqty")) + num(row.get("cfbuyqty"))
net_sell_qty = num(row.get("daysellqty")) + num(row.get("cfsellqty"))
upld = num(row.get("upldprc"))
sell_avg = (
(num(row.get("daysellamt")) / mult + upld * prcftr * num(row.get("cfsellqty")))
/ net_sell_qty
) if net_sell_qty else 0.0
buy_avg = (
(num(row.get("daybuyamt")) / mult + upld * prcftr * num(row.get("cfbuyqty")))
/ net_buy_qty
) if net_buy_qty else 0.0
# Booked profit is measured over whichever side is closed out.
closed_qty = net_sell_qty if qty > 0 else net_buy_qty
booked_pnl = (sell_avg - buy_avg) * closed_qty * mult
return {
"net_qty": qty,
"ltp": ltp,
"unrealised_mtm": unrealised_mtm,
"unrealised_pnl": unrealised_pnl,
# rpnl is Infinn's own realised figure; booked_pnl is the documented
# recomputation. They can differ for carried-forward positions.
"realised_reported": num(row.get("rpnl")),
"realised_computed": booked_pnl,
"mtm": num(row.get("rpnl")) + unrealised_mtm,
"pnl": booked_pnl + unrealised_pnl,
"break_even": num(row.get("bep")),
}Keeping it live without polling
The Positions Book page carries the warning: "This endpoint should be strictly used as a single call for fetching m2m without a while loop. For live m2m tracking please use the web socket feed."
"""Live mark-to-market with exactly one REST call.
Positions are read once. After that, every LTP tick recomputes the value
locally -- which is both correct and free, where polling would consume the
whole rate-limit budget within a handful of instruments.
"""
import json
class LivePortfolio:
def __init__(self, positions):
# Key by exchange and token, because that is what ticks carry.
self.positions = {
(p["exch"], p["token"]): p
for p in positions if p.get("token")
}
self.prices = {}
def subscription_key(self):
"""The 'k' string for a touchline or LTP subscription."""
return "#".join(f"{exch}|{token}" for exch, token in self.positions)
def on_tick(self, message):
"""Handles one 'tf' or 'lf' message and returns the new total."""
if message.get("t") not in ("tf", "lf") or "lp" not in message:
return None
self.prices[(message["e"], message["tk"])] = num(message["lp"])
return self.total()
def total(self):
mtm = pnl = 0.0
for key, row in self.positions.items():
valued = value_position(row, live_ltp=self.prices.get(key))
mtm += valued["mtm"]
pnl += valued["pnl"]
return {"mtm": mtm, "pnl": pnl}Holdings are counted differently again
A holding has no single quantity field. The number is spread across a dozen buckets, and the two figures you actually want are both computed.
valuation quantity = btstqty + holdqty + brkcolqty + unplgdqty + benqty
+ max(npoadqty, dpqty) − usedqty
saleable quantity = btstqty + holdqty + unplgdqty + benqty + dpqty
− usedqtybrkcolqty(broker collateral) is in the valuation and not in the saleable figure. Pledged shares still have value; you just cannot sell them.- The valuation uses
max(npoadqty, dpqty)- the larger of the two, not the sum. Adding them double-counts.
def holding_quantities(row):
"""Returns the two documented quantities for one holdings row.
They differ by brkcolqty: pledged shares count towards 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 f: num(row.get(f))
common = (g("btstqty") + g("holdqty") + g("unplgdqty")
+ g("benqty") - g("usedqty"))
return {
# max(), not sum() -- the two fields overlap.
"valuation": common + g("brkcolqty") + max(g("npoadqty"), g("dpqty")),
"saleable": common + g("dpqty"),
}Checking margin before you order
On remarks: "Order Success" it is the margin that would be used.
On remarks: "Insufficient Balance" it is the shortfall still required - Infinn's own documentation says to show it captioned as "Shortfall margin".
Branch on remarks before you label the number, or you will show customers a figure that means the opposite of its caption.
def interpret_order_margin(response):
"""Turns an Order Margin response into something safe to display.
The meaning of `marginused` depends entirely on `remarks`, so the
caption is chosen here rather than in the UI.
"""
remarks = str(response.get("remarks", ""))
amount = num(response.get("marginused"))
# Documented verdicts that mean the order will go through.
if remarks.startswith("Order Success"):
return {
"will_pass": True,
"caption": "Margin required",
"amount": amount,
"cash_available": num(response.get("cash")),
}
if remarks == "Insufficient Balance":
return {
"will_pass": False,
"caption": "Shortfall margin", # NOT "margin required"
"amount": amount,
"cash_available": num(response.get("cash")),
}
# The remaining documented verdicts all mean rejection:
# "Eligible Sell: ", "No Holdings uploaded", "Invalid scrip",
# "RED is under Reconciliation"
return {
"will_pass": False,
"caption": remarks or "Order would be rejected",
"amount": amount,
"cash_available": num(response.get("cash")),
}Basket margin
Hedged positions need far less margin together than separately, which is what Basket Margin measures. Its numbers are relative to your existing usage, so Limits must be called first.
| Excluding existing margin | Including existing margin | |
|---|---|---|
| Post-trade margin | marginusedtrade − marginused(Limits) | marginusedtrade |
| Basket margin | marginused − marginused(Limits) | marginused |