انتقل إلى المحتوى
guide7 نوفمبر 2026 · 10 min read

How a crypto exchange matching engine works: order types, price-time priority, self-trade prevention and determinism

How a crypto exchange matching engine works: the order book, price-time priority, order types, self-trade prevention, determinism, latency and what to test.

BitPolaris Engineering

English original

A crypto exchange matching engine holds the order book and decides which orders trade, at what price and in what sequence. Kraken and Coinbase Exchange both document price-time priority: the best price trades first, and at the same price the earliest order trades before later ones. The trade prints at the price of the order resting on the book. Around that loop sit order types, self-trade prevention, balance checks, the sequencer and journal that make results reproducible, market data and the brakes. This guide explains each from public exchange documentation and ends with what to test before you buy an order matching engine.

What the engine does, and what it does not

An order passes five stages: the gateway authenticates it, applies rate limits and rejects malformed input; pre-trade risk checks the account can pay and locks the funds; the sequencer gives it a number that, from then on, defines what happened first; matching produces fills, a resting remainder or a rejection; and the outputs send trades to the ledger, updates to the owner and book changes to the public feed.

The engine is not the ledger: it knows which orders exist and what traded, the ledger knows who owns what, and keeping the two consistent is much of the work in an exchange core.

The order book data structure

Each market has bids sorted from the highest price down and asks from the lowest up, and each price level is a first-in, first-out queue. A typical implementation combines a sorted structure of price levels, a linked list of orders per level and a hash map from order ID to position, so a cancel does not search the book. Market makers typically cancel and replace quotes far more often than they trade, so cancel cost matters as much as match cost.

The grid is configuration: tick size, quantity step and minimum, minimum order value. Binance publishes these per symbol as the PRICE_FILTER, LOT_SIZE and NOTIONAL filters, a useful template for what your console should expose. Use fixed-point decimals, never binary floating point; 0.1 has no exact binary form, and a ledger that drifts per trade will not reconcile.

Price-time priority versus pro-rata

Kraken’s exchange trading rules describe a single order queue in which the best price is matched first and, at the same price, “priority is given to the earliest order received”. Coinbase Exchange describes price-time priority “as received by the matching engine”: a resting buy at 100 USD filled by an incoming sell at 80 USD trades at 100 USD. Kraken’s rules also say that an order whose limit price is amended goes to the back of the queue at the new price, and that a triggered conditional order joins the back of the queue. Publish an answer for every kind of amendment; market makers price their quotes on it.

Pro-rata, the main alternative, splits an incoming order among resting orders at a price in proportion to their size, with remainders allocated by time. Databento’s breakdown of CME’s algorithms lists three-month SOFR futures outrights matching by a top-order allocation, then pro-rata with a two-lot minimum, then FIFO.

Price-time (FIFO) Pro-rata
Who fills first at a price The earliest order Every resting order, in proportion to its size
What it rewards Speed and early commitment Size at the level
Side effect A race to the front of the queue An incentive to post oversized orders
Where you find it Spot books such as Kraken’s and Coinbase Exchange’s Some futures and options books, such as parts of CME

For a spot crypto venue, price-time is what traders expect, and it is easy to write in the form MiCA Article 76(1)(e) asks of a trading platform’s operating rules: “non-discretionary rules” and “objective criteria for the efficient execution of orders”.

Order types and time-in-force

An order type says how an order prices itself; time-in-force says how long it may live. Write yours down with this precision.

Instruction Behaviour Public reference
Limit, good-till-cancelled (GTC) Rests at its price or better until filled or cancelled Binance, Coinbase Exchange, Kraken
Market Trades immediately with no price guarantee Coinbase Exchange takes a size or a funds amount, not both; Kraken allows no time-in-force on market orders
Stop (stop-market) Waits off the book; when triggered, becomes a market order Binance STOP_LOSS
Stop-limit When triggered, places a limit order Binance STOP_LOSS_LIMIT; Kraken stop-loss-limit
Post-only Rejected if any part would trade immediately Binance LIMIT_MAKER; Coinbase Exchange post-only; Kraken post flag
Immediate-or-cancel (IOC) Fills what it can now, cancels the rest Binance, Coinbase Exchange, Kraken
Fill-or-kill (FOK) Fills in full now or not at all Binance, Coinbase Exchange, Kraken API
Good-till-time or -date Rests until a stated expiry Coinbase Exchange GTT; Kraken GTD

Three details separate a working implementation from a demo. Stop orders sit in a trigger table outside the book, and their trigger price (last trade, mark or index) must be documented. FOK needs a dry run that confirms the whole quantity is available before any part executes. Market orders need protection on thin books: Kraken rejects them when the spread is wide, “typically when the spread is 2.5-20% of market price depending on the currency pair”.

Self-trade prevention

A self-trade happens when an account’s incoming order would match its own resting order. No asset changes owner, yet volume prints and the last price can move, which is why venues block it; MiCA Article 76(7)(g) requires trading systems “able to prevent or detect market abuse”. Self-trade prevention (STP) decides which order gives way.

