Modelling an order
A type, integers rather than floats, a rank rather than a time, and the rules that keep an order valid.
Lesson 212 min
By the end of this lesson
- Model an order with integers for prices and quantities
- Tell the rules the engine checks from those left to your code
- Use a discriminated union and never to have a forgotten case flagged
In this lesson4
An order looks simple: buy or sell, how many, at what price. The bugs hide in the details of the type: a price stored as a float, a negative quantity accepted, two orders arriving "at the same time". This lesson settles an order model and the rules that keep it valid.
What the literature says
In the reference survey on order books, an order is a triple: a price, a size and a submission time (Gould et al., 2013, section 2.1). The BVMAC rules admit two order types into the trading system: the limit order and the market order, which has no price (BVMAC General Rules 2025, art. 157 to 160).
Here is the teaching engine's type:
export type Sens = 'achat' | 'vente'
export interface Ordre {
id: string
sens: Sens
quantite: number
limite: number | null // null: market order
rang: number // arrival rank, instead of a time
auteur?: string // display label
}
Limit order
An order setting a maximum buying price or a minimum selling price; its unexecuted part rests in the book.
Three design choices
A null rather than a type field. limite: number | null encodes both admitted types in a single field. The alternative is a discriminated union, wordier but more explicit:
type OrdreModele =
| { type: 'limite'; sens: Sens; quantite: number; limite: number }
| { type: 'marche'; sens: Sens; quantite: number }
It has one advantage: the day a third type arrives, the compiler flags every incomplete switch. The rules state that the BVMAC "may authorise other order types" (same text).
A rank rather than a time. Two orders can carry the same time to the millisecond. A strictly increasing counter never produces a tie, and time priority becomes a simple integer comparison. The 2008 draft market rules already provided for "a sequential order number per security" (Instruction no. 2, 2008); it is an old text, quoted here for the idea.
Integers rather than floats. This is the choice that prevents the most bugs.
0.1 + 0.2 === 0.3 // false: 0.30000000000000004
10_050 + 50 === 10_100 // true, always
The engine expresses prices and quantities as integers. For shares this is natural: orders are expressed in local currency, per share (BVMAC General Rules 2025, art. 156). Bonds are quoted as a percentage of face value with two decimals (art. 186): store them in hundredths of a point, so 99.50% becomes 9950. An amount prix × quantite stays exact as long as it does not exceed Number.MAX_SAFE_INTEGER, about 9 × 10¹⁵; beyond that, switch to bigint.
The tick size (the smallest allowed price step) is set by a BVMAC instruction (BVMAC General Rules 2025, art. 133 and 166), but its current value was not found. Make it a per-security parameter, never a constant.
The rules that keep an order valid
quantiteis a strictly positive integer;limiteisnullor a strictly positive integer (and, later, a multiple of the tick);idis unique within the session;rangstrictly increases from one order to the next.
The engine checks only one of them: the first. Send it orders and compare its verdict with your rules. Try a quantity of 0, then 2.5, then a limit of -3 or 10000.5.
Try 0, 2.5, -3 or an empty limit.
When the engine accepts what your rules reject, you have not necessarily found a bug: you have found a decision to make and a test to write.
Now follow a form input all the way to the Ordre object. Two details to watch for: the rank assigned at step 4, which is not 1, and the decimal limit at step 5, which the engine lets through.
raw input
form submitted
Strings, not yet an order
From memory: why an integer rank rather than a time for time priority?
Going further
In the lesson The domain in ten objects, the order was just a box on the map. Here it becomes a type; three questions remain open in production.
Validate at the boundary, once. The scene shows it: between the form and the engine, a parsing step turns strings into types. Make it a function that returns either a valid order or the list of all errors. The rest of the code then handles only orders that are already valid.
import type { Ordre, Sens } from '@criee/marche'
type Resultat =
| { ok: true; ordre: Omit<Ordre, 'rang'> }
| { ok: false; erreurs: string[] }
// lireNombre: '10 100' → 10100, '2,5' → 2.5, '' → null
function lireOrdre(s: { id: string; sens: string; quantite: string; limite: string }): Resultat {
const erreurs: string[] = []
const quantite = lireNombre(s.quantite) ?? NaN
const limite = lireNombre(s.limite) // null if the field is empty: market order
if (s.sens !== 'achat' && s.sens !== 'vente') erreurs.push('unknown side')
if (!Number.isInteger(quantite) || quantite <= 0) erreurs.push('quantity not a positive integer')
if (limite !== null && (!Number.isInteger(limite) || limite <= 0)) erreurs.push('limit not a positive integer')
return erreurs.length
? { ok: false, erreurs }
: { ok: true, ordre: { id: s.id, sens: s.sens as Sens, quantite, limite } }
}
Step by step, on three fictional inputs:
lireOrdre({ id: 'o1', sens: 'achat', quantite: '2,5', limite: '10 100,5' })returns{ ok: false, erreurs: ['quantity not a positive integer', 'limit not a positive integer'] }: both errors at once, not just the first.lireOrdre({ id: 'o2', sens: 'achat', quantite: '25', limite: '10 100' })returns a limit order at10100.lireOrdre({ id: 'o3', sens: 'vente', quantite: '10', limite: '' })returns a market order,limite: null.
The other two rules (unique identifier, increasing rank) cannot be checked on an order in isolation: they need the session state, so they belong in the engine or in the gateway that feeds it.
The day prix × quantite overflows. The amounts below are fictional and deliberately extreme:
Number.MAX_SAFE_INTEGER // 9007199254740991
const prix = 9_000_000, quantite = 2_000_000_000
Number.isSafeInteger(prix * quantite) // false
prix * quantite + 1 === prix * quantite // true: the +1 is lost
BigInt(prix) * BigInt(quantite) + 1n // 18000000000000001n, exact
Beyond MAX_SAFE_INTEGER, two neighbouring integers share the same representation: the error is silent. A test that checks Number.isSafeInteger on every amount costs one line.
The discriminated union and never. With OrdreModele, a switch can require every order type to be handled:
function decrire(o: OrdreModele): string {
switch (o.type) {
case 'limite': return `limit at ${o.limite}`
case 'marche': return 'at market'
default: {
const jamais: never = o // stops compiling if an order type is forgotten
return jamais
}
}
}
Add a third variant to OrdreModele: the line const jamais: never = o stops compiling, and the compiler leads you to every switch to complete.
From memory: in the scene, why does order o2 get rank 2? And, from the previous lesson, how many executions can it produce?
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.