Skip to content
Criée

The book, a sorted structure

Two sides sorted by price then rank, aggregated into levels, and the cost of possible structures.

Lesson 311 min

By the end of this lesson

  • Write the price-then-rank sort key for each side of the book
  • Read the aggregated view and the spread returned by the engine
  • Estimate the cost of an insertion, sorted array or levels with binary search
In this lesson5

An order book is "the set of all active orders in a market at time t" (Gould et al., 2013, section 2.1). For a developer, it is first a data structure: two sorted lists, one per side, with a precise sort key. The whole engine rests on this sort.

The sort key

The execution rule is priority by price, then by time: at the same price, the order that arrived first goes ahead (AMF, "Choosing and placing a stock market order"). A market order has priority over a limit order (BVMAC General Rules 2025, art. 159).

Price-time priority

The book's sorting rule: best price first; at the same price, the order that arrived first.

The "best price" does not mean the same thing on both sides. On the buy side, the best is the highest; on the sell side, the lowest. The sort key is therefore a pair [prix, rang], with a sort direction that depends on the side. Here is the engine's function:

export function trierCote(ordres: Ordre[], sens: Sens): Ordre[] {
  const cle = (o: Ordre) =>
    o.limite === null ? (sens === 'achat' ? Infinity : -Infinity) : o.limite
  return [...ordres].sort((a, b) => {
    const pa = cle(a)
    const pb = cle(b)
    if (pa !== pb) return sens === 'achat' ? pb - pa : pa - pb
    return a.rang - b.rang
  })
}

Two details deserve attention. A market order gets an infinite notional price (+∞ when buying, -∞ when selling): it thus goes ahead of every limit order, with no special case in the comparator. And [...ordres] copies the array before sorting, because Array.prototype.sort sorts in place.

Two sides facing each other. On the left, five green buyers’ crates; on the right, five coral sellers’ crates, of different lengths depending on the quantity offered. At the top, the two best prices: one hand on each side reaches towards the other, separated by a small gap, the spread.
An order book as a market stall: the best prices at the top, face to face

Sorting, order by order

Send the orders one at a time. To the right of each row, the key [prix, rang] explains its place. Watch D, at the same price as A but arriving later, and G, the market order.

Sorting a book, order by order0/7

Empty book. Send the first order.

Buys

key: price descending, then rank ascending

  1. empty

Sells

key: price ascending, then rank ascending

  1. empty

From memory: on the sell side, two orders at 10,100, ranks 2 and 6, and one at 10,050, rank 5. In what order are they served?

From book to screen: aggregating by level

A trading screen does not show orders one by one, but price levels: at each price, the total quantity and the number of orders. Gould's survey calls depth the sum of quantities at a given price, and spread the gap between the best selling price and the best buying price (section 2.1).

const carnet = new Carnet()
carnet.passer({ id: 'A', sens: 'achat', quantite: 40, limite: 9950 })
carnet.passer({ id: 'D', sens: 'achat', quantite: 15, limite: 9950 })
carnet.passer({ id: 'E', sens: 'vente', quantite: 20, limite: 10050 })

carnet.vue()
// { achats: [{ prix: 9950, quantite: 55, ordres: 2 }],
//   ventes: [{ prix: 10050, quantite: 20, ordres: 1 }] }
carnet.fourchette()
// { achat: 9950, vente: 10050, ecart: 100 }

By default, vue() shows five levels. The 2008 draft planned to publish the five best aggregated limits (Instruction no. 2, section 5); the value is a parameter, not a current rule.

A price level has a life of its own: it is born with the first order at that price, grows, drops back when a better price arrives, shrinks under executions, then disappears with its last order. Follow the 9,950 level, framed in yellow, and the queue of orders it holds.

The life of a price level1/6

Buy side, vue()

9,95040 · 1 order(s)
A 40 · r1

Niveau 9,950

{
prix: 9950
quantite: 40
ordres: 1
}

carnet.passer({ id: 'A', achat, 40, 9950 })

9,950: 40 shares

The level is born with a first order.