Mode Effect Coinbase Exchange Kraken Binance
Cancel newest Incoming order cancelled; resting order stays cn cancel-newest (default) EXPIRE_TAKER
Cancel oldest Resting order cancelled; incoming order continues co cancel-oldest EXPIRE_MAKER
Cancel both Both cancelled cb cancel-both EXPIRE_BOTH
Decrement Smaller order cancelled, larger reduced by the same amount dc (default) Not offered DECREMENT
None Trade allowed Not offered Not offered; STP applies to all orders NONE

Binance sets the allowed modes and the default per symbol, and adds a TRANSFER mode for trade groups. In an evaluation, ask about scope, precedence and reporting. Binance compares the same account or accounts sharing a tradeGroupId, so linked accounts, such as a market maker’s sub-accounts, can be kept from trading with each other. Coinbase Exchange gives the taker’s instruction precedence, as Binance typically does. Binance reports the prevented quantity on expired orders, so client records reconcile. Publish your default per market and log every prevented match.

Pre-trade risk: where balances are locked

The usual design locks funds before an order reaches the book: a limit buy locks price times quantity in the quote asset (plus the maximum fee if fees are charged in quote), a sell locks the base quantity, and each fill or cancel releases exactly what it consumed, so available plus locked always equals the balance. Market buys have no known cost in advance; engines require a quote budget, estimate from the book with a buffer, or lock the available balance and release the remainder.

Where the lock lives matters. A ledger-side lock keeps the engine simple but costs a database write per order; an in-memory lock is faster but makes the engine a second record of balances to reconcile after every restart. Either is defensible; a vendor who cannot say which they built is not.

Other limits complete the picture: maximum order size, maximum open orders (Binance MAX_NUM_ORDERS) and price bands around a recent average price (Binance PERCENT_PRICE). MiCA Article 76(7)(d) expects systems able “to reject orders that exceed pre-determined volume and price thresholds or are clearly erroneous”.

Determinism, sequencing and recovery

A deterministic engine produces the same book, trades and trade IDs every time it processes the same inputs in the same order. Recovery, replicas and audits depend on it, and it is easy to lose: the matching path must not read the wall clock (timestamps are assigned at sequencing), iterate over unordered hash maps, use floating point or depend on thread scheduling.

The best-known public description is the LMAX architecture, written up by Martin Fowler in 2011: business logic in memory on a single thread, every input event in a durable journal, a state that “is entirely derivable by processing the input events”, snapshots to shorten replay, and follower nodes processing the same input stream as the leader. On a crypto venue that means a sequencer that numbers every command, a journal written before the order is acknowledged, and an in-memory book that can always be rebuilt.

Recovery then becomes a procedure: load the last snapshot, replay the journal tail, and let the ledger, market data and notifications discard output with sequence numbers they have already applied. A standby consuming the same journal can take over without rebuilding state from the ledger, and replay answers the customer who asks why an order filled at a given price. MiCA Article 76(15) requires a trading platform to keep order data for at least five years, including what links each order to the transactions it produced, or to give the authority access to the order book; a sequenced journal is a direct source for that record.

Matching engine latency: claims versus what matters

Headline numbers measure the inner loop. Fowler’s article describes 6 million orders per second on a single thread; the open-source exchange-core project reports 5 million operations per second on one order book on what its README calls 10-year-old hardware (Intel Xeon X5690), with latency figures that cover only risk processing and matching, excluding network, inter-process communication and journaling.

A bare “orders per second” claim therefore tells you little. Set against those figures, the inner loop is unlikely to be what limits a new venue; the gateway, journal writes, the ledger applying fills and WebSocket fan-out during a volatile minute are more likely candidates. Ask for gateway-to-acknowledgement latency at p50, p99 and p99.9 with journaling, risk checks and market data on, at your expected peak with a realistic share of cancels, again during a burst above it, plus the delay from trade to public feed. MiCA Article 76(7)(b) asks for “sufficient capacity to deal with peak order and message volumes”; a load-test report naming hardware and order mix is the evidence.

Market data: snapshots and deltas

Feeds publish trades, a book aggregated by price level and, on some venues, every order. They send a snapshot, then deltas carrying sequence or update IDs so clients detect gaps:

  • Binance tells clients to buffer diff-depth events, fetch a REST snapshot, discard events at or below its lastUpdateId and apply the rest; the stream updates every 1,000 ms, or 100 ms on request.
  • Coinbase Exchange uses sequence numbers on its full channel and says its level2 channel “guarantees delivery of all updates”.
  • Kraken adds a CRC32 checksum of the top ten levels to each book update, so a client can prove its local book matches.

Build market data from the engine’s sequenced output, not from queries of the book, so the feed matches what traded. MiCA Article 76(9) to (11) requires bid and ask prices and depth published continuously, trades as close to real time as technically possible, and the data free 15 minutes after publication and kept for at least two years.

