# 📊 SmartBulls F&O Hedge Margin Logic & Calculation Guide

This document defines the mathematical formulas, database configurations, real-time data calculations, and strategy execution rules for the **SmartBulls F&O Hedge Margin Engine**.

---

## 1. Executive Overview

When a user holds offsetting positions in Futures & Options (e.g., Short Call + Long Call, Short Put + Long Put, or Future + Protective Option), their market risk is capped. The **Hedge Margin Engine** calculates:

1. **Standalone (Gross) Margin ($M_{\text{gross}}$)**: The total margin required if legs are placed independently.
2. **Net Blocked Hedged Margin ($M_{\text{hedged}}$)**: The actual reduced margin required after applying spread risk calculations and configuration rules.
3. **Hedge Benefit Credit ($\text{Hedge Benefit}$)**: The difference ($M_{\text{gross}} - M_{\text{hedged}}$) released back into the user's available cash balance.

---

## 2. Database Configuration Schema & Data

The engine's benefit percentages, days-to-expiry (DTE) tiers, lot constraints, and safety floor percentages are fully dynamic and managed via MySQL database tables.

### 2.1 Table: `hedge_margin_benefit_config`

Controls the benefit percentage released based on strategy type and **Days to Expiry (DTE)**.

#### Schema Structure:
| Column | Type | Description |
|---|---|---|
| `id` | INT | Primary Key |
| `underlying` | VARCHAR(50) | Underlying asset filter (`ALL`, `NIFTY`, `BANKNIFTY`, etc.) |
| `instrument_type` | VARCHAR(50) | Instrument filter (`OPTION`, `FUTURE`, `ALL`) |
| `hedge_type` | VARCHAR(50) | Strategy Code (`CE_CE`, `PE_PE`, `FUT_PE`, `FUT_CE`, `SPREAD`, `CONDOR`) |
| `from_days` | INT | Minimum Days to Expiry (inclusive) |
| `to_days` | INT | Maximum Days to Expiry (inclusive) |
| `benefit_percentage` | DECIMAL(5,2) | Discount percentage off standalone short margin |
| `min_lots` | INT | Minimum lots required to qualify |
| `max_lots` | INT | Maximum lots allowed |
| `enabled` | ENUM('Yes','No') | Enabled flag |
| `created_at` | TIMESTAMP | Record creation timestamp |
| `updated_at` | TIMESTAMP | Record last update timestamp |

#### Current Production Configuration Snapshot:

| id | underlying | instrument_type | hedge_type | from_days | to_days | benefit_percentage | min_lots | max_lots | enabled |
|---|---|---|---|---|---|---|---|---|---|
| **1** | ALL | OPTION | `CE_CE` | 15 | 999 | **70.00%** | 1 | 10000 | Yes |
| **2** | ALL | OPTION | `CE_CE` | 8 | 14 | **60.00%** | 1 | 10000 | Yes |
| **3** | ALL | OPTION | `CE_CE` | 3 | 7 | **50.00%** | 1 | 10000 | Yes |
| **4** | ALL | OPTION | `CE_CE` | 1 | 2 | **40.00%** | 1 | 10000 | Yes |
| **5** | ALL | OPTION | `CE_CE` | 0 | 0 | **30.00%** | 1 | 10000 | Yes |
| **6** | ALL | OPTION | `PE_PE` | 15 | 999 | **70.00%** | 1 | 10000 | Yes |
| **7** | ALL | OPTION | `PE_PE` | 8 | 14 | **60.00%** | 1 | 10000 | Yes |
| **8** | ALL | OPTION | `PE_PE` | 3 | 7 | **50.00%** | 1 | 10000 | Yes |
| **9** | ALL | OPTION | `PE_PE` | 1 | 2 | **40.00%** | 1 | 10000 | Yes |
| **10** | ALL | OPTION | `PE_PE` | 0 | 0 | **30.00%** | 1 | 10000 | Yes |
| **11** | ALL | ALL | `FUT_PE` | 15 | 999 | **65.00%** | 1 | 10000 | Yes |
| **12** | ALL | ALL | `FUT_PE` | 8 | 14 | **55.00%** | 1 | 10000 | Yes |
| **13** | ALL | ALL | `FUT_PE` | 3 | 7 | **45.00%** | 1 | 10000 | Yes |
| **14** | ALL | ALL | `FUT_PE` | 0 | 2 | **35.00%** | 1 | 10000 | Yes |
| **15** | ALL | ALL | `FUT_CE` | 15 | 999 | **65.00%** | 1 | 10000 | Yes |
| **16** | ALL | ALL | `FUT_CE` | 8 | 14 | **55.00%** | 1 | 10000 | Yes |
| **17** | ALL | ALL | `FUT_CE` | 3 | 7 | **45.00%** | 1 | 10000 | Yes |
| **18** | ALL | ALL | `FUT_CE` | 0 | 2 | **35.00%** | 1 | 10000 | Yes |



