A hands-on look at how a limit order book works — matching engines, price discovery, support and resistance zones — with a live simulation you can drive yourself.
Every price you see on a stock chart is the residue of a negotiation — not between two people sitting across a table, but between thousands of anonymous limit orders queued in a data structure called the limit order book (LOB). Understanding the book turns a noisy price chart from a mystery into something close to legible.
This post builds a live, interactive order book simulation from the ground up, explains what support and resistance actually are at a mechanical level, and lets you play matching-engine operator yourself. If you are interested in how these simulated prices compare to different random-walk models and real stock data, see the companion post: Generating Fake Stock Charts: From Random Walks to Order Books.
What Is a Limit Order Book?
At any major exchange — NYSE, NASDAQ, CME — every security is matched by a software system called a continuous double auction. Participants submit two kinds of orders:
| Type | What it says | When it executes |
|---|---|---|
| Limit order | "I'll buy 200 shares, but only at $99.80 or better" | Waits in the book until a matching counterparty arrives, or is cancelled |
| Market order | "Buy 100 shares right now at whatever price the book offers" | Executes immediately against the best resting orders |
The book itself is just two sorted queues:
Asks (sellers, sorted ascending by price):
$100.40 × 200 ← further from mid
$100.30 × 500 ← best ask ──┐
─────────────────────────────── │
SPREAD = $0.20 │ The spread is the
─────────────────────────────── │ minimum cost of
$100.10 × 400 ← best bid ──┘ round-tripping
$100.00 × 800
$ 99.90 × 1200 ← further from mid
Bids (buyers, sorted descending by price):The spread — best ask minus best bid — is the minimum transaction cost. Market makers earn this spread by continuously quoting on both sides; their profit is the slippage they collect from impatient buyers and sellers who cross the spread via market orders.
How a Trade Happens
When a new limit buy order arrives at **100.30), the matching engine:
- Pairs it with the $100.30 sell order
- Decrements both quantities by the traded amount
- Records the trade price — $100.30
That single tick update is what you see moving on a chart. There is no central authority setting the price. The price emerges from the crowd.
Support and Resistance — A Mechanical Definition
Technical analysts talk about support and resistance as if they are mystical forces. They are not. They are direct consequences of order book density.
Resistance zones
A resistance zone is a price range where a large cluster of sell (ask) orders is waiting to be executed. As the price rises into that cluster, each incoming market buy order is absorbed by the waiting asks. The buying pressure is literally eaten by the resting supply. Until all those asks are consumed, the price cannot advance further — it is resisted by the unfilled sell orders.
The red bands on the heatmap below represent resistance zones. The brighter the red, the denser the concentration of asks at that price level.
Support zones
A support zone is the mirror image: a dense cluster of buy (bid) orders below the current price. A falling price runs into those bids, which absorb the selling pressure and bounce the price upward.
The green bands on the heatmap represent support zones.
These are not self-fulfilling prophecies based on trader psychology (though that reinforcement is real too). They are an observable consequence of the order flow that currently exists in the book.
Live Simulation
The playground below runs a full continuous double auction. Each step:
- A batch of fake traders submit limit orders priced by a Gaussian distribution around the current mid-price
- A fraction of existing orders are randomly cancelled (mimicking real-world cancellation rates, which exceed 90% on some exchanges)
- The matching engine pairs any crossing orders and records trade prices
The price chart heatmap overlays the full order book depth as coloured bands:
- 🟥 Red bands = ask orders (resistance). Brighter = more orders at that level.
- 🟩 Green bands = bid orders (support). Brighter = more orders at that level.
Things to try:
- 🧱 Resistance demo — Seeds a thick wall of ask orders just above the current price. Watch the red band appear on the chart. Hit ▶ Start and observe how the price repeatedly tries to climb through the wall and is pushed back down. Then click Buy 1000 to punch a large market order through — the price spikes as the wall is consumed. Once the asks are gone, new orders refill the book and the price may drift back.
- Order bias slider — Drag toward
+1 aboveto have fake traders concentrate their orders above mid. Watch red resistance bands build up above the current price. Drag toward−1 belowto build green support below. - High cancel rate — Makes the book thin and unstable. Zones dissolve quickly, spreads widen, and price jumps erratically.
- Low sigma — Orders cluster tightly around mid. The book is deep near the spread, zones are dense, and price moves in small steps.
Order Book & Matching Engine
Continuous double auction: fake traders submit limit orders, the matching engine pairs crossing bids & asks, and price discovery emerges from the aggregate pressure.
Price chart — green bands = bid depth (support), red bands = ask depth (resistance). Brighter = more orders queued at that price.
Order book pressure
Order book depth
price / qtyMarket orders — greedy fill against resting book liquidity
What This Reveals About Price Charts
The heatmap is the book's "gravity field"
Dense zones of orders act like gravitational attractors or repellers. Price drifts toward support, bounces off resistance. When a resistance zone is finally consumed by aggressive buying (a large market order, or sustained buy pressure), the price can gap up rapidly because there are no resting asks to absorb the momentum — until the next zone forms.
Resistance becomes support
After a price level is bought through and the asks are consumed, resting bids from buyers who didn't fill at lower prices often accumulate at the old resistance level. Traders call this "resistance becomes support". Mechanically: the former ask wall has been cleared, but new limit buy orders now pile up at that price because buyers remember it as a "fair level". The zone flips.
Market impact of large orders
Click Buy 1000 a few times in a row. Each time you do, the price jumps upward, potentially blowing through several levels. This is market impact — a large order moves the price against itself. Institutional traders split large orders into smaller pieces over time (VWAP or TWAP execution) precisely to minimize this effect.
In real exchanges, around 95% of all limit orders are cancelled before execution. High-frequency traders submit and cancel thousands of orders per second, continuously updating their quotes as the market moves. This cancellation rate is why the displayed book depth is a poor predictor of where large orders will actually fill — the visible depth is a shadow of the true supply and demand.
The Matching Engine — Under the Hood
The simulation implements a simplified price-time priority matching engine:
// Execute up to 3 matches per step (prevents price runaway)
for (let match = 0; match < 3; match++) {
const bestBid = Math.max(...bids.keys())
const bestAsk = Math.min(...asks.keys())
if (bestBid < bestAsk) break // no crossing orders — done
// Trade at midpoint of the crossing prices
const tradePrice = snap((bestBid + bestAsk) / 2)
const bq = bids.get(bestBid)!
const aq = asks.get(bestAsk)!
const filled = Math.min(bq, aq)
// Decrement or remove the matched levels
filled >= bq ? bids.delete(bestBid) : bids.set(bestBid, bq - filled)
filled >= aq ? asks.delete(bestAsk) : asks.set(bestAsk, aq - filled)
trades.push(tradePrice)
mid = tradePrice
}This is a stripped-down version of what NASDAQ's INET system does millions of times per second. The key principle is price priority: the best-priced orders trade first. When multiple orders are at the same price, time priority breaks the tie (first in, first out) — though our simulation doesn't track order arrival time.
Order arrival: the Gaussian model
Fake traders place orders drawn from a Gaussian centred slightly on their side of the spread (buyers discount, sellers premium), with standard deviation σ set by the "Price spread σ" slider:
// Buyer: wants to pay less than mid
const buyPrice = snap(gauss(mid - σ * 0.5 + biasOffset, σ * 0.8))
// Seller: wants to receive more than mid
const sellPrice = snap(gauss(mid + σ * 0.5 + biasOffset, σ * 0.8))The bias parameter shifts biasOffset = bias × σ, tilting order placement up or down. At +1, buyers are willing to pay above mid and sellers cluster orders above mid too — this builds upward momentum. At −1, the reverse: orders pile up below mid, building support and downward pressure.
Limitations of This Model
This simulation is deliberately simplified. A production-grade LOB simulator would also need to model:
- Iceberg orders — large institutional orders that show only a small "tip" in the public book; the rest is hidden and revealed incrementally
- Order arrival as a Poisson process — real order flow has well-characterised inter-arrival statistics, not a fixed-rate batch
- Informed vs. noise traders — some market participants have genuine information edge; this creates adverse selection for market makers
- Latency and co-location — in real HFT, reaction time of microseconds matters; the "first" matcher physically closest to the exchange wins
- Cross-asset correlations — index futures drive equity prices; ETF arbitrage links individual stocks to the index
Each of these introduces additional statistical structure. The best open-source approaches use agent-based models where heterogeneous participants interact — the Santa Fe Artificial Stock Market being the classic academic example.
Further Reading
- Glosten, L. R., & Milgrom, P. R. (1985). Bid, ask and transaction prices in a specialist market with heterogeneously informed traders. Journal of Financial Economics.
- Cont, R., Stoikov, S., & Talreja, R. (2010). A stochastic model for order book dynamics. Operations Research.
- Bouchaud, J.-P., Farmer, J. D., & Lillo, F. (2009). How markets slowly digest changes in supply and demand. Handbook of Financial Markets.
- Farmer, J. D., et al. (2005). The predictive power of zero intelligence in financial markets. PNAS.
Related Articles
Generating Fake Stock Charts: From Random Walks to Order Books
A deep dive into synthetic stock price generation — from naive coin-flip random walks, through Gaussian distributions and fat tails, to a simulated order book — and how candlestick pattern analysis reveals the gap between each model and reality.
The Abelian Sandpile: A Group Hiding in a Pile of Sand
The Bak–Tang–Wiesenfeld sandpile model (ASM) is a deceptively simple cellular automaton that conceals a rich algebraic structure — an abelian group whose identity element is a non-trivial fractal-like configuration.