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

# Margin

> Sub-accounts, transfers, margin, and trading capacity.

Margin is computed per sub-account. Deposits land in the main spot account; to trade with leverage, users move collateral into a margin sub-account and place orders against that account.

## Sub-accounts

Sub-accounts isolate balances, positions, and margin checks from each other.

| Index | Type         | Use                                                                  |
| ----- | ------------ | -------------------------------------------------------------------- |
| `0`   | Spot         | Main deposited balances. No borrowing; exempt from margin checks.    |
| `1`   | Cross-margin | Default leveraged account. Collateral is pooled inside this account. |
| `2+`  | Any type     | User-created spot, cross-margin, or isolated sub-accounts.           |

### Account types

| Type         | Behavior                                                                                                               |
| ------------ | ---------------------------------------------------------------------------------------------------------------------- |
| Spot         | Holds owned assets only. Spot trades and withdrawals use this style of balance.                                        |
| Cross-margin | Collateral and positions share one surplus calculation within the sub-account. Isolated-only assets cannot trade here. |
| Isolated     | Collateral and positions are restricted to one asset plus USD. Some assets require isolated margin.                    |

Cross-margin is not global across all of a user's accounts. Two cross-margin sub-accounts have separate collateral pools and separate liquidation risk.

## Creating Accounts And Transfers

There is no separate "create sub-account" endpoint. Create an account by transferring spot balance into a new `target_index` with `target_account_type` set.

`POST /account/transfer/sub-account` moves spot balance between sub-accounts owned by the same user. The request is signed and submitted to the OMS, which forwards it to the clearing engine.

Transfers and withdrawals move spot balances only, so a leveraged position cannot leave a sub-account intact. A margin position has two legs:

* **Asset (base) balance** — the directional exposure. It cannot be transferred or withdrawn while non-zero; [close it](/trading/orders#closing-a-position) by trading it to zero through orders.
* **Quote (USD) balance** — the cash leg. Once the asset balance is zero, `POST /account/transfer/close-position` folds the remaining quote into the sub-account's spot balance, from where it can be transferred (for example, back to the main account) or withdrawn.

A position therefore exits a sub-account only by being closed, never by being moved out with an open asset balance.

The examples below show request shape. Real requests must include a valid signature over `inner` and any required additional signers.

To transfer into an existing account:

```json theme={null}
{
  "inner": {
    "user": "<user public key>",
    "source_index": 0,
    "target_index": 1,
    "transfer_asset": "0",
    "transfer_amount": "1000000000000000000",
    "nonce": 1
  },
  "signature": []
}
```

To create a new account, choose an unused `target_index` and include the type:

```json theme={null}
{
  "inner": {
    "user": "<user public key>",
    "source_index": 0,
    "target_index": 2,
    "target_account_type": "CrossMargin",
    "transfer_asset": "0",
    "transfer_amount": "1000000000000000000",
    "nonce": 1
  },
  "signature": []
}
```

For isolated margin, use `{"Isolated": {"asset": "2"}}` as the target type. Spot sub-accounts use `"Spot"`.

Validation rules:

* `source_index` and `target_index` must differ.
* `transfer_amount` must be non-zero and available in the source account, in 18-decimal internal units.
* If the target exists, omit `target_account_type`; if it does not exist, include it.
* A transfer out of a margin account must leave the source passing margin checks. If a configured minimum sub-account balance applies, the remaining balance must be either zero or above that minimum.
* A transfer into a margin account must satisfy account-type rules and any configured minimum balance.
* Assets with zero collateral factor cannot be transferred out of a spot account.
* Isolated-only assets cannot be moved into cross-margin. An isolated account accepts only its isolated asset and USD.

Rename user-created accounts with `PATCH /account/{user_id}/sub-account/{account_index}/name`. Accounts `0` and `1` keep the reserved names `Spot` and `Margin`. Custom names must be 1-32 characters, cannot contain control characters, and cannot be `Spot` or `Margin`.

## Margin requirements

Margin is computed in USD per sub-account from per-asset risk parameters published onchain in the registry and served by `GET /registry/risk-parameters`. Values in examples are illustrative.

### Requirements and surplus

A sub-account is measured against two thresholds.

* **Maintenance margin (MM)** — the threshold for avoiding liquidation, calculated as **MM surplus**: the distance from liquidation (`distance_from_liquidation` internally, `maintenance_margin_surplus` in the API). An account becomes liquidatable only when it has borrows, has no circuit-broken collateral, and its MM surplus falls below zero.
* **Initial margin (IM)** — the threshold for opening or increasing a position, calculated as **IM surplus**. A risk-increasing order is admitted only if it leaves IM surplus >= zero.

### Risk parameters

MM and IM replace raw market value with conservative, risk-adjusted value. Three per-asset registry parameters set the haircuts:

* **Collateral factor (CF)** — only `CF` of an asset's value counts as collateral, rounded down. Applies to the asset side of MM.
* **Liability factor (LF)** — borrows count at `(2 - LF)` of value, rounded up; e.g. LF = 50% counts a borrow at 1.5x. Applies to the borrow side of MM.
* **IM factor** — for IM, assets are valued at `im_factor * CF * price` and borrows at `(2 - im_factor) * (2 - LF) * price`. `im_factor` is 1.0 at low exposure and steps down toward a floor as net spot-margin exposure in an asset approaches its open-interest cap, tightening IM as the market crowds.

<img src="https://mintcdn.com/tplus/4-smlrZA3aZwuaoy/images/im-factor.svg?fit=max&auto=format&n=4-smlrZA3aZwuaoy&q=85&s=b47959406bddf80175e84a9ce8676244" alt="im_factor steps down from 1.0 toward a floor as spot-margin exposure approaches the open-interest cap" width="520" height="320" data-path="images/im-factor.svg" />

*Illustrative. `im_factor` is 1.0 at low exposure and steps down to a floor as exposure nears the cap; the breakpoints and floor are per-asset registry parameters.*

### Equations

```text theme={null}
equity = sum(assets * price) - sum(borrows * price)

MM surplus = sum(assets * CF * max(oracle, mark))
           - sum(borrows * (2 - LF) * min(oracle, mark))

IM surplus at oracle = sum(assets * im_factor * CF * oracle)
                     - sum(borrows * (2 - im_factor) * (2 - LF) * oracle)

IM surplus at mark = sum(assets * im_factor * CF * mark)
                   - sum(borrows * (2 - im_factor) * (2 - LF) * mark)

USD always uses CF = LF = im_factor = 1 and price = 1 (never haircut).
```

## Margin checks

This is when each requirement is evaluated:

| Check                   | When                  | Condition                                                               |
| ----------------------- | --------------------- | ----------------------------------------------------------------------- |
| Maintenance margin (MM) | Continuous monitoring | Account MM surplus >= zero.                                             |
| Initial margin (IM)     | Trade finalization    | IM surplus >= at both oracle and mark price.                            |
| Pre-flight IM           | Order placement       | IM surplus minus the heavier side's open-order pressure stays positive. |

IM checks apply only to accounts with open borrows.

Risk-reducing trades skip IM requirements. ie. an account with negative IM surplus can submit a trade that still results in a negative IM surplus as long as IM surplus improved.

## Trading capacity and order pressure

Every resting order reserves margin in case it fills. **Trading capacity** is the IM surplus left after that reservation:

```text theme={null}
trading_capacity = IM_surplus - max(buy_side_pressure, sell_side_pressure)
```

`GET /margin/user/{user_id}` reports it as `available_margin`. Both pressure terms are defined below.

### Order pressure

An order's **pressure** is the margin it would consume if it filled, including taker fees. Only the quantity that would *increase* risk counts:

* A buy nets against an existing margin **short in the same asset**; only buy quantity beyond that short adds pressure.
* A sell nets against an existing margin **long in the same asset**; only sell quantity beyond that long adds pressure.
* A reduce-only order's reducing quantity has zero pressure; quantity that would flip or grow exposure is not valid as reduce-only.

Offsets are **per asset**: a short in ETH nets only against ETH buys, never against buys on another book.

For one order's risk-increasing notional:

```text theme={null}
buy_pressure  = notional * (1 - CF * im_factor) + taker_fee
sell_pressure = notional * ((2 - LF) * (2 - im_factor) - 1) + taker_fee
```

Example — a `5,000 USD` order on an asset with `CF = 80%`, `LF = 80%`, `im_factor = 90%`, taker fee `2.5 bps` (`1.25 USD`):

```text theme={null}
buy_pressure  = 5,000 * (1 - 80% * 90%) + 1.25 = 1,401.25 USD
sell_pressure = 5,000 * ((2 - 80%) * (2 - 90%) - 1) + 1.25 = 1,601.25 USD
```

### Aggregating across books

Pressure pools **by direction across every book** in the sub-account: all buys into `buy_side_pressure`, all sells into `sell_side_pressure`, regardless of asset. Capacity subtracts only the larger total:

```text theme={null}
buy_side_pressure  = sum of buy_pressure  over every resting buy,  all books
sell_side_pressure = sum of sell_pressure over every resting sell, all books
```

The `max` is taken **once over the whole sub-account**, not per book. Buys and sells move exposure in opposite directions, so only the heavier side is reserved. Offsets stay per-asset — a BTC short never nets against ETH buys — but residual pressures pool across assets within each side.

Example — one cross-margin sub-account, IM surplus `3,000 USD`, same risk params as above (buy factor `0.28`, sell factor `0.32`, fee `2.5 bps` of notional), resting orders on three books:

| Book | Side | Notional  | Fee      | Pressure     |
| ---- | ---- | --------- | -------- | ------------ |
| ETH  | Buy  | 5,000 USD | 1.25 USD | 1,401.25 USD |
| BTC  | Buy  | 3,000 USD | 0.75 USD | 840.75 USD   |
| SOL  | Sell | 4,000 USD | 1.00 USD | 1,281.00 USD |

```text theme={null}
buy_side_pressure  = 1,401.25 + 840.75 = 2,242.00 USD
sell_side_pressure = 1,281.00 USD
trading_capacity   = 3,000 - max(2,242.00, 1,281.00) = 758.00 USD
```

The SOL sell adds no margin cost while the buy side is heavier. Rest a second `4,000 USD` SOL sell and sell-side pressure becomes `2,562.00 USD`, overtakes the buy side, and capacity drops to `3,000 - 2,562.00 = 438.00 USD`.

### Admission

A new order only adds to its own side, so it can only lower that side's capacity. It is admitted if the resulting capacity stays above a small minimum, else rejected with `InsufficientMargin`.

* Negative capacity triggers [auto-reduce](/trading/orders#auto-reduce), which cancels or shrinks resting orders farthest-from-market first, per side.
* Market-maker accounts: post-only orders skip this pre-flight check. MM accounts are exempt from auto-reduce.

## Account leverage

Leverage reported by the margin API is total notional divided by equity:

```text theme={null}
account_leverage = total_notional / account_equity
```

Example: `60,000 USD` total notional and `15,000 USD` equity reports `4x` leverage.

## Protocol caps

Caps are checked on the proposed post-trade protocol state for every modified non-USD asset. They reject only cap-increasing changes; decreases or unchanged exposure pass.

| Cap                       | Check                                                                                                               | Effect when hit                                                                                     |
| ------------------------- | ------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- |
| Total open interest       | `max(total asset credits, total asset borrows)`, converted to notional at mark and oracle; either price can breach. | Risk-increasing leveraged trades reject; reducing trades pass.                                      |
| Spot-margin open interest | `abs(total asset credits - total asset borrows)` in asset units.                                                    | Approaching it lowers `im_factor`; exceeding it rejects risk-increasing trades.                     |
| Collateral cap            | Sum of that asset's spot balances in margin sub-accounts.                                                           | Additional collateralizing transfers or trades reject once they would increase usage above the cap. |

The checks are:

```text theme={null}
total_OI_qty = max(total_margin_asset_credits, total_margin_asset_borrows)
total_OI_notional = total_OI_qty * price

spot_margin_OI = abs(total_margin_asset_credits - total_margin_asset_borrows)

total_collateralized = sum(asset spot balances in margin sub-accounts)
```

Total OI example: if post-trade ETH total OI would be `2,010 ETH`, mark is `100 USD`, oracle is `99 USD`, and the cap is `200,000 USD`, the mark-side notional is `201,000 USD`, so the trade is rejected. A trade that reduces total OI passes even if the market is already above the cap.

Spot-margin OI example: if aggregate ETH credits are `700 ETH` and aggregate ETH borrows are `950 ETH`, spot-margin OI is `abs(700 - 950) = 250 ETH`. With a `200 ETH` cap, a trade that increases the imbalance is rejected; a trade that brings it toward zero passes.

Collateral cap example: if margin sub-accounts already hold `9,500 ETH` and the ETH collateral cap is `10,000 ETH`, adding `600 ETH` as margin collateral is rejected because post-trade usage would be `10,100 ETH`. Removing collateral passes.

## Margin endpoints

| Endpoint                                                    | Use                                                                                                                                       |
| ----------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
| `GET /inventory/user/{user_id}`                             | Balances and margin positions by sub-account. Optional `sub_account` filter.                                                              |
| `GET /margin/user/{user_id}`                                | Equity, IM/MM surplus, requirements, leverage, liquidation status, unrealized PnL, and optional position breakdowns.                      |
| `POST /account/simulate/{user_id}`                          | Projected margin state for a hypothetical trade. Can apply `pending_transfers` before the trade; simulated notional is capped at 50M USD. |
| `POST /account/transfer/sub-account`                        | Move spot balance between sub-accounts; also creates new sub-accounts.                                                                    |
| `POST /account/transfer/close-position`                     | Move a flat position's residual quote (USD) into spot balance and remove the position. The asset balance must already be zero.            |
| `PATCH /account/{user_id}/sub-account/{account_index}/name` | Rename a user-created sub-account.                                                                                                        |
| `GET /positions/{user_id}`                                  | Open positions by sub-account.                                                                                                            |

See the [Trading API](/api-reference/overview) for authentication, signing, and request schemas. External venue accounts can also count as collateral via [cross-margining](/funds/cross-margining).
