> 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/closed-loop.md).

# Closed Loop

The Nexus Exchange is one dynamical system. This document formalizes it as a state-space model in three staged parts, from a single corpus of verified component mathematics. Part I is the heart: the Exchange **engine** alone, a self-contained transition system $$S' = f(S, u)$$ in which the oracle price $$u$$ is simply *given* — every economic fact of the venue (matching, position lifecycle, funding, margining, liquidation, loss absorption) is an event map acting on one state vector. Part II summarizes the **input process**: $$u$$ is not raw but the output of a guarded process $$u' = g(u, \text{prints})$$, detailed in the oracle component document. Part III is the **union**: the closed loop obtained by composing the two, whose invariants — bounded equity shock per accepted tick, the conditional freeze under staleness — exist only because the guarded input and the engine response interlock.

Notation throughout matches the component corpus: $$C\_a$$ collateral, $$s$$ signed position size with $$\sigma = \operatorname{sign}(s)$$ and $$q = |s|$$, $$P\_e$$ entry price, $$m\_k$$ mark, $$\Phi$$ insurance fund, $$f$$ funding rate, $$E$$ equity, $$M$$ margin requirements. Claims are grounded by inline equation references into the component models; where the corpus lacks an expression, the gap is named rather than papered over.

## The input process: $$u' = g(u, \text{sources})$$

The input is itself a guarded process $$u' = g(u, \text{prints})$$: an incoming print moves the trusted anchor only if it passes the single-step and path deviation guards ([(O.1)](/math-engine/oracle.md), [(O.2)](/math-engine/oracle.md), [(O.3)](/math-engine/oracle.md)); a silent feed trips the staleness predicate ([(O.4)](/math-engine/oracle.md)) and routes prints into a multi-print re-anchor confirmation with escalation ([(O.5)](/math-engine/oracle.md), [(O.6)](/math-engine/oracle.md)). One event map, given below, summarizes the whole process; the oracle component document carries the detail.

### Oracle print (input process)

The single event of the input process $$u' = g(u, \text{prints})$$. On a fresh anchor, an incoming print is accepted only if it passes the single-step guard ([(O.1)](/math-engine/oracle.md)) and, once the ten-print history is full, the path guard ([(O.2)](/math-engine/oracle.md) against [(O.3)](/math-engine/oracle.md)); acceptance moves $$(P\_{oracle}, t\_{last})$$ and appends to the history, rejection changes nothing. When the staleness predicate trips ([(O.4)](/math-engine/oracle.md)), prints route into the re-anchor protocol instead: each print within the active bound of the running candidate advances the confirmation counter, an inconsistent print restarts it ([(O.5)](/math-engine/oracle.md)), escalation widens the bound by print count or elapsed time ([(O.6)](/math-engine/oracle.md)), and promotion requires $$\max(k, 2) \ge 2$$ consecutive confirmations — while pending, the anchor and its timestamp never move. The engine sees only the result: $$u$$ steps by at most a factor $$1 + \theta$$ per fresh accept, or jumps on a confirmed re-anchor commit. Touches: $$P\_{oracle}, t\_{last}, \Omega$$ only — no engine coordinate.

$$
u' = \begin{cases} (P\_{new},\ t\_{now}) & \neg\mathrm{stale} \wedge \Delta\_{step} \le \theta \wedge \Delta\_{path} \le \theta\sqrt{N\_h} \quad (\text{fresh accept}) \ (P\_{cand},\ t\_{now}) & \mathrm{stale} \wedge n\_p' \ge \max(k, 2) \quad (\text{re-anchor promotion}) \ (P\_{oracle},\ t\_{last}) & \text{otherwise (reject / pending)} \end{cases} \tag{U.1}
$$

## The union: the closed loop

The union is the closed loop: the guarded input process feeds the engine, and the engine feeds back into its own input. Downward, every accepted print re-prices the entire state at once — equity, maintenance floors, and the order collar all move with $$m\_k$$ (the funding premium is the exception, per the leg-specific damping below) — and the guards compose into the closed-loop bounds above: a fresh tick's motion is capped by $$\theta$$ before the engine ever sees it, so the equity shock per tick is bounded ([(O.1)](/math-engine/oracle.md) composed with [(O.8)](/math-engine/oracle.md) and [(M.5)](/math-engine/margin-math.md)), while a stale feed freezes exactly the anchor leg ([(O.4)](/math-engine/oracle.md)) and leaves liquidation live on the trade leg. Upward, every fill — including the cascade's own close fills — enters the five-trade window that shapes the trade reference ([(O.7)](/math-engine/oracle.md)): the engine influences the mark that will next judge its accounts, damped by $$(1-w)$$ and by the volume-weighted median's majority-volume requirement.