## 3. Realtime Data Inputs & Base Calculations

To calculate margins in real-time, the engine uses live market ticks from Redis / Kite Ticker:

1. **Spot Cash Price ($\text{LTP}_{\text{spot}}$)**: Current market price of underlying instrument (or fallback entry price).
2. **Quantity ($Q$)**: Number of contracts ($\text{Lots} \times \text{Lot Size}$). Note: Short positions store $Q < 0$ in MySQL.
3. **Days to Expiry ($\text{DTE}$)**:
   $$\text{DTE} = \max\left(0, \lceil \frac{\text{Expiry Timestamp} - \text{Current Timestamp}}{86400} \rceil\right)$$

### 3.1 Standalone Margin Formulas

- **Option BUY Leg**:
  $$M_{\text{long}} = \text{Option Premium (Entry/LTP)} \times Q$$

- **Option SELL Call (`CE`) Leg**:
  $$\text{SPAN} = \text{Spot Cash Price} \times Q \times \left(\frac{\text{Margin \%}}{100}\right)$$
  $$\text{Intrinsic} = (\text{Spot Cash Price} - \text{Strike}) \times Q$$
  $$M_{\text{short\_CE}} = \text{SPAN} + \text{Intrinsic}$$

- **Option SELL Put (`PE`) Leg**:
  $$\text{SPAN} = \text{Spot Cash Price} \times Q \times \left(\frac{\text{Margin \%}}{100}\right)$$
  $$\text{Intrinsic} = (\text{Strike} - \text{Spot Cash Price}) \times Q$$
  $$M_{\text{short\_PE}} = \text{SPAN} + \text{Intrinsic}$$

- **Futures (`FUT`) Leg**:
  $$M_{\text{fut}} = \text{Spot Cash Price} \times Q \times \left(\frac{\text{Margin \%}}{100}\right)$$

---

## 4. Strategy Formulas & Benefit Calculation

For any hedged pair on the same underlying (`parentid`), $Q_{\text{hedged}} = \min(Q_{\text{leg1}}, Q_{\text{leg2}})$.

### 4.1 Strategy 1: `CE_CE` / `PE_PE` (Option Vertical Spreads)

1. **Debit Spreads** (e.g. Bull Call Spread, Bear Put Spread):
   $$\text{Max Loss} = (\text{Premium}_{\text{long}} - \text{Premium}_{\text{short}}) \times Q_{\text{hedged}}$$
2. **Credit Spreads** (e.g. Bear Call Spread, Bull Put Spread):
   $$\text{Max Loss} = (\text{Strike Width} \times Q_{\text{hedged}}) - \text{Net Credit}$$
3. **Safety Buffer**:
   $$\text{Safety Buffer} = \text{Spot Cash Price} \times Q_{\text{hedged}} \times 2.0\%$$
4. **Required Hedged Margin**:
   $$M_{\text{hedged}} = \min(M_{\text{gross}}, \text{Safety Buffer} + \text{Max Loss})$$
