> For the complete documentation index, see [llms.txt](https://docs.nexus.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.nexus.xyz/math-engine/margin-math.md).

# Margin Math

Every position on the Exchange is backed by collateral. This document derives the complete margin model from the implementation: the initial margin reserved when exposure is opened, the maintenance margin that must be preserved to keep it open, and the account-level aggregates — equity, margin ratio, and available margin — that gate every new order. The model is linear in size and price, parameterized per market by an initial margin rate $$r\_{im}$$ and a maintenance margin rate $$r\_{mm}$$ with $$r\_{mm} < r\_{im}$$, and extended per position by an optional leverage selection that can only make requirements stricter, never looser.

![All per-position quantities fan in to a single account-level equity, which fans back out into the two derived quantities (available margin, margin ratio) that respectively gate admission and trigger liquidation — and every admitted order feeds new position state back into that fan-in.](/files/03EWErZK8wafwLLRbAS1)

*All per-position quantities fan in to a single account-level equity, which fans back out into the two derived quantities (available margin, margin ratio) that respectively gate admission and trigger liquidation — and every admitted order feeds new position state back into that fan-in.*

## Setting

| Symbol         | Name                      | Description                                                                                                                                               | Units                 | Domain    |
| -------------- | ------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------- | --------- |
| $$q$$          | size                      | Position or order size (unsigned magnitude).                                                                                                              | base units (e.g. BTC) | \[0, ∞)   |
| $$P$$          | price                     | Mark price used for margin computation; falls back to the position's entry price when no fresh mark is available.                                         | USDX per base unit    | (0, ∞)    |
| $$r\_{im}$$    | initial\_margin\_rate     | Market initial margin rate, equal to one over the market's maximum leverage.                                                                              | dimensionless ratio   | (0, 1]    |
| $$r\_{mm}$$    | maintenance\_margin\_rate | Market maintenance margin rate; strictly less than the initial margin rate.                                                                               | dimensionless ratio   | (0, 1]    |
| $$L$$          | leverage                  | Account-selected leverage for a market. Unset or zero falls back to the market rate; values of 1 or more map to a rate of 1/L floored at the market rate. | multiplier            | \[1, ∞)   |
| $$s\_0$$       | existing\_signed          | Signed size of the resting position before an order: positive long, negative short, zero flat.                                                            | base units, signed    | unbounded |
| $$o$$          | order\_signed             | Signed size of the order: a buy is positive, a sell is negative.                                                                                          | base units, signed    | unbounded |
| $$C$$          | collateral                | Account collateral on deposit.                                                                                                                            | USDX                  | \[0, ∞)   |
| $$\Pi$$        | total\_unrealized\_pnl    | Sum of unrealized profit and loss across the account's open positions.                                                                                    | USDX                  | unbounded |
| $$N$$          | total\_notional           | Sum of position size times mark price across open positions.                                                                                              | USDX                  | (0, ∞)    |
| $$M\_{used}$$  | total\_initial\_margin    | Sum of initial margin held for existing positions — the stamped allocated margin where set, otherwise the market rate against the current mark.           | USDX                  | \[0, ∞)   |
| $$M\_{avail}$$ | available\_margin         | Equity minus total initial margin held; can be negative when profitable positions offset requirements elsewhere.                                          | USDX                  | unbounded |
| $$\ell$$       | lot\_size                 | Market lot size; position sizes are integer multiples of it.                                                                                              | base units            | (0, ∞)    |
| $$m$$          | mark                      | Fresh mark price for a position's market.                                                                                                                 | USDX per base unit    | (0, ∞)    |
| $$e$$          | entry\_price              | Volume-weighted entry price of a position.                                                                                                                | USDX per base unit    | (0, ∞)    |
| $$s$$          | signed\_size              | Signed position size: +size for a long, −size for a short.                                                                                                | base units, signed    | unbounded |
| $$\varphi$$    | funding\_integral         | Accumulated signed funding on a position; positive means the account has paid funding (a debit against equity), negative means it has received funding.   | USDX                  | unbounded |

## The mechanism

### Margin rates

Each market carries a default initial margin rate $$r\_{im} = 1/L\_{max}$$, where $$L\_{max}$$ is the market's maximum leverage. An account may select a lower leverage $$L$$ for a market, which tightens the rate to $$1/L$$. The two are combined with a maximum so that a leverage selection can never reserve less margin than the market minimum: a selection above $$L\_{max}$$ would imply a rate below the floor and is clamped back to $$r\_{im}$$ (validation rejects such values before storage; the clamp is defense in depth). An unset or zero leverage falls back to the market rate.

$$
r\_{eff} = \max!\left(\frac{1}{L},; r\_{im}\right) \tag{M.1}
$$

### Position margin requirements

The margin reserved to open exposure is linear in size, price, and rate. The rate is the market default $$r\_{im}$$ or, under per-position leverage, the effective rate from (M.1). The implementation computes the product exactly in decimal arithmetic and rounds the result away from zero at 28 decimal places, so the Exchange always requires at least the exact amount, never less.

$$
M\_{init} = q \cdot P \cdot r\_{im} \tag{M.2}
$$

Once open, a position must maintain a smaller cushion computed with the market's maintenance rate $$r\_{mm}$$. Because the implementation enforces $$r\_{mm} < r\_{im}$$ at parameter parse time, maintenance margin is strictly below initial margin for any positive size and price ((M.2)), giving every position a buffer between opening and liquidation thresholds. The same round-up (away from zero, 28 decimal places) applies.

$$
M\_{maint} = q \cdot P \cdot r\_{mm} \tag{M.3}
$$

### Pre-trade exposure

When an order of signed size $$\delta$$ arrives against a resting signed position $$s\_0$$ (positive long, negative short), the Exchange charges margin only for exposure the order *adds*. If the order flips the position through zero, the entire new side is fresh exposure; otherwise only the growth in position magnitude counts, clamped at zero so that pure reductions and closes add nothing. The result is always non-negative and is scaled by the initial margin rate via (M.2) to obtain the pre-trade margin charge; risk-reducing orders therefore charge zero, with the margin they free recognized after the fill rather than pre-credited.

$$
\Delta q = \begin{cases} |s\_0 + \delta| & \text{if } s\_0(s\_0+\delta) < 0 \quad \text{(flip)} \ \max!\big(|s\_0 + \delta| - |s\_0|,; 0\big) & \text{otherwise} \end{cases} \tag{M.4}
$$

### Account-level aggregates

Account equity is collateral plus the sum of unrealized profit and loss across all open positions. It is the account's liquidation-relevant net worth: gains on one position directly offset losses or margin requirements on another under cross margin.

$$
E = C + \Pi \tag{M.5}
$$

The margin ratio normalizes equity ((M.5)) by total position notional, where each position's notional is its size times the current mark price (falling back to entry price when no mark is available). It is undefined — the implementation returns no value — when the account has no open positions or when total notional is zero.

$$
\rho = \frac{E}{N} = \frac{C + \Pi}{\sum\_i q\_i , m\_i} \tag{M.6}
$$

Available margin is equity ((M.5)) minus the initial margin held for every existing position. A position stamped with an allocated margin at fill time (from the account's selected leverage) is held at exactly that amount; otherwise the market rate applies against the current mark per (M.2). The result can be negative, and can also exceed collateral when unrealized gains outweigh margin held — cross-margin offsetting is intentional.

$$
M\_{avail} = E - M\_{used} = (C + \Pi) - \sum\_i M\_{init,i} \tag{M.7}
$$

### Order admission

A new or increasing order is admitted when available margin ((M.7)) is at least the initial margin its quantity requires at the effective rate ((M.2)); equality passes — the comparison is greater-than-or-equal. Reduce-only orders skip the check entirely, since reducing a position releases margin rather than consuming it. On rejection the Exchange surfaces both the required and available amounts.

$$
H = M\_{avail} - q \cdot P \cdot r\_{im} ;; \geq ; 0 \iff \text{order admitted} \tag{M.8}
$$

Inverting (M.2) gives the largest position collateral can support at the mark price and market rate. The exact quotient is floored to an integer number of lots (truncation toward zero), so an account never receives a rounded-up fractional lot: sub-lot collateral yields a hard zero.

$$
q\_{max} = \left\lfloor \frac{C}{P \cdot r\_{im} \cdot \ell} \right\rfloor \cdot \ell \tag{M.9}
$$

### Portfolio aggregates

For cross-margined accounts, portfolio equity recomputes each position's unrealized PnL from fresh mark prices rather than trusting a cached value: signed size times mark-minus-entry, less the accumulated funding integral (positive $$\varphi$$ means funding paid, reducing equity). Isolated-mode positions are excluded — their margin is tracked per position. The formula below shows one position's contribution; the implementation sums over all cross positions.

$$
E\_{pf} = C + \sum\_i \Big( s\_i ,(m\_i - e\_i) - \varphi\_i \Big) \tag{M.10}
$$

The portfolio's initial margin sums (M.2) at the current mark across cross-mode positions. Positions stamped with an allocated margin contribute that amount instead of the market-rate computation, positions in markets with missing parameters are defensively skipped, and a missing mark price falls back to the entry price. The evaluable form shows one unstamped position's term.

$$
M\_{init}^{pf} = \sum\_i q\_i , m\_i , r\_{im,i} \tag{M.11}
$$

The maintenance analogue of (M.11): (M.3) summed across cross-mode positions at fresh marks, with the same entry-price fallback and missing-parameter skip. Because $$r\_{mm} < r\_{im}$$ per market, the portfolio maintenance total never exceeds the portfolio initial total on the same positions.

$$
M\_{maint}^{pf} = \sum\_i q\_i , m\_i , r\_{mm,i} \tag{M.12}
$$

## Invariants

* $$r\_{mm} < r\_{im}$$ for every market, enforced at parameter parse time; hence $$M\_{maint} < M\_{init}$$ ((M.3), (M.2)) for any positive size and price, and the same ordering holds for the portfolio sums.
* Required margin never rounds down: (M.2) and (M.3) round away from zero at 28 decimal places, so the stored requirement is always $$\geq$$ the exact real value.
* The effective initial margin rate is floored at the market rate: $$r\_{eff} \geq r\_{im}$$ ((M.1)), so per-position leverage can only tighten requirements.
* $$\Delta q \geq 0$$ always ((M.4)); pure reductions and exact closes yield exactly $$0$$, and a flip charges only the new side, never the full order size.
* Margin is monotone: $$M\_{init}$$ strictly increases in both size and price for fixed positive parameters.
* (M.9) always returns an integer multiple of the lot size, and collateral below one lot's requirement yields exactly zero — never a rounded-up position.
* Reduce-only orders unconditionally pass the margin check; the admission boundary in (M.8) is inclusive (available equal to required is admitted).
* Isolated-mode positions are excluded from every portfolio aggregate ((M.10), (M.11), (M.12)); their margin is checked per position.

## Worked example

Consider a BTC market with $$r\_{im} = 0.05$$ (20x maximum leverage), $$r\_{mm} = 0.025$$, and lot size $$\ell = 0.001$$, with the mark at $$P = 50{,}000$$. An account deposits $$C = 10{,}000$$ of collateral and submits a buy for $$q = 1$$ BTC with no leverage override. By (M.2) the order requires $$1 \times 50{,}000 \times 0.05 = 2{,}500$$ of initial margin. With no open positions, equity equals collateral ((M.5)), available margin is $$10{,}000$$ ((M.7)), and the headroom in (M.8) is $$10{,}000 - 2{,}500 = 7{,}500 \geq 0$$, so the order is admitted. Had the account instead selected 10x leverage, (M.1) gives $$r\_{eff} = \max(1/10, 0.05) = 0.10$$ and the requirement doubles to $$5{,}000$$.

After the fill the account is long $$s\_0 = +1$$ BTC at entry $$50{,}000$$. Its margin ratio ((M.6)) is $$\rho = 10{,}000 / 50{,}000 = 0.20$$, comfortably above the maintenance rate. The largest position this collateral could have supported is given by (M.9): the exact quotient $$10{,}000 / (50{,}000 \times 0.05) = 4$$ BTC is already a clean lot multiple, so $$q\_{max} = 4$$. With only $$2{,}750.50$$ of collateral the quotient would be $$1.1002$$ BTC, floored to $$1.100$$ — the fractional $$0.0002$$ above the lot grid is discarded, never rounded up.

Now suppose the account sells $$3$$ BTC against its $$+1$$ BTC position. By (M.4) the trade flips through zero: $$s\_0 + \delta = 1 - 3 = -2$$, so the added exposure is $$|{-2}| = 2$$ BTC — the new short side only, not the full 3 BTC order. The pre-trade charge is therefore $$2 \times 50{,}000 \times 0.05 = 5{,}000$$ via (M.2). A sell of at most $$1$$ BTC would have added zero exposure and, if flagged reduce-only, would bypass the margin check entirely.

## Analysis

### Sensitivity

Elasticities ε = (∂y/∂x)·(x/y), computed numerically from the verified expressions at each worked-example point. |ε| > 1 means the output moves more than proportionally with that input.

| Expression                      | Input                     | Elasticity ε |
| ------------------------------- | ------------------------- | ------------ |
| `effective_initial_margin_rate` | leverage                  | -1           |
| `effective_initial_margin_rate` | initial\_margin\_rate     | 0            |
| `initial_margin_required`       | size                      | 1            |
| `initial_margin_required`       | price                     | 1            |
| `initial_margin_required`       | initial\_margin\_rate     | 1            |
| `maintenance_margin_required`   | size                      | 1            |
| `maintenance_margin_required`   | price                     | 1            |
| `maintenance_margin_required`   | maintenance\_margin\_rate | 1            |
| `added_exposure`                | order\_signed             | 1.5          |
| `added_exposure`                | existing\_signed          | -0.5         |
| `equity`                        | total\_unrealized\_pnl    | 0.8          |
| `equity`                        | collateral                | 0.2          |
| `margin_ratio`                  | collateral                | 1            |
| `margin_ratio`                  | total\_notional           | -1           |
| `margin_ratio`                  | total\_unrealized\_pnl    | 0            |
| `available_margin`              | total\_unrealized\_pnl    | 1.053        |
| `available_margin`              | total\_initial\_margin    | -0.3158      |
| `available_margin`              | collateral                | 0.2632       |
| `order_margin_headroom`         | available\_margin         | 1.333        |
| `order_margin_headroom`         | size                      | -0.3333      |
| `order_margin_headroom`         | price                     | -0.3333      |
| `order_margin_headroom`         | initial\_margin\_rate     | -0.3333      |
| `max_position_size`             | collateral                | 125          |
| `max_position_size`             | price                     | -125         |
| `max_position_size`             | initial\_margin\_rate     | -6.25        |
| `max_position_size`             | lot\_size                 | 0            |
| `portfolio_equity`              | mark                      | 2.4          |
| `portfolio_equity`              | entry\_price              | -1.6         |
| `portfolio_equity`              | signed\_size              | 0.8          |
| `portfolio_equity`              | collateral                | 0.2          |
| `portfolio_equity`              | funding\_integral         | 0            |
| `portfolio_initial_margin`      | size                      | 1            |
| `portfolio_initial_margin`      | mark                      | 1            |
| `portfolio_initial_margin`      | initial\_margin\_rate     | 1            |
| `portfolio_maintenance_margin`  | size                      | 1            |
| `portfolio_maintenance_margin`  | mark                      | 1            |
| `portfolio_maintenance_margin`  | maintenance\_margin\_rate | 1            |

![Sensitivity tornado — Initial margin required](/files/JGGTcbOONtqaBNanIrmp)

![Sensitivity tornado — Added exposure](/files/O3GFF452mWU2tNjEXskQ)

![Sensitivity tornado — Maximum position size](/files/EYQi35NWa5QnEVfoYAVW)

### Response curves

![Required initial margin grows linearly in price, with lower leverage (a higher effective rate) reserving proportionally more; position size is held at 1 unit.](/files/g9PmW80VidySGXTa3q9l)

*Required initial margin grows linearly in price, with lower leverage (a higher effective rate) reserving proportionally more; position size is held at 1 unit.*

![Against a +1 long, sells up to the position size add zero exposure, larger sells charge only the new short side, and buys charge the full increment; the existing position is held at +1.](/files/bHAFtr24Rfu4TtX4rWnG)

*Against a +1 long, sells up to the position size add zero exposure, larger sells charge only the new short side, and buys charge the full increment; the existing position is held at +1.*

![Maximum openable size scales linearly with collateral but steps down to the lot grid, and collateral below one lot's requirement yields exactly zero; price and margin rate are held constant.](/files/779CEUviCPNA4iQqKL6R)

*Maximum openable size scales linearly with collateral but steps down to the lot grid, and collateral below one lot's requirement yields exactly zero; price and margin rate are held constant.*

### Parameter space

Joint parameter effects evaluated from the verified expressions over 2-D grids.

![The zero-headroom line available\_margin = size × 2,500 USDX separates accepted from rejected orders at 50,000 USDX price and 5% initial margin, with rejection depth growing linearly with size.](/files/nUSOT7J7KAT3ZK20ywyE)

*The zero-headroom line available\_margin = size × 2,500 USDX separates accepted from rejected orders at 50,000 USDX price and 5% initial margin, with rejection depth growing linearly with size.*

![Along the curve leverage = 1/initial\_margin\_rate the binding constraint switches from the trader's chosen leverage to the market floor, so higher leverage requests stop reducing margin once they cross it.](/files/apVJg8H4WdTyr72k48Q7)

*Along the curve leverage = 1/initial\_margin\_rate the binding constraint switches from the trader's chosen leverage to the market floor, so higher leverage requests stop reducing margin once they cross it.*

## References

* Derived from and adversarially verified against the Exchange's Rust implementation and its test suite.
* Sibling model: [funding-rate](/math-engine/funding-rate.md)
* Sibling model: [insurance-fund](/math-engine/insurance-fund.md)
* Sibling model: [liquidation-engine](/math-engine/liquidation-engine.md)
* Sibling model: [oracle](/math-engine/oracle.md)
* Sibling model: [order-book](/math-engine/order-book.md)
* Sibling model: [position-tracker](/math-engine/position-tracker.md)
* Sibling model: [settlement](/math-engine/settlement.md)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## 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, and the optional `goal` query parameter:

```
GET https://docs.nexus.xyz/math-engine/margin-math.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

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.
