# Opportunity Cost Feature for Sold Positions
## Overview
Added a new "Current Value If Held" column to the Tradebook page for sold positions. This helps users understand whether they sold at the right time or missed potential gains/avoided losses.
## User Story
**As a User**, I want to see what my sold positions would be worth today, so that I can evaluate the quality of my exit decisions.
## Feature Description
For positions that have been completely sold (netQuantity = 0), the tradebook now displays:
1. **Current Value If Held**: What the sold shares would be worth at current market price
2. **Opportunity Cost**: The difference between current value and actual sell proceeds
3. **Opportunity Cost %**: Percentage difference
### Calculation Logic
```typescript
// For sold positions only
currentValueIfHeld = totalSellQuantity × currentPrice
opportunityCost = totalSellValue - currentValueIfHeld
// If opportunityCost is:
// - NEGATIVE (red/orange): Current price > avg sell price → Sold too early, missed gains
// - POSITIVE (green): Current price < avg sell price → Sold at right time, avoided losses
```
### Example Scenarios
#### Scenario 1: Sold Too Early (Negative Opportunity Cost)
```
Bought: 100 shares @ ₹100 = ₹10,000
Sold: 100 shares @ ₹150 = ₹15,000
Realized P&L: +₹5,000 ✅
Current Price: ₹200
Current Value If Held: ₹20,000
Opportunity Cost: ₹15,000 - ₹20,000 = -₹5,000 (33.33%) ❌
Interpretation: Sold too early, missed additional ₹5,000 gains
```
#### Scenario 2: Sold at Right Time (Positive Opportunity Cost)
```
Bought: 100 shares @ ₹100 = ₹10,000
Sold: 100 shares @ ₹150 = ₹15,000
Realized P&L: +₹5,000 ✅
Current Price: ₹120
Current Value If Held: ₹12,000
Opportunity Cost: ₹15,000 - ₹12,000 = +₹3,000 (25%) ✅
Interpretation: Sold at right time, avoided ₹3,000 loss
```
#### Scenario 3: Stock Crashed After Sale
```
Bought: 100 shares @ ₹100 = ₹10,000
Sold: 100 shares @ ₹150 = ₹15,000
Realized P&L: +₹5,000 ✅
Current Price: ₹80
Current Value If Held: ₹8,000
Opportunity Cost: ₹15,000 - ₹8,000 = +₹7,000 (87.5%) ✅✅
Interpretation: Excellent exit! Avoided ₹7,000 loss
```
## Technical Implementation
### Backend Changes
**File**: `equity/app/api/tradebook/route.ts`
Added calculation in the trade group processing loop:
```typescript
// Calculate Opportunity Cost for sold positions
if (group.status === 'sold' && currentPrice > 0 && group.totalSellQuantity > 0) {
group.currentValueIfHeld = group.totalSellQuantity * currentPrice;
group.opportunityCost = group.totalSellValue - group.currentValueIfHeld;
group.opportunityCostPercent = (group.opportunityCost / group.currentValueIfHeld) * 100;
}
```
### Frontend Changes
**Files Modified**:
- `equity/components/TradeGroupHeader.tsx` - Display the new column
- `equity/components/TradeGroup.tsx` - Pass new props
- `equity/components/VirtualTradeList.tsx` - Updated interface
- `equity/app/tradebook/page.tsx` - Updated interface
**UI Display**:
- New column appears only for sold positions
- Shows after "Sold At" column and before "XIRR" column
- Color coding:
- **Green**: Positive opportunity cost (sold at right time)
- **Red/Orange**: Negative opportunity cost (sold too early)
### Interface Updates
```typescript
interface TradeGroup {
// ... existing fields ...
// For sold positions only
currentValueIfHeld?: number;
opportunityCost?: number;
opportunityCostPercent?: number;
}
```
## Database Changes
**None Required** ✅
This is a purely calculated field based on existing data:
- `totalSellQuantity` (from trades)
- `totalSellValue` (from trades)
- `currentPrice` (from live price API)
## Security Considerations
- ✅ No new data access patterns
- ✅ Uses existing user-scoped queries
- ✅ No additional API endpoints
- ✅ Calculation performed server-side in existing route
## UI/UX
### Location
Tradebook page → Sold positions → New column after "Sold At"
### Display Format
```
Current Value If Held
₹20,000
-₹5,000 (-25%) ← Red if negative, green if positive
```
### When Shown
- Only for completely sold positions (netQuantity = 0)
- Only when current price is available (> 0)
- Only when sell quantity > 0
### When Hidden
- Active positions (shows Unrealized P&L instead)
- Positions with no current price data
- Empty positions
## Console Logging
For debugging, each sold position logs:
```
[Tradebook Opportunity Cost] SYMBOL: Sold X @ avg ₹Y = ₹Z, Current @ ₹A = ₹B, Opportunity Cost: ₹C (D%)
```
Example:
```
[Tradebook Opportunity Cost] RELIANCE: Sold 100 @ avg ₹150.00 = ₹15000.00, Current @ ₹200 = ₹20000.00, Opportunity Cost: -₹5000.00 (-25.00%)
```
## Testing Recommendations
### Test Cases
1. **Sold position with current price higher than sell price**
- Should show negative opportunity cost (red)
- Example: Sold @ ₹100, Current @ ₹120
2. **Sold position with current price lower than sell price**
- Should show positive opportunity cost (green)
- Example: Sold @ ₹100, Current @ ₹80
3. **Sold position with no current price**
- Should not show the column
- Example: Delisted stock
4. **Active position (not sold)**
- Should not show opportunity cost column
- Should show unrealized P&L instead
5. **Multiple partial sells**
- Should calculate based on total sold quantity
- Example: Sold 50 @ ₹100, Sold 50 @ ₹150, Current @ ₹120
## Performance Impact
- **Minimal**: Calculation happens during existing loop
- **No additional API calls**: Uses already-fetched price data
- **No database queries**: Pure calculation from in-memory data
## Future Enhancements (Not Implemented)
Potential improvements for future versions:
1. **Time-based opportunity cost**: Show how opportunity cost changes over time
2. **Benchmark comparison**: Compare against index (Nifty/Sensex) performance
3. **Best exit timing**: Highlight the best price since sale
4. **Regret score**: Quantify how much was "left on the table"
5. **Alert system**: Notify if sold stock moves significantly
## Documentation Updates
Updated files:
- `Documentation/04-Business-Requirements/Equity-Portfolio.md` - Added opportunity cost feature
- `OPPORTUNITY_COST_FEATURE.md` - This comprehensive guide
## Non-Goals
This feature does NOT:
- ❌ Provide trading recommendations
- ❌ Calculate tax implications
- ❌ Consider dividends received after sale
- ❌ Account for reinvestment gains elsewhere
- ❌ Show historical price charts
- ❌ Store opportunity cost data in database
## Migration Required
**None** ✅
This is a pure calculation feature:
- No database schema changes
- No data migration needed
- Works immediately on page refresh
- Backward compatible
## Rollback Plan
If issues arise, simply revert the following files:
1. `equity/app/api/tradebook/route.ts`
2. `equity/components/TradeGroupHeader.tsx`
3. `equity/components/TradeGroup.tsx`
4. `equity/components/VirtualTradeList.tsx`
5. `equity/app/tradebook/page.tsx`
No data cleanup needed.
---
**Status**: ✅ Implemented
**Date**: December 30, 2025
**Breaking Changes**: None
**Database Changes**: None
**Migration Required**: None