Courses / Machine Coding and Low-Level Design in TypeScript / Chapter 23
Module 9 · Design problems VI: social, trading and puzzles · Chapter 23 of 28
Online Stock Brokerage: Orders, Order Book, Matching and Portfolio
Builds on Solving a Design Problem: Requirements to Tested Code in Six Steps, Design Patterns in TypeScript: Creational, Structural and Behavioural, Parking Lot: Floors, Spots, Tickets and Fees and Hotel Management: Rooms, Bookings, Stays and Billing. Next up: Jigsaw Puzzle: Pieces, Edges, Fitting and a Solver.
Part 1 · Requirements
What the brokerage must do
An exchange is a queue with rules: the best price goes first, and at one price the earliest order goes first. This chapter builds a small brokerage that holds the money, keeps the order book and matches trades.
A requirement is a sentence about the system that someone can check. Functional requirements say what the system does, and we write them before any class exists. Every market rule below is in our model: one simple, consistent rulebook, not a description of any real exchange. The shares are one invented symbol, DEMO, and the investors are Asha, Bala, Chitra and Dev.
- A member has an account with cash and a count of shares for each symbol.
- A member places a buy or a sell order for a whole number of shares.
- A limit order names the worst price the member accepts: a buy at or below it, a sell at or above it.
- A market order takes the best prices available and names no price.
- A stop-loss order waits until the last traded price reaches its trigger. Then it becomes a limit order.
- The order book holds the waiting orders. Best price first, and at one price the earliest order first.
- An order can be filled in parts. A partial fill leaves the rest waiting.
- A buy blocks the cash it may spend, and a sell blocks the shares it may give up. A member can cancel a waiting order and get the hold back.
- A member can see cash, blocked cash and shares, the portfolio.
One broker's public documentation names the same ideas: limit, market, stop-loss with a trigger and a limit price, stop-loss market with a trigger only, and a validity of day or immediate-or-cancel. We keep the first three, with a validity field that allows day and immediate-or-cancel orders. Expiry at the close and changing an order come in the last lesson, and stop-loss market is only named here.
Quality, numbers and scope
Non-functional requirements say how well the system behaves. Money must add exactly, so prices and cash are integer paise, a hundredth of a rupee: a share at ₹250 has the price 25000. A refused order must change nothing: no cash held, no order stored, no book change. The book must never trade out of order: price first, then arrival. And no member may ever be promised more cash or shares than they own, which the holds guarantee.
We rejected two designs. The first checks the balance when a trade happens, so placing an order costs nothing. It is simple, but a member could place ten orders that together need ten times their cash, and each trade would then fail halfway through a match. We block at placing, so a trade can never fail for funds. The second keeps one sorted list of all orders and scans it for each match. It works, and a match gets slower with every waiting order. We keep one list for each price, best price first, so a match looks only at the best level.
Two numbers shape the code: a price level holds orders oldest first, and a trade uses the price of the resting order. The second one means an eager buyer who bids ₹251 into a seller at ₹250 pays ₹250.
| Must | Should | Out of scope |
|---|---|---|
| Accounts, market, limit and stop orders, book, partial fills, holds, cancel, portfolio | Immediate-or-cancel, end-of-day expiry, modify, one book at a time | Short selling, fees, taxes, margin, auctions |
Check yourself
A buy limit at ₹251 meets a resting sell at ₹250. At what price is the trade made, and why?
- At ₹250. In our model a trade uses the price of the order that was already waiting.
- The buyer still gets the better deal than they asked for, and the extra hold is returned.
Why does a market order never rest in the book?
- It names no price, so there is no level for it to wait at.
- It takes what is available, and anything it could not buy is dropped.
Why block cash when the order is placed and not when it trades?
- A trade can then never fail for lack of funds in the middle of a match.
- Ten orders cannot together promise more cash than the member owns.
Part 2 · Use cases
Actors and use cases
An actor is someone outside the system who uses it. A use case is one goal an actor wants to reach. The brokerage has one actor, the member. The exchange that matches orders is part of the system here, so it is not an actor.
A use case diagram shows actors, the use cases they start and how those relate. Include means a use case always runs another one as part of itself. Extend means an exceptional case adds steps to a base case under a condition. Placing an order always includes blocking funds or shares, and cancelling always includes releasing the hold. A refusal for lack of funds or shares extends placing.
The blue box is the actor and the pills are use cases, with the refusal in red. An arrow from the actor means the actor starts that use case. Every other arrow runs from a base case to the case it includes or the case that extends it, labelled "includes" or "extended by". Formal UML draws the extend arrow the other way, from the extension to the base; here the label carries the meaning.
"See the portfolio" sits beside the actor because it needs no other step. Read the diagram as a checklist of goals: each pill becomes a method or two and a few tests, and the red pill shows where the unhappy path hangs off the happy one.
Flows and alternatives
Each use case gets a short written flow: a trigger, the main steps and the alternatives. Writing alternatives now is cheap. Finding them after the code exists is not.
| Use case | Main flow | Alternatives |
|---|---|---|
| Add funds | Add a positive amount to the cash | Zero or negative: refuse |
| Place an order | Check it, block cash or shares, match, rest or finish | Bad numbers, not enough funds or shares: refuse |
| Modify an order | Shrink it, or change its price | Not live, not yours, cannot afford: refuse |
| Cancel an order | Take it out of the book, release the hold | Already filled or cancelled, not yours: refuse |
| See the portfolio | Cash, blocked cash and holdings | None |
Every alternative is a named refusal, and each one must change nothing. A refused order leaves the cash, the shares and the book as they were, and we assert that.
Three details need a decision now. A market order that finds nothing to trade against is stored as rejected so that the member can see what happened, while an order refused for bad numbers or lack of funds is not stored at all. A stop order is refused if its trigger has already been crossed by the last price, because it would fire at once and the member probably meant something else. And a stop needs a last price to compare with, so the first trade of a symbol must come before any stop on it.
Use cases as test names
As in the parking lot chapter, each use case becomes a test.todo name, a map of the work that is reported but not run, and each one becomes a real test by the end.
test.todo('a member adds funds'); test.todo('a member places an order'); test.todo('a member modifies an order'); test.todo('a member cancels an order'); test.todo('a member sees the portfolio');
✔ a member adds funds (0.585ms) # TODO ✔ a member places an order (0.1127ms) # TODO ✔ a member modifies an order (0.0648ms) # TODO ✔ a member cancels an order (0.0537ms) # TODO ✔ a member sees the portfolio (0.0732ms) # TODO ℹ tests 5 ℹ todo 5
Output (durations vary)
All five names are reported as todo, and none counts as passed. If a name never gets a test, the requirement behind it was probably missed. Modifying an order arrives in the last lesson, so its test waits until then.
What is the difference between include and extend?
- Include: the base case always runs the included case, as placing an order always blocks funds or shares.
- Extend: an exceptional case adds steps under a condition, as the refusal does when the funds are not enough.
An order is refused for lack of funds. What must be true of the account and the book afterwards?
- Nothing has changed: no cash is blocked, no order is stored and the book is as before.
Why is the exchange not an actor on the diagram?
- It is part of the system we build. An actor is someone outside the system who starts a use case.
Part 3 · Class diagram
From nouns to classes
Read the requirements again and underline the nouns: member, account, order, book, price level, trade, symbol, holding, portfolio, hold. Not every noun becomes a class. A useful test is whether the thing has rules to protect or behaviour that varies.
| Noun | Decision | Why |
|---|---|---|
| Account, holding, hold | Class Accounts | Guards the rule that cash and shares are never over-promised |
| Order | Interface Order | A record that the exchange updates as it fills |
| Order request | Interface OrderRequest | What a client sends, before the exchange gives it an id |
| Price level | Interface Level | A price and its orders, oldest first |
| Side of the book | Class BookSide | Keeps levels best price first, for bids or asks |
| Book | Class OrderBook | One bid side, one ask side and the last price |
| Trade | Interface Trade | Written once, never changed |
| Matching | Class Engine | Walks the book and settles each trade |
| Everything together | Class Exchange |
The class diagram
A class diagram shows classes, what they hold and how they relate. Multiplicity is the number on each link end: 1 means exactly one, 0..* means any number, including none, and 2 means exactly two.
place(req): Ordercancel(id, account): Orderbook(symbol): OrderBookportfolio(account)orders(), trades()open, addFunds, availablereserveCash, releaseCashreserveShares, releaseSharessettleBuy, settleSellmatch(taker, book): Trade[]finish(order, book)release(order)bids, asks: BookSidelast: Paiselevels: Level[], best firstbest(), add(), remove()walk(qty): cost, sharesprice: Paiseorders: Order[], oldest firstid, seq, account, symbolside, kind, validityquantity, price, triggerfilled, status, reservedid, symbol, price, quantitybuyOrder, sellOrder- Exchange 1 → 1 Accounts
- Exchange 1 → 1 Engine
- Exchange 1 → 0..* OrderBook
- Exchange 1 → 0..* Order
The skeleton in TypeScript
A diagram is only a claim until a compiler reads it. We start with the words the model uses: side, kind, validity and status.
export type Side = 'buy' | 'sell'; export type Kind = 'market' | 'limit' | 'stop'; export type Validity = 'day' | 'ioc'; export type Status = | 'open' | 'triggerPending' | 'partiallyFilled' | 'filled' | 'cancelled' | 'rejected'; // What a client sends. Prices are paise per share. export interface OrderRequest { account: string; symbol: string; side: Side; kind: Kind; quantity: number; price?: Paise; // limit orders, and the limit of a stop order trigger?: Paise; // stop orders only validity?: Validity; // day unless it says ioc }
The Order record follows, with the trade. A buy keeps reserved, the cash still held for it.
export interface Order { readonly id: string; readonly seq: number; readonly account: string; readonly symbol: string; readonly side: Side; readonly kind: Kind; readonly validity: Validity; quantity: number; // an order may be reduced, never raised readonly price: Paise | undefined; readonly trigger: Paise | undefined; filled: number; status: Status; reserved: Paise; // cash held for a buy, still unspent }
Every refusal will be a BrokerError with a code, so callers and tests branch on the code and never on the message.
export type BrokerCode = | 'UNKNOWN_ACCOUNT' | 'UNKNOWN_ORDER' | 'BAD_QUANTITY' | 'BAD_PRICE' | 'BAD_AMOUNT' | 'BAD_TRIGGER' | 'INSUFFICIENT_FUNDS' | 'INSUFFICIENT_SHARES' | 'NOT_OPEN' | 'NOT_YOURS'; export class BrokerError extends Error { readonly code: BrokerCode; constructor(code: BrokerCode, message: string) { super(message); this.name = 'BrokerError'; this.code = code; } }
Money is a type alias with a formatter for display.
// Prices and cash are whole paise: 25000 means 250 rupees. export type Paise = number; const inr = new Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR', }); export const rupees = (p: Paise): string => inr.format(p / 100);
Type-check the project:
npx tsc -p .
(no output, exit code 0)Output
Part 4 · Order lifecycle and the place-to-fill sequence
Order statuses
A state machine lists the states, the events that cause moves and the events a state refuses. An order has five states you can move through. triggerPending is a stop order waiting for its price. open is a limit order resting in the book. partiallyFilled has traded some shares and rests with the rest. filled and cancelled are final. A sixth status, rejected, is where a market order with nothing to trade against starts and ends, so no move leads to it.
Watch for a filled order refusing a cancel
Read it as steps
A buy of 20 meets only 10 shares, rests, then fills. After that a cancel is refused.
The scene follows Chitra's order for 20 shares when only 10 are for sale. It fills in two steps. After the second fill a cancel arrives and is refused with NOT_OPEN, because nothing is left to cancel. The whole picture is easier to read as a table: for each status, what a fill and a cancel do.
| Status | fill |
|---|
From place to fill
Follow one buy order. Chitra wants 40 shares and will pay up to ₹251. The book already holds three sell orders: Asha has 30 at ₹250, Bala has 20 at ₹250 behind her, and Asha has 10 more at ₹252.
Watch for the cash being blocked before the book is touched
Read it as steps
Cash is blocked first, trades happen at the resting price, and the difference comes back.
The exchange blocks the most cash the order could use, ₹10,040, before it touches the book. Then the engine walks the sell side from the best price. It takes 30 shares from Asha and 10 from Bala, both at ₹250, because the oldest order at the best price goes first. Each trade is made at the resting price, ₹250, so the order spends ₹10,000 and the extra ₹40 held is released. The ₹252 order is never touched: the order is already full.
| Step | Can fail with | Changes anything? |
|---|---|---|
| Check the numbers | bad quantity or price | No |
| Block cash or shares | not enough funds or shares | The hold |
Run the driver
The driver is the demo.ts script from the approach chapter, which runs the core flow once and prints what happened. It places the three sell orders, then Chitra's buy of 40 at ₹251, then a second buy of 30 at ₹250, and prints the trades, the book and three portfolios.
ex.place(req('asha', 'sell', 'limit', 30, 25000)); ex.place(req('bala', 'sell', 'limit', 20, 25000)); ex.place(req('asha', 'sell', 'limit', 10, 25200)); const buy = ex.place(req('chitra', 'buy', 'limit', 40, 25100)); console.log(`order ${buy.id}: ${buy.status}, filled ${buy.filled}`); for (const t of ex.trades()) { const who = `${ex.order(t.buyOrder).account} buys from `; const from = ex.order(t.sellOrder).account; const at = `${t.quantity} at ${rupees(t.price)}`; console.log(`${t.id} ${at}: ${who}${from}`); } const rest = ex.place(req('chitra', 'buy', 'limit', 30, 25000)); console.log(`order ${rest.id}: ${rest.status}, filled ${rest.filled}`);
const levels = (s: BookSide) => s.levels .map((l) => `${rupees(l.price)} x${l.orders.length}`) .join(', '); console.log(`asks: ${levels(ex.book(SYM).asks)}`); console.log(`bids: ${levels(ex.book(SYM).bids)}`); ['asha', 'bala', 'chitra'].forEach(show);
order O4: filled, filled 40 T1 30 at ₹250.00: chitra buys from asha T2 10 at ₹250.00: chitra buys from bala order O5: partiallyFilled, filled 10 asks: ₹252.00 x1 bids: ₹250.00 x1 asha ₹57,500.00 (₹0.00 blocked) 70 DEMO bala ₹55,000.00 (₹0.00 blocked) 30 DEMO chitra ₹37,500.00 (₹5,000.00 blocked) 50 DEMO
Output
Read it top to bottom. The first buy was filled in full with two trades at ₹250.00, 30 from Asha and 10 from Bala. The second buy of 30 at ₹250 finds only Bala's last 10, so it fills 10 and rests with 20 as a bid. The book now holds one ask, Asha's 10 at ₹252, and one bid, Chitra's 20 at ₹250. Chitra holds 50 shares, paid ₹12,500 and has ₹5,000 blocked for the 20 she still wants.
Why is the cash blocked before the engine touches the book?
- A refusal then happens while nothing has changed, so a refused order leaves no trace.
- Once the match starts, no step can fail for funds.
In the driver run, why does the first buy pay ₹250 and not ₹251?
- The trades use the resting orders' price, ₹250.
Part 5 · Code: the order book
Price levels
The book keeps each side as a list of price levels, best price first. A level holds the orders at one price, oldest first. That one rule, the order inside a level, is time priority, and the order of the levels is price priority. Together they are price-time priority.
export interface Level { readonly price: Paise; orders: Order[]; // oldest first: time priority inside the level } // One side of the book. Levels are kept best price first. export class BookSide { readonly levels: Level[] = []; readonly #better: (a: Paise, b: Paise) => boolean; constructor(better: (a: Paise, b: Paise) => boolean) { this.#better = better; } best(): Level | undefined { return this.levels[0]; }
BookSide is given a comparison when it is built: for bids a higher price is better, for asks a lower one is. add finds the first level that is the same price or a worse price. If it finds the same price, the order joins the end of that level. If it finds a worse price, a new level is inserted before it. If it finds nothing, the order starts a new last level.
add(order: Order, price: Paise): void { const at = this.levels.findIndex( (l) => l.price === price || this.#better(price, l.price), ); if (at < 0) this.levels.push({ price, orders: [order] }); else if (this.levels[at]!.price === price) { this.levels[at]!.orders.push(order); } else this.levels.splice(at, 0, { price, orders: [order] }); } remove(order: Order, price: Paise): void { const at = this.levels.findIndex((l) => l.price === price); if (at < 0) return; const level = this.levels[at]!; level.orders = level.orders.filter((o) => o !== order); if (level.orders.length === 0) this.levels.splice(at, 1); }
Finding a level is a linear scan, which is fine for a few levels. A real book would use a sorted map or a tree so that the search takes logarithmic time, and the interface would stay the same. A level that becomes empty is removed, so best always names a level with at least one order.
export class OrderBook { readonly bids = new BookSide((a, b) => a > b); readonly asks = new BookSide((a, b) => a < b); last: Paise | undefined; }
The book also remembers last, the price of the latest trade. Stop orders will use it in the next lesson.
Matching
The engine takes an incoming order, called the taker, and matches it against the other side. The orders already waiting are the makers. A taker crosses a level when its price is as good as or better than the level's: a buy at or above the ask, a sell at or below the bid. A market order crosses every level.
const crosses = (o: Order, price: Paise): boolean => o.kind === 'market' || (o.side === 'buy' ? price <= o.price! : price >= o.price!);
// Match an incoming order against the other side, best price first. match(taker: Order, book: OrderBook): Trade[] { const against = taker.side === 'buy' ? book.asks : book.bids; const trades: Trade[] = []; while (taker.filled < taker.quantity) { const level = against.best(); if (!level || !crosses(taker, level.price)) break; const maker = level.orders[0]!; const left = maker.quantity - maker.filled; const qty = Math.min(taker.quantity - taker.filled, left); trades.push(this.#trade(taker, maker, level.price, qty)); book.last = level.price; if (maker.filled === maker.quantity) { against.remove(maker, level.price); } } return trades; }
Each trade takes the smaller of what the taker still wants and what the oldest maker still offers. If the maker is used up, it leaves the book and the next one becomes the oldest. The loop ends when the taker is full, the other side is empty or the best level no longer crosses.
// The trade happens at the resting order's price. #trade(taker: Order, maker: Order, price: Paise, qty: number): Trade { const buy = taker.side === 'buy' ? taker : maker; const sell = taker.side === 'buy' ? maker : taker; const value = qty * price; this.#accounts.settleBuy(buy.account, buy.symbol, qty, value); this.#accounts.settleSell(sell.account, sell.symbol, qty, value); buy.reserved -= value; for (const o of [taker, maker]) { o.filled += qty; o.status = o.filled === o.quantity ? 'filled' : 'partiallyFilled'; } if (maker.status === 'filled') this.release(maker); return { id: `T${++this.#n}`, symbol: taker.symbol, price, quantity: qty, buyOrder: buy.id, sellOrder: sell.id, }; }
#trade is where the rule "the resting price" lives: it is passed the level's price, never the taker's. It moves cash and shares through the accounts, reduces the buyer's hold by the value traded and marks both orders. When the maker is filled, its leftover hold goes back at once. After matching, finish decides what happens to the taker.
Tests for price-time priority
Each test is a sentence about the market that a trader would recognise. The first three check price priority, time priority and the resting price.
test('the best price fills first', () => { const { ex } = rig(); ex.place(req('asha', 'sell', 'limit', 1, 25200)); ex.place(req('asha', 'sell', 'limit', 1, 25000)); ex.place(req('asha', 'sell', 'limit', 1, 25100)); ex.place(req('chitra', 'buy', 'market', 3)); assert.deepEqual(prices(ex), [25000, 25100, 25200]); }); test('at one price the earlier order fills first', () => { const { ex } = rig(); const first = ex.place(req('asha', 'sell', 'limit', 10, 25000)); const second = ex.place(req('bala', 'sell', 'limit', 10, 25000)); ex.place(req('chitra', 'buy', 'limit', 10, 25000)); assert.equal(first.status, 'filled'); assert.equal(second.status, 'open'); assert.equal(second.filled, 0); }); test('a trade is made at the resting price', () => { const { ex } = rig(); ex.place(req('asha', 'sell', 'limit', 10, 25000)); const buy = ex.place(req('chitra', 'buy', 'limit', 10, 25100)); assert.deepEqual(prices(ex), [25000]); assert.equal(buy.reserved, 0); assert.equal(ex.portfolio('chitra').blocked, 0); });
test('a partial fill leaves the rest resting', () => { const { ex } = rig(); const ask = ex.place(req('asha', 'sell', 'limit', 5, 25000)); const bid = ex.place(req('chitra', 'buy', 'limit', 8, 25000)); assert.equal(ask.status, 'filled'); assert.equal(bid.status, 'partiallyFilled'); assert.equal(bid.filled, 5); assert.equal(ex.book(SYM).bids.best()!.orders[0], bid); }); test('a resting order can fill in two steps', () => { const { ex } = rig(); ex.place(req('asha', 'sell', 'limit', 10, 25000)); const bid = ex.place(req('chitra', 'buy', 'limit', 20, 25000)); assert.equal(bid.status, 'partiallyFilled'); ex.place(req('bala', 'sell', 'limit', 10, 25000)); assert.equal(bid.status, 'filled'); assert.equal(bid.filled, 20); });
✔ the best price fills first (3.3492ms) ✔ at one price the earlier order fills first (0.299ms) ✔ a trade is made at the resting price (0.3169ms) ✔ an order that does not cross rests in the book (0.1716ms) ✔ a partial fill leaves the rest resting (0.2194ms) ✔ a resting order can fill in two steps (0.1708ms) ✔ a market order never rests (0.1696ms) ✔ a market order with nothing to trade against is rejected (0.1193ms) ℹ tests 8 ℹ pass 8 ℹ fail 0
Output (durations vary)
The second test is the one that proves time priority. Two sells at the same price are waiting, Asha's first. A buy for 10 fills Asha's order completely, and Bala's order stays open with nothing filled. The third test checks that the trade price is ₹250 and that the buyer's hold is released to zero. The last tests show a market order that finds only 4 shares: it fills them, is cancelled and holds nothing, and a market order into an empty book is rejected.
Part 6 · Code: funds and stop-loss orders
Blocking and releasing
The accounts hold two kinds of promise. For cash, blocked is the cash set aside for waiting buys, and the member can spend cash - blocked. For shares, each holding has its own blocked count for waiting sells.
reserveCash(id: string, amount: Paise): void { if (amount > this.available(id)) { throw new BrokerError('INSUFFICIENT_FUNDS', `${id} lacks funds`); } this.#get(id).blocked += amount; } releaseCash(id: string, amount: Paise): void { this.#get(id).blocked -= amount; } reserveShares(id: string, symbol: string, quantity: number): void { const h = this.#holding(this.#get(id), symbol); if (quantity > h.quantity - h.blocked) { const why = `${id} lacks shares`; throw new BrokerError('INSUFFICIENT_SHARES', why); } h.blocked += quantity; }
A buy limit reserves its price times its quantity, the most it could spend. A buy market has no price, so the exchange asks the book to walk the sell side for that quantity and reserves the cost of what exists. A sell reserves shares. If a market order finds nothing to trade against, it reserves nothing and is stored as rejected.
// Block cash or shares. Returns the cash held, or undefined when a // market order finds nothing to trade against. #reserve(req: OrderRequest, book: OrderBook): number | undefined { const { account, symbol, quantity } = req; if (req.side === 'sell') { if (req.kind === 'market' && !book.bids.best()) return undefined; this.accounts.reserveShares(account, symbol, quantity); return 0; } const cash = req.kind === 'market' ? book.asks.walk(quantity).cost : req.price! * quantity; if (cash === 0) return undefined; this.accounts.reserveCash(account, cash); return cash; }
A trade then uses the hold. settleBuy takes the value out of both the cash and the blocked cash, and adds the shares. settleSell does the reverse.
// A trade moves reserved cash out and shares in, or the reverse. settleBuy(id: string, symbol: string, qty: number, value: Paise) { const a = this.#get(id); a.cash -= value; a.blocked -= value; this.#holding(a, symbol).quantity += qty; } settleSell(id: string, symbol: string, qty: number, value: Paise) { const a = this.#get(id); const h = this.#holding(a, symbol); h.quantity -= qty; h.blocked -= qty; a.cash += value; }
Refusals and cancels
The order of steps in place is the guarantee that a refused order changes nothing. The checks come first, then the hold, and only then is an order created and stored.
place(req: OrderRequest): Order {
this.accounts.available(req.account); // unknown account throws here
const book = this.book(req.symbol);
validate(req, book.last);
const held = this.#reserve(req, book);
const o = this.#create(req, held ?? 0);
if (held === undefined) o.status = 'rejected';
else if (o.kind === 'stop') this.#stops.push(o);
else this.#process(o, book);
return o;
}An unknown account throws on the first line. The numbers are checked next, then the hold, which may throw for lack of funds or shares. Only after that does #create give the order its number, so a refused order does not even use up an id. A cancel is the mirror image: take the order out of its list, release the hold, then mark it cancelled.
cancel(id: string, account: string): Order {
const o = this.order(id);
if (o.account !== account) throw new BrokerError('NOT_YOURS', id);
if (!LIVE.includes(o.status)) {
throw new BrokerError('NOT_OPEN', `${id} is ${o.status}`);
}
const book = this.book(o.symbol);
if (o.status === 'triggerPending') {
this.#stops.splice(this.#stops.indexOf(o), 1);
} else {
(o.side === 'buy' ? book.bids : book.asks).remove(o, o.price!);
}
this.#engine.release(o);
o.status = 'cancelled';
return o;
}test('a buy beyond the balance is refused and changes nothing', () => { const { ex } = rig(); const big = req('chitra', 'buy', 'limit', 3000, 25000); // ₹7,50,000 assert.throws(() => ex.place(big), { code: 'INSUFFICIENT_FUNDS' }); assert.equal(ex.orders().length, 0); assert.equal(ex.portfolio('chitra').blocked, 0); assert.equal(ex.book(SYM).bids.best(), undefined); }); test('placing blocks cash and cancelling gives it back', () => { const { ex } = rig(); const bid = ex.place(req('chitra', 'buy', 'limit', 10, 25000)); assert.equal(ex.portfolio('chitra').blocked, 250000); assert.equal(ex.portfolio('chitra').available, 4_750_000); ex.cancel(bid.id, 'chitra'); assert.equal(ex.portfolio('chitra').blocked, 0); assert.equal(bid.status, 'cancelled'); assert.equal(ex.book(SYM).bids.best(), undefined); });
test('shares are blocked too, so they cannot be sold twice', () => { const { ex } = rig(); ex.place(req('bala', 'sell', 'limit', 40, 26000)); const again = req('bala', 'sell', 'limit', 11, 26000); assert.throws(() => ex.place(again), { code: 'INSUFFICIENT_SHARES' }); ex.place(req('bala', 'sell', 'limit', 10, 26000)); assert.equal(ex.orders().length, 2); });
The trigger book
A stop-loss order is a limit order that has not started. It holds its shares or cash from the start, but it does not go into the book. It waits in a separate list, the trigger book, until a trade moves the last price to its trigger. A sell stop fires when the last price falls to its trigger or below. A buy stop fires when the price rises to it or above.
#process(o: Order, book: OrderBook): void { const trades = this.#engine.match(o, book); this.#trades.push(...trades); this.#engine.finish(o, book); if (trades.length > 0) this.#fireStops(o.symbol, book); } // A trade moves the last price, and that can wake waiting stops. #fireStops(symbol: string, book: OrderBook): void { const last = book.last!; const hit = (s: Order) => s.symbol === symbol && (s.side === 'sell' ? last <= s.trigger! : last >= s.trigger!); for (const s of this.#stops.filter(hit)) { if (!this.#stops.includes(s)) continue; // woken by an earlier one this.#stops.splice(this.#stops.indexOf(s), 1); s.status = 'open'; this.#process(s, book); } }
After every #process that made a trade, #fireStops looks at the waiting stops of that symbol. Each one that has been reached is taken out, marked open and processed as a limit order, which can trade and move the price again. That is why the loop checks that a stop is still waiting: an earlier one may already have woken it. Here is the scene for a real run of stop-demo.ts: Bala has a stop to sell 10 with trigger ₹245 and limit ₹244. The last price is ₹250.
Watch for the stop waiting outside the order book
Read it as steps
Part 7 · Extensions and trade-offs
Every use case, tested
The use case lesson left five test.todo names. Modifying an order exists only in this lesson, so the rest of the chapter lives in a copy of the project with new files added: SessionExchange extends Exchange with a closing time and order changes. With it, each todo becomes a real test that drives the use case the way the member would. These are acceptance tests: they check a goal from the outside, while the earlier tests check single rules.
test('a member adds funds', () => { const ex = world(); ex.accounts.addFunds('chitra', 50_000); assert.equal(ex.portfolio('chitra').available, 150_000); assert.throws(() => ex.accounts.addFunds('chitra', -5), { code: 'BAD_AMOUNT', }); }); test('a member places an order', () => { const ex = world(); const o = ex.place(req('chitra', 'buy', 'limit', 4, 25000)); assert.equal(o.status, 'open'); assert.equal(ex.portfolio('chitra').blocked, 100_000); }); test('a member modifies an order', () => { const ex = world(); const o = ex.place(req('asha', 'sell', 'limit', 20, 25000)); ex.reduce(o.id, 'asha', 12); assert.equal(o.quantity, 12); const moved = ex.replace(o.id, 'asha', 25500); assert.equal(moved.price, 25500); assert.equal(o.status, 'cancelled'); });
test('a member cancels an order', () => { const ex = world(); const o = ex.place(req('chitra', 'buy', 'limit', 4, 25000)); ex.cancel(o.id, 'chitra'); assert.equal(o.status, 'cancelled'); assert.equal(ex.portfolio('chitra').blocked, 0); }); test('a member sees the portfolio', () => { const ex = world(); ex.place(req('asha', 'sell', 'limit', 4, 25000)); ex.place(req('chitra', 'buy', 'limit', 4, 25000)); const p = ex.portfolio('chitra'); assert.equal(p.cash, 0); assert.deepEqual(p.holdings, [ { symbol: SYM, quantity: 4, blocked: 0, last: 25000 }, ]); });
✔ a member adds funds (1.5531ms) ✔ a member places an order (0.4839ms) ✔ a member modifies an order (0.4092ms) ✔ a member cancels an order (0.206ms) ✔ a member sees the portfolio (0.8099ms) ℹ tests 5 ℹ pass 5 ℹ fail 0 ℹ todo 0
Output (durations vary)
Five pass and no todo is left. The whole extended project, with every earlier test, also passes.
ℹ tests 30 ℹ pass 30 ℹ fail 0 ℹ todo 0
Output: whole suite
Immediate-or-cancel, expiry and changes
An immediate-or-cancel order, IOC, takes what it can at once and drops the rest. The base code already does this, because finish cancels any non-resting remainder, so the extension only needs tests. The part that is new is the end of the day. Our day orders last until a closing time, and sweep cancels every live day order when the clock has passed it.
test('an ioc order takes what it can and drops the rest', () => { const { ex } = session(); ex.place(req('asha', 'sell', 'limit', 4, 25000)); const o = ex.place( req('chitra', 'buy', 'limit', 10, 25000, { validity: 'ioc' }), ); assert.equal(o.filled, 4); assert.equal(o.status, 'cancelled'); assert.equal(ex.book(SYM).bids.best(), undefined); assert.equal(ex.portfolio('chitra').blocked, 0); });
// Adds a closing time, quantity changes and price changes. export class SessionExchange extends Exchange { readonly #clock: Clock; readonly #closeAt: number; constructor(clock: Clock, closeAt: number) { super(); this.#clock = clock; this.#closeAt = closeAt; } // After the close, every live day order is cancelled. sweep(): number { if (this.#clock.now() < this.#closeAt) return 0; const day = this.orders().filter( (o) => o.validity === 'day' && LIVE.includes(o.status), ); for (const o of day) this.cancel(o.id, o.account); return day.length; }
test('day orders expire at the close and free their holds', () => { const { ex, clock } = session(); const bid = ex.place(req('chitra', 'buy', 'limit', 10, 24000)); const ask = ex.place(req('asha', 'sell', 'limit', 10, 26000)); assert.equal(ex.sweep(), 0); clock.advance(5 * HOUR); assert.equal(ex.sweep(), 0); clock.advance(HOUR); assert.equal(ex.sweep(), 2); assert.equal(bid.status, 'cancelled'); assert.equal(ask.status, 'cancelled'); assert.equal(ex.portfolio('chitra').blocked, 0); assert.equal(ex.book(SYM).asks.best(), undefined); });
✔ an ioc order takes what it can and drops the rest (1.9564ms) ✔ an ioc order that trades nothing is cancelled (0.1544ms) ✔ day orders expire at the close and free their holds (0.3729ms) ✔ a smaller order keeps its place in the queue (0.3063ms) ✔ a new price goes to the back, even the same price (0.4135ms) ✔ a change that cannot be afforded leaves the order alone (0.7348ms) ✔ a bad new price leaves the order alone (0.2759ms) ✔ a refused order does not stop the queue behind it (10.935ms) ✔ different symbols do not wait for each other (32.6927ms) ℹ tests 9 ℹ pass 9 ℹ fail 0
Output (durations vary)
The sweep test sets the clock to 9 in the morning and a close at 3 in the afternoon. At 2 it cancels nothing. At 3 it cancels both orders and returns the cash and the shares they held.
One book at a time
Everything so far runs in one synchronous call, so two orders can never interleave inside place. The parking lot chapter shows what happens when an await sits between a check and an action, and builds the KeyedMutex that fixes it. We reuse that class unchanged. In a brokerage the awaited step is a pre-trade check, such as a call to a risk service. Its time varies, so orders can reach the book in a different order from the one in which they were accepted.
export class Gateway { readonly #ex: Exchange; readonly #risk: RiskCheck; readonly #mutex: KeyedMutex; // Every gateway of one exchange must share one mutex. constructor(ex: Exchange, risk: RiskCheck, mutex: KeyedMutex) { this.#ex = ex; this.#risk = risk; this.#mutex = mutex; } // The check finishes at its own pace, so orders can overtake. async placeUnsafe(req: OrderRequest): Promise<Order> { await this.#risk.check(req); return this.#ex.place(req); } // One order at a time for each symbol, in the order they arrived. place(req: OrderRequest): Promise<Order> { return this.#mutex.run(req.symbol, () => this.placeUnsafe(req)); } }
The gateway receives the one shared mutex, as in the parking lot, and uses the symbol as the key: orders for one symbol queue, and different symbols do not wait for each other. The race run places Asha's sell, Bala's sell and Chitra's buy, in that order. Asha's check is slow, 20 ms, Bala's 5 ms and Chitra's 1 ms.
type Mode = 'placeUnsafe' | 'place'; async function run(label: string, mode: Mode) { const { ex } = rig(); const risk = new DelayRisk({ asha: 20, bala: 5, chitra: 1 }); const gate = new Gateway(ex, risk, new KeyedMutex()); const first = gate[mode](req('asha', 'sell', 'limit', 10, 25000)); const second = gate[mode](req('bala', 'sell', 'limit', 10, 25000)); const buy = gate[mode](req('chitra', 'buy', 'limit', 10, 25000)); const [a, b, c] = await Promise.all([first, second, buy]); const from = (id: string) => ex.order(id).account; const t = ex.trades()[0]!; console.log(`${label}: chitra bought from ${from(t.sellOrder)}`); console.log(` asha ${a.status}, bala ${b.status}`); console.log(` chitra ${c.status}`); } await run('no queue', 'placeUnsafe'); await run('one queue', 'place');
no queue: chitra bought from bala asha open, bala filled chitra filled one queue: chitra bought from asha asha filled, bala open chitra filled
Output (one real run; the order was the same on every run here)
Without a queue, Chitra's quick check lets her reach the book first and rest. Bala's order then arrives and trades with her, while Asha, who was first, is still waiting. With one queue per symbol, the orders enter the book in the order they were accepted, so Chitra trades with Asha. Two tests check the rest. A refused order inside the queue does not stop the one behind it, and an order on another symbol does not wait for a slow one.
Where this design is weak
Every design has costs. The scan for a level is linear. The book keeps filled orders in memory forever. Holds treat a market buy's cost as fixed at placing, which is only true because matching is synchronous. Self-trades, where an investor's buy meets their own sell, are ordinary trades in our model. There is one process and one mutex, so a second server would need a lock in shared storage. And a real exchange has opening and closing auctions, circuit limits and fees that we leave out.
| Term | Meaning |
|---|---|
| Order book | The waiting orders for a symbol, bids on one side and asks on the other |
| Price-time priority | Better prices first, and at one price the earlier order first |
| Taker, maker | The incoming order, and the orders already waiting |
| Partial fill | A trade for part of an order, leaving the rest waiting |
| Stop-loss | An order that becomes a limit order when the last price reaches its trigger |
| Immediate-or-cancel | An order that takes what it can now and drops the rest |
A teammate gives each gateway its own new KeyedMutex(). Do orders still enter the book in order?
- No. Each mutex queues only its own gateway's calls, so orders from two gateways still overtake each other.
- The mutex must be shared, as the parking lot chapter shows.
In the race run, why does Chitra trade with Bala when there is no queue?
- Her check is the fastest, so she reaches the book first and rests there.
- Bala's order arrives next and meets her bid, while Asha, who was accepted first, arrives last.
All chapters · Previous: Social Network: Friends, Posts, Privacy and the News Feed