Circuit breakers, price bands and trading states

Brakes work at three levels. Per order, price bands and market price protection reject orders far from a reference price or into a wide spread. Per market, trading states restrict what is accepted: Coinbase Exchange can flag a product trading-disabled, cancel-only, post-only or limit-only, one at a time, and in post-only mode “no orders will be matched”. Per venue, there is the halt, and not every venue automates it: Kraken’s rules say it “does not employ the use of automated circuit breakers to halt trading”; they describe discretionary suspension, a maintenance mode and a cancel-only mode.

MiCA requires operating rules that set the conditions for suspension (Article 76(1)(g)) and systems that keep trading orderly under severe stress (Article 76(7)(c)): document the trigger, who may pull it and how the market reopens, and log each switch. A band is only as good as its reference price: guarding an exchange’s reference price shows how a brake can freeze the price it protects.

How the BitPolaris engine fits

The BitPolaris Exchange block includes a matching engine written in Go with gRPC and AMQP transport: spot matching with limit, market and stop-limit orders and self-trade prevention. It is the engine that runs the reference exchange; the system has been in production since 2024. Markets and maker-taker fee tiers are set in the 53-screen operations console, and the book and trade feed stream over WebSocket.

Liquidity is separate: the Mirror engine quotes 97 markets from reference venues and hedges fills there, subject to venue balances and risk limits; your own market makers use the API; a panic control pulls all mirrored books (how mirroring works). Where a regime restricts the operator’s own dealing on its platform, as MiCA Article 76(5) does, who runs a market-making account is a question for counsel, not a software setting.

We do not publish an orders-per-second figure; apply the tests below to us as to any vendor. On the self-hosted and source-code licences the logs, database and configuration sit on your servers, so you can repeat them.

What to test in an RFP

Test How to run it What a pass looks like
Determinism Replay a recorded session on a fresh node Identical trades, trade IDs and final book
Crash recovery Kill the engine during a load run Resumes from snapshot plus journal; no lost or duplicated fills; the ledger reconciles
Self-trade prevention Cross orders from one account and from linked sub-accounts, in each mode The documented order is cancelled; prevented quantity reported and logged
Order-type edges FOK against partial liquidity, post-only that would cross, a stop triggered through a gap Each behaves exactly as the rulebook says
Balance locks A random sequence of places, fills and cancels Available plus locked equals the balance for every account after every event
Price bands and limits Orders outside the band, above the maximum size, beyond the open-order cap Rejected with a specific reason code
Load Your peak order mix with cancels, journaling and risk checks on, then a burst above it p50, p99 and p99.9 gateway latency and feed lag, hardware named
Market data Drop a client mid-burst and rebuild from snapshot and deltas Gaps detected; rebuilt book matches the exchange’s
Trading states Switch a market to cancel-only, halt it, reopen it The engine obeys each state; every switch is in the audit log

The requirements checklist sets these beside deployment, custody and exit requirements; the self-hosted guide covers what your team runs once the engine is on your servers.

Matching engine FAQ

What is a crypto exchange matching engine?

The software that holds each market’s order book and matches orders under fixed rules, usually price-time priority. It sequences orders that passed the gateway and pre-trade checks, produces trades and updates, and feeds the ledger and public market data. Balances live in the ledger, not the engine.

What is price-time priority?

The best-priced order trades first and, at the same price, the earliest trades first, at the resting order’s price. Kraken and Coinbase Exchange document it for their spot books. The main alternative, pro-rata, splits fills by resting size and appears on some futures and options books.

Which self-trade prevention mode should be the default?

Cancel newest is the simplest to explain and is Kraken’s default; decrement-and-cancel, Coinbase Exchange’s default, cancels the smaller order and reduces the larger. Either way, allow a per-order override, cover linked sub-accounts and log every prevented match.

How fast does a matching engine need to be?

Fast enough that the matching loop is never the constraint; published single-threaded designs reach millions of operations per second there. Customers feel gateway-to-acknowledgement latency at p99 during a burst, with journaling and risk checks on, and the delay before trades reach the public feed; ask for both, with hardware named.

Do regulators require a deterministic matching engine?

MiCA does not use the word. Article 76 requires non-discretionary execution rules, capacity for peak volumes, rejection of orders beyond set thresholds, full testing, business continuity and at least five years of order records; a sequenced, replayable engine is a direct way to evidence them. This is a technical reading of the rules, not legal advice; counsel should confirm.

BitPolaris licenses the exchange software behind a live venue: a Go matching engine with self-trade prevention, the Mirror liquidity engine and a 53-screen operations console, on your servers, as source code or as a hosted cloud instance. Prices are public.

See the Exchange block · Build a year-one estimate

Sources

All pages read on 7 November 2026.

احجز مكالمة تحديد نطاق لمدة 30 دقيقة

Crypto exchange, payments, wallet, custody and token launch software, already running in production. Run it on your own servers, license the source code, or let us host it under your brand.