> ## Documentation Index
> Fetch the complete documentation index at: https://docs.nilemarkets.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Margin Model

> Isolated margin with variable leverage — IM (2% default) sets entry, MM (1% default) triggers liquidation, equity = lockedMargin + unrealizedPnL

The protocol uses an **isolated margin** model. Each position has independent collateral that determines leverage, liquidation threshold, and maximum loss. Margin rates are snapshotted at position open time.

## Position Equity

```
equity = lockedMargin + unrealizedPnL
```

| Parameter     | Type                                             | Description                                                               |
| ------------- | ------------------------------------------------ | ------------------------------------------------------------------------- |
| lockedMargin  | **Onchain**: stored in Position struct           | USDC collateral locked for this position (mutable via margin adjustments) |
| unrealizedPnL | **Computed**: derived from current forward price | Mark-to-market profit or loss (signed)                                    |

| Condition                     | Status                                                 |
| ----------------------------- | ------------------------------------------------------ |
| `equity >= lockedMargin`      | Healthy — profitable or breakeven                      |
| `MM <= equity < lockedMargin` | Underwater — losses but not liquidatable               |
| `equity < MM`                 | Liquidatable — anyone can close the position           |
| `equity <= 0`                 | Bad debt — losses exceed margin, pool absorbs the rest |

## Two Margin Levels

Every position has two thresholds that create a buffer zone between opening and liquidation.

```
minIM = notional × imFactorBps / BPS_DENOMINATOR
mmThreshold = notional × mmFactorBps / BPS_DENOMINATOR
```

| Parameter        | Default      | Description                                               |
| ---------------- | ------------ | --------------------------------------------------------- |
| imFactorBps      | 200 bps (2%) | Minimum collateral to open. **Onchain**: stored in Config |
| mmFactorBps      | 100 bps (1%) | Liquidation threshold. **Onchain**: stored in Config      |
| BPS\_DENOMINATOR | 10,000       | Fixed constant                                            |

The protocol enforces `imFactorBps > mmFactorBps` — any attempt to violate this reverts. This gap creates the buffer: equity starts above IM and must erode through the buffer before liquidation.

```
|---- Notional (100%) ----|
|-- IM (2%) --|
|- MM (1%) -|
              ^            ^
              |            |
        Liquidation    Position
         threshold      opens here
```

For current parameter values, see [Margin Requirements](/protocol/margin-requirements).

## Variable Leverage

Traders choose their own margin within `[minIM, notional]`. More margin means lower leverage and a larger liquidation buffer.

| Margin       | Leverage | Buffer Before Liquidation | Best For                              |
| ------------ | -------- | ------------------------- | ------------------------------------- |
| 2% (minimum) | 50x      | \~1% adverse move         | High-conviction short-term trades     |
| 5%           | 20x      | \~4% adverse move         | Active trading with moderate risk     |
| 10%          | 10x      | \~9% adverse move         | Balanced risk/reward                  |
| 20%          | 5x       | \~19% adverse move        | Conservative positions, longer tenors |
| 100%         | 1x       | Cannot be liquidated      | Full hedging, maximum safety          |

## Isolated Margin

Each position's margin is completely independent:

* A loss on Position A does not affect Position B
* Maximum loss per position is capped at that position's locked margin
* Free collateral in your account is never at risk from open positions
* Liquidation of one position does not affect others

<Accordion title="Isolated vs cross margin">
  In a cross-margin system, all positions share a common margin pool. A loss on one position can drain margin from others, and the entire account balance is at risk.

  The protocol defines a `MarginMode` enum with `ISOLATED (0)` and `CROSS (1)` values, but only isolated margin is implemented in M2. The isolated model provides clearer risk boundaries and prevents cascading failures.
</Accordion>

## Margin Operations

<Columns cols={2}>
  <Card title="Add Margin" icon="plus">
    Increases locked margin, reducing leverage and increasing the liquidation buffer.

    * Allowed at any time, even when liquidatable (rescue mechanism)
    * Total locked margin cannot exceed notional
    * Amount transfers from free collateral
  </Card>

  <Card title="Remove Margin" icon="minus">
    Decreases locked margin, increasing leverage and freeing collateral.

    * Not allowed when liquidatable
    * Remaining margin must stay above minIM
    * Equity after removal must stay above MM threshold
  </Card>
</Columns>

## Snapshotted Rates

When a position is opened, margin configuration parameters are snapshotted and stored with the position:

| Snapshotted Field             | Description                               |
| ----------------------------- | ----------------------------------------- |
| snapshotImBps                 | Initial margin factor at time of open     |
| snapshotMmBps                 | Maintenance margin factor at time of open |
| snapshotTradingFeeBps         | Trading fee rate at time of open          |
| snapshotLiquidationPenaltyBps | Liquidation penalty at time of open       |
| snapshotOracleFee             | Oracle fee at time of open                |

Admin configuration changes only affect newly opened positions. Existing positions retain the parameters they were opened with — no admin action can retroactively move the liquidation threshold.

## Worked Example

<Accordion title="Full margin lifecycle">
  **Setup:**

  * Notional: 1,000 USDC
  * Margin deposited: 50 USDC (5%, 20x leverage)
  * Minimum IM: 20 USDC (2%)
  * MM threshold: 10 USDC (1%)

  **After -30 USDC unrealized PnL:**

  ```
  Locked margin: 50 USDC
  Equity: 50 + (-30) = 20 USDC
  Status: underwater but above MM (20 > 10)
  ```

  **Add 25 USDC margin:**

  ```
  Locked margin: 75 USDC
  Equity: 75 + (-30) = 45 USDC
  Leverage: 1,000 / 75 = 13.3x (safer)
  ```

  **Price recovers, PnL now +15 USDC:**

  ```
  Locked margin: 75 USDC
  Equity: 75 + 15 = 90 USDC
  ```

  **Remove 30 USDC margin:**

  ```
  Locked margin: 45 USDC (45 >= 20 min IM — allowed)
  Equity: 45 + 15 = 60 USDC (60 >= 10 MM — allowed)
  Leverage: 1,000 / 45 = 22.2x
  ```
</Accordion>

<Accordion title="What happens if PnL loss exceeds locked margin?">
  When a position's market PnL loss exceeds its locked margin (`|marketPnl| > imLocked`), the excess becomes **bad debt**. The trader's realized loss is capped at `imLocked`, and the remaining loss is absorbed by pool equity. A `BadDebt` event is emitted for monitoring. The pool equity floor is clamped to zero — it cannot go negative.
</Accordion>

## Account Equity

Beyond individual positions, the protocol tracks aggregate account equity:

```
accountEquity = collateralBalance + aggregateUnrealizedPnL
```

**Computed**: `aggregateUnrealizedPnL` sums unrealized PnL across all open positions. Available via the subgraph for informational purposes.
