Teacher sheet
The market in code
- Who it is for
- Developers and testers with no financial training who can read TypeScript; best run as a team workshop rather than a lecture.
- Prerequisites
- Reading TypeScript: discriminated unions, pure functions, unit tests.
- The order book, order type and auction lessons of the Market mechanics course (/en/etudiant/).
- Optional: the repository open to read the @criee/marche engine code alongside the lessons.
Sessions
Session 1 · The domain, the order and the book90 min
- The domain in ten objects
- Tell an order, an execution and a settlement apart in code
- Treat the settlement delay as a parameter, since no text fixes it
- Explain why numbering executions makes an import replayable without duplicates
- Modelling an order
- 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
- The book, a sorted structure
- 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
- 10 min · Opening question, written answer: “What is the difference between an execution and a settlement?” Compare after the reading
- 25 min · Reading of “The domain in ten objects”: the domain map on screen and the object transformation; a buy of 40 filled by two sells gives how many executions? Then the quiz
- 25 min · Reading of “Modelling an order”: have participants feed invalid orders to the lesson’s validator, then discuss the discriminated union and the use of never; quiz
- 25 min · Reading of “The book, a sorted structure”: write the price-then-rank sort key for each side on the board, estimate the cost of an insertion; quiz
- 5 min · Wrap-up: everyone writes down why an integer rank replaces the time in priority
Session 2 · Continuous trading, auctions and invariants90 min
- Continuous trading, line by line
- Follow the Carnet.passer loop line by line down to the remainder
- Predict the trade price the engine uses in continuous trading
- Explain what happens to a market order’s remainder and to the caller’s object
- The auction in code
- Calculate the demand, supply and volume curve over the candidate prices
- Apply the auction tie-break rules and read which rule decided
- Predict who is filled at the equilibrium price, by time priority
- An engine’s invariants
- State the six invariants of an engine and recognise a breach
- Spot what threatens the determinism of a matching engine
- Use a property-based test: replay the seed, read the shrinking
- 10 min · Recall: on the sell side, two orders at 10,100 (ranks 2 and 6) and one at 10,050; in what order are they filled?
- 25 min · Reading of “Continuous trading, line by line”: walk through Carnet.passer, have participants predict the trade price and the remainder before running the trace; quiz
- 25 min · Reading of “The auction in code”: predict the auction before the engine does, then tackle the lesson’s challenge on building candidate prices; quiz
- 25 min · Reading of “An engine’s invariants”: the invariant bench, replaying a seed and reading the shrinking of a property-based test; quiz
- 5 min · Wrap-up: everyone links one of the six invariants to a line of code seen in the session
Session 3 · Tests, the FIX protocol and checking a session90 min
- From business rule to test case
- Turn a business rule into a given, when, then test case
- Choose the edge cases that put a rule to the test
- Handle an uncovered rule and interpret a surviving mutant
- Order life cycle and the FIX protocol
- Describe an order’s state machine and its forbidden transitions
- Recognise the FIX messages for an order and their default values
- Handle sequence numbers and duplicates in a FIX session
- From engine to MIMS: checking a session
- Follow an engine session through to the client account movements
- Check the allocation and the cash total to reveal an anomaly
- Choose the key that makes importing an executions file idempotent
- 10 min · Recall: what is the difference between an example test and a property-based test?
- 25 min · Reading of “From business rule to test case”: in pairs, write a priority rule as given, when, then, choose its edge cases, then the surviving-mutant challenge; quiz
- 25 min · Reading of “Order life cycle and the FIX protocol”: the state machine and forbidden transitions, the journey of a FIX message, sequence numbers and duplicates; quiz
- 25 min · Reading of “From engine to MIMS: checking a session”: the session summary, the sum of cash movements, choosing the key that makes an import idempotent; quiz
- 5 min · Wrap-up: everyone writes one test case they would add to their own project
Session 4 · Amend, replay, record90 min
- Amending and cancelling an order
- Predict how amending an order affects its time priority
- Write an amendment with annuler then passer, keeping the rank
- Handle what annuler returns, including for an order already filled
- Logging and replaying a session
- Rebuild the book at a given moment by replaying the log
- Compare two sessions by their fingerprint, where execution order matters
- Explain why the log and the snapshot must keep the ranks
- From an execution to entries
- Turn an execution into securities and cash movements carrying its reference
- Check that the movements of all accounts, commissions included, cancel out
- Correct a wrong execution by a reversing entry, without deleting anything
- 10 min · Day’s review at /en/revision/: everyone answers the questions that are due, then the ones several people missed are corrected aloud
- 25 min · Reading of “Amending and cancelling an order”: does B, reduced from 20 to 10, keep its place? Challenge: write an amendment with cancel then submit while keeping the rank; quiz
- 25 min · Reading of “Logging and replaying a session”: rebuild the book at a given moment, compare two sessions by their fingerprint; quiz
- 25 min · Reading of “From an execution to entries”: securities and cash movements, a zero sum including fees, correction by reversal; quiz
- 5 min · Wrap-up: everyone writes down why an erroneous execution is never deleted
Session 5 · Reference sheets and assessment60 min
- Sheet: the engine contract
- Recall the signature and guarantees of each engine function
- Recall the known limits of the teaching engine, each one to test
- Sheet: invariants and test cases
- Recall the six invariants and how they become assertions
- Recall the edge cases to cover and the checks after a session
- 10 min · Recall: what does fixing() return when no price allows a trade?
- 15 min · The “engine contract” sheet: each pair takes one function and presents its signature, guarantees and one known limitation to test
- 15 min · The “invariants and test cases” sheet: recite the six invariants in order, then list the checks to run after a session
- 15 min · Assessment at /en/developpeur/evaluation/, alone and without notes: 15 questions drawn from the quizzes, 11 correct answers for the certificate, to print or photograph
- 5 min · Wrap-up: everyone picks one invariant to turn into a test in their own code
Tips
- The site is a static export with no server: a page only reopens offline if the browser has already loaded it, and nothing guarantees it. Have the lessons for the session opened the day before, while connected, or project them from a computer that has already displayed them.
- Quiz answers feed the spaced review at /en/revision/: a question comes back the next day, then after 3, 7, 16 and 35 days. Open each session with the day’s review. Progress stays in each phone’s browser: a shared phone mixes results, and private browsing wipes them.
- The two final sheets have no quiz: print them and keep them by the desk during code reviews. The assessment at /en/developpeur/evaluation/ draws 15 questions from the course quizzes; 11 correct answers (70%) give a printable certificate, which is not a diploma.
- The known limitations of the teaching engine are listed in the contract sheet: present them as cases to test, not as bugs to fix during the workshop.
- A participant stuck on lesson 5 should first read “Computing an auction price” in the student course: the code only adds structure, not the rule.
Quiz answer keys
61 questions, with the right answer and its explanation.
The domain in ten objects
A buy order for 40 shares can produce...
→ zero, one or several executions
An order is matched against as many opposite orders as needed; it may also find none.
Who forwards a client's order to the BVMAC market?
→ a licensed brokerage firm
Trading on the BVMAC is the monopoly of brokerage firms licensed by COSUMAF.
What does the settlement of an execution change?
→ the position and the cash
Settlement moves the securities to the buyer and the money to the seller: position and cash account both move.
How should you code the settlement delay?
→ as a configuration parameter
No text found sets this delay on the BVMAC: a parameter avoids freezing an assumption.
Why number executions as they leave the engine?
→ to recognise an import already replayed
With no identifier, two imports of the same file would count the same shares twice; a stable number serves as the key.
Modelling an order
How should you store a bond price quoted at 99.50%?
→ an integer, 9950, in hundredths
Two exact decimals: count in hundredths of a point, with an integer.
In the engine's Ordre type, limite is null for...
→ an order at market
A market order has no price: null encodes the absence of a limit.
Which rule does the teaching engine check itself?
→ a strictly positive integer quantity
Carnet.passer throws if the quantity is not a strictly positive integer; the rest is up to you.
The BVMAC's current tick size is...
→ set by an instruction
The rules refer to a BVMAC instruction, which our research did not find.
What does lireOrdre return for a quantity “2,5” and a limit “10 100,5”?
→ both errors at the same time
The function gathers the errors before answering: the user fixes everything in one go.
Why write const jamais: never = o in the default branch?
→ the compiler flags a forgotten case
If an order type is not handled, o is no longer of type never at that point: compilation fails.
The book, a sorted structure
On the sell side, which limit order is the best?
→ the lowest price offered
A buyer prefers to pay less: when selling, the lowest price is served first.
Why does trierCote give a market order an infinite price?
→ to place it ahead of all
An infinite notional price puts it ahead of every limit order, with no special case in the comparator.
Two buy orders at the same price: which goes first?
→ the one with smaller rank
At the same price, time priority applies: the smallest arrival rank wins.
What does fourchette() return when one side is empty?
→ a gap equal to null
Without a best bid or a best ask, the gap does not exist: the engine returns null.
In the engine, changing an order returned by ordres()...
→ changes the book's order as well
trierCote copies the array but not the orders: the object returned is the book's own.
Levels 10,100, 10,000 and 9,950 on the buy side: where does indexNiveau put 10,050?
→ at index one
10,050 goes after 10,100 and before 10,000, so at index 1.
Continuous trading, line by line
Why can the loop stop at the first incompatible order?
→ the opposite side is sorted
Sorted from best to worst, the opposite side holds nothing compatible after the first refusal.
A sell at 9,950 is resting; a buy at 10,050 arrives. Trade price?
→ 9,950, the resting price
The engine executes at the price of the order already in the book.
A market buy for 20 finds only 12 shares. The other 8...
→ vanish without ever entering it
The condition entrant.limite !== null blocks storing: the remainder of a market order is dropped.
After c.passer(o), what is o.quantite on the caller's object?
→ its initial quantity, still unchanged
passer copies the incoming order and stores another copy for the remainder: the caller's object is not changed.
The auction in code
Why are only the limits present candidate prices?
→ between two limits, nothing changes
Cumulative demand and supply only move at the limits; a price in between would add no volume.
Two prices give the same volume and the same negative imbalance. The engine takes...
→ the lowest candidate price
Negative imbalance everywhere: supply exceeds, pressure pushes down, hence the lowest price.
At the equilibrium price, two buy orders have a limit equal to that price. Which is filled first?
→ the older of the two
At a limit equal to the price, time priority decides: the smallest rank goes first.
What is regle when a single price maximises the volume?
→ 'volume'
Tie-breaking stops at the first rule: a single candidate with the maximum volume is enough.
With no reference price, fixing on just two market orders returns...
→ a price equal to null
No limit, no reference price: the candidate list is empty, so there is no trade.
What complexity to compute the curve, with c candidates and n orders?
→ O(c × n) operations
For each candidate, the engine filters every buy and sell order.
An engine’s invariants
After an order in continuous trading, the best bid is 10,050 and the best ask 10,000. What do you conclude?
→ the book is crossed: bug
A buy at 10,050 and a sell at 10,000 are compatible: they should have traded. The invariant is broken.
Which of these calls threatens an engine's determinism?
→ a call to Date.now()
The system clock changes from one run to the next: two replays of the same log could diverge.
A property-based test fails on seed 137. What do you do first?
→ replay seed 137 exactly
The seed makes the failure reproducible: replay the session, shrink it, then turn it into an example test.
Shrinking reduces a failing session from 12 orders to 2. This result is...
→ the smallest counterexample found
Removing one more order would make the test pass: it is a local minimum, ready to become an example test.
Two replays diverge because two log events swapped places. The engine is...
→ still deterministic after all
Same sequence of inputs, same outputs: here, the sequence of inputs changed. It is the log that must be totally ordered.
From business rule to test case
In a test case, the “then” part must be...
→ a precise, checkable result
The “then” is checked by a machine: exact values, not an intention.
Which edge case best tests time priority?
→ two orders at one price
Time priority only applies at equal prices: it is the only situation that reveals it.
The engine does not handle all-or-nothing orders yet. What do you do with the case?
→ write a pending todo test
A pending test keeps the rule visible and serves as the specification of the future feature.
A mutant survives your whole test suite. This means...
→ no test observes this change
The mutant changes a behaviour nobody checks: a test is missing, or data that isolates the rule.
Order life cycle and the FIX protocol
Which FIX message carries a new order?
→ NewOrderSingle, of type D
NewOrderSingle (MsgType D) sends a new order; ExecutionReport (8) reports on it.
A NewOrderSingle without TimeInForce (59) is...
→ a day-only valid order
In FIX Latest, the absence of TimeInForce means a day order.
An order goes from “partly filled” back to “received”. This is...
→ a forbidden transition
The life cycle moves forward, never back: the transition table must reject this move.
In a FIX session, sequence numbers...
→ run consecutively from 1
The session is a continuous series of numbers starting at 1; the session layer provides for resynchronisation.
The same ExecutionReport arrives twice after a resynchronisation. The tracking must...
→ count the execution only once
An execution counted twice distorts the quantity filled, then the position: the gateway must ignore what it has already seen.
From engine to MIMS: checking a session
An execution of 30 shares is allocated as 35 shares between two clients. What do you conclude?
→ a clear allocation anomaly
The allocated sum must equal the executed quantity: 5 shares appear from nowhere.
Before commission, a client buys 40 shares at 10,000. Their cash account changes by...
→ minus 400,000 francs
A purchase debits the account by price × quantity: 40 × 10,000 = 400,000.
Why does a buy limited to 9,950 have no movement after an auction at 10,000?
→ its limit never crosses
A buyer limited to 9,950 refuses to pay 10,000: it is not filled, no movement is expected.
An execution was recorded on the buy side only. Which check reveals it?
→ a zero sum of cash
The buyer is debited while nobody is credited: the sum of cash movements is no longer zero.
The same execution file is imported twice. The deduplication key must be...
→ the reference of each execution
Two distinct executions can have the same price and the same quantity; only their reference tells them apart without ambiguity.
Amending and cancelling an order
A resting order has its quantity reduced. Its time priority is...
→ kept, it holds its old rank
Reducing the quantity keeps priority; increasing the quantity or changing the limit loses it.
How does modifier keep priority with the engine's API?
→ by re-submitting its old rank
passer accepts a supplied rank: re-submitting the order with its old rank gives it back its place in the queue.
What does annuler return for an order already fully filled?
→ false, the order is gone
A filled order is no longer in the book: annuler returns false and nothing changes.
Why validate the new quantity before calling annuler?
→ to avoid losing the order
If passer throws after annuler, the order has left the book without being re-submitted: it is lost.
A raised limit crosses a resting sell. modifier returns...
→ an array of immediate executions
The re-submitted order is matched against the opposite side like any incoming order: it can execute at once.
Logging and replaying a session
To rebuild the book at time t, you need to...
→ replay the first t events
The state at time t is the replay of the log's first t events on a fresh book.
Why does MoteurJournalise write the rank into the log?
→ because no API exposes the counter
A restored book starts again at 1: without a logged rank, recovery renumbers the orders and priority changes.
Two sessions have the same executions in a different order. Their fingerprints...
→ differ, because order counts
The fingerprint is computed on the serialised sequence: changing the order changes the text, so the fingerprint.
An event in the log turns out to be wrong. What do you do?
→ you append a correcting event
The log is append-only: you correct by adding, never by rewriting, like the Official Price List.
At event 6, recovery without ranks gives the same view. Is the replay right?
→ no, a hidden rank differs
a3 got rank 1 instead of 5: invisible in the aggregated view, the difference surfaces at the next event.
From an execution to entries
An execution between two clients produces how many securities movements?
→ two, in opposite directions
The buyer receives the shares, the seller delivers them: two movements of the same quantity, with opposite signs.
A validated execution turns out to be wrong. What does the back office do?
→ it adds the opposite movements
The reversal adds the opposite entries: balances return, the history keeps both.
Why does each movement carry the reference of its execution?
→ to avoid any double counting
The reference serves as an idempotence key: an execution already integrated is not integrated again.
The example's commission rate, 0.5%, is...
→ just a fictional course parameter
No source in the course sets a rate: it is a fictional parameter, like MIMS's configured fee schedule.
After commissions, which sum of cash movements must be zero?
→ that of all the accounts
Commissions leave the client accounts and enter the commissions account: only the overall sum is zero.