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.

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.
Empty book. Send the first order.
Buys
key: price descending, then rank ascending
- empty
Sells
key: price ascending, then rank ascending
- 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.
Buy side, vue()
Niveau 9,950
carnet.passer({ id: 'A', achat, 40, 9950 })
9,950: 40 shares
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:
bas = 0,haut = 3,milieu = 1: 10,000 is not above 10,050, sohaut = 1.milieu = 0: 10,100 is above 10,050, sobas = 1.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
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.