> For the complete documentation index, see [llms.txt](https://gitbook.hashpower.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://gitbook.hashpower.io/03.margin-system.md).

# Margin System

The HPDX Futures margin system ensures all positions are properly collateralized, protecting both parties from counterparty default risk.

***

## Overview

Margin is collateral deposited into the Futures contract to guarantee position obligations. The system continuously monitors margin levels and automatically liquidates undercollateralized positions.

```
┌────────────────────────────────────────────────────────────────────┐
│                        MARGIN HIERARCHY                            │
├────────────────────────────────────────────────────────────────────┤
│                                                                    │
│     Balance                                                        │
│        │                                                           │
│        ▼                                                           │
│  ┌───────────────────────────────────────────────────────────────┐ │
│  │ Excess Margin (withdrawable)                                  │ │
│  │ ═══════════════════════════════════════════════════════════   │ │
│  │ ▲                                                             │ │
│  │ │ Unrealized Profit                                           │ │
│  │ ├─────────────────────────────────────────────────────────    │ │
│  │ │ Maintenance Margin        ◄── Minimum to avoid liquidation  │ │
│  │ ├─────────────────────────────────────────────────────────    │ │
│  │ │ Unrealized Loss (if any)                                    │ │
│  └───────────────────────────────────────────────────────────────┘ │
│                                                                    │
│  If Balance < Min Margin → LIQUIDATABLE                            │
│                                                                    │
└────────────────────────────────────────────────────────────────────┘
```

***

## Margin Types

### 1. Deposited Collateral (Balance)

The actual token balance held in the contract, represented as wrapped tokens (`wToken`):

### 2. Maintenance Margin

The **minimum collateral** required to hold a position without triggering liquidation:

```
Maintenance Margin = Entry Price × Duration × Quantity × Margin Percent
```

**Components:**

| Factor         | Description                                         |
| -------------- | --------------------------------------------------- |
| Entry Price    | The price per day at which the position was entered |
| Duration       | `deliveryDurationDays` (e.g., 7 days)               |
| Quantity       | Number of contracts (absolute value)                |
| Margin Percent | `liquidationMarginPercent`                          |

**Example:**

```
Entry Price:           4,100,000 (4.10 USDC/day, 6 decimals)
Duration:              7 days
Quantity:              1 contract
Liquidation Percent:   20%

Maintenance Margin = 4,100,000 × 7 × 1 × 0.20
                   = 5,740,000 (5.74 USDC)
```

### 3. Effective Margin (Min Margin)

The **actual margin requirement** after accounting for unrealized P\&L:

```
Effective Margin = Maintenance Margin - Unrealized PnL
```

**For Long Positions:**

```
Unrealized PnL = (Market Price - Entry Price) × Duration × Quantity
```

**For Short Positions:**

```
Unrealized PnL = (Entry Price - Market Price) × Duration × Quantity
```

**Impact:**

| Scenario            | Effect on Effective Margin                       |
| ------------------- | ------------------------------------------------ |
| Profitable position | Lower effective margin (easier to maintain)      |
| Losing position     | Higher effective margin (more collateral needed) |

***

***

## Margin Examples

### Example 1: Opening a Long Position

```
Initial Balance:       100,000,000 (100.00 USDC)
Market Price:          4,100,000 (4.10 USDC/day)
Entry Price:           4,100,000 (at market)
Duration:              7 days
Margin Percent:        20%

Maintenance Margin = 4,100,000 × 7 × 1 × 0.20 = 5,740,000
Unrealized PnL = 0 (just opened)
Min Margin = 5,740,000

Excess Margin = 100,000,000 - 5,740,000 = 94,260,000 ✓
```

### Example 2: Price Moves Against Position

```
Market Price moves to: 4,120,000 (4.12 USDC/day)
Entry Price:           4,100,000

For a SHORT position:
Unrealized PnL = (4,100,000 - 4,120,000) × 7 = -140,000 (loss)
Maintenance Margin = 5,740,000
Effective Margin = 5,740,000 - (-140,000) = 5,880,000

If Balance = 5,500,000:
Deficit = 5,880,000 - 5,500,000 = 380,000 → LIQUIDATABLE
```

### Example 3: Price Moves In Favor

```
Market Price moves to: 4,080,000 (4.08 USDC/day)
Entry Price:           4,100,000

For a SHORT position:
Unrealized PnL = (4,100,000 - 4,080,000) × 7 = 140,000 (profit)
Maintenance Margin = 5,740,000
Effective Margin = 5,740,000 - 140,000 = 5,600,000

Min Margin can go to 0 for highly profitable positions.
```

***

## Liquidations

### What Triggers a Liquidation?

A participant becomes liquidatable when:

```
Balance < Min Margin
```

Liquidation is **permissionless**: any address can submit a liquidation transaction once the condition above holds.

> **Keeper incentives are currently disabled.** The `liquidationFee` parameter is retained in storage and still appears on the liquidation events, but it is fixed at `0` — no fee is transferred to `msg.sender`. The protocol runs the sole keeper for now; the hook is kept for a future incentive iteration.

### Liquidation Process

The **trigger** is a Maintenance Margin breach (`Balance < MM`), but the **goal** is to restore the account to its Initial Margin buffer: liquidation closes only as many lots as needed to bring the balance back to (at most) IM, not necessarily the whole book. The keeper selects the worst-first subset to close off-chain.

Liquidation is split into order and position entry points so that keepers can unwind the cheaper, refund-only orders before touching positions:

```
LIQUIDATION SEQUENCE
════════════════════

1. Keeper detects: Balance < Maintenance Margin
        │
        ▼
2. liquidateOrders(participant)
   └─► Cancel every open order owned by participant
   └─► Reclaim the locked margin
        │
   Still under Maintenance Margin?
        │
        ▼
3. liquidatePositions(participant, ids[])
   └─► Close a keeper-chosen worst-first subset of lots (one tx)
   └─► Settle each lot's PnL at the hashprice oracle price
   └─► Guard: if lots remain, leftover balance must be ≤ IM buffer
       else OverLiquidation (skipped on a full close → bad-debt path)
   └─► Bad debt (if any) is absorbed by the insurance fund
```

`liquidatePositions` closes the keeper-supplied set in **one transaction** and reads margin **once** at the end: if any lots remain and a real `IM > MM` buffer exists, it reverts `OverLiquidation` when the leftover balance ends up **above** IM — i.e. the keeper closed *more* than needed to reach the IM buffer and should have supplied a smaller set. A fully-closed account skips that guard (deep-underwater / bad-debt path). Stale or foreign ids in the supplied set are skipped rather than reverting the batch. The single-lot `liquidatePosition(participant, positionId)` entry point remains available for closing one lot at a time.

All entry points revert with `NotLiquidatable` when the target's `Balance ≥ Maintenance Margin`, and the position entry points revert `OrdersStillOpen` while the participant still has resting orders.

***

## Off-chain Keepers

### Role of a Keeper

A keeper is any off-chain service that:

1. **Monitors** all participant margin utilization via subgraph queries
2. **Alerts** users when utilization exceeds warning thresholds
3. **Submits** `liquidateOrders` / `liquidatePositions` transactions for undercollateralized accounts, sizing the worst-first close so the account lands back within the `[MM, IM]` band

Because liquidation is permissionless, there is no privileged validator role for this flow — anyone can run a keeper. Keeper incentives (`liquidationFee`) are currently disabled (fixed at `0`).

### Margin Utilization Calculation

```
Utilization = Min Margin / Balance × 100%

< 80%:    Safe
80-100%:  Warning (notifications sent)
≥ 100%:   Liquidatable by any keeper
```

***

## Best Practices

### For Traders

1. **Monitor Utilization**: Keep utilization below 80% to avoid warnings
2. **Add Buffer**: Deposit more than the minimum required
3. **Set Alerts**: Use the notification service for margin warnings
4. **Act Quickly**: Top up collateral immediately when warned

### For Miners (Sellers)

1. **Account for Volatility**: Hash prices can move significantly
2. **Conservative Sizing**: Don't over-commit production capacity
3. **Settlement Reserves**: Keep extra margin to cover an adverse mark at maturity settlement

### Utilization Guidelines

| Utilization | Status      | Action                     |
| ----------- | ----------- | -------------------------- |
| 0-50%       | Safe        | Normal operation           |
| 50-80%      | Moderate    | Monitor closely            |
| 80-95%      | Warning     | Consider adding margin     |
| 95-100%     | Critical    | Immediate action required  |
| >100%       | Liquidation | Liquidatable by any keeper |

***

## Read next

* [Trading Guide](/04.trading-guide.md) - Managing orders and positions
* [Settlement](/05.delivery-settlement.md) - Cash settlement of positions at maturity