The cost of this choice

The teaching engine stores each side in an unsorted array and calls trierCote on every incoming order: O(n log n) per order, for n resting orders. It is readable and enough for a few hundred orders. A production engine would rather organise each side into sorted price levels, each level holding a "first in, first out" queue:

// Sketch: one level = one FIFO queue; levels stay sorted
interface NiveauPrix { prix: number; file: Ordre[] }
interface Cote { niveaux: NiveauPrix[] } // buys: descending price

Inserting then means finding the level (binary search, O(log p) for p levels) and appending to the queue, O(1).

We found no reliable source describing the data structure of the BVMAC's book or any other platform's. The two structures above are design choices of the teaching engine, presented for their cost, not as the way a real system works.

Going further

The [prix, rang] key rests on the integer rank chosen in the lesson Modelling an order. What remains is what this sort costs, and what it does not protect.

The real cost of an order. In the teaching engine, passer sorts the opposite side for every incoming order (trierCote copies then sorts, O(n log n)), and every call to vue() or fourchette() sorts both sides. Over a session of m orders, the total cost grows as m × n log n. With levels already sorted, finding the place of a price becomes a binary search:

// Buy side: levels sorted by falling price
function indexNiveau(niveaux: { prix: number }[], prix: number): number {
  let bas = 0
  let haut = niveaux.length
  while (bas < haut) {
    const milieu = (bas + haut) >> 1
    if (niveaux[milieu]!.prix > prix) bas = milieu + 1
    else haut = milieu
  }
  return bas
}

const niveaux = [{ prix: 10100 }, { prix: 10000 }, { prix: 9950 }]
indexNiveau(niveaux, 10000) // 1: the level exists, the order joins the end of the queue
indexNiveau(niveaux, 10050) // 1: new level, inserted between 10,100 and 10,000
indexNiveau(niveaux, 9900)  // 3: new level, in last position

Step by step, for 10,050:

  1. bas = 0, haut = 3, milieu = 1: 10,000 is not above 10,050, so haut = 1.
  2. milieu = 0: 10,100 is above 10,050, so bas = 1.
  3. bas === haut: the loop stops, the index is 1.

The index alone does not say whether the level exists: compare niveaux[i]?.prix with the price sought. And inserting into an array shifts everything after it, O(p); a balanced tree avoids that shift. These are design choices, with no source on real platforms (see the box above).

A trap: ordres() returns the internal objects. trierCote copies the array, not the orders inside it:

const c = new Carnet()
c.passer({ id: 'A', sens: 'achat', quantite: 40, limite: 9950 })
c.ordres().achats[0]!.quantite = 0 // a screen that "fixes" a display
c.vue()        // { achats: [{ prix: 9950, quantite: 0, ordres: 1 }], ventes: [] }
c.fourchette() // { achat: 9950, vente: null, ecart: null }

A level with zero quantity shows up in the view, and the spread shows a best buy that no longer exists. This is known limit no. 1 of the engine contract sheet. Write the test that reveals it (change a returned order, then check that vue() has not changed): it will be red, and that is intended.

From memory: why does the sort key use an integer rank rather than a time? And what does an incoming order cost, in the teaching engine, against n resting orders?

Your turn

On the sell side, which limit order is the best?

1On the sell side, which limit order is the best?

Why does trierCote give a market order an infinite price?

2Why does trierCote give a market order an infinite price?

Two buy orders at the same price: which goes first?

3Two buy orders at the same price: which goes first?

What does fourchette() return when one side is empty?

4What does fourchette() return when one side is empty?

In the engine, changing an order returned by ordres()...

5In the engine, changing an order returned by ordres()...

Levels 10,100, 10,000 and 9,950 on the buy side: where does indexNiveau put 10,050?

6Levels 10,100, 10,000 and 9,950 on the buy side: where does indexNiveau put 10,050?

Read next: Gould et al., « Limit order books », Quantitative Finance, 2013

A question? Ask your teacher, or an AI assistant, giving it the title of this lesson.

Share:WhatsAppLinkedIn

Going further