5. **Hedge Benefit Credit**:
   $$\text{Hedge Benefit} = M_{\text{gross}} - M_{\text{hedged}}$$

---

### 4.2 Strategy 2: `FUT_CE` / `FUT_PE` (Futures + Option Hedges)

1. **Short FUT + Long CE (Covered Short)**:
   - Capped Max Loss: $\max(0, \text{Strike} - \text{Futures Price} + \text{Call Premium}) \times Q_{\text{hedged}}$
   - $\text{Safety Buffer} = \text{Spot Cash Price} \times Q_{\text{hedged}} \times 2.0\%$
   - $\text{Required Hedged Margin} = \text{Safety Buffer} + \text{Max Loss} + \text{Call Premium Paid}$
   - $\text{Hedge Benefit} = M_{\text{gross}} - M_{\text{hedged}}$

2. **Long FUT + Long PE (Protective Put)**:
   - Capped Max Loss: $\max(0, \text{Futures Price} - \text{Strike} + \text{Put Premium}) \times Q_{\text{hedged}}$
   - $\text{Safety Buffer} = \text{Spot Cash Price} \times Q_{\text{hedged}} \times 2.0\%$
   - $\text{Required Hedged Margin} = \text{Safety Buffer} + \text{Max Loss} + \text{Put Premium Paid}$
   - $\text{Hedge Benefit} = M_{\text{gross}} - M_{\text{hedged}}$

---

### 4.2 Strategy 2: `PE_PE` (Put Option Spread - Bull Put / Bear Put)

1. **Greedy Pairing**: Sort Short PEs by strike descending and Long PEs by strike ascending.
2. **Strike Width & Net Credit**:
   $$\text{Strike Width} = \max\left(0, \text{Strike}_{\text{short}} - \text{Strike}_{\text{long}}\right)$$
   $$\text{Net Credit} = (\text{Premium}_{\text{sell}} - \text{Premium}_{\text{buy}}) \times Q_{\text{hedged}}$$
3. **Maximum Spread Loss ($\text{MaxLoss}$)**:
   $$\text{MaxLoss} = \begin{cases} (\text{Strike Width} \times Q_{\text{hedged}}) - \text{Net Credit} & \text{if Net Credit} \ge 0 \\ (\text{Strike Width} \times Q_{\text{hedged}}) + |\text{Net Credit}| & \text{if Net Credit} < 0 \end{cases}$$
4. **Safety Floor Margin**:
   $$\text{SafetyMargin} = \text{LTP}_{\text{spot}} \times Q_{\text{hedged}} \times 5.0\%$$
5. **Config Benefit Discount**:
   Lookup $B\%$ for `PE_PE` using current $\text{DTE}$.
   $$\text{Raw Benefit} = M_{\text{short\_PE}} \times \left(\frac{B\%}{100}\right)$$
6. **Final Hedged Margin Required**:
   $$M_{\text{hedged}} = \max\left(\text{MaxLoss}, \text{SafetyMargin}, M_{\text{gross}} - \text{Raw Benefit}\right)$$
7. **Hedge Benefit Credit**:
   $$\text{Hedge Benefit} = M_{\text{gross}} - M_{\text{hedged}}$$

---

### 4.3 Strategy 3 & 4: `FUT_PE` & `FUT_CE` (Futures + Option Hedges)

1. **Pairing**: Pair 1 Futures leg with 1 Protective Option leg (`FUT` + `PE` or `FUT` + `CE`).
2. **Config Benefit Discount**:
   Lookup $B\%$ for `FUT_PE` or `FUT_CE` in `hedge_margin_benefit_config` using current $\text{DTE}$.
3. **Hedge Benefit Credit**:
   $$\text{Hedge Benefit} = M_{\text{fut}} \times \left(\frac{B\%}{100}\right)$$
4. **Final Hedged Margin Required**:
   $$M_{\text{hedged}} = M_{\text{gross}} - \text{Hedge Benefit}$$

---

