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:
|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_DENOMlo = 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.
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.
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 pricefill_i = size_i if supply covered demandfill_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 sizeadverse = how far the limit sits on the losing side of the oracleimr_o = the oracle price's margin requirement at sizemargin 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,
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:
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.
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_remfunding_index += num / FUNDING_PERIODfunding_rem = num % FUNDING_PERIODfunding_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_indexnotional = size * mark / PRICE_SCALEpayment = |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:
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.
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:
remaining = eff > 0 ? min(eff, margin) : 0liq_base = remaining > 0 ? remaining : marginliq_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_elapsedbrake_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 penaltyf = (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:
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 upexit = 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 fundingcover = |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.
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
0 < mmr < imr, enforced once at init_market.
A newly opened position meets its margin requirement at both the fill
price and the oracle price, so it can never be immediately liquidatable.
All division is integer division. No floats, no signed division.
Every intermediate product is computed at 128 bits; anything that
wouldn’t fit back into 64 fails outright instead of wrapping.
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.
A trader’s vault balance always equals free_balance + locked_balance,
after every single instruction.