# Liquidation

### Overview

Liquidation is the process by which the risk engine reduces or closes positions when an account's margin falls below maintenance requirements. Backpack employs a multi-tiered liquidation system designed to:

1. Minimize user losses through gradual position reduction
2. Maintain orderbook execution where possible
3. Prevent systemic risk through backstop mechanisms
4. Ensure platform solvency in extreme conditions

Account margin, assets, and positions are valued against mark price to prevent manipulation via last-trade price spikes. Liquidations execute on-book or via other waterfall mechanisms.

***

### Liquidation Trigger

#### When Liquidation Occurs

Liquidation initiates when the **Maintenance Margin Ratio (MMR) reaches 100%**.

```
MMR = Account MMF / Account Margin Fraction
```

Where:

* Account Margin Fraction = Net Equity / Total Exposure Notional
* Account MMF = Σ(Notional Position Size × Position MMF) / Total Exposure Notional

#### What Happens at Trigger

When MMR hits 100%, the liquidation engine executes the following:

1. **Cancel all open orders** — Frees locked margin
2. **Repay borrows and unwind positions** — Borrow repayment and position unwinding happen in parallel

#### Estimated vs. Actual Liquidation Price

The estimated liquidation price displayed in the UI is a **reference only**. It assumes:

* No changes to other positions
* No changes to collateral composition
* No funding payments or interest accrual
* Static mark prices on other assets

**Actual liquidation occurs when MMR ≥ 100%**, which accounts for your total subaccount state.

For accounts with complex exposure (multiple positions, non-USD collateral, active borrows), the system may not display an accurate estimated liquidation price.

***

### The Liquidation Waterfall

Backpack uses a three-stage liquidation waterfall. Each stage activates only if the previous stage cannot fully restore margin health.

```
┌─────────────────────────────────────────────────────────────────┐
│                    LIQUIDATION WATERFALL                        │
├─────────────────────────────────────────────────────────────────┤
│                                                                 │
│  Stage 1: ORDERBOOK LIQUIDATION                                 │
│  ├── Reduce-only orders placed on public orderbook              │
│  ├── Executes against available market liquidity                │
│  ├── Price bands prevent execution at extreme prices            │
│  └── Gradual reduction until margin health restored             │
│                           │                                     │
│                           ▼                                     │
│  Stage 2: BACKSTOP LIQUIDITY PROVIDERS (BLPs)                   │
│  ├── Activates when: ACMF breached                              │
│  ├── Positions transfer to BLP participants                     │
│  ├── Portion of remaining equity paid to backstop fund          │
│  └── BLPs assume position management                            │
│                           │                                     │
│                           ▼                                     │
│  Stage 3: AUTO-DELEVERAGING (ADL)                               │
│  ├── Activates when: ACMF breached AND no BLP capacity          │
│  ├── Profitable counterparties' positions partially closed      │
│  ├── No account or user restrictions after priority scoring     │
│  └── Last resort to maintain system solvency                    │
│                                                                 │
└─────────────────────────────────────────────────────────────────┘
```

> **Price Display Note:** Backstop and ADL transactions are executed off-book (outside the public orderbook). As a result, these execution prices are not reflected in K-line charts.

#### Stage 1: Orderbook Liquidation

**Trigger:** MMR ≥ 100%

**Mechanism:**

* Liquidation engine places **reduce-only market orders** on the public orderbook
* Orders execute against resting liquidity at prevailing market prices
* Liquidation runs in a loop (1 second per tick, 50% probability each tick), reducing 10% of the position per iteration, capped by liquidation capacity
* Process continues until MMR < 100%

**Protections:**

* **Price bands** prevent execution at manipulated prices
* **Gradual reduction** minimizes market impact
* Liquidations are visible on the public orderbook and trade feed

**Partial Liquidation:** The system liquidates only the minimum amount necessary to restore margin health. This means:

* You may retain a reduced position after liquidation
* Remaining equity stays in your account
* If price continues moving against you, additional liquidations may occur

#### Stage 2: Backstop Liquidity Providers (BLPs)

**Trigger:** Account Margin Fraction falls below **Auto-Close Margin Fraction (ACMF)**

**Auto-Close Margin Fraction Calculation:**

```
ACMF = max(Account MMF / ACMF Divisor, Account MMF - ACMF Offset)
```

The ACMF is always less than the MMF, creating a buffer zone between maintenance margin breach and BLP handoff.

**Mechanism:**