The damping is **leg-specific**, and the two legs differ. On the MARGIN leg a fill's influence is still damped by $$(1-w)$$, because the mark blends the trade reference at that weight. On the FUNDING leg it is not: the premium index (F.1) takes the trade reference at full weight, so a fill moves the next funding sample undamped. The remaining guards on that leg are the volume-weighted median's majority-volume requirement and the per-window cap $$c$$; there is no time-based recency gate — the reference reverts to the oracle only when the five-trade window is empty (the market has never traded, or a large oracle re-anchor just cleared its history), not when its prints have simply aged. This two-way coupling is what makes the composed system a genuine feedback loop rather than a filter followed by a plant: a liquidation prints fills, the fills move the trade leg, the moved mark re-evaluates the next account.

The composed system's long-run geometry: healthy states at an agreeing mark ($$m\_k = P\_{oracle,k}$$, zero premium) are not full equilibria — accrual still adds zero, but settlement no longer transfers nothing: the fixed interest term leaves the rate at $$f = i \cdot W/28800$$ even at zero premium, so [(S.6)](/math-engine/settlement.md) still moves a small amount through the pool every interval. The trigger stays silent, and the position, book, and fund coordinates hold fixed while $$C\_a$$ and $$C\_{pool}$$ keep cycling through that small transfer. Two absorbing regimes matter. Fund depletion: $$\Phi = 0$$ after an exhausting absorption ([(I.2)](/math-engine/insurance-fund.md) hits its floor exactly) arms ADL through both nested predicates and stays armed until a spread or penalty credit refills the balance ([(I.7)](/math-engine/insurance-fund.md), [(I.10)](/math-engine/insurance-fund.md)); the credit-before-absorb ordering (settled, code-verified) means a single liquidation carrying both profit and debt absorbs against $$\Phi + g$$, never the pre-credit balance. Liquidation stall: a negative cross share produces an oversized close that [(L.13)](/math-engine/liquidation-engine.md) rejects on every scan — a live-lock fixed point of the cascade in which the account remains triggered but untouched, exiting only when the mark or the share changes.

What the composition does *not* yet witness, named plainly. (1) adl\_settlement\_unmodeled: the ADL counterparty settlement map — closing price, per-counterparty size reduction, both sides' $$C\_a$$ updates, open-interest preservation — has no component expressions; the cascade's conservation invariant is scoped up to this leg, and the next cycle derives it from code (v0.0.9 audit, medium). (2) residual\_entry\_remark\_unwitnessed: the settle map values a partial liquidation's unfilled remainder at the mark and folds it into cash ([(L.16)](/math-engine/liquidation-engine.md) inside [(L.17)](/math-engine/liquidation-engine.md)), while the position layer retains the remainder's entry price ([(T.1)](/math-engine/position-tracker.md) is untouched by reductions) — consistency requires either excluding $$\Pi\_{\mathrm{res}}$$ from the cash settle or re-anchoring the residual's entry at the mark, and no expression witnesses either; conservation is therefore stated for fully-filled cascades. (3) cancel\_release\_arithmetic\_unwitnessed: the cancel/expiry map's per-order margin release has no corpus expression, though the guards that depend on it ([(M.16)](/math-engine/margin-math.md), [(M.14)](/math-engine/margin-math.md)) fix its required semantics. (4) adl\_arming\_condition\_ambiguity: the two arming predicates are nested, not symmetric — settle-amount firing implies threshold firing, and the surviving question is whether ADL executes when the threshold arms with $$D\_{\mathrm{adl}} = 0$$. Conversely, one previously-open gap is now closed: the liquidation penalty's fund-side destination is witnessed by the v0.0.9 expressions [(I.9)](/math-engine/insurance-fund.md), [(I.10)](/math-engine/insurance-fund.md), and [(I.11)](/math-engine/insurance-fund.md), retiring liquidation\_penalty\_sink as an open finding of this model.

## Invariants of the closed loop

### Bounded equity shock per fresh-anchor tick

