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

SourceCoversWhy you need it
HoldingsShares bought on earlier days and settled into dematThis is what you own outright. It does not appear in positions.
Positions BookToday's trading, and carried-forward derivativesThis is where today's profit and loss lives. It does not appear in holdings.
Live pricesCurrent value of bothNeither endpoint gives a reliable live price: holdings' lp is disabled by default, and polling positions is explicitly discouraged.
Holdings and positions are not the same thing

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.

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. Broker collateral counts towards what a holding is worth, but not towards what you can sell. And the valuation uses max(npoadqty, dpqty) — the larger of the two, not the sum.
Both documented holdings formulas
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 out
exch_tsym is an array

One 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

Positions, valued per the documented formulas
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")),
  }
mult and prcftr are both 1 for equities and not otherwise

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.

Collect every token, subscribe once
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)
Do not fetch quotes one by one

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

portfolio.py — a live portfolio valuation
"""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()

Cross-checking your numbers

Check against the terminal before trusting it

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 disagreeCheck
Holdings value is too lowYou are probably using the saleable quantity. Valuation includes brkcolqty; saleable does not.
Holdings value is too highYou may be summing npoadqty and dpqty. The formula uses max() of the two.
Derivative positions are out by a large factormult and prcftr are not being applied. Both are 1 for equities and not for derivatives.
P&L does not match the contract noteYou are showing MTM. P&L uses netupldprc as its reference, not netavgprc.
Everything is slightly offCharges. 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 entirelyprd 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.

Next

Esc
↑↓ navigate↵ openEsc close/ to search