1. Remaining position is transferred to Backstop Liquidity Providers
2. A portion of remaining account equity is paid to the backstop liquidity fund
3. BLPs assume management of the position
4. Account margin is zeroed (account remains active for trading) or reduced to safe margin levels

**BLP Requirements:**

* Minimum balance requirements on platform
* Commitment to absorb specified liquidation volumes
* May be required to meet market making standards

#### Stage 3: Auto-Deleveraging (ADL)

See [Auto-Deleveraging (ADL)](#auto-deleveraging-adl) section for complete details.

***

### Liquidation Fees

**Rate:** 1% per fill

**Scope:**

* System-triggered perpetual futures liquidations
* System-triggered borrow/spot-margin liquidations

**Calculation:**

* Fee is applied to the filled notional amount of each liquidation order
* Deducted from liquidation proceeds (not charged separately)

**Exclusions:**

* User-initiated position closes (regular trading fees apply)
* Manual repayment of borrows

***

### Liquidation Process by Product

#### Perpetual Futures Liquidation

1. Open orders cancelled
2. Available balance used to repay borrows
3. Collateral sold to cover remaining borrow liability
4. Position reduced via orderbook
5. If ACMF breached → BLP takeover
6. If BLP capacity exceeded → ADL

**Settlement:** Liquidation proceeds settle in USDC. PnL (positive or negative) is realized immediately.

#### Spot Margin Liquidation

1. Open orders cancelled
2. Available balance used to repay borrows
3. Collateral sold to cover remaining borrow liability
4. If collateral insufficient → additional asset liquidation

**Settlement:** Borrowed assets are repaid to the lending pool. Remaining collateral (if any) stays in account.

#### Borrow Position Liquidation

When a borrow position specifically triggers liquidation:

1. System sells collateral to repay borrow
2. Liquidation fee applied to sold amount
3. Remaining collateral returned to account

**100% Utilization Scenario:** If the lending pool is fully utilized and collateral cannot be redeemed, ADL mechanisms activate.

***

### Auto-Deleveraging (ADL)

#### Overview

Auto-Deleveraging is an **emergency mechanism** that activates when standard liquidation processes cannot complete. ADL ensures:

1. Lenders receive the value of their lent assets
2. The platform remains solvent
3. Losses do not socialize beyond direct counterparties

ADL is a **last resort** used only when:

* Prices move faster than liquidation can execute
* Orderbook liquidity is insufficient
* BLP capacity is exceeded
* Market utilization prevents lend redemption

> **Price Display Note:** ADL transactions are executed directly in the backend, bypassing the public orderbook. These execution prices are not reflected in K-line charts.

#### ADL for Futures Positions

**Trigger Conditions:** Account margin fraction falls below ACMF AND no BLP capacity available

This typically occurs when:

* Liquidating account's position cannot be closed via orderbook
* BLP capacity is insufficient
* Remaining equity cannot cover losses at available prices

**Counterparty Selection:**

ADL does not randomly select counterparties. The system ranks traders with opposing positions by their **ADL Priority Score**:

```
ADL Priority = f(Unrealized PnL, Effective Leverage)
```

Traders with the highest combination of:

1. **Profit** on the position (higher unrealized PnL = higher priority)
2. **Leverage** on the position (higher leverage = higher priority)

…are selected first for ADL.

**No Account Restrictions:** ADL has no account or user restrictions. After all priority scoring (first and second pass), there is a complete matching of longs and shorts regardless of account.

**Lower priority:** Basis trades and delta-neutral positions are deprioritized and will only be ADL'd when other positions are insufficient.

**Execution Process:**

1. System identifies the liquidating position's size and direction
2. Counterparties are ranked by ADL Priority
3. Highest-priority counterparty's position is partially closed
4. Close price = bankruptcy price of the liquidated account
5. Process repeats until liquidating position is fully absorbed

**Example:**

```
Liquidating Account:
  - Long 10 BTC-PERP
  - Bankruptcy price: $50,000
  - Cannot close via orderbook

ADL Queue (Short BTC-PERP holders ranked by priority):
  1. Trader A: Short 5 BTC, +$20,000 PnL, 10x leverage
  2. Trader B: Short 8 BTC, +$15,000 PnL, 5x leverage
  3. Trader C: Short 3 BTC, +$5,000 PnL, 2x leverage

Execution:
  - Trader A: 5 BTC of short closed at $50,000
  - Trader B: 5 BTC of short closed at $50,000
  - Liquidation complete
```

**Notification:**

* ADL fills appear in your fill history with origin `ADL_AUTOCLOSE`
* WebSocket order updates include `O: "ADL_AUTOCLOSE"`

#### ADL for Borrow/Lend Positions

ADL in the borrow/lend system protects lenders when borrowers default or when market conditions prevent normal liquidation.

**Scenario 1: Borrower Default**

When a borrower's account goes bankrupt without holding the borrowed asset:

**Example:**

```
Initial State:
  - Borrower borrows 1 BTC from Lender
  - Borrower sells the BTC, holds USDC
  - BTC price rises significantly
  - Borrower's collateral insufficient to cover borrow

Liquidation:
  - Borrower's account goes bankrupt
  - BTC trading at $100,000
  - Borrower no longer has BTC to return

Resolution:
  - System liquidates Borrower's remaining assets
  - Lender receives $100,000 USDC (notional value)
  - Lender receives value, but in USD not BTC
  - Loan is closed
```

**Key Principle:** The primary mandate is ensuring the Lender receives the value of their lent assets—either in the original token or in notional USD terms at liquidation time.

**Scenario 2: 100% Utilization**

When lending pool utilization reaches 100%, lent assets cannot be redeemed. If a lender with lent collateral faces liquidation:

**Process:**

1. Lender has positions backed by lent collateral
2. Lender's positions move against them → liquidation triggers
3. Liquidation engine attempts to redeem lent assets
4. Pool at 100% utilization → redemption blocked
5. ADL activates

**ADL Resolution:**

6. System identifies borrowers with available collateral
7. Notional USDC (≤ original lend value) transfers: Borrower → Lender
8. Lender's loan position closes
9. Lender now has USDC to cover liquidation
10. Borrower's loan is closed; collateral may have converted

**Borrower Impact:**

* Borrower's loan is forcibly closed
* Borrower's collateral may convert to a different asset
* Borrower's total account value remains unchanged
* No loss to borrower—only asset composition changes

***

### Liquidation in the API

#### Fill Types

The `/fills` endpoint returns all fills including system orders. Use the `fillType` parameter to filter:

| fillType               | Description                          |
| ---------------------- | ------------------------------------ |
| `User`                 | Regular user orders only             |
| `BookLiquidation`      | Orderbook liquidation fills          |
| `Adl`                  | Auto-deleveraging fills              |
| `Backstop`             | Backstop Liquidity Provider fills    |
| `Liquidation`          | All liquidation types                |
| `AllLiquidation`       | All liquidation types combined       |
| `CollateralConversion` | Collateral conversion to settle debt |

#### Order Update Stream Origins

WebSocket `account.orderUpdate` stream includes an `O` field indicating the origin:

| Origin                        | Description                          |
| ----------------------------- | ------------------------------------ |
| `USER`                        | User-initiated order                 |
| `LIQUIDATION_AUTOCLOSE`       | Liquidation engine closed position   |
| `ADL_AUTOCLOSE`               | Auto-deleveraging event              |
| `COLLATERAL_CONVERSION`       | Collateral conversion to settle debt |
| `SETTLEMENT_AUTOCLOSE`        | Settlement of dated market position  |
| `BACKSTOP_LIQUIDITY_PROVIDER` | BLP facilitated the liquidation      |

#### Querying Liquidation Price

Query estimated liquidation price via REST:

```
GET /api/v1/position?symbol=BTC_USDC_PERP
```

Returns `estLiquidationPrice` for the specified position.

**Note:** The `l` field in the position update WebSocket stream is deprecated and returns `0`. Use the REST endpoint for liquidation price queries.

#### Settlement History

Query settlement operations including liquidations:

```
GET /wapi/v1/history/settlement
```

Filter by source:

* `BackstopLiquidation`
* `TradingFeesSystem`
* `RealizePnl`

***

### Viewing Liquidation History

#### In the UI

**Futures Liquidations:**

* Navigate to: Portfolio → Futures → Liquidations
* Direct link: <https://backpack.exchange/portfolio/futures/liquidations>

**Borrow/Lend Liquidations:**

* Navigate to: Portfolio → Lending → Liquidations
* Direct link: <https://backpack.exchange/portfolio/borrow-lend/liquidations>

#### Via API

Use the fill history endpoint with `fillType` filter:

```
GET /wapi/v1/history/fills?fillType=AllLiquidation
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://support.backpack.exchange/technical-docs/trading/liquidation.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