### 4.4 Strategy 5: `CONDOR` (Iron Condor Spread)

1. **Pairing**: Combines 1 `CE_CE` Call Spread and 1 `PE_PE` Put Spread on the same underlying.
2. **Formula**:
   $$\text{MaxLoss}_{\text{condor}} = \max\left(\text{MaxLoss}_{\text{CE}}, \text{MaxLoss}_{\text{PE}}\right)$$
   $$M_{\text{hedged}} = \max\left(\text{MaxLoss}_{\text{condor}}, \text{SafetyMargin}\right)$$

---

## 5. Real-Time Step-by-Step Worked Example

### Scenario: NIFTY Bear Call Spread (`CE_CE`)
- **Underlying Spot Price ($\text{LTP}_{\text{spot}}$)**: `₹23,500.00`
- **Current Date**: `2026-09-23` | **Expiry Date**: `2026-10-03` ($\text{DTE} = 10 \text{ days}$)
- **Lot Size**: `75` | **Base Margin %**: `10%`

#### User Positions:
1. `SELL NIFTY 23500 CE`, Qty: `75` (1 Lot), Sell Price: `₹150.00`
2. `BUY NIFTY 23700 CE`, Qty: `75` (1 Lot), Buy Price: `₹50.00`

---

### Step-by-Step Calculation:

#### Step 1: Lookup DTE Tier in `hedge_margin_benefit_config`
- For `hedge_type = 'CE_CE'` and `DTE = 10` (range `8` to `14` days $\rightarrow$ row `id = 2`):
  $$\mathbf{\text{benefit\_percentage} = 60.00\%}$$

#### Step 2: Calculate Standalone Margins ($M_{\text{gross}}$)
- **Short 23500 CE Leg**:
  - SPAN Margin = $23,500 \times 75 \times 10\% = ₹1,76,250$
  - Intrinsic Value = $\max(0, 23,500 - 23,500) \times 75 = ₹0$
  - $M_{\text{short\_CE}} = \mathbf{₹1,76,250.00}$
- **Long 23700 CE Leg**:
  - Premium Paid = $50 \times 75 = \mathbf{₹3,750.00}$
- **Gross Margin ($M_{\text{gross}}$)**:
  $$M_{\text{gross}} = 1,76,250 + 3,750 = \mathbf{₹1,80,000.00}$$

#### Step 3: Calculate Spread Risk ($\text{MaxLoss}$)
- **Strike Width**: $23,700 - 23,500 = 200 \text{ points}$
- **Max Width Risk**: $200 \times 75 = ₹15,000$
- **Net Credit Received**: $(150 - 50) \times 75 = ₹7,500$
- **Max Loss**:
  $$\text{MaxLoss} = 15,000 - 7,500 = \mathbf{₹7,500.00}$$

#### Step 4: Calculate Safety Buffer Margin (5.0%)
$$\text{SafetyMargin} = 23,500 \times 75 \times 5.0\% = \mathbf{₹88,125.00}$$

#### Step 5: Compute Net Blocked Margin & Released Benefit
- **Raw Config Discount**: $1,76,250 \times 60\% = ₹1,05,750$
- **Net Margin Floor Check**:
  $$M_{\text{gross}} - \text{Raw Discount} = 1,80,000 - 1,05,750 = ₹74,250$$
- **Net Blocked Margin ($M_{\text{hedged}}$)**:
  $$M_{\text{hedged}} = \max(7,500, 88,125, 74,250) = \mathbf{₹88,125.00}$$
- **Hedge Benefit Credit**:
  $$\text{Hedge Benefit} = M_{\text{gross}} - M_{\text{hedged}} = 1,80,000 - 88,125 = \mathbf{₹91,875.00}$$

---

### Final Result Summary:
- **Standalone Gross Margin**: `₹1,80,000.00`
- **Net Blocked Margin in Account**: `₹88,125.00`
- **Hedge Benefit Credited Back**: `₹91,875.00`
- **Margin Saved**: **51.04%** relief on total capital required!
