---
title: "On-Chain Order Books and Perpetual DEXs"
book: "Markets III: Commodities, Energy and Crypto"
subject: quant
language: en
chapter: 21
exercises: 8
source: https://one-course.com/books/quant/3/en/chapter/21-on-chain-order-books-and-perpetual-dexs
---

# Chapter 21 — On-Chain Order Books and Perpetual DEXs

On one decentralised venue every order, every cancel and every liquidation of a [perpetual futures](https://one-course.com/books/quant/3/en/chapter/17-perpetual-futures#def-m3-perpetual-futures-perp) market is a transaction in a block. The venue’s [validators](https://one-course.com/books/quant/3/en/chapter/14-blockchains-for-traders#def-m3-blockchains-for-traders-pow) agree not only on what happened but on the order in which it happened, and that order decides who is filled: a market maker whose quote has gone stale sends a cancel, an arbitrageur sends an order to hit the quote, and both arrive in the same block. On a [centralised exchange](https://one-course.com/books/quant/3/en/chapter/15-centralised-exchanges#def-m3-centralised-exchanges-cex) the matching engine’s clock settles the race. On a chain, a rule written into the protocol does. This chapter explains why putting an order book on a chain is hard, examines in detail the design of the venue that has gone furthest in doing it, looks at what went wrong when markets were stressed, and compares the other designs: order books kept off chain by [validators](https://one-course.com/books/quant/3/en/chapter/14-blockchains-for-traders#def-m3-blockchains-for-traders-pow), and exchanges that dispense with order books altogether and trade at an [oracle](https://one-course.com/books/quant/3/en/chapter/14-blockchains-for-traders#def-m3-blockchains-for-traders-contract)’s price.

## 21.1 Why an on-chain order book is hard

**Definition 21.1 (Perpetual DEX, on-chain order book).**

A *perpetual DEX* is a [decentralised exchange](https://one-course.com/books/quant/3/en/chapter/20-automated-market-makers#def-m3-automated-market-makers-amm) for [perpetual futures](https://one-course.com/books/quant/3/en/chapter/17-perpetual-futures#def-m3-perpetual-futures-perp), whose margin, positions and settlement are held and computed by a [blockchain](https://one-course.com/books/quant/3/en/chapter/14-blockchains-for-traders#def-m3-blockchains-for-traders-chain)’s state rather than by a company. An *on-chain order book* is a central limit order book whose orders, cancels and matches are transactions executed and recorded by the chain’s consensus.

A market maker on a centralised venue sends thousands of messages a second and cancels most of its orders; a message costs nothing and is processed in microseconds. On a general-purpose chain every message is a transaction that pays gas ([Chapter 14](https://one-course.com/books/quant/3/en/chapter/14-blockchains-for-traders#ch-m3-blockchains-for-traders)) and waits for a block, seconds away: quoting costs money, cancels are slow, and anyone watching the [mempool](https://one-course.com/books/quant/3/en/chapter/14-blockchains-for-traders#def-m3-blockchains-for-traders-mempool) sees the cancel coming. Three consequences follow. The chain must be built for the purpose, with blocks in fractions of a second and no per-message gas for trading actions. The ordering of actions inside a block must be specified by the protocol, since the block’s proposer could otherwise sell the right to go first. And every function of the exchange that a company would perform (the index, the [mark price](https://one-course.com/books/quant/3/en/chapter/17-perpetual-futures#def-m3-perpetual-futures-index), liquidation, the backstop) must be performed by the protocol and its [validators](https://one-course.com/books/quant/3/en/chapter/14-blockchains-for-traders#def-m3-blockchains-for-traders-pow), in public.

**Definition 21.2 (App-chain).**

An *app-chain* is a [blockchain](https://one-course.com/books/quant/3/en/chapter/14-blockchains-for-traders#def-m3-blockchains-for-traders-chain) built to run one application, here an exchange, with its own [validators](https://one-course.com/books/quant/3/en/chapter/14-blockchains-for-traders#def-m3-blockchains-for-traders-pow), consensus parameters and transaction rules chosen for that application rather than for general computation.

## 21.2 Hyperliquid in detail

Hyperliquid is an [app-chain](#def-m3-on-chain-order-books-and-perpetual-dexs-appchain) whose state includes the order books, margin and positions of its perpetual and spot markets (it calls this part HyperCore), alongside a general-purpose smart-contract environment.

**As of September 2026 — Consensus, latency and throughput.**

Hyperliquid’s documentation describes a proof-of-stake chain secured by HyperBFT, a variant of HotStuff consensus, with the order books and margin state held in the chain’s state rather than off chain. It reports a median end-to-end latency of 0.2 seconds and a 99th percentile of 0.9 seconds for an order from a co-located client, and a throughput of about 200 000 orders a second, limited by execution. It states that there is no designated market-maker programme, and no special rebates, fees or latency advantages.

**Definition 21.3 (In-block priority rule).**

An *in-block priority rule* is the protocol rule that sorts the trading actions of a block before they are applied to the order books, overriding the order in which the block’s proposer received or listed them.

**As of September 2026 — The in-block ordering of one venue.**

Hyperliquid’s documentation states that within a block, actions are sorted in each consensus batch (usually one or two per block) as: first, actions that send no GTC or IOC order to any book; second, cancels; third, actions that send at least one GTC or IOC order. Within each category actions keep the order proposed by the block’s proposer. Its books match in price-time priority, with prices on a tick grid and sizes on a lot grid; [post-only orders](https://one-course.com/books/quant/3/en/chapter/15-centralised-exchanges#def-m3-centralised-exchanges-postonly) (ALO) rest without executing.

![An in-block priority rule of the kind describes: the block’s actions are sorted into three classes and applied class by class, in proposed order within each class. A maker’s cancel and new post-only quote are applied before any taker’s order in the same block. Schematic.](https://one-course.com/images/onecourse/chapters/quant-3/m3-on-chain-order-books-and-perpetual-dexs/fig-54d3d8313242.svg)

***Figure 21.1.** An [in-block priority rule](#def-m3-on-chain-order-books-and-perpetual-dexs-priority) of the kind [Box 21.2](#dat-m3-on-chain-order-books-and-perpetual-dexs-order) describes: the block’s actions are sorted into three classes and applied class by class, in proposed order within each class. A maker’s cancel and new post-only quote are applied before any taker’s order in the same block. Schematic.*

The rule is a deliberate transfer of value from takers to makers. On a centralised venue a taker who reacts faster than a maker’s cancel picks off the stale quote; here, if both reach the same block, the cancel wins, as does the maker’s new post-only quote. Makers can quote tighter because they are picked off less, and a taker who wants to hit a stale quote must get into an earlier block than the maker’s cancel. The tutorial replays a thousand blocks: with the taker arriving first half the time, arrival order lets it pick off 610 lots, 940 ticks of the maker’s value; the class rule, none.

![A maker’s losses to stale-quote pick-offs over a thousand blocks under two in-block rules, with fair value moving a normal two ticks a block and the taker’s order arriving before the maker’s cancel half the time. Under the class rule the maker’s cancel and requote always come first. Synthetic replay. Data: the chapter’s tutorial.](https://one-course.com/images/onecourse/chapters/quant-3/m3-on-chain-order-books-and-perpetual-dexs/fig-9edb65462ae9.svg)

***Figure 21.2.** A maker’s losses to stale-quote pick-offs over a thousand blocks under two in-block rules, with fair value moving a normal two ticks a block and the taker’s order arriving before the maker’s cancel half the time. Under the class rule the maker’s cancel and requote always come first. Synthetic replay. Data: the chapter’s tutorial.*

The rest of the exchange is on chain too. Prices come from [validators](https://one-course.com/books/quant/3/en/chapter/14-blockchains-for-traders#def-m3-blockchains-for-traders-pow) rather than from the venue’s own trades alone, so that the thin books of a young venue cannot be used to move its own references.

**As of September 2026 — Oracle, mark and liquidation at one venue.**

Hyperliquid’s [validators](https://one-course.com/books/quant/3/en/chapter/14-blockchains-for-traders#def-m3-blockchains-for-traders-pow) each publish, about every three seconds, a spot [oracle](https://one-course.com/books/quant/3/en/chapter/14-blockchains-for-traders#def-m3-blockchains-for-traders-contract) price per perpetual: a weighted median of spot mid prices on Binance, OKX, Bybit, Kraken, KuCoin, Gate.io, MEXC and Hyperliquid, with weights 3, 2, 2, 1, 1, 1, 1 and 1 (external sources only for assets whose main spot liquidity is elsewhere); the clearinghouse uses the stake-weighted median of the [validators](https://one-course.com/books/quant/3/en/chapter/14-blockchains-for-traders#def-m3-blockchains-for-traders-pow)’ prices. The [mark price](https://one-course.com/books/quant/3/en/chapter/17-perpetual-futures#def-m3-perpetual-futures-index) is the median of the [oracle](https://one-course.com/books/quant/3/en/chapter/14-blockchains-for-traders#def-m3-blockchains-for-traders-contract) price plus a 150-second moving average of the basis, the median of the venue’s best bid, best ask and last trade, and a weighted median of perpetual mids on five external venues. Maintenance margin is half the initial margin at maximum leverage (1.25% to 16.7%); liquidations are first sent to the book as market orders (20% at a time for positions above 100 000 USDC); below two thirds of maintenance margin a position is taken over by the liquidator vault, a strategy of the protocol’s vault, HLP, whose depositors share its P&L.

**Definition 21.4 (Liquidity vault).**

A *liquidity vault* is a pool of depositors’ capital run by a protocol, or by a manager under protocol rules, that makes markets, takes over liquidated positions or supplies capital to a venue, sharing its P&L among its depositors.

A vault that backstops liquidations is the venue’s [insurance fund](https://one-course.com/books/quant/3/en/chapter/18-margin-liquidation-and-loss-allocation#def-m3-margin-liquidation-and-loss-allocation-fund) and its market maker of last resort, owned by whoever deposits in it. Its depositors earn the liquidation buffer on average and bear the tail when a position it inherits cannot be closed at a sensible price.

## 21.3 Incidents

Stress tests the design where a centralised venue’s staff would step in. In the 10 October 2025 sell-off ([Chapter 18](https://one-course.com/books/quant/3/en/chapter/18-margin-liquidation-and-loss-allocation#ch-m3-margin-liquidation-and-loss-allocation)), CoinDesk Research measured the largest contraction of open interest on Hyperliquid, from USD 14 billion to 6 billion, a fall of 57%. The venue’s [auto-deleveraging](https://one-course.com/books/quant/3/en/chapter/18-margin-liquidation-and-loss-allocation#def-m3-margin-liquidation-and-loss-allocation-adl) closed profitable positions of other traders, and an analysis by Tarun Chitra of Gauntlet, reported by Protos, argued that its queue-based ranking closed about USD 650 million more of them than was necessary. Earlier, on 12 March 2025, a trader holding a 50 times leveraged long of 113 000 ether withdrew margin until the position was liquidated into the vault: the trader kept about USD 1.8 million of profit and the vault lost about 4 million; the venue then cut its maximum leverage to 40 times on bitcoin and 25 on ether.

A second kind of incident is specific to a venue whose backstop is a public vault. A trader opens a large position in a thin market, lets it be liquidated so that the vault inherits it, and then moves the external spot prices that feed the [oracle](https://one-course.com/books/quant/3/en/chapter/14-blockchains-for-traders#def-m3-blockchains-for-traders-contract), on smaller venues where that is cheap; the vault, holding a position it cannot close without moving the book, marks a growing loss. The protocol’s defences are an [open-interest cap](#def-m3-on-chain-order-books-and-perpetual-dexs-oicap) per asset and per account, margin tiers that raise maintenance margin with size, and, in the last resort, governance: the [validators](https://one-course.com/books/quant/3/en/chapter/14-blockchains-for-traders#def-m3-blockchains-for-traders-pow) can vote to delist a market.

**Definition 21.5 (Open-interest cap).**

An *open-interest cap* is a limit on the total open interest of a market, or on the position of one account in it, beyond which the venue rejects orders that would increase it.

**Proposition 21.6 (The loss of a vault that inherits a squeezed position).**

A vault takes over a short position of notional $N$ with a fraction $b$ of it left as margin, and the price then rises by a fraction $s$ before the vault can close. Its loss is $N(s - b)^+$. To keep the loss within $L$ for squeezes up to $s_{\max}$, the positions it may inherit must be capped at $N \le L/(s_{\max} - b)$.

**Proof.** The short loses $Ns$ and the inherited margin covers $Nb$ of it; the bound follows by solving $N(s_{\max} - b) \le L$. ∎

![Loss of a vault that inherits a short in a market whose maximum leverage is 3 times (maintenance margin 16.7%, takeover at two thirds of it, leaving 11.1% of notional as margin), as a function of the rise that follows (). Illustrative positions. Data: the chapter’s tutorial.](https://one-course.com/images/onecourse/chapters/quant-3/m3-on-chain-order-books-and-perpetual-dexs/fig-d3dabbb99f38.svg)

***Figure 21.3.** Loss of a vault that inherits a short in a market whose maximum leverage is 3 times (maintenance margin 16.7%, takeover at two thirds of it, leaving 11.1% of notional as margin), as a function of the rise that follows ([Proposition 21.6](#prop-m3-on-chain-order-books-and-perpetual-dexs-squeeze)). Illustrative positions. Data: the chapter’s tutorial.*

**As of September 2026 — Delisting by validators.**

Hyperliquid’s documentation states that [validators](https://one-course.com/books/quant/3/en/chapter/14-blockchains-for-traders#def-m3-blockchains-for-traders-pow) vote on whether to delist validator-operated perpetuals; if they do, the perpetuals settle to the one-hour time-weighted spot [oracle](https://one-course.com/books/quant/3/en/chapter/14-blockchains-for-traders#def-m3-blockchains-for-traders-contract) price before the scheduled voting time, all positions are settled and open orders cancelled. The pattern above happened on 26 March 2025: a JELLY short passed to the vault, HLP, through liquidation, spot buying elsewhere took the vault’s unrealised loss to USD 13.5 million, and the [validators](https://one-course.com/books/quant/3/en/chapter/14-blockchains-for-traders#def-m3-blockchains-for-traders-pow) voted to delist the market, which settled at 0.0095 while about 0.50 was being fed to the [oracle](https://one-course.com/books/quant/3/en/chapter/14-blockchains-for-traders#def-m3-blockchains-for-traders-contract).

A vote that settles a market at a price is the decentralised equivalent of an exchange’s emergency powers. It can protect a vault from a squeeze; it also shows that the market’s rules can be changed by the [validators](https://one-course.com/books/quant/3/en/chapter/14-blockchains-for-traders#def-m3-blockchains-for-traders-pow) while positions are open, a governance risk that a trader prices in the same way as a centralised venue’s discretion.

## 21.4 App-chain and oracle-priced designs

Two other designs trade some of the on-chain book’s properties for performance or simplicity.

**As of September 2026 — An app-chain with an off-chain book.**

dYdX’s documentation describes its chain (“v4”) as a proof-of-stake chain built on CometBFT and the Cosmos SDK, whose [validators](https://one-course.com/books/quant/3/en/chapter/14-blockchains-for-traders#def-m3-blockchains-for-traders-pow) keep the order book in memory, off chain and outside consensus; when orders match, the block’s proposer adds the matches to its proposed block, and a block is committed when two thirds of the stake approve it. Proposers take turns in a stake-weighted round robin.

**Definition 21.7 (Oracle-priced exchange).**

An *oracle-priced exchange* is a perpetual or spot DEX that has no order book: traders open and close positions against a [liquidity pool](https://one-course.com/books/quant/3/en/chapter/20-automated-market-makers#def-m3-automated-market-makers-amm) at a price supplied by an [oracle](https://one-course.com/books/quant/3/en/chapter/14-blockchains-for-traders#def-m3-blockchains-for-traders-contract), with fees and price-impact charges set by the protocol, and the pool’s depositors take the other side of every trade.

**As of September 2026 — An oracle-priced perpetual exchange.**

GMX’s documentation describes a decentralised spot and perpetual exchange on Arbitrum, Avalanche and MegaETH, with leverage up to 100 times, that routes every order against its [liquidity pools](https://one-course.com/books/quant/3/en/chapter/20-automated-market-makers#def-m3-automated-market-makers-amm) and quotes the [oracle](https://one-course.com/books/quant/3/en/chapter/14-blockchains-for-traders#def-m3-blockchains-for-traders-contract) [index price](https://one-course.com/books/quant/3/en/chapter/17-perpetual-futures#def-m3-perpetual-futures-index) rather than relying on an order book or external market makers; it uses Chainlink Data Streams [oracles](https://one-course.com/books/quant/3/en/chapter/14-blockchains-for-traders#def-m3-blockchains-for-traders-contract), and liquidity providers earn 63% of the fees from trading, liquidations, borrowing and swaps on Arbitrum and Avalanche.

![Four designs of a derivatives venue, by who holds the book, who decides the order of actions, and who holds the collateral. Schematic.](https://one-course.com/images/onecourse/chapters/quant-3/m3-on-chain-order-books-and-perpetual-dexs/fig-a4167dabd224.svg)

***Figure 21.4.** Four designs of a derivatives venue, by who holds the book, who decides the order of actions, and who holds the collateral. Schematic.*

The oracle-priced design removes order-book games and replaces them with [oracle](https://one-course.com/books/quant/3/en/chapter/14-blockchains-for-traders#def-m3-blockchains-for-traders-contract) games: the pool loses whenever a trader knows the price better than the [oracle](https://one-course.com/books/quant/3/en/chapter/14-blockchains-for-traders#def-m3-blockchains-for-traders-contract), as an [automated market maker](https://one-course.com/books/quant/3/en/chapter/20-automated-market-makers#def-m3-automated-market-makers-amm) loses to arbitrageurs ([Chapter 20](https://one-course.com/books/quant/3/en/chapter/20-automated-market-makers#ch-m3-automated-market-makers)), and it must defend itself with fees, delays and limits on open interest. The off-chain book restores speed but hands the ordering of matches to each block’s proposer. For a trading firm the questions are those of any venue ([Chapter 15](https://one-course.com/books/quant/3/en/chapter/15-centralised-exchanges#ch-m3-centralised-exchanges)), with different answers: who orders its messages, what happens to its collateral if the venue fails, and who can change the rules while it is positioned.

## 21.5 Tutorial: two orderings of one block

**Goal.** Replay blocks of maker quotes, cancels and taker orders through a price-time-priority book under arrival order and under the class rule, and count the stale quotes picked off. **End state:** Figures [21.2](#fig-m3-on-chain-order-books-and-perpetual-dexs-pickoff) and [21.3](#fig-m3-on-chain-order-books-and-perpetual-dexs-squeeze).

1. **The rule.** Sort a block’s actions by class, keeping arrival order within each class. `def order_block (actions: list [Action], rule: str ) -> list [Action]: if rule == " arrival " : return list (actions) if rule == " cancels_first " : cls = {" alo " : 0 , " cancel " : 1 , " gtc " : 2 , " ioc " : 2 } return sorted (actions, key=lambda a: cls [a.kind]) # sort is stable: arrival order within a class raise ValueError(f " unknown in-block rule { rule} " ) def run_block (book: Book, actions: list [Action], rule: str ) -> list [Fill]: fills = [] for a in order_block(actions, rule): fills += book.apply(a) return fills` **Listing 21.1.** The in-block ordering and the block runner. code/firm/blockbook/firm_blockbook.py
2. **The replay.** A maker requotes every block; a taker attacks quotes that fair value has passed. `def replay (rule: str , blocks: int = 1_000 , seed: int = 21 , p_taker_first: float = 0.5 ) -> list [tuple [int , int , float ]]: """A maker quotes 5 lots two ticks either side of fair value with post-only orders and, every block, cancels and requotes around the new fair value. When fair value jumps past a resting quote, a taker sends an IOC to pick it off. Within a block the taker's order arrives before the maker's cancel with probability p_taker_first. Returns (block, lots picked off so far, maker's cumulative loss in ticks).""" rng = random.Random(seed) book, fair, oid = Book(), 1_000 , 1 run_block(book, [Action(" alo " , " M " , " sell " , fair + 2 , 5 , 1 ), Action(" alo " , " M " , " buy " , fair - 2 , 5 , 2 )], " arrival " ) live = {1 : (" sell " , fair + 2 ), 2 : (" buy " , fair - 2 )} picked, loss, rows = 0 , 0.0 , [] for blk in range (1 , blocks + 1 ): fair += round (rng.gauss(0 , 2.0 )) maker = [Action(" cancel " , " M " , oid=o) for o in live] new = {oid + 1 : (" sell " , fair + 2 ), oid + 2 : (" buy " , fair - 2 )} maker += [Action(" alo " , " M " , s, p, 5 , o) for o, (s, p) in new.items()] oid += 2 taker = [] for s, p in live.values(): if s == " sell " and p < fair: taker.append(Action(" ioc " , " T " , " buy " , p, 5 )) if s == " buy " and p > fair: taker.append(Action(" ioc " , " T " , " sell " , p, 5 )) acts = taker + maker if rng.random() < p_taker_first else maker + taker for f in run_block(book, acts, rule): if f.maker == " M " : picked += f.qty loss += f.qty * abs (fair - f.price) live = {o: sp for o, sp in new.items() if any (q[1 ] == o for q in book.bids + book.asks)} rows.append((blk, picked, loss)) return rows` **Listing 21.2.** The pick-off replay. code/markets-3/21-on-chain-order-books-and-perpetual-dexs/python/m3_perpdex.py
3. **Run** `replay` with the rules `arrival` and `cancels_first` , then `fig_perpdex.py` .

**What to change next.** Let the taker arrive first 90% of the time; let the maker’s cancel fall in the next block with some probability and see what the class rule still protects; add a second maker who never cancels.

## 21.6 Build: the block-batched book

**Purpose.** To trade on block-based venues the miniature firm must predict how its actions will be ordered and matched; to backtest there it must replay blocks exactly; and its risk must include the venue’s [open-interest caps](#def-m3-on-chain-order-books-and-perpetual-dexs-oicap) and its [mark price](https://one-course.com/books/quant/3/en/chapter/17-perpetual-futures#def-m3-perpetual-futures-index).

**Interface.** `Action(kind, trader, side, price, qty, oid)` with kinds `alo`, `gtc`, `ioc`, `cancel`; `Book(oi_cap)` with `apply(action)` and `best()`; `order_block(actions, rule)` for `arrival` and `cancels_first`; `run_block(book, actions, rule)`; `mark_price(oracle_basis, book_median, external)`, the median of the three. Uses `firm.perp` and `firm.liquidation` for margin.

**Rules.** Integer ticks and lots; stable sorting, so that replays are deterministic; [post-only orders](https://one-course.com/books/quant/3/en/chapter/15-centralised-exchanges#def-m3-centralised-exchanges-postonly) that would cross are rejected; orders that would take a position beyond the cap are rejected.

**Acceptance tests.** `code/firm/blockbook/tests/`: price-time priority and post-only rejection; a stale quote picked off under arrival order and protected under the class rule; the [open-interest cap](#def-m3-on-chain-order-books-and-perpetual-dexs-oicap); the median mark.

**Stretch.** Consensus batches within a block; margin checks at order entry and at the resting side’s fill; liquidation orders entering the block as IOCs.

Sources and further reading

- Hyperliquid documentation: HyperCore overview, order book, oracle, robust price indices, liquidations, protocol vaults, delisting, market making. Accessed September 2026.
- dYdX documentation, “Intro to dYdX Chain Architecture”; GMX documentation, introduction. Accessed September 2026.
- CoinDesk Research, 17 October 2025; Protos, 10 December 2025 (see [Chapter 18](https://one-course.com/books/quant/3/en/chapter/18-margin-liquidation-and-loss-allocation#ch-m3-margin-liquidation-and-loss-allocation) ).
- CoinDesk, “Hyperliquid Loses $4M After Whale’s Over $200M Ether Trade Unwinds”, 12 March 2025; “HyperLiquid Delists JELLY After Vault Squeezed in $13M Tussle”, 26 March 2025.

## 21.7 Exercises

**Exercise 21.1 ★.**

In one block arrive, in this order: an IOC buy at 101, a cancel of the ask at 101, and a post-only ask at 103. What executes under arrival order, and under the class rule?

**Solution of Exercise 21.1.**

Arrival order: the IOC buys the ask at 101, the cancel finds nothing, the new ask rests at 103. Class rule: the new ask at 103 rests, the cancel removes the ask at 101, and the IOC finds no ask at or below 101 and expires. Only the maker’s quote at 103 is left in both cases.

**Exercise 21.2 ★.**

Why can a general-purpose chain with 12-second blocks and per-transaction gas not host a competitive order book?

**Solution of Exercise 21.2.**

Every quote and cancel would cost gas and wait up to a block: makers could neither afford to update quotes nor cancel before being picked off, so they would quote wide or not at all; and the public [mempool](https://one-course.com/books/quant/3/en/chapter/14-blockchains-for-traders#def-m3-blockchains-for-traders-mempool) would show every cancel before it executed.

**Exercise 21.3 ★.**

What does the stake-weighted median of [validators](https://one-course.com/books/quant/3/en/chapter/14-blockchains-for-traders#def-m3-blockchains-for-traders-pow)’ [oracle](https://one-course.com/books/quant/3/en/chapter/14-blockchains-for-traders#def-m3-blockchains-for-traders-contract) prices protect against?

**Solution of Exercise 21.3.**

A [validator](https://one-course.com/books/quant/3/en/chapter/14-blockchains-for-traders#def-m3-blockchains-for-traders-pow), or a minority of stake, publishing a false price: the median ignores outliers, and moving it requires a majority of the stake to move together. The weighted median over venues inside each [validator](https://one-course.com/books/quant/3/en/chapter/14-blockchains-for-traders#def-m3-blockchains-for-traders-pow)’s price protects against one venue’s price being moved.

**Exercise 21.4 ★★.**

An asset has a maximum leverage of 20 times. What is its maintenance margin under the rule of [Box 21.3](#dat-m3-on-chain-order-books-and-perpetual-dexs-oracle), and at what equity is a position taken over by the vault?

**Solution of Exercise 21.4.**

Initial margin at 20 times is 5%, so maintenance is 2.5%; the vault takes over below two thirds of it, an equity of about 1.67% of notional.

**Exercise 21.5 ★★.**

A vault inherits a USD 4 million short at 3 times maximum leverage and the price then doubles. What does it lose?

**Solution of Exercise 21.5.**

$4\text{ million} \times (1 - 0.111) =$ USD 3.56 million.

**Exercise 21.6 ★★.**

Compare the risks a liquidity provider bears in an oracle-priced pool and in an order-book venue’s vault.

**Solution of Exercise 21.6.**

In an oracle-priced pool the provider is the counterparty to every trade at the [oracle](https://one-course.com/books/quant/3/en/chapter/14-blockchains-for-traders#def-m3-blockchains-for-traders-contract)’s price, and loses to anyone who knows the price better or sooner ([oracle](https://one-course.com/books/quant/3/en/chapter/14-blockchains-for-traders#def-m3-blockchains-for-traders-contract) latency, manipulation), plus the traders’ net P&L. In a vault it bears the inventory of its market making and the tail of inherited liquidations. Both concentrate the venue’s risk on depositors; the pool’s is continuous, the vault’s comes in jumps.

**Exercise 21.7 ★★★.**

*Coding.* With `replay`, raise the probability that the taker arrives first to 0.9. How do the two rules compare?

**Solution of Exercise 21.7.**

Arrival order: 980 lots picked off and 1 480 ticks lost; the class rule: none. The rule’s protection does not depend on who arrives first within the block, only on the maker’s cancel being in the same block.

**Exercise 21.8 ★★★.**

*Find the flaw.* “The venue is decentralised, so no one can change a market’s rules while I hold a position.”

**Solution of Exercise 21.8.**

[Validators](https://one-course.com/books/quant/3/en/chapter/14-blockchains-for-traders#def-m3-blockchains-for-traders-pow) can vote to delist a market and settle it at a price they specify by rule, and protocol parameters (margins, caps, the [oracle](https://one-course.com/books/quant/3/en/chapter/14-blockchains-for-traders#def-m3-blockchains-for-traders-contract)’s sources) can change by governance. Decentralised means that no single company decides, not that nothing can change.

## 21.8 Problem: The Squeezed Vault

**Problem 21.1.**

Weekend problem — a thin market, a large short, a public backstop

A thin [token](https://one-course.com/books/quant/3/en/chapter/14-blockchains-for-traders#def-m3-blockchains-for-traders-key) trades as a perpetual with a maximum leverage of 3 times. A trader opens a USD 10 million short and lets it be liquidated; the vault takes it over at two thirds of the maintenance margin. The [token](https://one-course.com/books/quant/3/en/chapter/14-blockchains-for-traders#def-m3-blockchains-for-traders-key)’s spot price, on small external venues, is then pushed up.

**Part I — The takeover.**

1. What is the maintenance margin, and what margin comes with the position when the vault takes it over?
2. Why could the position not be closed in the book before the takeover?
3. What does the vault lose if the price rises 100% before it can close? 400%?
4. Why can the trader profit although his short was liquidated?
5. What does the [oracle](https://one-course.com/books/quant/3/en/chapter/14-blockchains-for-traders#def-m3-blockchains-for-traders-contract) ’s construction make the attacker do?

**Part II — The cap.**

6. What cap on a single position keeps the vault’s loss within USD 5 million for squeezes up to 500%?
7. What would a cap of USD 2 million have limited the loss to at 400%?
8. Why should the cap depend on the depth of the external spot markets?
9. What other parameters could the venue tighten?
10. What does the vault’s depositor need to know about these parameters?

**Part III — Governance.**

11. What does a [validators](https://one-course.com/books/quant/3/en/chapter/14-blockchains-for-traders#def-m3-blockchains-for-traders-pow) ’ vote to delist do to open positions?
12. Who gains and who loses from settling at the [oracle](https://one-course.com/books/quant/3/en/chapter/14-blockchains-for-traders#def-m3-blockchains-for-traders-contract) ’s one-hour average?
13. Is the vote a failure of decentralisation or a feature of it?
14. How would a centralised venue have handled the same attack?
15. How does a trading firm price this governance risk?

**Part IV — Judgement.**

16. Should a vault backstop thin markets at all?
17. What makes an on-chain venue safer than a centralised one, and what does not?
18. Where would you want the firm’s market making: on the order-book DEX, the off-chain book or the oracle-priced pool?
19. State the *named result* : the vault’s loss as a function of the squeeze for a USD 10 million position, and the cap that bounds it to USD 5 million at 500%.
20. In one sentence: what is a public backstop?

**Solution of Problem 21.1.**

**1.** Half of the 33.3% initial margin at 3 times: 16.7%; at two thirds of that, 11.1% of notional, about USD 1.11 million. **2.** The book was too thin: a market order for USD 10 million would have moved the price far, and was sent in 20% slices that did not restore margin. **3.** USD 8.89 million at 100%; USD 38.89 million at 400%. **4.** He holds offsetting long positions in other accounts or markets that gain from the rise, while the loss on the liquidated short stops at his margin. **5.** Move the spot price on several external venues at once, since the [oracle](https://one-course.com/books/quant/3/en/chapter/14-blockchains-for-traders#def-m3-blockchains-for-traders-contract) is a weighted median over them: the cheapest venues to move set how much the attack costs. **6.** $5/(5 - 0.111) \approx$ USD 1.02 million. **7.** USD 7.78 million. **8.** The squeeze the attacker can afford depends on what it costs to move the [oracle](https://one-course.com/books/quant/3/en/chapter/14-blockchains-for-traders#def-m3-blockchains-for-traders-contract)’s sources; thin external markets make large squeezes cheap. **9.** Higher margin tiers for large positions, lower maximum leverage, total [open-interest caps](#def-m3-on-chain-order-books-and-perpetual-dexs-oicap), [oracle](https://one-course.com/books/quant/3/en/chapter/14-blockchains-for-traders#def-m3-blockchains-for-traders-contract) sources and weights, and the size of liquidation slices. **10.** The caps, tiers and [oracle](https://one-course.com/books/quant/3/en/chapter/14-blockchains-for-traders#def-m3-blockchains-for-traders-contract) rules that bound its tail, and the governance process that can change them. **11.** All positions are settled at the rule’s price and orders cancelled. **12.** Those short the squeezed asset gain relative to a settlement at the squeezed price, the attacker’s longs lose; the vault is spared the continuing squeeze. **13.** Both: it is a collective decision by rule-holders, not by a company, but it shows that rules can change during a position. **14.** By its own staff: raising margins, restricting the market, delisting, or settling at a chosen price under its terms of service. **15.** As a discount or a limit on positions in markets where such votes are plausible (thin, recently listed, vault-backstopped). **16.** Only with caps sized to the external markets’ depth, or not at all for [tokens](https://one-course.com/books/quant/3/en/chapter/14-blockchains-for-traders#def-m3-blockchains-for-traders-key) whose spot can be moved cheaply. **17.** Safer: custody on chain, public state, rules that apply to all; not safer: [oracle](https://one-course.com/books/quant/3/en/chapter/14-blockchains-for-traders#def-m3-blockchains-for-traders-contract) dependence, public backstops that can be targeted, governance intervention, and smart-contract risk. **18.** Where the in-block rule protects its quotes and the fees suit its volume, typically the [on-chain order book](#def-m3-on-chain-order-books-and-perpetual-dexs-perpdex) with cancels first; the oracle-priced pool is a counterparty, not a place to make markets. **19.** *Named result:* a loss of USD $10\text{ million} \times (s - 0.111)$ for a squeeze $s$ (USD 38.89 million at 400%), and a cap of about USD 1.02 million to keep it within USD 5 million at 500%. **20.** Depositors’ capital that stands behind every liquidation, and so a target for anyone who can make a liquidation go wrong.

## 21.9 Interview questions

**Interview question 21.1 ★ trader.**

How does an [in-block priority rule](#def-m3-on-chain-order-books-and-perpetual-dexs-priority) that applies cancels before orders change a market maker’s economics?

**Solution of Interview question 21.1.**

It removes the pick-off of stale quotes whenever the maker’s cancel lands in the same block as the taker’s order, lowering adverse selection; makers can quote tighter and larger, and takers must beat the maker by a whole block to pick off a quote.

*What the interviewer is looking for: adverse selection moved from makers to takers.*

**Interview question 21.2 ★ developer.**

What changes in your order-management system when the venue is a [blockchain](https://one-course.com/books/quant/3/en/chapter/14-blockchains-for-traders#def-m3-blockchains-for-traders-chain) with sub-second blocks?

**Solution of Interview question 21.2.**

Messages are signed transactions with nonces; acknowledgements come per block; the state of orders is read from blocks, not from a private stream; in-block ordering rules determine matching; gas or [rate limits](https://one-course.com/books/quant/3/en/chapter/15-centralised-exchanges#def-m3-centralised-exchanges-ratelimit) per action; reconciliation against the chain’s state; and key management for signing wallets.

*What the interviewer is looking for: blocks as the clock, and signatures as the session.*

**Interview question 21.3 ★★ researcher.**

Compare a weighted median of external prices with a volume-weighted average as an [oracle](https://one-course.com/books/quant/3/en/chapter/14-blockchains-for-traders#def-m3-blockchains-for-traders-contract).

**Solution of Interview question 21.3.**

A median ignores up to half the weight of outliers, so a manipulated or broken venue does not move it; a volume-weighted average follows every source in proportion and can be moved by wash-traded volume. The median can jump between sources and lags when the market moves on the heavy ones.

*What the interviewer is looking for: robustness against responsiveness.*

**Interview question 21.4 ★★ risk.**

What limits would you set for a firm’s exposure to a [perpetual DEX](#def-m3-on-chain-order-books-and-perpetual-dexs-perpdex)’s vault or pool?

**Solution of Interview question 21.4.**

Deposits in a vault or pool as a credit and tail exposure: a limit by venue, sized to stress losses (squeezes, [oracle](https://one-course.com/books/quant/3/en/chapter/14-blockchains-for-traders#def-m3-blockchains-for-traders-contract) failures), lock-up periods, monitoring of open interest and caps, and of governance proposals.

*What the interviewer is looking for: tail losses and liquidity of the deposit.*

**Interview question 21.5 ★★ trader, researcher.**

How would you attack an [oracle-priced exchange](#def-m3-on-chain-order-books-and-perpetual-dexs-oracle), and how would you defend it?

**Solution of Interview question 21.5.**

Attack: trade when the [oracle](https://one-course.com/books/quant/3/en/chapter/14-blockchains-for-traders#def-m3-blockchains-for-traders-contract) is stale (latency), move thin [oracle](https://one-course.com/books/quant/3/en/chapter/14-blockchains-for-traders#def-m3-blockchains-for-traders-contract) sources, or open positions at a price known to be about to change. Defend: robust multi-source [oracles](https://one-course.com/books/quant/3/en/chapter/14-blockchains-for-traders#def-m3-blockchains-for-traders-contract), delays or price-impact fees, [open-interest caps](#def-m3-on-chain-order-books-and-perpetual-dexs-oicap), and limits on position size relative to the sources’ depth.

*What the interviewer is looking for: the gap between the [oracle](https://one-course.com/books/quant/3/en/chapter/14-blockchains-for-traders#def-m3-blockchains-for-traders-contract) and the true price.*

**Interview question 21.6 ★★★ developer.**

Design a deterministic replay system for a block-based venue’s order books from its published blocks.

**Solution of Interview question 21.6.**

Ingest blocks with their transactions in proposed order; implement the venue’s in-block rule and matching exactly; replay from a known snapshot, verifying the resulting book and positions against published state at checkpoints; keep the replayer deterministic (integer arithmetic, stable sorting) and version it with the protocol’s upgrades.

*What the interviewer is looking for: exact rules, snapshots and checkpoints.*
