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.

The documented arithmetic
total credits    = cash + payin + payout + daycash + unclearedcash
                 + brkcollamt + collateral + aux_brkcollamt

available margin = total credits − marginused

utilisation      = marginused
Two of those fields are not in the field table

collateral 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.

FieldPart ofMeaning
cashCreditsCash margin available
payinCreditsTransferred in today
payoutCreditsRequested for withdrawal today
daycashCreditsBroker-added leverage or adjustment
unclearedcashCreditsPay-ins not yet settled, e.g. by cheque
brkcollamtCreditsPre-valued collateral
collateralCreditsin the formula, not in the field table
aux_brkcollamtCreditsin the formula, not in the field table
marginusedUtilisationTotal margin or funds used today
urmtomNeitherUnrealised MTM. In the sample response, absent from the field tables.
grexpoNeitherGross exposure. In the sample response only; see Known limitations.
Available margin, defensively
"""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.00

Mark-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.

The documented formula
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-marketProfit & loss
Reference pricenetavgprcnetupldprc, falling back to netavgprc when 0
MeasuresMovement since you tradedMovement since the position was carried in
Realised partrpnlActualBookedPNL, the documented recomputation
Totalrpnl + unrealisedActualBookedPNL + unrealised
Differs when-The position was carried forward, so netupldprc is not zero
Labelling one as the other is a real bug

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.

FieldMeaningEquitiesDerivatives
multContract price multiplier, used for order-value maths1Varies by contract
prcftrPrice factor, documented as gnpn/(gdpd) and shown as ((GN / GD) * (PN/PD))1.000000Varies by contract
Why these exist

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.

The documented arithmetic
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 + ActualUnrealizedMtoM

All of it, in one function

Position valuation following the documented formulas
"""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 documentation says this explicitly

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."

Fetch positions once, then recompute from ticks
"""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.

The API gives you buckets, not a totalbtstqtyholdqtyunplgdqtybenqtydpqtybrkcolqtyusedqty− usedValuation quantityall of the above, minus usedqtySaleable quantitythe same, but WITHOUT brkcolqtyBroker collateral counts towards what the holding is worth, but not towards what you can sell.max(npoadqty, dpqty) is used in the valuation formula — the larger of the two, not the sum.
Figure 1. The two documented holdings formulas. Broker collateral counts towards what a holding is worth, but not towards what you can sell.
Both documented formulas
valuation quantity = btstqty + holdqty + brkcolqty + unplgdqty + benqty
                   + max(npoadqty, dpqty) − usedqty

saleable quantity  = btstqty + holdqty + unplgdqty + benqty + dpqty
                   − usedqty
Two things to notice
  • brkcolqty (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.
Both holdings figures
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

Your orderqty, price, productGetOrderMargina dry run"Order Success"marginused = will be used"Insufficient Balance"marginused = shortfallPlaceOrdergo aheadStoptell the userThe same field means two different thingsOn success marginused is the margin that would be used. On failure it is the extra amount still needed. Branch on remarks before you label it.
Figure 2. Order Margin answers "would this pass?" before you commit -- but the field it answers with changes meaning depending on the verdict.
marginused means two opposite things

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.

Interpreting an Order Margin response
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 marginIncluding existing margin
Post-trade marginmarginusedtrade − marginused(Limits)marginusedtrade
Basket marginmarginused − marginused(Limits)marginused

Next

Esc
↑↓ navigate↵ openEsc close/ to search