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

# Liquidation Logic

> Exchange-specific margin-based liquidation simulation in backtest

## Why Simulate Liquidation?

A leveraged backtest without liquidation simulation is fiction. A 10× leveraged position can be liquidated by a **10% adverse move** — but without liquidation modeling, the backtest simply holds through the drawdown and recovers. This produces impossibly good results.

ClyptQ simulates liquidation **per exchange** with the correct maintenance margin rate (MMR), liquidation fee, and margin ratio formula for each venue.

## How Liquidation Works

### The Check

After every tick, for every futures account with open positions, ClyptQ checks whether the account should be liquidated:

```
For each futures account:
  1. Calculate unrealized PnL across all positions
  2. Calculate equity = cash + unrealized_pnl - liquidation_fee
  3. Calculate maintenance margin = total_notional × MMR
  4. Compute margin ratio (exchange-specific formula)
  5. If margin ratio breaches threshold → LIQUIDATE all positions
```

### Two Margin Ratio Formulas

Exchanges use one of two formulas to compute margin ratio:

**Inverted (Binance):**

```
margin_ratio = (maintenance_margin / equity) × 100

Liquidation trigger: margin_ratio ≥ 100%
```

When equity falls below maintenance margin, the ratio exceeds 100% and liquidation triggers.

**Normal (Bybit, Gateio, Kraken, Coinbase):**

```
margin_ratio = equity / maintenance_margin

Liquidation trigger: margin_ratio < threshold (typically 1.0)
```

When equity falls below maintenance margin, the ratio drops below 1.0 and liquidation triggers.

Both formulas express the same economic condition — equity insufficient to cover margin requirements — but the numbers and threshold directions differ.

## Exchange-Specific Parameters

| Exchange     | Default MMR | Liquidation Fee | Threshold | Formula  | Notes                                |
| ------------ | ----------- | --------------- | --------- | -------- | ------------------------------------ |
| **Binance**  | 1.3%        | 0.75%           | 100%      | Inverted | Tiered MMR by position size          |
| **Bybit**    | 0.5%        | 0.6%            | 1.0       | Normal   | Lower MMR, more leverage allowed     |
| **Gateio**   | 1.0%        | 0.5%            | 1.5       | Normal   | Higher threshold (more conservative) |
| **Coinbase** | 6.67%       | 1.0%            | 1.0       | Normal   | CFTC regulated, MM = IM × ⅔          |
| **Kraken**   | 2.0%        | 1.5%            | 1.0       | Normal   | Regulated, higher fees               |

<Info>
  The **Default MMR** values are Tier 1 (smallest position) rates. In reality, exchanges use tiered MMR where larger positions require higher maintenance margin. ClyptQ supports **dynamic tier resolution** for exchanges that expose tier data via CCXT: Binance (requires API key), Bybit, Gateio, and Kraken fetch real-time tier brackets. Coinbase does not expose tier data — it always uses the static default (6.67%).
</Info>

## Liquidation Calculation Step by Step

### Example: Binance Futures (Inverted Formula)

```
Account state:
  Cash: $5,000
  Position: Long 2 BTC at entry $50,000
  Current price: $47,500 (5% decline)

Step 1: Unrealized PnL
  pnl = (current_price - entry_price) × quantity
  pnl = ($47,500 - $50,000) × 2 = -$5,000

Step 2: Liquidation fee estimate
  total_notional = |2 × $47,500| = $95,000
  liquidation_fee = $95,000 × 0.0075 = $712.50

Step 3: Equity
  equity = cash + unrealized_pnl - liquidation_fee
  equity = $5,000 + (-$5,000) - $712.50 = -$712.50

Step 4: Maintenance margin
  maintenance_margin = total_notional × MMR
  maintenance_margin = $95,000 × 0.013 = $1,235

Step 5: Margin ratio (Binance inverted)
  margin_ratio = (maintenance_margin / equity) × 100
  equity is negative → margin_ratio = ∞

Step 6: Check
  ∞ ≥ 100% → LIQUIDATED ✓
```

All positions are closed at market price, liquidation fee is deducted, and the account's remaining equity (if any) is the post-liquidation balance.

### Example: Bybit Futures (Normal Formula)

```
Account state:
  Cash: $10,000
  Position: Short 1 BTC at entry $50,000
  Current price: $54,500 (9% adverse move)

Step 1: Unrealized PnL
  pnl = (entry_price - current_price) × |quantity|  (short)
  pnl = ($50,000 - $54,500) × 1 = -$4,500

Step 2: Liquidation fee estimate
  total_notional = |1 × $54,500| = $54,500
  liquidation_fee = $54,500 × 0.006 = $327

Step 3: Equity
  equity = $10,000 + (-$4,500) - $327 = $5,173

Step 4: Maintenance margin
  maintenance_margin = $54,500 × 0.005 = $272.50

Step 5: Margin ratio (Bybit normal)
  margin_ratio = equity / maintenance_margin
  margin_ratio = $5,173 / $272.50 = 18.98

Step 6: Check
  18.98 > 1.0 → SAFE ✓
```