$$
\big\lvert E(S, u') - E(S, u) \big\rvert ;\le; w, \theta, P\_{oracle} \sum\_i q\_i \qquad \text{(fresh-anchor accept branch only)} \tag{U.2}
$$

On the fresh-anchor accept branch of the input process, one oracle tick can shock an account's equity by at most $$w,\theta,P\_{oracle}\sum\_i q\_i$$ per market: the accepted anchor moves by at most $$\theta,P\_{oracle}$$ ([(O.1)](/math-engine/oracle.md)), the blend damps the anchor leg by $$w$$ ([(O.8)](/math-engine/oracle.md)), and equity is affine in the mark with slope bounded by total size ([(T.2)](/math-engine/position-tracker.md), [(M.5)](/math-engine/margin-math.md)). Explicitly excluded: the re-anchor commit branch — commits are bounded by $$\theta\_r/\theta\_e$$ relative to the *candidate*, not by $$\theta$$ relative to the prior anchor, and can exceed this bound (simulator result reanchor\_commit\_exceeds\_tick\_bound).

*Why it holds:* This invariant exists only at the composition: the engine alone accepts any $$u$$, and the oracle alone bounds prices, not equity. The accept guard rejects before any state write, so a committed fresh tick satisfies $$|\Delta P\_{oracle}| \le \theta P\_{oracle}$$; the mark is a convex combination, so $$|\Delta m\_k| = w,|\Delta P\_{oracle}|$$ with $$W\_k$$ unchanged by an oracle event; and $$E$$ is affine in $$m\_k$$ with slope $$\sum\_i s\_{i,k}$$, giving the bound by the triangle inequality. The exclusion is forced: re-anchor promotion moves the anchor to the candidate in one step, which the corpus bounds only relative to the candidate chain.

*Composes:* [*(O.1)*](/math-engine/oracle.md) [*(O.8)*](/math-engine/oracle.md) [*(T.2)*](/math-engine/position-tracker.md) [*(M.5)*](/math-engine/margin-math.md) [*(M.8)*](/math-engine/margin-math.md)

### Staleness freezes the anchor leg only

$$
\mathrm{stale} ;\Longrightarrow; (P\_{oracle}',, t\_{last}') = (P\_{oracle},, t\_{last}) \quad\text{and}\quad \lvert \Delta m\_k \rvert \le (1 - w), \lvert \Delta P\_{trade} \rvert \tag{U.3}
$$

While the anchor is stale ([(O.4)](/math-engine/oracle.md)), no pending print can move $$P\_{oracle}$$ or $$t\_{last}$$ — the re-anchor protocol persists only candidate bookkeeping until $$\max(k,2)$$ confirmations ([(O.5)](/math-engine/oracle.md)) — so the anchor leg of the mark is frozen and mark motion is confined to the trade leg, damped by $$(1-w)$$ and defended by the volume-weighted median ([(O.8)](/math-engine/oracle.md), [(O.7)](/math-engine/oracle.md)). Stated honestly: staleness does **not** pause liquidations — the trigger [(L.4)](/math-engine/liquidation-engine.md) keeps evaluating at the partially-frozen mark, whose trade leg the engine's own fills keep moving. The fail-closed property is confined to the anchor.

*Why it holds:* Only the trusted-accept path writes the anchor pair, and the pending branch returns without calling it, with the Trusted/Pending discriminant preventing a silent commit — so the anchor leg's contribution to $$\Delta m\_k$$ is zero under staleness. The mark is a convex combination, so the residual motion is exactly $$(1-w),\Delta P\_{trade}$$, and shifting $$P\_{trade}$$ requires manipulated prices to carry strictly more than half the window's volume. The liquidation half is a non-claim: no component expression conditions the trigger on freshness, so the composed system inherits liquidation-at-the-frozen-leg rather than a pause.

*Composes:* [*(O.4)*](/math-engine/oracle.md) [*(O.5)*](/math-engine/oracle.md) [*(O.8)*](/math-engine/oracle.md) [*(O.7)*](/math-engine/oracle.md) [*(L.4)*](/math-engine/liquidation-engine.md)

## Appendix — the complete formal system

This appendix is rendered mechanically from the state-space classification (`models/state-space.json`) — derived, not written. Its completeness claim is *checked*: the closure gate (`ci/closure.py`) verifies on every run that every corpus expression is classified, every state coordinate is written by an event and read somewhere, and every event map cites only defined coordinates. The state space factors into 16 coordinates (global fund and cash books; per-market book, trade window, premium accumulator, oracle anchor and re-anchor pending block; per-account collateral and reserved margin; per-position size/entry/direction and funding accumulator), 9 inputs, 20 parameters, and 54 derived observables, with all 133 corpus variables and 84 expressions classified totally across 10 events. Alphabet completion added adl\_execution, oracle\_reanchor\_step, oracle\_reanchor\_commit — including adl\_execution emitted with empty writes so the closure gate keeps flagging the unmodeled ADL counterparty settlement map. Deliberately uncited update maps (deposit/withdrawal transfer, cancel removal and reservation release, anchor assignments, trade-window push, funding resets) remain named gaps rather than inventions.

### B.1 The state vector

**per-market**

| Coordinate           | Symbol            | Units                    | Owner  | Description                                                                                                                                                                                                                                                 |
| -------------------- | ----------------- | ------------------------ | ------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `trade_window`       | $$W\_k$$          | five (price, size) pairs | oracle | The last five executed fills of the market, written by the fill map (including liquidation close fills) and read by the volume-weighted median trade reference — the engine-owned leg of the mark blend.                                                    |
| `oracle_anchor`      | $$P\_{oracle,k}$$ | USDX per unit of asset   | oracle | The trusted anchor price of the market — the engine's exogenous input process state; moved only by the guarded fresh-accept and re-anchor-commit branches of the oracle map, never by any engine event.                                                     |
| `anchor_timestamp`   | $$t\_{last,k}$$   | milliseconds             | oracle | Timestamp of the last trusted anchor update, read by the staleness predicate; frozen together with the anchor while a re-anchor is pending.                                                                                                                 |
| `oracle_guard_state` | $$\Omega\_k$$     | prints and milliseconds  | oracle | The input process's defense bookkeeping: the ten-print history (whose oldest element the path check reads) and the pending re-anchor block (candidate price, pending print count, confirmation counter, opening timestamp); touched only by the oracle map. |

### B.2 Inputs and parameters

Inputs are exogenous — they arrive from outside the state; parameters are constants of market or system configuration.

**Inputs**

| Input                      | Symbol       | Units                  | Description                                                                                                                     |
| -------------------------- | ------------ | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------- |
| `oracle_print_price`       | $$P\_{new}$$ | USDX per unit of asset | An incoming external oracle print being validated against the anchor or the pending re-anchor candidate.                        |
| `wall_clock_time`          | $$t\_{now}$$ | milliseconds           | Feed-supplied timestamp of the incoming print or staleness evaluation, in Unix milliseconds.                                    |
| `time_delta`               | $$\Delta t$$ | seconds                | Exogenous elapsed time since the previous funding premium sample; non-advancing samples are ignored.                            |
| `order_quantity`           | $$q$$        | base units             | Quantity of an arriving order; must be a lot multiple to pass admission.                                                        |
| `order_limit_price`        | $$P\_{lim}$$ | USDX per base unit     | Limit price of an arriving limit order; must be strictly positive, tick-aligned, and inside the mark collar.                    |
| `order_signed_size`        | $$o$$        | base units, signed     | Signed size of an arriving order (buy positive, sell negative), read by the added-exposure computation.                         |
| `max_slippage_bps`         | $$\beta$$    | basis points           | Taker-supplied per-order slippage cap on a market order; absent means no cap.                                                   |
| `preview_requested_qty`    | $$q\_{req}$$ | base units             | Quantity requested by a hypothetical market order in the read-only VWAP preview; undefined for non-positive requests.           |
| `external_transfer_amount` | $$x$$        | USDX                   | External USDX amount of a deposit or withdrawal; not a corpus variable — carried by the composition's deposit/withdrawal event. |

**Parameters**

| Parameter                    | Symbol        | Units                         | Scope       | Description                                                                                                                                                                                                                                                                                                                                  |
| ---------------------------- | ------------- | ----------------------------- | ----------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `funding_rate_cap`           | $$c$$         | fraction per funding interval | per-market  | Symmetric cap on the funding rate. The crypto perps use 0.001 (0.1%); the FX, commodity, and index perps (seven markets, including NDQ) are configured at 0.0005. Which of the seven are actually deployed changes with the venue's rollout state — see Market Specifications for the live per-market set rather than a fixed snapshot here. |
| `adl_threshold`              | $$\kappa$$    | USDX                          | per-market  | ADL trigger threshold on the fund balance; default zero arms ADL only at full depletion.                                                                                                                                                                                                                                                     |
| `maintenance_margin_rate`    | $$r\_m$$      | dimensionless ratio           | per-market  | Market maintenance margin rate; strictly less than the initial margin rate.                                                                                                                                                                                                                                                                  |
| `initial_margin_rate`        | $$r\_i$$      | dimensionless ratio           | per-market  | Market initial margin rate, equal to one over the market's maximum leverage.                                                                                                                                                                                                                                                                 |
| `account_leverage`           | $$L$$         | multiplier                    | per-account | Account-selected leverage per market (integer >= 1, validated before storage); user configuration with no state-mutating expression in the corpus, hence a parameter, not a coordinate.                                                                                                                                                      |
| `tick_size`                  | $$\delta$$    | USDX per base unit            | per-market  | Minimum price increment; non-positive tick disables alignment.                                                                                                                                                                                                                                                                               |
| `lot_size`                   | $$\ell$$      | base units                    | per-market  | Market lot size; order and position sizes are integer multiples of it; zero disables the alignment check.                                                                                                                                                                                                                                    |
| `taker_fee_bps`              | $$b\_t$$      | basis points                  | per-market  | Taker fee rate charged on fill notional.                                                                                                                                                                                                                                                                                                     |
| `maker_rebate_bps`           | $$b\_m$$      | basis points                  | per-market  | Maker rebate rate, stored negative by convention; applied by absolute value.                                                                                                                                                                                                                                                                 |
| `liquidation_penalty_bps`    | $$b\_{liq}$$  | basis points                  | per-market  | Penalty rate applied to the notional of liquidation fills and routed to the insurance fund.                                                                                                                                                                                                                                                  |
| `price_band_bps`             | $$b\_{band}$$ | basis points                  | per-market  | Maximum admissible relative deviation of a limit price from the mark (the admission collar).                                                                                                                                                                                                                                                 |
| `oracle_deviation_threshold` | $$\theta$$    | dimensionless fraction        | per-market  | Single-step deviation threshold for accepting an oracle print against the anchor.                                                                                                                                                                                                                                                            |
| `oracle_history_size`        | $$N\_h$$      | prints                        | global      | Fixed size of the rolling price-update window used by the path-manipulation check (HISTORY\_SIZE = 10).                                                                                                                                                                                                                                      |
| `oracle_staleness_seconds`   | $$\tau\_s$$   | seconds                       | per-market  | Staleness threshold: the anchor is stale strictly beyond this many seconds since the last trusted update.                                                                                                                                                                                                                                    |
| `reanchor_max_deviation`     | $$\theta\_r$$ | dimensionless fraction        | per-market  | Per-step consistency bound for re-anchor confirmations against the running candidate.                                                                                                                                                                                                                                                        |
| `escalation_max_deviation`   | $$\theta\_e$$ | dimensionless fraction        | per-market  | Widened per-step bound applied once the escalation trigger has fired.                                                                                                                                                                                                                                                                        |
| `required_confirmations`     | $$k$$         | prints                        | per-market  | Consecutive mutually-consistent prints required to promote a re-anchor; floored at 2 effectively.                                                                                                                                                                                                                                            |
| `escalation_prints`          | $$N\_e$$      | prints                        | per-market  | Print-count arm of the re-anchor escalation trigger.                                                                                                                                                                                                                                                                                         |
| `escalation_seconds`         | $$\tau\_e$$   | seconds                       | per-market  | Wall-clock arm of the re-anchor escalation trigger, measured from the opening of the pending sequence.                                                                                                                                                                                                                                       |
| `oracle_mark_weight`         | $$w$$         | dimensionless fraction        | per-market  | Oracle weight in the mark blend; unit-interval, default 0.95 (oracle-dominant).                                                                                                                                                                                                                                                              |

### B.3 Derived observables

Pure functions of state, inputs, and parameters — recomputed, never persisted.

| Quantity                   | Symbol              | Units                 | Defined by                                   | Description                                                                                                                                                                                                                |
| -------------------------- | ------------------- | --------------------- | -------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `mark_price`               | $$m\_k$$            | USDX per base unit    | [(O.8)](/math-engine/oracle.md)              | Convex blend of the trusted anchor and the volume-weighted trade reference; equals the anchor when no trade reference exists. Recomputed on demand, never persisted.                                                       |
| `trade_ref`                | $$P\_{trade}$$      | USDX per base unit    | [(O.7)](/math-engine/oracle.md)              | Volume-weighted median price of the five-trade window; falls back to the last trade price when the window is short.                                                                                                        |
| `premium_index`            | $$p$$               | dimensionless         | [(F.1)](/math-engine/funding-rate.md)        | Fractional deviation of the perp reference (NOT the mark) from the anchor at a sample; skipped when the anchor is non-positive.                                                                                            |
| `funding_rate`             | $$f$$               | fraction per interval | [(F.3)](/math-engine/funding-rate.md)        | Clamped, pro-rated time-weighted average premium plus the fixed interest term — $$\text{clamp}((A/T + i) \cdot W/28800, -c, +c)$$ — recomputed fresh from (A, T) at settlement with the T = 0 branch returning zero.       |
| `funding_payment`          | $$\Pi^f$$           | USDX                  | [(F.4)](/math-engine/funding-rate.md)        | Signed per-position funding payment sigma q P\_oracle f, struck at the oracle price rather than the mark; simultaneously the settlement event's collateral update delta.                                                   |
| `unrealized_pnl`           | $$\mathrm{uPnL}$$   | USDX                  | [(T.2)](/math-engine/position-tracker.md)    | Per-position mark-to-market PnL; the account total is its sum over open positions (coherence-merged with liquidation-engine.fresh\_unrealized\_pnl).                                                                       |
| `account_equity`           | $$E$$               | USDX                  | [(M.8)](/math-engine/margin-math.md)         | Collateral plus mark-to-market PnL (net of funding integrals in the portfolio form); coherence-merged across margin-math.equity, margin-math.portfolio\_equity, and liquidation-engine.account\_equity.                    |
| `maintenance_margin`       | $$M\_m$$            | USDX                  | [(M.4)](/math-engine/margin-math.md)         | Maintenance margin at the mark; coherence-merged with the portfolio and liquidation-engine instances.                                                                                                                      |
| `initial_margin`           | $$M\_i$$            | USDX                  | [(M.2)](/math-engine/margin-math.md)         | Initial margin at the mark (stamped allocated margin where set); coherence-merged with the portfolio instance.                                                                                                             |
| `available_margin`         | $$M\_{avail}$$      | USDX                  | [(M.7)](/math-engine/margin-math.md)         | Equity minus total initial margin held; can be negative; gates order admission, not withdrawal.                                                                                                                            |
| `added_exposure`           | $$\Delta q$$        | base units            | [(M.11)](/math-engine/margin-math.md)        | Magnitude of newly-opened exposure an order adds: growth on increase, zero on reduce/close, the whole new side on a flip.                                                                                                  |
| `admission_added_margin`   | $$M\_{add}$$        | USDX                  | [(M.12)](/math-engine/margin-math.md)        | Initial margin charged on added exposure at the mark and effective rate; also the amount written into the reservation at admission.                                                                                        |
| `isolated_margin_cushion`  | $$C\_{iso}$$        | USDX                  | [(L.5)](/math-engine/liquidation-engine.md)  | Collateral backing an isolated position: the margin allocated at fill time if recorded, otherwise the open-time initial margin at market rate; the trigger ((L.4)) and the liquidation pricing both use this single value. |
| `bankruptcy_price`         | $$p\_b$$            | USDX per base unit    | [(L.8)](/math-engine/liquidation-engine.md)  | Price at which the position's backing collateral is exactly exhausted; coherence-merged with position-tracker.bankruptcy\_price; may be zero or negative before alignment.                                                 |
| `aligned_bankruptcy_price` | $$\tilde{p}\_b$$    | USDX per base unit    | [(L.9)](/math-engine/liquidation-engine.md)  | Tick-aligned close-order limit: floor for sells (liquidation-engine.aligned\_price\_sell), ceil for buys (liquidation-engine.aligned\_price\_buy), clamped to one tick.                                                    |
| `liquidation_price`        | $$p\_{liq}$$        | USDX per base unit    | [(T.8)](/math-engine/position-tracker.md)    | Analytically-solved mark at which equity meets the maintenance requirement; display/analysis, neither moves state nor gates events.                                                                                        |
| `cross_collateral_share`   | $$s\_i$$            | USDX                  | [(L.6)](/math-engine/liquidation-engine.md)  | Loss-proportional share of the shared cross pool per market, with the remainder folded into the largest-loss position's share.                                                                                             |
| `collateral_share_sum`     | $$S$$               | USDX                  | \`\`                                         | Sum of the proportional shares before the remainder fold; prose-defined only — no corpus expression id (read by the remainder fold).                                                                                       |
| `position_loss`            | $$\ell\_i$$         | USDX                  | \`\`                                         | max(0, -uPnL\_i) per market with entry-price fallback; defined only in variable prose, no corpus expression id.                                                                                                            |
| `total_loss`               | $$\mathcal{L}$$     | USDX                  | \`\`                                         | Sum of position losses across the positions liquidated together; prose-defined only.                                                                                                                                       |
| `safe_size`                | $$q\_{safe}$$       | base units            | [(L.11)](/math-engine/liquidation-engine.md) | Largest lot-multiple size whose 1.5x-padded initial margin the collateral share covers.                                                                                                                                    |
| `liquidation_qty`          | $$q\_{liq}$$        | base units            | [(L.12)](/math-engine/liquidation-engine.md) | Close-order quantity: full size in Full mode or degenerate cases, else reduction to safe size.                                                                                                                             |
| `fill_quantity`            | $$q^{\star}$$       | base units            | [(B.6)](/math-engine/order-book.md)          | Quantity of a single fill: min of taker and front-maker remainders; coherence-merged with settlement.size and position-tracker.fill\_quantity.                                                                             |
| `fill_price`               | $$P^{\star}$$       | USDX per base unit    | [(B.7)](/math-engine/order-book.md)          | Price of a single fill — always the maker's limit price; coherence-merged with settlement.price and position-tracker/liquidation-engine fill prices.                                                                       |
| `closed_quantity`          | $$q\_c$$            | base units            | [(T.3)](/math-engine/position-tracker.md)    | Portion of an opposing fill that closes existing size: min(size, fill quantity).                                                                                                                                           |
| `total_filled`             | $$Q\_f$$            | base units            | \`\`                                         | Sum of the liquidation close order's fill quantities; within-event accumulation, prose-defined only.                                                                                                                       |
| `spread_profit`            | $$g$$               | USDX                  | [(L.14)](/math-engine/liquidation-engine.md) | Positive part of fills' price improvement over the aligned bankruptcy price, summed over fills; credited to the fund.                                                                                                      |
| `realized_fill_pnl`        | $$\Pi\_{fill}$$     | USDX                  | [(L.15)](/math-engine/liquidation-engine.md) | Signed realized PnL of liquidation fills, each at its own fill price; a component of the cascade's per-market settlement X\_i.                                                                                             |
| `residual_unfilled_pnl`    | $$\Pi\_{res}$$      | USDX                  | [(L.16)](/math-engine/liquidation-engine.md) | Mark-valued PnL of the unfilled remainder of the close order; zero on complete fill.                                                                                                                                       |
| `bad_debt`                 | $$D$$               | USDX                  | [(L.17)](/math-engine/liquidation-engine.md) | Non-negative shortfall after fills-aware settlement against the collateral share; drawn from the fund, then ADL.                                                                                                           |
| `absorbed_amount`          | $$D\_{abs}$$        | USDX                  | [(I.1)](/math-engine/insurance-fund.md)      | min(bad debt, fund balance): the delta by which the fund and its absorption ledger move.                                                                                                                                   |
| `adl_settle_amount`        | $$D\_{adl}$$        | USDX                  | [(I.4)](/math-engine/insurance-fund.md)      | Shortfall handed to ADL after the fund is drained; an instruction is emitted only when strictly positive.                                                                                                                  |
| `adl_priority_score`       | $$\rho$$            | dimensionless         | [(L.18)](/math-engine/liquidation-engine.md) | ADL ranking score pi \* L, descending with deterministic account-id tie-break; coherence-merged with the insurance-fund instance.                                                                                          |
| `adl_pnl_percent`          | $$\pi$$             | fraction              | \`\`                                         | ADL candidate's unrealized PnL as a fraction of position value; no corpus expression defines it — a gap for the closure gate.                                                                                              |
| `liquidation_penalty_owed` | $$\Lambda\_{owed}$$ | USDX                  | [(S.4)](/math-engine/settlement.md)          | Penalty owed on filled liquidation notional at the market's penalty rate.                                                                                                                                                  |
| `penalty_charged`          | $$\Lambda$$         | USDX                  | [(I.9)](/math-engine/insurance-fund.md)      | Penalty actually debited/credited: the owed amount capped at available collateral, so the pair cannot mint USDX.                                                                                                           |
| `fill_notional`            | $$V^{\star}$$       | USDX                  | [(S.1)](/math-engine/settlement.md)          | Notional of a single fill, size times price, exact decimal.                                                                                                                                                                |
| `net_exchange_revenue`     | $$V$$               | USDX                  | [(S.5)](/math-engine/settlement.md)          | Settlement-record closure: total taker fees minus total maker rebates.                                                                                                                                                     |
| `margin_ratio`             | $$\rho\_M$$         | dimensionless         | [(M.6)](/math-engine/margin-math.md)         | Equity over total notional; undefined at zero notional; diagnostic — gates nothing in the corpus.                                                                                                                          |
| `max_position_size`        | $$q\_{max}$$        | base units            | [(M.15)](/math-engine/margin-math.md)        | Largest lot-aligned position openable with given collateral at the market rate; sizing/display analysis.                                                                                                                   |
| `withdrawable_collateral`  | $$W\_{max}$$        | USDX                  | [(M.16)](/math-engine/margin-math.md)        | Full realized collateral for a flat, unreserved account, zero otherwise; the withdrawal guard's cap.                                                                                                                       |
| `best_bid`                 | $$P\_b$$            | USDX per base unit    | \`\`                                         | Highest resting bid — a structural readout of the order\_book coordinate; no corpus expression id.                                                                                                                         |
| `best_ask`                 | $$P\_a$$            | USDX per base unit    | \`\`                                         | Lowest resting ask — a structural readout of the order\_book coordinate; no corpus expression id.                                                                                                                          |
| `mid_price`                | $$P\_{mid}$$        | USDX per base unit    | [(B.4)](/math-engine/order-book.md)          | Midpoint of best bid and ask, snapshotted once at market-order submission for the slippage cap; undefined when either side is empty.                                                                                       |
| `slippage_span`            | $$\Delta\_{slip}$$  | USDX per base unit    | [(B.9)](/math-engine/order-book.md)          | Half-width of the admissible VWAP band anchored at the mid-price snapshot.                                                                                                                                                 |
| `available_qty`            | $$Q\_{avail}$$      | base units            | \`\`                                         | Pre-match opposing liquidity at prices satisfying the taker's limit; within-event readout of the book, prose-defined only.                                                                                                 |
| `taker_remaining`          | $$q\_t$$            | base units            | \`\`                                         | Taker's unfilled remainder during the matching walk; within-event intermediate, prose-defined only.                                                                                                                        |
| `running_notional`         | $$V\_k$$            | USDX                  | \`\`                                         | Cumulative notional of fills accepted so far in a market-order walk; within-event accumulator, prose-defined only.                                                                                                         |
| `running_filled`           | $$Q\_k$$            | base units            | \`\`                                         | Cumulative quantity of fills accepted so far in a market-order walk; within-event accumulator, prose-defined only.                                                                                                         |
| `walk_notional`            | $$V$$               | USDX                  | \`\`                                         | Total notional of a hypothetical price-time-priority walk for the VWAP preview; prose-defined only.                                                                                                                        |
| `vwap_estimate`            | $$\overline{P}$$    | USDX per base unit    | [(B.11)](/math-engine/order-book.md)         | Read-only market-order VWAP preview; undefined when liquidity cannot cover the request.                                                                                                                                    |
| `funding_integral`         | $$\varphi$$         | USDX                  | \`\`                                         | Per-position accumulated funding read by portfolio equity; identically zero under the composed settle-and-reset convention (phi = 0) — no accrual map exists in the corpus, by design.                                     |
| `total_notional`           | $$N$$               | USDX                  | \`\`                                         | Sum of size times mark over open positions; prose-defined only, the margin ratio's denominator.                                                                                                                            |
| `open_positions`           | $$n\_{pos}$$        | count                 | \`\`                                         | Count of the account's open positions — a structural readout of the position coordinates; no corpus expression id.                                                                                                         |

### B.4 The transition matrix

**Guards**

| Event                    | Guard                                                                                                                                                                                                                                                          | Reads                                                     |
| ------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------- |
| `oracle_print_accept`    | \neg stale (oracle.is\_stale = 0) \wedge \Delta\_{step} \le \theta (oracle.single\_step\_deviation) \wedge (\|H\| = N\_h \Rightarrow \Delta\_{path} \le \theta\sqrt{N\_h}) (oracle.path\_deviation vs oracle.path\_threshold)                                  | `oracle_anchor`, `anchor_timestamp`, `oracle_guard_state` |
| `oracle_reanchor_step`   | stale (oracle.is\_stale = 1) \wedge print arrives \wedge confirmations after this step < \max(k, 2); active per-step bound is \theta\_r, widened to \theta\_e once the escalation trigger fires (oracle.reanchor\_step\_deviation, oracle.escalation\_trigger) | `oracle_guard_state`, `oracle_anchor`, `anchor_timestamp` |
| `oracle_reanchor_commit` | stale \wedge consecutive mutually-consistent confirmations \ge \max(k, 2) (oracle.reanchor\_step\_deviation within the active bound on the promoting print)                                                                                                    | `oracle_guard_state`, `anchor_timestamp`                  |

**Writes** — rows are state coordinates, columns are events; a cell cites the component equation defining that update; `·` means provably untouched.

| Coordinate                        | `oracle_print_accept` | `oracle_reanchor_step` | `oracle_reanchor_commit` |
| --------------------------------- | --------------------- | ---------------------- | ------------------------ |
| `oracle_anchor` (per-market)      | ✓                     | ·                      | ✓                        |
| `anchor_timestamp` (per-market)   | ✓                     | ·                      | ✓                        |
| `oracle_guard_state` (per-market) | ✓                     | ✓                      | ✓                        |

## References

* The engine alone: [global](/math-engine/global.md)
* The oracle component model: [oracle](/math-engine/oracle.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/closed-loop.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.
