# SmartBulls F&O Margin Engine & Portfolio Hedging System Architecture

## Executive Summary
This document provides the authoritative technical documentation for the SmartBulls Futures & Options (F&O) Margin Engine and Portfolio Hedging System. It covers single-leg margin calculations, portfolio-level spread risk pairing, pre-order margin impact validation, trading terminal summary aggregation, de-hedging exit protection, and database schema integrations across Node.js microservices and PHP backend APIs.

---

## Section 1: Single-Leg Margin Calculations (`fno-cal.js` & `conn.php`)

### 1.1 Futures Contracts (`stock_type = 'future'`)
- Futures margin is identical for `BUY` (Long) and `SELL` (Short).
- **Formula**:
  $$\text{Margin} = \text{Underlying Spot Cash Price} \times \text{Quantity} \times \left(\frac{\text{Base Margin \%}}{100}\right)$$

### 1.2 Option BUY Positions (`stock_type IN ('option', 'indices')`, `action = 'BUY'`)
- Maximum risk is strictly limited to the premium paid upfront. No SPAN margin is charged.
- **Formula**:
  $$\text{Margin} = \text{Option Premium (Price)} \times \text{Quantity}$$

### 1.3 Option SELL Positions (`stock_type IN ('option', 'indices')`, `action = 'SELL'`)
- Short option positions carry market risk calculated using classic **SPAN Margin + Intrinsic Value Adjustment**.
- **Formulas**:
  - **SPAN Margin**:
    $$\text{SPAN} = \text{Spot Cash Price} \times \text{Quantity} \times \left(\frac{\text{Base Margin \%}}{100}\right)$$
  - **Short Call (`CE`) Intrinsic**:
    $$\text{Intrinsic}_{\text{CE}} = (\text{Spot Cash Price} - \text{Strike Price}) \times \text{Quantity}$$
    $$\mathbf{\text{Total Standalone Short CE Margin}} = \text{SPAN} + \text{Intrinsic}_{\text{CE}}$$
  - **Short Put (`PE`) Intrinsic**:
    $$\text{Intrinsic}_{\text{PE}} = (\text{Strike Price} - \text{Spot Cash Price}) \times \text{Quantity}$$
    $$\mathbf{\text{Total Standalone Short PE Margin}} = \text{SPAN} + \text{Intrinsic}_{\text{PE}}$$

*Example (NIFTY Spot = 22,716.20 | Margin % = 11% | Qty = 65):*
- **SPAN**: $22,716.20 \times 65 \times 11\% = \mathbf{₹1,62,420.83}$
- **22,900 CE Sell** (OTM): $\text{Intrinsic} = (22,716.20 - 22,900) \times 65 = -₹11,947 \implies \text{Margin} = \mathbf{₹1,50,473.83}$
- **22,700 CE Sell** (ITM): $\text{Intrinsic} = (22,716.20 - 22,700) \times 65 = +₹1,053 \implies \text{Margin} = \mathbf{₹1,63,473.83}$

---

## Section 2: Portfolio Hedging Engine (`hedge_margin_calculator.js`)

### 2.1 Core Strategy & Pairing Logic
The portfolio hedge engine groups positions by `parentid` (underlying asset) to enable cross-expiry hedging (e.g. Monthly Future + Weekly Options, or differing Option expiries) and pairs opposing risk legs to calculate hedged margin requirements.

#### A. Database Quantity Normalization
In MySQL `positions` table, short positions store quantities as negative values (`qty < 0`).
```javascript
const rawQty = parseFloat(p.qty || 0);
const action = rawQty < 0 ? 'SELL' : (p.action.toUpperCase() || 'BUY');
const qty = Math.abs(rawQty);
```

#### B. Strategy Pairing Handlers
1. **Futures + Option Hedges (`FUT_CE` / `FUT_PE`)**:
   - **Covered Short (Short FUT + Long CE)**: Capped upside risk.
   - **Protective Put (Long FUT + Long PE)**: Capped downside risk.
   - $\text{Max Loss} = \text{Capped Price Distance} \times Q_{\text{hedged}} + (\text{Option Premium Paid})$
   - $\text{Safety Buffer} = \text{Spot Cash Price} \times Q_{\text{hedged}} \times 2\%$
   - $\text{Required Hedged Margin} = \text{Safety Buffer} + \text{Max Loss}$