### Example: Gateio (Higher Threshold)

Gateio uses a **1.5 threshold** instead of 1.0 — meaning liquidation triggers earlier than on other exchanges:

```
Same setup, equity = $400, maintenance_margin = $272.50

margin_ratio = $400 / $272.50 = 1.47

On Bybit:   1.47 > 1.0 → SAFE
On Gateio:  1.47 < 1.5 → LIQUIDATED ✓
```

This is why exchange-specific simulation matters — the same position can be liquidated on one exchange and safe on another.

## What Happens at Liquidation

When liquidation triggers:

1. **All positions in the account are closed** at current market price (with slippage applied)
2. **Liquidation fee is deducted** from equity
3. **ExecutionResult** is created with `trigger_type: "liquidation"` metadata
4. **Console warning** is printed: `⚠️ [LIQUIDATION] binance:futures: 2 positions liquidated`
5. **Remaining equity** (if positive) stays as cash in the account

The ExecutionResult includes full audit data:

```python theme={null}
result.raw_response = {
    "trigger_type": "liquidation",
    "equity_before": 1235.50,
    "maintenance_margin": 1300.00,
    "margin_ratio": 105.2,         # Exceeded 100% (Binance)
    "mmr_used": 0.013,
    "liquidation_fee": 712.50,
    "pnl": -4287.50,
}
```

## Cross vs Isolated Margin

### Cross Margin (Default)

All positions in an account share the same margin pool. The entire account balance is used as collateral:

```
Account: $10,000 cash
Position A: Long 1 BTC ($50,000 notional)
Position B: Long 10 ETH ($15,000 notional)

Total notional: $65,000
Maintenance margin: $65,000 × 1.3% = $845
Equity: $10,000 + unrealized_pnl_A + unrealized_pnl_B
```

A loss on Position A is offset by the full account balance, including unrealized gains on Position B.

### Isolated Margin

Each position has its own margin allocation. Losses on one position cannot consume margin from another:

```
Position A: $5,000 isolated margin
Position B: $5,000 isolated margin

Position A can only lose $5,000 — Position B's margin is protected.
```

<Info>
  ClyptQ's current backtest uses **cross margin** by default (all positions share the account balance). Isolated margin simulation is planned for a future release.
</Info>

## Configuration

### Default Behavior

No configuration needed. Liquidation is checked automatically for every futures account after each tick:

```python theme={null}
# This is enough — liquidation uses exchange defaults
AccountSpec(
    exchange="binance",
    market_type="futures",
    base_currency="USDT",
    initial_cash=10_000,
    max_leverage=10.0,
)
```

### Custom MMR Override

For tiered positions or custom risk parameters:

```python theme={null}
# In the executor's check_liquidation call, you can override MMR
# This is useful for simulating large positions in higher tiers
# (e.g., Binance Tier 5 has 5% MMR for > $40M notional)
```

## Impact on Strategy Design

### Leverage Selection

Higher leverage means less equity buffer before liquidation:

| Leverage | Equity as % of Position | Liquidation at % Loss   |
| -------- | ----------------------- | ----------------------- |
| 1×       | 100%                    | Never (spot equivalent) |
| 3×       | 33%                     | \~30% adverse move      |
| 5×       | 20%                     | \~18% adverse move      |
| 10×      | 10%                     | \~8% adverse move       |
| 20×      | 5%                      | \~3.5% adverse move     |

Without liquidation simulation, a 10× backtest survives a 50% drawdown and "recovers." With simulation, it gets liquidated at \~8% and the equity goes to near zero.

### Stop Loss as Liquidation Prevention

Using stop-loss orders prevents liquidation and preserves capital:

```python theme={null}
FuturesTargetPositionIntention(
    ...
    leverage=5.0,
    stop_loss=entry_price * 0.95,  # 5% stop (well before 18% liq)
)
```

ClyptQ's TP/SL simulation works together with liquidation — if the stop-loss doesn't trigger (e.g., gap down), liquidation still fires as a backstop.

## Related Pages

<CardGroup cols={2}>
  <Card title="Exchange Specifics" icon="building-columns" href="/backtesting/exchange-specifics">
    Full exchange parameter tables including margin tiers
  </Card>

  <Card title="Cost Models" icon="receipt" href="/backtesting/cost-models">
    Fee structures that interact with liquidation costs
  </Card>
</CardGroup>
