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

# The Math

> The exact formulas behind pricing, margin, funding, and liquidation

The other architecture pages explain the ideas. This page is the precise
reference underneath them: the actual formulas the program checks on every
instruction. All of it runs as unsigned integer math, every `a * b / c` goes
through a 128-bit intermediate, and division always leans against the
trader rather than silently rounding in their favor.

## Units and scale

| Constant | Value | Meaning |
| - | - | - |
| `PRICE_SCALE` | 10000 | prices carry 4 decimals |
| `BPS_DENOM` | 10000 | basis point denominator |
| `RATE_SCALE` | 1,000,000 | funding rate precision |
| `FUNDING_PERIOD` | 28800 | seconds over which a full funding rate is paid |
| `MAX_BAND_BPS_CAP` | 1000 | the widest an oracle band can be set, 10% |
| `MAX_BOOK_AGE_CAP` | 3600 | the longest a book can be configured to stay fresh |

```
notional = price * size / PRICE_SCALE
```

## Market parameters

Enforced once, at `init_market`, so a market can never be created in a state
that's already unsafe:

```
0 < mmr < imr <= BPS_DENOM
0 < leverage <= BPS_DENOM / imr
oi_cap > 0
pro oracle: oracle_max_age <= 15s
```

## Order book price

Covered in full on [The Shared Book](https://docs.devnet.perp.ordr.trade/architecture/shared-book.md):

```
price = mid + offset * tick_size
```

`|offset| * tick_size` has to fit in 64 bits, and a negative offset can
never push the price to zero or below. Bids sort by highest offset, asks by
lowest, ties broken by time.

## Oracle band

A fill is only ever allowed within a band around the oracle price:

```
band = oracle * max_band_bps / BPS_DENOM
lo   = max(0, oracle - band)
hi   = oracle + band
```

Walking the book best-first, the first order outside `[lo, hi]`, worse than
the trader's own limit, or already fully matched stops that side's fill
there.

## Book freshness

The freshness check behind
[Staying fresh without racing anyone](https://docs.devnet.perp.ordr.trade/architecture/shared-book.md#staying-fresh-without-racing-anyone):

```
fresh = now_ms <= last_seqno + max_book_age_ms
     && last_seqno <= now_ms + 60_000
```

An open or close needs a fresh book. A stale one simply accrues no funding
that pass.

## Batch clearing (`uncross`)

The core of [Batching and Liquidations](https://docs.devnet.perp.ordr.trade/architecture/batching-and-liquidations.md).
Only orders from a strictly earlier slot are eligible. Buys (open long,
close short) clear against the asks, sells against the bids, and any level
outside the oracle band or past a trader's limit is ignored:

```
walk levels best price first:
  demand(px) = every eligible order's size whose limit accepts px
  supply    += this level's size
  stop at the first level where supply >= demand(px)

clear_px = that level's price
fill_i   = size_i                               if supply covered demand
fill_i   = floor_to_lot(size_i * supply/demand)  at the level that didn't
```

Every fill at that price pays the same batch VWAP of the levels actually
consumed, rounded up for buys and down for sells:

```
vwap = sum(filled_k * price_k) / total_filled
```

## Open margin check

Checked twice: once at `submit_order`, and again inside `uncross` against
whatever the oracle has become by then, using the worst price the batch
could still realistically give it:

```
worst   = long ? limit : max(limit, best_bid)
imr_req = worst price's margin requirement at size
adverse = how far the limit sits on the losing side of the oracle
imr_o   = the oracle price's margin requirement at size

margin must cover imr_req, and (margin - adverse) must cover imr_o
```

Passing both checks up front is what guarantees a batch fill never needs to
be unwound later for being under-margined. The reserved `margin` moves from
`free_balance` to `locked_balance` at submit; once filled,
`margin_used = margin * filled / size`, rounded up, becomes the position's
real margin, and `claim` refunds whatever wasn't used.

## Liquidation key

What a market's liquidation heap, see
[Batching and Liquidations](https://docs.devnet.perp.ordr.trade/architecture/batching-and-liquidations.md#what-one-uncross-call-does),
actually sorts on: the price at which a position's equity would exactly
equal its maintenance requirement, nudged slightly toward the current price
so it triggers a touch early rather than a touch late:

```
m_px  = margin * PRICE_SCALE / size
long:  key = (entry - m_px) * BPS_DENOM / (BPS_DENOM - mmr) * (1 + 10bps)
short: key = (entry + m_px) * BPS_DENOM / (BPS_DENOM + mmr) * (1 - 10bps)
```

Longs sit in a max-heap on this key, shorts in a min-heap, so the single
worst position on each side is always the one on top. The key is only ever
a trigger, not a verdict: health is recomputed exactly at the moment of
liquidation, and a position that's actually healthy again gets re-keyed to
just past the oracle instead of being touched.

## PnL

```
long:  pnl = (exit - entry) * size / PRICE_SCALE
short: pnl = (entry - exit) * size / PRICE_SCALE
```

## Funding

### Accrual, sampled every `uncross`

The mark is the midpoint of the real best bid and ask, and only counts when
the book is fresh, genuinely two-sided, uncrossed, inside the oracle band,
and each best level holds at least 10 lots; otherwise there's no mark this
pass and nothing accrues. The index is the oracle price itself:

```
dt             = min(now - funding_ts, 60s)
num            = funding_rate * dt + funding_rem
funding_index += num / FUNDING_PERIOD
funding_rem    = num % FUNDING_PERIOD

funding_rate = clamp((mark - index) * RATE_SCALE / index, ±max_funding_rate)
             = 0 when there is no valid mark this pass
```

`max_funding_rate` can never be set above 1% per funding period, and the
crank ticks at least every 60 seconds specifically so a quiet market still
accrues the right amount over time, not zero.

### Payment, netted in at close or liquidation

```
d        = funding_index - entry_funding_index
notional = size * mark / PRICE_SCALE
payment  = |d| * notional / RATE_SCALE
```

A long pays when `d > 0` and receives when `d < 0`; a short is the mirror
of that. Funding is never deducted from margin as it accrues, only folded
into the final result: `net = pnl ± payment`.

## Uncross fee

Whoever's `uncross` or `claim` call actually settles a fill earns 1 basis
point of it, unless the trader settled their own order:

```
fee = (vwap * filled / PRICE_SCALE) * 1 / BPS_DENOM
```

An open reserves the worst-case fee at submit time alongside its margin,
and refunds whatever wasn't owed once it's actually filled. A close pays it
straight out of the close proceeds, capped at whatever those proceeds are.

## Close and claim

What `uncross` computes for a filled close:

```
margin_part = slot.margin * filled / slot.size
net         = pnl(entry -> vwap, filled) ± funding(oracle)
```

What `claim` actually pays out. A profit is paid from the pool first, then
the market's insurance fund if the pool alone falls short, and if even that
isn't enough, the rest is left as an IOU for a later claim once the pool's
balance recovers:

```
paid = min(net, pool balance) + min(net - that, insurance balance)
free_balance   += margin_part + paid
locked_balance -= margin_part
```

A loss is paid to the pool, capped at the position's own margin, never more:

```
loss = min(net, margin_part)
free_balance   += margin_part - loss
locked_balance -= margin_part
```

Invariant: a trader's vault balance always equals
`free_balance + locked_balance`.

## Liquidation

Checked inside every `uncross`, up to 8 positions per side per call:

```
net       = pnl(entry -> oracle) ± funding(oracle)
eff       = margin ± net
maint_req = (oracle * size / PRICE_SCALE) * mmr / BPS_DENOM

liquidatable = eff < 0 || eff < maint_req
```

### How the liquidated margin splits

```
remaining = eff > 0 ? min(eff, margin) : 0
liq_base  = remaining > 0 ? remaining : margin

liq_fee  = liq_base  * 4%   (to whoever ran the uncross)
if_fee   = remaining * 1%   (to the market's insurance fund)
leftover = remaining - liq_fee - if_fee   (back to the trader)
```

A self-liquidation sends the keeper's cut to insurance instead of to the
trader's own transaction. Any profit beyond the position's margin is never
paid out on a liquidation, only on a normal close.

## Fair fill bound

No fill, under any path, including the guaranteed-exit fallback inside a
batch, is ever worse for the trader than the live spot or oracle:

```
ref  = spot (or EMA, if there's no spot)
buy  fill price >= ref     (open long, close short)
sell fill price <= ref     (open short, close long)
```

## Liquidation price brake

```
step     = brake_px * 1%/second * seconds_elapsed
brake_px = moves toward the oracle by at most that step
```

Liquidation health and liquidation prices are checked against `brake_px`,
not the raw oracle, which is what stops a single wick from wiping out a
position in one batch. Opens, closes, and exits still price off the live
oracle; only liquidation triggers off the braked one.

## Partial liquidation

```
N = notional    E = equity    t = (imr + mmr) / 2    p = 75 bps penalty
f = (t*N - E) / (N * (t - p))
closed = ceil(size * f), rounded to whole lots
```

The closed portion's loss goes to the pool, plus 0.50% of its notional to
the keeper and 0.25% to insurance. Whatever's left of the position stays
open, re-keyed at its new size. A liquidation only goes to full close when
equity has hit zero, the position is too small to partially close
meaningfully, or fewer than two lots would remain.

## Cross margin

The equity, initial, and maintenance requirements behind
[Margin and Vaults](https://docs.devnet.perp.ordr.trade/architecture/margin-and-vaults.md):

```
equity  = collateral + sum(pnl_i + funding_i)
initial = sum(size_i * price_i / PRICE_SCALE * imr_i / BPS_DENOM)
maint   = sum(size_i * price_i / PRICE_SCALE * mmr_i / BPS_DENOM)
target  = sum(size_i * price_i / PRICE_SCALE * (imr_i + mmr_i)/2 / BPS_DENOM)
```

Opening needs `equity >= initial + reserved + the new order's margin and
fee`, with only one cross order in flight at a time. Withdrawing needs
`collateral - unrealized losses - amount >= initial`, with nothing pending.
Every batch scans the next 64 cross accounts in line; one under maintenance
gets a forced partial close, sized the same way as an isolated partial
liquidation but against `target` instead of a single position's own
maintenance line, with a smaller 0.50% / 0.25% keeper and insurance cut.

## Emergency exit

The fallback price a stale book or an unmatched remainder settles at,
penalized against the trader rather than left to a vanished price:

```
base = min(ema, spot)   (closing long, selling)
base = max(ema, spot)   (closing short, buying)
penalty = base * 1%, rounded up
exit = base - penalty   (sell)
exit = base + penalty   (buy)
```

A stale book sends every pending close through `exit` outright. A fresh
book only lifts a close to `exit` if the book's own price was worse, and
only applies it to whatever's left unfilled.

## Solvency

What `uncross` recomputes for the pool at the end of every batch, so a
maker's capital is checked against reality continuously rather than
trusted:

```
owed  = what the pool would owe traders if every position closed at price p,
        net of funding
cover = |long OI - short OI| * p / PRICE_SCALE * 20%
req   = owed + cover
```

A pool's `required` is the sum of `req` across every one of its markets,
`payable` is closed profit not yet paid out. A new position is only
admitted if the pool, filled fully at the oracle price, would still cover
`required + payable` afterward, and `maker_withdraw` fails outright unless
what's left behind still does too.

> [!NOTE]
>
> `math.md` also sketches an LP-vault layer on top of this: outside capital,
> performance fees, a high-water mark, a drawdown breaker. That part isn't
> in the current `Pool` or `PoolMaker` accounts, so it's left out here; this
> page only documents what's actually deployed.

## Invariants

1. `0 < mmr < imr`, enforced once at `init_market`.
2. A newly opened position meets its margin requirement at both the fill
   price and the oracle price, so it can never be immediately liquidatable.
3. All division is integer division. No floats, no signed division.
4. Every intermediate product is computed at 128 bits; anything that
   wouldn't fit back into 64 fails outright instead of wrapping.
5. Fill prices and margin round against the trader; PnL and funding
   magnitudes round down, so a loss can end up at most one unit smaller
   than it should be, never larger.
6. A trader's vault balance always equals `free_balance + locked_balance`,
   after every single instruction.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.