2. **Option Vertical Spreads (`CE_CE` / `PE_PE`)**:
   - **Debit Spreads (Bull Call / Bear Put)**: $\text{Max Loss} = \text{Net Debit Paid} = (\text{Premium}_{\text{long}} - \text{Premium}_{\text{short}}) \times Q_{\text{hedged}}$
   - **Credit Spreads (Bear Call / Bull Put)**: $\text{Max Loss} = (\text{Strike Width} \times Q_{\text{hedged}}) - \text{Net Credit}$
   - $\text{Safety Buffer} = \text{Spot Cash Price} \times Q_{\text{hedged}} \times 2\%$
   - $\text{Required Hedged Margin} = \text{Safety Buffer} + \text{Max Loss}$

3. **Hedge Benefit Credit**:
   $$\text{Hedge Benefit} = M_{\text{gross}} - M_{\text{hedged}}$$

---

## Section 3: Integration Points & Control Flow

### 3.1 Pre-Order Combined Margin Validation (`/api/combined-margin-order`)
When a user opens the order window to place a new F&O order:
1. The engine fetches existing open positions plus the candidate order.
2. Calls `FnoCalService.calculateOrderMarginImpact(uid, candidateOrder)`.
3. Calculates current portfolio margin vs. hypothetical new portfolio margin.
4. Returns:
   - `standalone_margin`: Single-leg margin of the new order.
   - `hedge_benefit`: Additional margin released by hedging.
   - `incremental_margin`: Net cash impact of placing the order.
   - `can_place`: Boolean indicating if `user_available_balance >= incremental_margin`.

### 3.2 Exit Protection / Anti De-Hedging (`stock-order.js`)
When a user attempts to exit a protective `BUY` leg of an active option spread:
1. The engine simulates removing the target `BUY` position.
2. Calculates the new post-exit portfolio margin (which becomes the unhedged standalone short margin).
3. If `available_balance < new_unhedged_margin`, the exit order is blocked with:
   > *"Cannot square off hedge leg: Insufficient margin to maintain the remaining unhedged short position. Square off the short position first."*

### 3.3 Trading Terminal Balance & Portfolio Card Integration
- **`trading_terminal_summary.service.js`**:
  - `investments.fno`: Displays **Net Blocked Margin** ($M_{\text{gross}} - \text{Hedge Benefit}$).
  - `investments.fno_gross`: Preserves **Gross Standalone Margin**.
  - `investments.hedge_benefit`: Reports total **Hedge Benefit**.
  - `contestData.invested`: Displays **Net Total Invested Capital** across all open positions.
  - `available_balance` / `finalDynamicBalance`:
    $$\text{Available Balance} = \text{Fund Value} + \text{Topup} + \text{Winning} - \text{Charges} - \text{Net Invested} - \text{Pending}$$

- **PHP Backend Sync (`public/helpers/conn.php`)**:
  - `trading_terminal_segment_details()` invokes `/var/www/html/node_api/scratch/calculate_user_hedge.js` or reads Redis key `portfolio_hedge:{uid}:{cid}` to deduct `hedge_benefit` from `fno_invested` and return net blocked margin to the mobile app.

---

## Section 4: Real Trade Worked Example (User Rutv2638)

### Positions:
- `BUY NIFTY 23400 CE`, Qty: `65`, Buy Price: `₹96.50`
- `SELL NIFTY 23500 CE`, Qty: `65`, Sell Price: `₹34.75`
- Underlying Spot Price: `₹23,346.40`, Min Margin Safety Buffer: `5.0%`

### Calculation Walkthrough:
1. **Short Leg Standalone Margin**: ₹1,72,117.92
2. **Long Leg Standalone Premium**: ₹6,272.50
3. **Gross Standalone Margin ($M_{\text{gross}}$)**: ₹1,78,390.42
4. **Spread Max Loss ($\text{MaxLoss}$)**: ₹6,500.00
5. **Safety Buffer Margin ($\text{SafetyMargin}$)**: $23,346.40 \times 65 \times 5\% = \mathbf{₹75,875.80}$
6. **Net Hedged Margin Required ($M_{\text{hedged}}$)**: $\max(6,500.00, 75,875.80) = \mathbf{₹75,875.80}$
7. **Hedge Benefit Released**: $178,390.42 - 75,875.80 = \mathbf{₹1,02,514.62}$


