The Order Book: How Price is Actually Born

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.

·9 min read

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:

TypeWhat it saysWhen 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(meetingorbeatingthebestaskof100.30** (meeting or beating the best ask of 100.30), the matching engine:

  1. Pairs it with the $100.30 sell order
  2. Decrements both quantities by the traded amount
  3. 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:

  1. A batch of fake traders submit limit orders priced by a Gaussian distribution around the current mid-price
  2. A fraction of existing orders are randomly cancelled (mimicking real-world cancellation rates, which exceed 90% on some exchanges)
  3. 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 above to have fake traders concentrate their orders above mid. Watch red resistance bands build up above the current price. Drag toward −1 below to 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.

Order arrival rate: 10 / step
Price spread σ: 0.5%
Cancel rate: 20%
Order bias: neutral

Price chart — green bands = bid depth  (support), red bands = ask depth (resistance). Brighter = more orders queued at that price.

Mid: $100.00Best bid: $99.90Best ask: $100.10Spread: $0.20Bid/ask imbalance:0%

Order book pressure

Bids 398Asks 396
Resistance zones (red) are price levels where a dense wall of sell orders waits to be executed. As price rises into that cluster, the incoming buy orders are absorbed by the waiting asks, slowing or reversing the advance — the price gets “pushed back down” by unfilled supply. Support zones (green) work in reverse: concentrated bids cushion falling prices and bounce them upward. Use the Order bias slider to pile orders above or below mid-price and watch how the zones form and shift.

Order book depth

price / qty
101.20
17
101.10
11
101.00
26
100.90
23
100.80
11
100.70
27
100.60
41
100.50
27
100.40
30
100.30
61
100.20
52
100.10
40
spread
$0.20
99.90
27
99.80
36
99.70
30
99.60
41
99.50
51
99.40
41
99.30
34
99.20
26
99.10
14
99.00
22
98.90
21
98.80
20
Speed:2 steps/s
step #0

Market 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:

matching-engine.ts
// 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:

  1. Iceberg orders — large institutional orders that show only a small "tip" in the public book; the rest is hidden and revealed incrementally
  2. Order arrival as a Poisson process — real order flow has well-characterised inter-arrival statistics, not a fixed-rate batch
  3. Informed vs. noise traders — some market participants have genuine information edge; this creates adverse selection for market makers
  4. Latency and co-location — in real HFT, reaction time of microseconds matters; the "first" matcher physically closest to the exchange wins
  5. 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