44 - PnL Tracker

Overview

The PnL (Profit & Loss) Tracker provides real-time intraday P&L monitoring by combining tradebook data with historical price data. It calculates mark-to-market (MTM) P&L for all positions throughout the trading day and displays it via interactive charts.

Architecture Diagram

┌──────────────────────────────────────────────────────────────────────────────┐
│                          PnL Tracker Architecture                            │
└──────────────────────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────────────────────┐
│                         Data Sources                                         │
│                                                                              │
│  ┌─────────────────┐  ┌─────────────────┐  ┌─────────────────┐             │
│  │  Tradebook      │  │  Position Book  │  │  History API    │             │
│  │  (Broker API)   │  │  (Broker API)   │  │  (1-minute bars)│             │
│  └────────┬────────┘  └────────┬────────┘  └────────┬────────┘             │
│           │                    │                    │                       │
│           └────────────────────┼────────────────────┘                       │
│                                │                                             │
│                                ▼                                             │
└─────────────────────────────────────────────────────────────────────────────┘


┌─────────────────────────────────────────────────────────────────────────────┐
│                       PnL Calculation (blueprints/pnltracker.py)            │
│                                                                              │
│  ┌─────────────────────────────────────────────────────────────────────┐   │
│  │                    Position Window Tracking                          │   │
│  │                                                                      │   │
│  │  1. Parse trades from tradebook                                     │   │
│  │  2. Group by symbol/exchange                                        │   │
│  │  3. Create position windows (start_time, end_time, qty, price)      │   │
│  │  4. Apply rate limiting (2 calls/sec for history API)               │   │
│  │  5. Calculate MTM using historical close prices                     │   │
│  │  6. Aggregate all symbols into portfolio P&L                        │   │
│  └─────────────────────────────────────────────────────────────────────┘   │
│                                    │                                         │
│                                    ▼                                         │
│  ┌─────────────────────────────────────────────────────────────────────┐   │
│  │                    P&L Calculation Formula                           │   │
│  │                                                                      │   │
│  │  For LONG positions:                                                 │   │
│  │    MTM P&L = (Current Price - Entry Price) × Quantity               │   │
│  │                                                                      │   │
│  │  For SHORT positions:                                                │   │
│  │    MTM P&L = (Entry Price - Current Price) × Quantity               │   │
│  │                                                                      │   │
│  │  Realized P&L = (Exit Price - Entry Price) × Quantity  [Long]       │   │
│  │                = (Entry Price - Exit Price) × Quantity  [Short]     │   │
│  └─────────────────────────────────────────────────────────────────────┘   │
└─────────────────────────────────────────────────────────────────────────────┘


┌─────────────────────────────────────────────────────────────────────────────┐
│                         Frontend Display                                     │
│                                                                              │
│  ┌─────────────────────────────────────────────────────────────────────┐   │
│  │  Metrics Cards                                                       │   │
│  │                                                                      │   │
│  │  ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐              │   │
│  │  │ Current  │ │   Max    │ │   Min    │ │   Max    │              │   │
│  │  │   MTM    │ │   MTM    │ │   MTM    │ │ Drawdown │              │   │
│  │  │ +₹3,750  │ │ +₹4,200  │ │ +₹1,000  │ │  -₹800   │              │   │
│  │  └──────────┘ └──────────┘ └──────────┘ └──────────┘              │   │
│  └─────────────────────────────────────────────────────────────────────┘   │
│                                                                              │
│  ┌─────────────────────────────────────────────────────────────────────┐   │
│  │  P&L Chart (LightWeight Charts)                                     │   │
│  │                                                                      │   │
│  │       ₹                                                              │   │
│  │    4000│        ╭──────╮                                            │   │
│  │    3000│    ╭───╯      ╰──╮                                         │   │
│  │    2000│╭───╯              ╰──────                                  │   │
│  │    1000│                                                            │   │
│  │       0├────────────────────────────► Time                          │   │
│  │        9:15  10:00  11:00  12:00  1:00                              │   │
│  └─────────────────────────────────────────────────────────────────────┘   │
└─────────────────────────────────────────────────────────────────────────────┘

Implementation Details

Position Window Tracking

The PnL tracker creates "position windows" to track when positions were opened and closed:

Trade Timestamp Parsing

The system handles multiple timestamp formats from different brokers:

Rate Limiting

Historical data API calls are rate-limited to avoid broker rate limits:

Carry-Forward Position PnL Tracking

The PnL tracker handles carry-forward positions — positions opened on previous days that are still open today. This is critical for NRML/CNC positions that span multiple trading sessions.

Position Detection:

  • Compares current positions (from positionbook) against today's trades

  • Positions with quantities but no matching entry trades are carry-forward

  • Historical data fetched from 9:15 AM to calculate intraday P&L movement

P&L Calculation for Carry-Forward:

  • Uses previous day's close price as the reference

  • Tracks MTM from market open using 1-minute historical bars

  • Merges carry-forward PnL series with regular trade PnL series

API Endpoint

Get P&L Data

Response:

Response Fields

Field
Type
Description

current_mtm

number

Current mark-to-market P&L

max_mtm

number

Maximum P&L reached during the day

max_mtm_time

string

Time when max P&L was reached (HH:MM)

min_mtm

number

Minimum P&L during the day

min_mtm_time

string

Time when min P&L was reached (HH:MM)

max_drawdown

number

Largest drawdown from peak (negative)

pnl_series

array

Time series data for P&L chart

drawdown_series

array

Time series data for drawdown chart

Calculation Flow

Data Dependencies

The PnL tracker relies on these services (no dedicated database):

Service
Purpose

services/tradebook_service.py

Get today's executed trades

services/positionbook_service.py

Get current positions

services/history_service.py

Get 1-minute historical bars

database/auth_db.py

Get user auth token and API key

Frontend Components

React Page

Location: frontend/src/pages/PnLTracker.tsx

The React frontend:

  • Polls /pnltracker/api/pnl periodically

  • Renders metrics cards (current MTM, max, min, drawdown)

  • Uses LightWeight Charts for interactive P&L visualization

  • Shows separate drawdown chart below main chart

Legacy Jinja Template

Location: templates/pnltracker.html

Available at /pnltracker/legacy for backwards compatibility.

Edge Cases Handled

Sub-Minute Trades

When a position is opened and closed within the same minute (no historical data points):

Pre-Trade Period

Zero P&L data is added from market open (9:15 AM IST) to first trade time for complete visualization.

Timezone Handling

All timestamps are converted to IST (Asia/Kolkata) timezone:

Drawdown Calculation

Key Files Reference

File
Purpose

blueprints/pnltracker.py

Blueprint with P&L calculation logic

services/tradebook_service.py

Fetches tradebook from broker

services/positionbook_service.py

Fetches current positions

services/history_service.py

Fetches historical price data

frontend/src/pages/PnLTracker.tsx

React UI component

templates/pnltracker.html

Legacy Jinja template

Last updated