CLOB - Central Limit Order Book
A Central Limit Order Book (CLOB) is a deterministic matching engine. It acts as a transparent, automated marketplace that accepts orders from traders, organizes those orders by price and time, and executes trades immediately whenever a buyer's demands crosses paths with a seller's supplies.
1. Structure
An order book is split cleanly down the middle into two opposing sides:
- The Asks (Sells) → This side contains orders from people who own the asset and want to sell it. They want the execution price to be as high as possible. The order book sorts these from the lowest price to the highest price. The very top of this list is the Best Ask (the cheapest available seller in the market).
- The Bids (Buys) → This side contains orders from people who have capital and want to buy the asset. They want the execution price to be as low as possible. The order book sorts these from the highest price to the lowest price. The very top of this list is the Best Bid (the buyer willing to pay the most).
Spread
The gap between the Best Bid and the Best Ask is called the bid-ask spread. In a normal market, these two prices never touch. For example, if the highest buyer is willing to pay $99.95 and the cheapest seller wants $100.00, the spread is $0.05. No trades happen until someone compromises on price.
The spread is one of the most important metrics in a market. A smaller spread (eg. $0.01) means the market is highly liquid and competitive, where there are many buyers and sellers who broadly agree on what the asset is worth. A wide spread (eg. $1.00) means the market is illiquid or uncertain, where buyers and sellers are far from agreeing on what the asset is worth, which makes trading more expensive.
2. Price Definition
A CLOB does not have a single fixed price for an asset. Instead, the order book contains a continuous spectrum of prices that buyers and sellers are willing to transact at, and the "price" that gets quoted at any given moment is derived from that spectrum.
There are several different price concepts in an order book:
The Mid Price is the most commonly quoted "price" of an asset. It is simply the mathematical midpoint between the Best Bid and the Best Ask. If the Best Bid is $99.95 and the Best Ask is $100.00, the mid price is $99.975. This is what most price feeds and charts display when they say the value an asset is worth.
The Last Traded Price is the price at which the most recent trade actually executed. This tells what the market agreed on a moment ago, not what it will agree on next. In fast-moving markets, the last traded price can diverge meaningfully from the current mid price.
The Mark Price is a concept used specifically in perpetuals markets. Because a perpetual contract doesn't settle like a spot trade, the protocol needs a stable, manipulation-resistant reference price for things like calculating unrealized PnL, triggering liquidations, and settling funding rates. The mark price is typically derived from a combination of the mid price and external oracle price feeds, weighted to smooth out any short-term manipulation attempts. It is the price the protocol officially recognizes.
Execution Price is the actual price a specific trader gets when their order gets filled. For small orders, this is usually very close to the Best Ask or Best Bid. For large orders, the execution price will be worse than the best available price because the order consumes multiple levels of the book before it is fully filled, in what is know as price impact (see Section 5).
3. Order Priority
To keep the marketplace fair, the order book treats every single incoming order according to a strict rule called Price-Time Priority (often referred to as FIFO (First-In, First-Out)).
- Price → The order book always prioritizes the best price for the market. If Buyer A offers $100 for a share, and Buyer B later offers $101, Buyer B instantly jumps to the front of the line because they are offering a better deal.
- Time → If two traders want to buy at the exact same price (e.g. both offer $100), the order book looks at who placed their order first. The trader who arrived first gets filled first. The later order is placed at the back of that specific price level's queue.
This system is intentionally designed to remove any possibility of favoritism, where the order book cannot be instructed to fill one trader before another unless their price or arrival time justifies it.
4. Order Lifecycle
When a new order enters the order book, it takes one of two possible pathways depending on the trader's instructions:
Market Orders (The Takers)
A market order is intended to be executed immediately.
- An incoming Market Buy immediately goes through the Best Ask (and upwards if needed).
- Because they take liquidity out of the book, these traders are called Takers.
- The trade-off is certainty of execution vs. certainty of price. A taker is guaranteed to get filled (assuming there are enough resting orders on the other side), but has no guarantee on exactly what price they will receive, especially for large orders.
Limit Orders (The Makers)
A limit order is a conditional instruction. If the trader wants to buy at exactly $100:
- If there is already a seller waiting at $100 or cheaper, a trade occurs instantly.
- If the cheapest seller is at $101, the order will not be filled. Instead, it gets placed into the Bid queue at the $100 price level. It becomes a Resting Order, waiting for a future seller willing to execute at this price.
- Because they add liquidity to the book for others to use, these traders are called Makers.
- The trade-off here is the inverse of a market order. A maker gets price certainty, because they will never fill at a worse price than they asked for, but they have no guarantee of when or whether their order fills at all. If the market never reaches their price, the order sits in the order book indefinitely.
Order Modifiers
Beyond the basic market/limit split, a CLOB typically supports additional instructions that control what happens to an order if it can't be immediately and fully filled:
- GTC (Good Till Cancelled) → The default. The order rests in the book until it is fully filled or the trader cancels it manually. Most resting limit orders are GTC.
- IOC (Immediate or Cancel) → The order attempts to fill whatever it can right now against available resting orders, and any unfilled portion is instantly canceled. Nothing is left resting in the book.
- FOK (Fill or Kill) → Even stricter than IOC. The order must be filled completely and immediately, or the entire thing is canceled outright. No partial fills allowed.
- Post-Only → The order is only accepted if it will rest in the book as a maker. If placing it would immediately execute as a taker, the order book rejects it. This is used by traders who specifically want the maker fee rate.
5. Matching Loop
When a matching event occurs, the order book processes the queue using a simple comparative check. Lets imagine an incoming buy order for 50 units matches against the resting sell orders:
-
Scenario 1 (Full Fill) → The resting order at the front of the queue is selling 30 units. The order book executes a trade for 30 units. The resting order is wiped out and deleted from the book. The incoming order still needs 20 units, so the order book looks at the next resting order in line to repeat the process.
-
Scenario 2 (Partial Fill): The resting order at the front of the queue is selling 100 units. The order book executes a trade for the incoming order's full 50 units. The incoming order is completely satisfied and disappears. The resting order's quantity drops from 100 to 50, and it retains its position at the front of the line for the next trade.
This loop continues until either the incoming order is completely filled, or there are no more resting orders left at an acceptable price, where whatever remains of the incoming order becomes a resting order itself (if it was a limit order), or is canceled (if it was a market or IOC order).
Price Impact
When a large order goes through multiple levels of the book, each successive fill happens at a slightly worse price than the one before it. This phenomenon is called Price Impact. It is the cost of consuming all available liquidity at one price level and having to move on to the next.
For example, if there are sellers at $100.00 (50 units), $100.05 (30 units), and $100.10 (40 units), and a buyer submits a market order for 100 units, they will receive:
- 50 units at $100.00
- 30 units at $100.05
- 20 units at $100.10
Their average execution price ends up being around $100.035 — worse than the initial best ask of $100.00. A very large order in a thin book can move the price significantly, which is why traders and protocols pay close attention to book depth (how many units are available at or near the best price).
Slippage
Slippage is the broader difference between the price a trader expected when they submitted an order and the price they actually received when it filled. Price impact is one cause of slippage, but not the only one.
Price impact is caused by your own order consuming multiple price levels, and it can be calculated in advance by inspecting the book. Slippage is the total execution shortfall from all sources, some of which are unpredictable.
The other main causes of slippage are:
Market movement during execution → In the time between a trader submitting an order and the order book confirming it, other trades can happen and the price can shift. Onchain, this window is the block time (~400ms on Solana). In a fast-moving market, the best ask when you submitted the transaction may no longer exist by the time your transaction is confirmed.
MEV and sandwich attacks → Onchain specifically, bots can observe a pending transaction in the mempool and insert their own trades, buying before the trader's order pushes the price up, then immediately selling after. The trader's fill happens at the artificially elevated price, and the bot captures the difference.
Quote cancellations → A resting order that was available when the matching loop started may have been canceled by its owner a fraction of a second earlier. The order book falls through to the next price level, giving a slightly worse fill than expected.
Slippage tolerance → A mechanism to control slippage risk. A trader sets a maximum acceptable slippage percentage (eg. 0.5%) and the protocol rejects the transaction entirely if the final execution price would fall outside that bound. This protects traders from unexpectedly bad fills but some orders may fail to execute during volatile periods.
Slippage is particularly consequential in a perpetuals protocol because leverage amplifies its effect. A 0.5% slippage on a 10x leveraged position represents a 5% loss on the trader's margin before the position has even begun to move. It also shifts the entry price, which directly affects where the liquidation threshold sits, meaning unexpected slippage can move a trader's liquidation price closer than they intended.
6. Adding orders to the Order Book
There are several things that have to happen first, and a few things that can cause an order to be rejected before it ever reaches the order book.
1. Validation → The order book first checks whether the order is structurally valid: Is the price a legal value (positive, within any configured bounds, aligned to the market's minimum tick size)? Is the quantity above the minimum order size? Does the trader have sufficient margin or collateral to back the position?
2. Margin Check → The order book needs to reserve margin against the potential position before the order rests. If the trader doesn't have enough free collateral to back the order at the specified size and leverage, the order is rejected immediately, before it touches the book.
3. Crossing Check → The order book checks whether the incoming order crosses the spread. A buy limit order at $100 that arrives when the best ask is $99 would immediately execute as a taker, not rest as a maker. The order book detects this and routes it through the matching loop first. Only if there is any unfilled portion of the order, does it go into the queue.
4. Placement → If the order doesn't get filled, it is inserted into the correct price level in the book. If other orders already exist at that price, the new order is placed behind them in time order.
5. Acknowledgement → The order book confirms the order has been accepted and is now resting.
An order can leave the book in three ways: it fills completely, the trader cancels it, or the order book rejects/removes it due to a margin health failure because the trader's account falls below the minimum required margin while the order is resting, and the order book cancels the order to protect itself.
7. Longs and Shorts
In a spot order book, a trade is simple and final as one party gives up an asset and receives cash and the other gives up cash and receives the asset. Ownership is transfered and the trade is done. In a perpetuals CLOB this is fundamentally different because instead of exchanging an asset, both sides are opening a contract that tracks the asset's price. No underlying asset ever changes hands.
Going Long
A trader who goes long is betting that the price will rise. When someone open a long position, they are entering a contract that pays them profits proportional to how much the price increases from their entry point. If SOL is at $150 when they open and rises to $180, they profit on the $30 difference, multiplied by their position size and leverage.
In order book terms, opening a long means buying a contract. The trader submits a buy order, either a market order to open immediately, or a limit order to open at a specific price, and when that order matches against a resting sell order, the long position is opened. The matched counterparty on the other side of that trade is opening (or closing) a short position.
Closing a long works in reverse as the trader submits a sell order to exit the contract. When it fills, the position is closed and PnL (Profit And Losso) is settled.
Going Short
A trader who goes short is betting that the price will fall. Their contract pays them profit proportional to how much the price decreases from their entry point. If SOL is at $150 when they open and drops to $120, they profit on the $30 difference, multiplied by their position size and leverage.
In order book terms, opening a short means selling a contract, even though the trader doesn't own any underlying asset. They submit a sell order, which rests on the ask side of the book or immediately matches against a resting bid. When it fills, the short position is open.
Closing a short works in reverse as the trader submits a buy order to exit. When it fills, the position is closed and PnL is settled.
How does this work in the order book
From the order book's perspective, there is no difference between a trader opening a long and a trader buying spot. Both submit a buy order. The book matches it against the best available ask and executes the trade. What distinguishes a perpetuals trade from a spot trade is what happens after the match. The protocol records an open position for both parties, tracks the entry price, calculates margin requirements, and monitors the position against liquidation thresholds. The book itself is agnostic to all of that.
This means the same order book simultaneously handles four types of activity, all of which look like regular buy or sell orders:
| Order direction | Intent |
|---|---|
| Buy | Opening a long |
| Buy | Closing a short |
| Sell | Opening a short |
| Sell | Closing a long |
If a trader has no open position and submits a buy order, it opens a long. If they already have an open short and submit a buy order of the same size, it closes the short. The book just sees a buy order either way.
Open Interest
Because every open position requires a counterparty on the other side, longs and shorts in the market are always equal in number, for every open long contract there is an open short contract on the other side. The total number of open contracts outstanding at any moment is called Open Interest (OI). This is one of the most important metrics for a perps protocol.
Rising open interest means money is entering the market and new positions are being opened, whereas a falling open interest means positions are being closed and capital is leaving. A sharp drop in OI often signals a wave of liquidations or a coordinated exit.
An high OI might not always be positive as having an OI when in comparision to the protocol's liquidity means that there is more open trades than there might be liquidity to fullfill them. This is especially dangerous in a market crash, where traders might panic sell and many others might get liquidated, creating a liquidity chokepoint where there isn't enough liquidity to absorb the crash, increasing slippage to extreme levels, potentially crashing the value of an asset (as it happened on October 10th 2025).
Margin, Leverage, and Liquidation
Because no asset is exchanged when a position opens, both the long and the short need margin which is collateral held by the protocol to cover potential losses. Margin is what makes leverage possible, for example a trader opening an order with $1,000 in margin at 10x leverage controls a $10,000 position. Their profit and loss is calculated on the full $10,000, but they only had to commit $1,000 upfront.
The protocol continuously monitors each open position against its margin. If the market moves against a trader and their losses approach the value of their posted margin, the protocol triggers a liquidation, forcibly closing the position to prevent the account from going negative. The liquidation price is determined when a position is opened based on the entry price, the leverage used, and the maintenance margin rate (MMR) set by the protocol.
In a CLOB specifically, liquidations are handled by submitting a market order on behalf of the distressed account to close the position at the best available price. In a thin or fast-moving market, this liquidation order can itself cause price impact, which is why positions need to be close before losses reach 100% of the margin, not after.
A liquidation might be calculated using the following formula:
8. Market Makers
The order book only works if there are resting orders on both sides for takers to match against. In theory, anyone can post a limit order and become a maker. In practice, most of the depth on any healthy order book comes from market makers.
A market maker is a trader or firm that simultaneously posts a buy limit order and a sell limit order on both sides of the book, continuously, across market conditions, essentially offering to buy from anyone who wants to sell, and sell to anyone who wants to buy.
For example, they post a bid at $99.95 and an ask at $100.00. If one retail trader buys at $100.00 and another sells at $99.95, the market maker has facilitated both sides and captured the $0.05 spread as profit which, multiplied across thousands of trades a day, adds up to consistent revenue (if they managed their positions well).
Rather than posting a single bid and a single ask, active market makers typically post several orders at multiple price levels simultaneously. This gives them exposure to different price points. They continuously update these quotes as the market moves, potentially cancelling and reposting orders hundreds of times per minute in fast and liquid markets, to keep their orders competitive and their inventory relatively neutral, without pending too much for each side of the order book. The tighter the spread the more trades they attract, but the less profit margin they have per trade and the more exposed they are to adverse selection.
Most exchanges and protocols actively incentivize market making through their fee structure. Makers typically pay a lower fee than takers, or in some cases the protocol pays them a small amount per filled maker order.
Some of the risks a market maker faces are:
Inventory risk → If a market maker posts bids and gets filled by many sellers, they accumulate a large long position. If the price then drops, that inventory loses value faster than the spread income compensates. Staying more or less neutral between bids and asks (managing inventory) is the core challenge of market making.
Adverse selection → Sophisticated traders (including algorithmic traders and arbitrageurs) often know something about where the price is going before market makers do, so when buy or sell they tend to be right, which means the market maker is repeatedly selling just before the price rises or buying just before it falls. A market maker's spread has to be wide enough to compensate for these losing trades against informed counterparties.
Latency risk → If news moves the price of an asset, a market maker's resting orders are suddenly stale, meaning their bid might be too high or their ask too low, leading to their postions being filled before they can update to a new price. This is one of the main disavantages in fully onchain CLOBs because block times create windows where market maker can't update quotes fast enough.
9. Book Depth and Market Health
The depth of an order book refers to how many units are available to buy or sell at various price levels near the best bid and best ask. A deep book has large quantities resting at many price levels, which means that even large orders cause minimal price impact. A shallow book has small resting quantities, so even moderately sized orders can move the price significantly.
Book depth is usually visualized as a depth chart, a cumulative chart that shows how much total volume is available from the best price upwards/downwards. The shape of this chart tells you a lot about how the market is feeling:
- A smooth, symmetrical depth chart suggests balanced, healthy liquidity on both sides.
- A chart that is much deeper on one side suggests more participants are positioned on that side, which can hint at the direction the value of an asset is going.
- A sudden massive block of bids or asks at one price are notable because they can act as support or resistance, but they can also be fake, meaning a participant posts those orders to create a false impression and cancels them before they fill.
10. Self-Trade Prevention
An important mechanism in a CLOB is self-trade prevention (STP). This is the rule that stops a trader from filling their own orders.
Self-trading can happen naturally in algorithmic trading, where the same entity is running multiple strategies that could end up on opposite sides of the same market. It creates artificial volume with no real economic transfer, and it can distort the price of the order book.
Most order books solve this by flagging orders with the trader's id so that when the matching loop is about to fill a new order against a resting order, it checks whether both orders belong to the same account. If they do, the order book either cancels the resting order, cancels the incoming order, or cancels both, depending on the protocol's configuration.