Help Needed: Robust PnL Calculation for Live Market Trading

Arvind_Muthu
Hi Developers,

I’ve been working on a live market PnL calculator for my trading system but have been struggling to implement a robust PnL calculation logic that handles complex scenarios.

Here’s the formula provided in the documentation:
PnL = (sellValue - buyValue) + (netQuantity * lastPrice * multiplier)

My Trading Style
I primarily trade non-directional option selling, where:
• Multiple entries occur on the same option strike.
• I may close and reopen the same option strike multiple times.
• Quantities are adjusted dynamically (e.g., reduce/increase positions on the same instrument).

Problem Statement
When I re-enter the same strike after closing it earlier, the average price changes, leading to incorrect PnL calculations. The complexity arises due to overlapping states like:
• Tracking open positions and closed positions.
• Handling partial exits or adding positions for the same strike.
• Adjusting for FIFO when dealing with multiple trades on the same instrument.

I’m not sure whether to base my calculations on the order book or use a combination of open/close positions to get the accurate PnL seen in platforms like Kite.

Questions for the Community
1. Should I rely solely on the order book for PnL calculation, or maintain a separate tracker for open/closed positions?
2. What’s the best way to handle weighted average price adjustments when the same strike is re-entered?
3. Is there a standard approach to reconcile real-time PnL with broker platforms like Zerodha?

I’m looking for advice, best practices, or any references/examples to build a reliable PnL logic. Your insights will be invaluable!
Thanks in advance!
  • Arvind_Muthu
    After a long journey, I cracked it!
    Built a P&L calculator using Zerodha API with Kite WebSocket, solving major challenges like re-entries, reversals, partial exits, additions, transitions between long & short positions, and FIFO.
    Ensures accurate PnL tracking & WAP adjustment. Used Tkinter & Flask app to monitor & use it.
  • Arvind_Muthu
    Just completed building and packaging my PnL Calculator library. It's now modular and reusable, designed as a Python package that can be easily imported into other trading strategies. The package handles major challenges like re-entries, reversals, partial exits, pyramiding, transitions between long & short positions, and FIFO, also ensures accurate PnL tracking & WAP adjustment.
Sign In or Register to comment.