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

# Risk Management

> How Rails protects accounts through liquidation and proactive order cancellation.

Rails employs two core risk management mechanisms: **Liquidation** and **Proactive Order Cancellation**. Both operate on top of Rails' margin model, where positions are held in one of two modes — **cross margin** (default) or **isolated margin**.

## Margin Modes

Each position is held in one of two modes. The `marginMode` field on each position reports the active mode: `C` for cross, `I` for isolated.

### Cross Margin (Default)

In cross margin mode, your cross margin equity acts as shared collateral across all cross margin positions. Unrealized profits from one position can support another, but deterioration in any position affects the health of the entire cross margin pool. See [Cross Margin Balance](/latest/account-balance#cross-margin-balance) and [Cross Margin Equity](/latest/account-balance#cross-margin-equity) for the component formulas.

### Isolated Margin

In isolated margin mode, each position has its own dedicated margin pool. Collateral allocated to an isolated position is used exclusively for that position — its risk is fully contained and does not affect cross margin positions or other isolated positions. See [Isolated Position Equity](/latest/account-balance#isolated-position-equity) for the formula.

**Order margin behavior:** Opening or increasing an isolated position moves the order margin from `crossMarginBalance` into `isolatedPositionMargin`. Partially closing an isolated position releases the corresponding proportion of margin (plus any realized PnL) back to `crossMarginBalance`.

See [Position Metrics](/latest/position-metrics) and [Account Equity & Balances](/latest/account-balance) for the component formulas.

### Adjusting Isolated Position Margin

Once an isolated position is open, you can manually add or remove margin to tune its risk profile. Both operations are performed via the [Update Margin](/latest/websocket-api/order-creation-stream/update-margin) WebSocket request, which takes the **absolute target value** for `isolatedPositionMargin` — the system computes the difference against the current value and transfers funds between `crossMarginBalance` and `isolatedPositionMargin` accordingly.

**Adding margin** — Transfer funds from your cross margin balance into the isolated position. The maximum amount is your current [Available Balance](/latest/account-balance#available-balance). Adding margin increases `isolatedPositionMargin` and therefore `isolatedPositionEquity`, moving the liquidation price further from the current market price. The transferred amount is deducted from `crossMarginBalance`.

**Removing margin** — Withdraw excess margin from an isolated position back to your cross margin balance. Only `excessMargin` is withdrawable:

```
requiredMargin = indexPrice × ABS(positionQty) / leverage
excessMargin   = MAX(0, isolatedPositionMargin + MIN(0, unrealizedPnL) - requiredMargin)
```

The `requiredMargin` floor ensures the position retains enough collateral to remain open at its current leverage. The `MIN(0, unrealizedPnL)` term applies unrealized losses only — unrealized losses reduce the margin available to withdraw, while unrealized profits do not increase it. If `isolatedPositionMargin + MIN(0, unrealizedPnL)` is already at or below `requiredMargin`, `excessMargin` is `0` and nothing can be withdrawn. Removing margin decreases `isolatedPositionEquity` and moves the liquidation price closer to the current market price.

**Adjusting leverage** — Increasing the leverage on an isolated position lowers `requiredMargin`, which increases `excessMargin` and therefore the amount available to withdraw. The released margin is **not** automatically returned to `crossMarginBalance` — it remains in `isolatedPositionMargin` until you explicitly remove it. Decreasing leverage raises `requiredMargin` and reduces the withdrawable excess.

<Note>
  Removing margin or increasing leverage on an isolated position brings the liquidation price closer to the current market price. Always verify the updated liquidation price before confirming changes.
</Note>

***

## Liquidation

Liquidation conditions differ by margin mode:

| Margin Mode     | Liquidation Condition                                                                                                  |
| --------------- | ---------------------------------------------------------------------------------------------------------------------- |
| Cross margin    | `crossMarginRatio` reaches 100% (See [Cross Margin Ratio](/latest/account-balance#cross-margin-ratio) for the formula) |
| Isolated margin | `isolatedPositionEquity` falls below the position's `maintenanceMargin`                                                |

### Liquidation Process

**Cross margin liquidation**:

1. All open orders on cross margin positions are immediately cancelled.
2. Cross margin positions are reduced/closed at the best available market price as needed to restore account health:
   * Positions **at or above** the market's large-position threshold are closed in **20% stages** (see [Partial Liquidation](#partial-liquidation)), with account health re-evaluated after each stage — staged closing stops early once `crossMarginRatio` falls back below 100%, leaving the remaining position open.
   * Positions **below** the threshold are closed in full in a single step.
3. Any remaining funds after covering losses are returned to your balance.

**Isolated margin liquidation**:

1. All open orders on the position are immediately cancelled.
2. The affected isolated position is closed at the best available market price.
3. Any remaining margin after covering losses is returned to your cross margin balance.
4. All other positions — cross margin and other isolated — are unaffected.

Liquidation fees may apply. Refer to the [Fee Schedule](https://help.rails.xyz/general/pricing-and-fees) for details.

### Partial Liquidation

Closing a large cross margin position with a single market order can cause significant **slippage** — the order eats through the order book, executing at progressively worse prices. To reduce this, Rails liquidates large cross margin positions **in stages** rather than all at once.

| Position                                                     | Liquidation behavior                                |
| ------------------------------------------------------------ | --------------------------------------------------- |
| Cross margin position **at or above** the market's threshold | Closed in stages — **20% of the position per step** |
| Cross margin position **below** the threshold                | Closed in full in a single step                     |
| **Any** isolated margin position                             | Always closed in full                               |

The large-position threshold is set **per market**, because order book depth differs across markets — liquid markets such as BTC-USDT support a higher threshold than thinner ones. Thresholds are calibrated against live order book depth and may be adjusted over time.

| Market   | Large-position threshold |
| -------- | ------------------------ |
| BTC-USDT | 37,500 USDT              |
| Default  | 25,000 USDT              |

**How staged liquidation works:**

1. When liquidation triggers on a large cross margin position, the engine closes **20% of the current position size**.
2. After each step, account health is re-evaluated. Because closing part of the position lowers its maintenance margin requirement, the partial close may be enough to bring `crossMarginRatio` back below 100% — in which case **liquidation stops and the remaining position is preserved**.
3. If the account is still at or above 100% after the step, the next 20% slice follows, subject to the timing rule below.

**Rapid re-trigger — escalation to full close:** Each partial step is given a short window (currently **30 seconds**) to let the order book replenish before the next slice. If the account re-enters liquidation **within that window**, the market is moving sharply against the position and staged closing is no longer protecting it — the engine then **immediately closes the entire remaining position** rather than continuing to slice.

<Note>
  **Why isolated positions are always closed in full.** An isolated position is backed only by its own dedicated margin at the fixed 5% maintenance margin rate. Closing part of it does not improve the margin situation for the remaining portion — it is equally underwater — so staged closing offers no benefit.
</Note>

<Note>
  Partial liquidation reduces the *amount* of maintenance margin required, which is what allows a partial close to restore account health. It does not change the maintenance margin *rate*, which is fixed at 5% for all positions regardless of size.
</Note>

### Estimated Liquidation Price

Rails displays a per-position liquidation price estimate. See [Liquidation Price](/latest/position-metrics#liquidation-price) for the formula.

In **cross margin** mode, the liquidation price for any individual position is an estimate that shifts dynamically with:

* Opening, closing, or modifying any cross margin position (affects `totalCrossMaintenanceMargin`).
* Changes in the index price of any held asset (affects `unrealizedPnL` and therefore `crossMarginEquity`).
* Funding payments accruing to or from your balance.
* Adjustments to isolated positions (affects `crossMarginBalance`).

In **isolated margin** mode, the price is more predictable since the position's equity is self-contained, but it will still shift if margin is added or removed.

Always monitor your [Cross Margin Ratio](/latest/account-balance#cross-margin-ratio) (for cross margin) or [Isolated Position Equity](/latest/account-balance#isolated-position-equity) (for isolated positions) directly rather than relying solely on the displayed liquidation price.

### How to Avoid Liquidation

**For cross margin positions:**

* Deposit additional funds to increase `totalBalance` and raise cross margin equity.
* Reduce position size to lower `totalCrossMaintenanceMargin`.
* Set a stop-loss to automatically close a position before it deteriorates further.
* Before opening new exposure in a market, switch it to isolated margin mode via [Update Margin Mode](/latest/rest-api/update-margin-mode) (requires no open position and no open orders for that market).

**For isolated positions:**

* Use [Update Margin](/latest/websocket-api/order-creation-stream/update-margin) to increase the margin allocated to the isolated position, raising `isolatedPositionEquity`.
* Reduce position size to lower the position's maintenance margin requirement.
* Set a stop-loss to close the position before liquidation is reached.

***

## Proactive Order Cancellation

A resting order that fills under deteriorated market conditions can push maintenance margin above cross margin equity instantly. To prevent this, Rails cancels risky orders *before* they are matched.

### How It Works

The system computes a [Simulated Cross Margin Ratio](/latest/account-balance#simulated-cross-margin-ratio) assuming all qualifying open orders are executed.

If this ratio reaches 90%, all orders that would increase net position exposure are cancelled. Orders that reduce position size (including `reduceOnly` orders) are never cancelled by this mechanism.

### Which Orders Are Included

Only orders that would increase your net position exposure are included in the simulation. Cross margin orders contribute to `simulatedMaintenanceMargin`; isolated margin orders contribute to `isolatedSelectedOrderMargin`, which reduces `simulatedCrossMarginEquity`. The system exempts offsetting/closing orders oldest-first up to the current position size; any remaining quantity that would open new exposure is included.

| Order Type                                         | Included in simulation? |
| -------------------------------------------------- | ----------------------- |
| Cross margin order that increases position size    | ✅ Yes                   |
| Isolated margin order that increases position size | ✅ Yes                   |
| `reduceOnly` order                                 | ❌ No                    |
| Fully offsets existing position                    | ❌ No                    |
| Partially increases net exposure                   | ✅ Excess quantity only  |

<Note>
  **Isolated margin orders affect cross margin health.** When an order on an isolated position is filled, the required order margin moves out of `crossMarginBalance` into `isolatedPositionMargin` — directly reducing cross margin equity. Proactive cancellation simulates that drawdown, guarding against a transfer that would push `crossMarginRatio` to 100% and trigger immediate liquidation of all cross margin positions.
</Note>

### Thresholds at a Glance

| Condition                                               | Trigger                                                        |
| ------------------------------------------------------- | -------------------------------------------------------------- |
| `crossMarginRatio` ≥ 100%                               | Liquidation — all cross margin positions closed                |
| `isolatedPositionEquity` ≤ position `maintenanceMargin` | Liquidation — that isolated position closed; others unaffected |
| `simulatedCrossMarginRatio` ≥ 90%                       | Proactive cancellation — risk-increasing orders cancelled      |
