Margin System
Portfolio margin calculation using SPAN-like stress testing
Diffusal uses a portfolio margin system inspired by CME SPAN (Standard Portfolio Analysis of Risk). Unlike isolated margin where each position is collateralized independently, portfolio margin allows netting of positions and calculates collateral requirements based on worst-case portfolio loss under stress scenarios.
Cross-Margin Architecture
Users do not collateralize individual positions. Instead, all positions share a single collateral pool. Each series has four distinct instrument types created in pairs, enabling capital efficiency: a long call can offset some risk from a short put, and premium receivables offset premium obligations.
Portfolio Equity Calculation
The core health metric is Portfolio Equity:
Option Value
For each position, option value is the current mark price times the option balance:
- Long positions (optionBalance > 0): Positive value (asset)
- Short positions (optionBalance < 0): Negative value (obligation)
Premium Balance
Premium balances represent deferred settlement obligations:
- premiumBalance > 0: User is OWED at settlement (receivable, increases equity)
- premiumBalance < 0: User OWES at settlement (obligation, decreases equity)
Premium is an actual obligation that directly affects equity. It accumulates across trades:
- Buyer:
premiumBalance -= price × size - Seller:
premiumBalance += price × size
Deferred Settlement
Important: Deposits do NOT change when opening positions:
- At trade time: Option and premium balances updated; only fees transferred (premium is deferred)
- During holding: Equity = Deposit + (mark × optionBalance) + premiumBalance
- At settlement: Net settlement = (intrinsic × optionBalance) + premiumBalance
Example
See Worked Examples below for detailed equity calculations demonstrating how Option Value and Premium Balance combine to determine portfolio equity.
Portfolio Equity vs Deposited Cash
An important distinction: Portfolio Equity includes the mark-to-market value of positions (Option Value + Premium Balance), while Deposited Cash is only the actual USDC in the vault.
| Metric | Definition | Used For |
|---|---|---|
| Portfolio Equity | Deposit + Option Value + Premium Balance | Margin health checks |
| Deposited Cash | Raw USDC deposit in vault | Settlement obligations |
Why This Matters
A user can have:
- High portfolio equity from profitable long positions (paper gains)
- Low deposited cash (minimal USDC actually in the vault)
- Expiring positions with settlement obligations requiring actual cash
The margin system sees a healthy portfolio (Equity ≥ MM), but at settlement the user may not have enough cash to pay obligations.
Example scenario:
| Item | Value |
|---|---|
| Deposited cash | $2,000 |
| Long-dated calls (paper value) | +$50,000 |
| Short puts expiring tomorrow (worst-case obligation) | -$8,000 |
| Portfolio Equity | $44,000 (healthy) |
| Cash needed at settlement | $8,000 (insufficient!) |
Settlement Readiness Liquidation
To handle this gap, the protocol has a separate liquidation mechanism that triggers when:
- Positions are within 1 day of expiry with net obligations
- Deposited cash is insufficient to cover worst-case settlement obligations
- User has liquidatable assets (non-expiring long positions or premium receivables)
This mechanism uses a waterfall approach:
- First: Liquidate non-expiring LONG positions at penalized mark price
- Then: If shortfall remains, liquidate premium receivables at a discount (default 5%, max 20%)
This is separate from margin-based liquidation that checks equity vs maintenance margin.
See Liquidation - Settlement Readiness for the full mechanism and worked examples.
Stress Testing (SPAN-like)
The margin system uses stress testing to determine required collateral. We test the corners of the risk space to find worst-case portfolio loss.
Stress Scenarios
We apply shocks to both spot price and implied volatility:
| Parameter | Down Shock | Up Shock |
|---|---|---|
| Spot Price | -30% | +30% |
| Implied Volatility | -30% | +50% |
This creates 4 corner scenarios:
| Scenario | Spot Shock | IV Shock | Primary Risk For |
|---|---|---|---|
| 1 | -30% | +50% | Short puts (down + high vol) |
| 2 | -30% | -30% | Long calls (down + vol crush) |
| 3 | +30% | +50% | Short calls (up + high vol) |
| 4 | +30% | -30% | Long puts (up + vol crush) |
4-Corner Stress Testing Diagram
┌──────────────────────────────────────────────────────────────────────────┐
│ CURRENT STATE │
│ ┌────────────────────────────────────────────────────────────────────┐ │
│ │ Portfolio Value at Current Spot & IV │ │
│ └───────────────────────────────┬────────────────────────────────────┘ │
└──────────────────────────────────┴───────────────────────────────────────┘
│
┌─────────────────────────┼─────────────────────────┐
│ │ │
▼ ▼ ▼
┌──────────────────────────────────────────────────────────────────────────┐
│ 4 STRESS SCENARIOS │
├─────────────────────────────────┬────────────────────────────────────────┤
│ │ │
│ ┌───────────────────────┐ │ ┌───────────────────────┐ │
│ │ Scenario 1 │ │ │ Scenario 2 │ │
│ │ Spot: -30% │ │ │ Spot: -30% │ │
│ │ IV: +50% │ │ │ IV: -30% │ │
│ │ Worst for: Short Puts│ │ │ Worst for: Long Calls │ │
│ └───────────┬───────────┘ │ └───────────┬───────────┘ │
│ │ │ │ │
├──────────────┼──────────────────┼──────────────────┼────────────────────┤
│ │ │ │ │
│ ┌───────────┴───────────┐ │ ┌───────────┴───────────┐ │
│ │ Scenario 3 │ │ │ Scenario 4 │ │
│ │ Spot: +30% │ │ │ Spot: +30% │ │
│ │ IV: +50% │ │ │ IV: -30% │ │
│ │Worst for: Short Calls │ │ │ Worst for: Long Puts │ │
│ └───────────┬───────────┘ │ └───────────┬───────────┘ │
│ │ │ │ │
└──────────────┴──────────────────┴──────────────────┴────────────────────┘
│ │
└───────────────────┬─────────────────┘
│
▼
┌──────────────────────────────────────────────────────────────────────────┐
│ MARGIN CALCULATION │
│ ┌────────────────────────────────────────────────────────────────────┐ │
│ │ Stress Loss = max(loss across all 4 scenarios) │ │
│ │ IM = Stress Loss + Buffer (5%) + Notional Buffer (15%) │ │
│ └────────────────────────────────────────────────────────────────────┘ │
└──────────────────────────────────────────────────────────────────────────┘Why These Values?
- ±30% spot: Captures significant market moves (e.g., crypto flash crashes, major news events)
- +50% IV: Volatility spikes are common during market stress (VIX can double in hours)
- -30% IV: Vol crush after events resolve (post-earnings, post-FOMC)
Stressed Option Loss Calculation
For each scenario:
- Recalculate all option premiums with stressed spot and IV using Black-Scholes
- Compute option value change vs current mark
- Track the maximum loss across all scenarios
Note: The Adverse PnL Buffer is calculated as Stress Loss × 0.05 (5% buffer). Premium balances are NOT stressed—they are deterministic obligations added separately.
Required Margin Calculation
Initial Margin (IM)
Where:
- Stress Loss: Maximum option loss across all 4 stress scenarios
- Adverse PnL Buffer: — A 5% safety buffer on top of stress loss
- Notional Buffer: — 15% of total option position notional (mark × |optionBalance|)
Important: Notional is based on option position value (mark × optionBalance), NOT underlying asset exposure.
Why Premium is NOT in Margin
Premium balance is included in equity but NOT in margin requirements:
- Premium is deterministic: Unlike option value (which fluctuates with market conditions), premium is a fixed, known amount
- Already reflected in equity: Equity = Deposit + Option Value + Premium Balance — negative premium already reduces equity
- No double-counting: Adding premium to margin would require users to hold extra capital beyond what's needed
- Settlement readiness: A separate mechanism ensures users can pay their premium obligations at settlement
Maintenance Margin (MM)
Health States
| State | Condition | Action |
|---|---|---|
| Healthy | Equity ≥ MM | Normal trading |
| Liquidatable | Equity < MM | Position can be liquidated |
Worked Examples
All examples use the following market conditions and option prices.
Reference Data
Market Parameters:
| Parameter | Value |
|---|---|
| ETH Spot Price | $3,000 |
| Implied Volatility | 50% |
| Risk-Free Rate | 5% |
| Time to Expiry | 30 days |
Option Prices (Black-Scholes):
| Option | Strike | Moneyness | Current Mark |
|---|---|---|---|
| ETH Call | $3,200 | OTM (strike > spot) | $98.76 |
| ETH Put | $2,800 | OTM (strike < spot) | $80.63 |
Stressed Prices (used for margin calculations):
Each scenario applies multiplicative shocks to spot and IV.
| Scenario | Spot | IV | Call $3,200 | Put $2,800 |
|---|---|---|---|---|
| Current | $3,000 | 50% | $98.76 | $80.63 |
| 1 (Down/Up) | $2,100 | 75% | $5.52 | $711.18 |
| 2 (Down/Down) | $2,100 | 35% | $0.00 | $688.69 |
| 3 (Up/Up) | $3,900 | 75% | $783.69 | $18.02 |
| 4 (Up/Down) | $3,900 | 35% | $716.03 | $0.04 |
Standard Entry Prices: Call @ $150, Put @ $120 (used across examples)
Step-by-Step: Stress Testing All 4 Scenarios
For a mixed portfolio with Long 10 Call and Short 5 Put:
User's Portfolio
| Direction | Option | Strike | Size | Entry | Current Mark | Position Value |
|---|---|---|---|---|---|---|
| Long | Call | $3,200 | +10 | $150 | $98.76 | +$987.60 |
| Short | Put | $2,800 | -5 | $120 | $80.63 | -$403.15 (liability) |
Note: For short positions, the "position value" represents the current liability — what it would cost to buy back the option to close the position.
Portfolio Value Under Stress
Position value formula:
| Scenario | Long Call (×10) | Short Put (×-5) | Portfolio Total |
|---|---|---|---|
| Current | +$987.60 | -$403.15 | +$584.45 |
| 1 | +$55.20 | -$3,555.90 | -$3,500.70 |
| 2 | +$0.00 | -$3,443.45 | -$3,443.45 |
| 3 | +$7,836.90 | -$90.10 | +$7,746.80 |
| 4 | +$7,160.30 | -$0.20 | +$7,160.10 |
Note: Long positions are assets (positive). Short positions are liabilities (negative). The short put liability ranges from -$0.20 (best case, near zero) to -$3,555.90 (worst case).
Stress Loss Calculation
Stress loss = Current portfolio value - Stressed portfolio value
| Scenario | Portfolio Change | Result |
|---|---|---|
| 1 | $584.45 - (-$3,500.70) | +$4,085.15 loss |
| 2 | $584.45 - (-$3,443.45) | +$4,027.90 loss |
| 3 | $584.45 - $7,746.80 | -$7,162.35 (gain) |
| 4 | $584.45 - $7,160.10 | -$6,575.65 (gain) |
Maximum Stress Loss: $4,085.15 (Scenario 1: Spot down, IV up)
Scenario 1 is worst because:
- Long call loses most value (OTM becomes deeper OTM)
- Short put liability increases (put becomes ITM with high IV)
Example A: Long Only (Bounded Margin)
Setup: A user has only long positions with $2,700 USDC deposited.
Option Position:
| Series | Option Balance | Description |
|---|---|---|
| ETH Call $3,200 | +10 | Long 10 calls |
Premium Position:
| Series | Premium Balance | Description |
|---|---|---|
| ETH Call $3,200 | -$1,500 | Paid $150 each for 10 calls |
Step 1: Calculate Option Value and Premium Balance
Option Value (mark × optionBalance):
Premium Balance:
Step 2: Calculate Portfolio Equity
Step 3: Long Margin Calculation
Under worst-case stress (Scenario 2: spot -30% to $2,100, IV -30% to 35%):
Stressed Option Loss:
Stress Loss + Adverse PnL Buffer:
Notional Buffer:
Initial Margin:
Step 4: Calculate Maintenance Margin
Step 5: Determine Health Status
Result: The position is Healthy.
Key insight: Users with long positions typically also hold Premium Payer positions (a separate instrument). Premium is NOT included in the margin requirement—it's already reflected in equity (reducing equity when negative). This prevents double-counting since the premium obligation is deterministic and known.
Settlement Scenarios:
Using the settlement formula:
| Intrinsic at Expiry | Net Settlement | Result |
|---|---|---|
| $0 (deep OTM) | $0 × 10 + (-$1,500) = -$1,500 | User pays $1,500 |
| $100 (slight ITM) | $1,000 + (-$1,500) = -$500 | User pays $500 |
| $150 (breakeven) | $1,500 + (-$1,500) = $0 | No payment |
| $300 (deep ITM) | $3,000 + (-$1,500) = +$1,500 | User receives $1,500 |
Longs CAN be liquidated if their equity falls below maintenance margin.
Example B: Partial Liquidation (Succeeds)
Setup: A user holds a balanced portfolio with $3,200 USDC deposited.
Option Positions:
| Series | Option Balance | Description |
|---|---|---|
| ETH Call $3,200 | +5 | Long 5 calls |
| ETH Put $2,800 | -5 | Short 5 puts |
Premium Positions:
| Series | Premium Balance | Description |
|---|---|---|
| ETH Call $3,200 | -$750 | Paid $150 each for 5 calls |
| ETH Put $2,800 | +$600 | Received $120 each for 5 puts |
| Total | -$150 | Net premium payer |
This portfolio is balanced (equal long and short contracts), but still has downside risk from the short puts.
Step 1: Calculate Option Value and Premium Balance
Option Value (mark × optionBalance):
Premium Balance:
Step 2: Calculate Portfolio Equity
Step 3: Calculate Stress Loss + Adverse PnL Buffer
Under Scenario 1 (spot → $2,100, IV → 75%):
- Call value drops: $98.76 → $5.52
- Put value spikes: $80.63 → $711.18
Current Option Value = +$90.65
Stressed Option Value:
Stressed Option Loss:
Step 4: Calculate Notional Buffer
Step 5: Calculate Initial Margin
Step 6: Calculate Maintenance Margin
Step 7: Determine Health Status
Result: The position is Liquidatable.
Partial Liquidation — detailed calculation:
Step 1: Calculate Debt
Step 2: Calculate Target Notional
The protocol uses notional-based partial liquidation:
Step 3: Liquidate Positions (Longest-Dated First)
With equal expiry (30 days), the protocol liquidates the long call first (sorted by position direction, longs before shorts):
Long call position notional: $493.80
Since $493.80 > Target Notional $181.18, only a partial liquidation of the call position is needed:
Step 4: Calculate Position Transfer (1% penalty)
For long calls (1.84 contracts @ $98.76 mark):
User receives $179.90 for their long positions.
Step 5: Calculate Bounty
Step 6: Re-check Health After Partial Liquidation
New deposit: $3,200 + $179.90 - $39.69 = $3,340.21
Remaining positions:
- Long 3.16 calls: $98.76 × 3.16 = $312.08
- Short 5 puts: $80.63 × (-5) = -$403.15
- New Option Value: -$91.07
- Premium Balance: -$150 (unchanged for remaining positions)
New Equity: $3,340.21 + (-$91.07) + (-$150) = $3,099.14
New margin requirements (recalculated with smaller positions):
- Stressed call: $5.52 × 3.16 = $17.44
- Stressed put: $711.18 × (-5) = -$3,555.90
- New Stressed Option Value: -$3,538.46
- New Stress Loss: -$91.07 - (-$3,538.46) = $3,447.39
- New Stress Loss + Buffer: $3,447.39 × 1.05 = $3,619.76
- New Notional: $312.08 + $403.15 = $715.23
- New Notional Buffer: $715.23 × 15% = $107.28
- New IM: $3,619.76 + $107.28 = $3,727.04
- New MM: $3,727.04 × 80% = $2,981.63
Health Check: $3,099.14 ≥ $2,981.63? YES ✓
Result: Partial liquidation succeeded. User retains 3.16 long calls and 5 short puts.
Key insight: The notional-based approach liquidates only the necessary value. Unlike position-count-based liquidation, the protocol supports partial position liquidation — only 1.84 of the 5 calls were liquidated to hit the target notional. The user retains their short put position and most of their long calls.
Example C: Full Liquidation (Partial Fails)
Setup: A user holds a short-heavy portfolio with only $2,500 USDC deposited.
Option Positions:
| Series | Option Balance | Description |
|---|---|---|
| ETH Call $3,200 | +2 | Long 2 calls |
| ETH Put $2,800 | -10 | Short 10 puts |
Premium Positions:
| Series | Premium Balance | Description |
|---|---|---|
| ETH Call $3,200 | -$300 | Paid $150 each for 2 calls |
| ETH Put $2,800 | +$1,200 | Received $120 each for 10 puts |
| Total | +$900 | Net premium receiver |
This portfolio is heavily short-biased (5:1 short-to-long ratio), creating significant downside risk.
Step 1: Calculate Option Value and Premium Balance
Option Value (mark × optionBalance):
Premium Balance:
Step 2: Calculate Portfolio Equity
Step 3: Calculate Stress Loss + Adverse PnL Buffer
Under Scenario 1 (spot → $2,100, IV → 75%):
- Call value drops: $98.76 → $5.52
- Put value spikes: $80.63 → $711.18
Current Option Value = -$608.78
Stressed Option Value:
Stressed Option Loss:
Step 4: Calculate Notional Buffer
Step 5: Calculate Initial Margin
Step 6: Calculate Maintenance Margin
Step 7: Determine Health Status
Result: The position is Liquidatable.
Partial Liquidation Attempt:
Step 1: Calculate Debt
Step 2: Calculate Target Notional
Step 3: Liquidate Positions (Longest-Dated First)
With equal expiry (30 days), the long call is liquidated first:
Long call position notional: $197.52
Since $197.52 < Target Notional $601.29, the entire call position is liquidated:
Next, the short put (notional $806.30) is partially liquidated:
Step 4: Calculate Position Transfers (1% penalty)
For long calls (2 contracts @ $98.76 mark):
For short puts (5.0 contracts @ $80.63 mark):
Net cash flow: $195.54 - $407.20 = -$211.66 (user pays)
Step 5: Calculate Bounty
Step 6: Re-check Health After Partial Liquidation
New deposit: $2,500 - $211.66 - $208.80 = $2,079.54
Remaining positions:
- Long 0 calls: $0
- Short 5.0 puts: $80.63 × (-5) = -$403.15
- New Option Value: -$403.15
- Premium Balance: +$900 (unchanged)
New Equity: $2,079.54 + (-$403.15) + $900 = $2,576.39
New margin requirements (recalculated):
- Stressed put value: $711.18 × (-5.0) = -$3,555.90
- New Stress Loss: (-$403.15) - (-$3,555.90) = $3,152.75
- Stress Loss + Buffer: $3,152.75 × 1.05 = $3,310.39
- New Notional Buffer: $403.15 × 15% = $60.47
- New IM: $3,310.39 + $60.47 = $3,370.86
- New MM: $3,370.86 × 80% = $2,696.69
Health Check: $2,576.39 < $2,696.69? STILL UNHEALTHY ✗
Step 7: Escalate to Full Liquidation
Since the user is still unhealthy after partial liquidation, the system escalates to full liquidation:
Liquidate remaining 5.0 short puts:
Final User State:
| Item | Amount |
|---|---|
| After partial | $2,079.54 |
| Remaining puts transfer | -$407.20 |
| Final deposit | $1,672.34 |
User retains $1,672.34 but has no positions (fully liquidated).
Key insight: With a 59.9% debt/IM ratio, partial liquidation cannot restore health in this case. The short put positions contribute most of the margin requirement (stress loss), but their current mark value ($80.63) is much lower than their stressed value ($711.18). Even after liquidating 60% of notional, the remaining positions still generate enough stress loss to keep the user underwater. The system correctly escalates to full liquidation.
Example D: Unliquidatable Long Position (With Sufficient Cash)
Setup: A user holds only long positions with sufficient cash (deposit ≥ premium paid) to guarantee they can never be liquidated.
Option Position:
| Series | Option Balance | Description |
|---|---|---|
| ETH Call $3,200 | +10 | Long 10 calls |
Premium Position:
| Series | Premium Balance | Description |
|---|---|---|
| ETH Call $3,200 | -$1,500 | Paid $150 each for 10 calls |
Deposited collateral: $3,000 USDC
Step 1: Calculate Current State (mark = $98.76)
Option Value:
Equity:
Margin components:
Current health: $2,487.60 > $948.10 ✓ Healthy
Step 2: Calculate Absolute Worst Case (Option Value → $0)
Even worse than the stress scenarios—the options become completely worthless:
Equity at worst case:
Margin at worst case (nothing left to lose):
Worst case health: $1,500 > $0 ✓ Still Healthy!
Mathematical Proof: When Long-Only Positions Cannot Be Liquidated
For long-only positions, the absolute worst case is Option Value → $0 (worse than any stress scenario).
Let represent option value and represent premium paid (positive amount):
At any option value :
For liquidation: Equity < MM
Key observation: For any , the right side is negative. So liquidation only happens if , i.e., .
At absolute worst ():
Health check passes if .
In this example:
- Deposit = $3,000
- Premium = $1,500
- $3,000 ≥ $1,500 ✓
Key insight: Since premium is NOT included in margin (only in equity), long-only positions can never be liquidated as long as deposit ≥ premium paid. The margin system only tracks option value risk, which naturally goes to zero as the options expire worthless—and at that point, both margin requirement and equity "floor" out together.
Important caveat: If a user's deposit is less than their premium paid, they can be liquidated even with only long positions. The protection only applies when cash covers premium obligations.
Risk Parameters
| Parameter | Default | Description |
|---|---|---|
INITIAL_MARGIN_RATE | 15% | % of notional for IM buffer |
MAINTENANCE_MARGIN_RATE | 80% | MM as % of IM |
STRESS_SPOT_DOWN | -30% | Spot down shock |
STRESS_SPOT_UP | +30% | Spot up shock |
STRESS_IV_UP | +50% | IV up shock |
STRESS_IV_DOWN | -30% | IV down shock |
ADVERSE_PNL_BUFFER | 0.05 | Buffer rate on stress loss |
Mark Price vs Trade Price
The margin system uses mark price (Black-Scholes theoretical) for all calculations, not the trade price:
| Concept | Source | Used For |
|---|---|---|
| Mark Price | Black-Scholes (oracle inputs) | Margin, PnL, liquidation triggers |
| Trade Price | Market (order book / RFQ) | Actual premium paid/received |
This prevents manipulation: a user cannot avoid liquidation by submitting fake orders at favorable prices.
Premium Balance Recording
When a trade executes, the actual trade price determines the Premium Balance. For example, if a user buys 10 contracts via RFQ at $51.50 each:
- optionBalance: +10 (long position)
- premiumBalance: -$515.00 (paid $51.50 × 10)
If the current mark price is $50.20:
- Option Value: $50.20 × 10 = $502.00
- Total Position Effect: $502.00 + (-$515.00) = -$13.00
The user paid above theoretical (the spread), so their combined Option Value + Premium Balance shows a small loss.
Integration with Trading
Pre-Trade Check
Before any trade, the system verifies:
- New position margin: Would the post-trade portfolio be healthy?
- Sufficient collateral: Does user have enough deposited USDC?
The trade execution updates positions for both buyer and seller, then performs a post-trade margin check to ensure both parties remain healthy. If either fails the margin check, the transaction reverts.
Deposit and Withdrawal
- Deposit: Always allowed (increases equity)
- Withdrawal: Only if post-withdrawal Equity ≥ Initial Margin
Backend Enforcement: These margin checks are enforced both on-chain (contracts revert if post-trade health is violated) and off-chain (backend rejects matches before submission). See Backend Operations for off-chain validation details.
Contract Implementation
The margin system is implemented across several contracts:
| Contract | Role |
|---|---|
| MarginEngine | Core SPAN-like stress testing library |
| DiffusalCollateralVault | Deposit/withdrawal with margin enforcement |
| DiffusalLiquidationEngine | Liquidation when MM is breached |
Related
Protocol Documentation
- Liquidation — What happens when equity falls below MM
- Options Settlement — Settlement flow using margin
Math Documentation
- Margin Calculations — Mathematical formulas and derivations
- Black-Scholes Model — Pricing used in stress calculations
Contract Documentation
- MarginEngine — Core SPAN-like stress testing library
- DiffusalCollateralVault — Deposit/withdrawal with margin enforcement
- DiffusalLiquidationEngine — Liquidation when MM is breached