How the Overnight Clearing Desk Works
Under-the-hood reference for the classroom simulation. All game logic lives in pure functions in site/overnight-engine.js. The instructor page and student bank pages call the same engine so the rules stay identical. Units are $ billions for balance-sheet amounts and percent for rates (4.40 means 4.40%).
Starting state
When the instructor hosts a new game, the engine creates a fresh session with newState():
- Day 1, phase
"trading" - Corridor: IORB 4.40%, SRF 4.50%
- Default yield curve (hardcoded fallback: 1M 4.45%, 6M 4.50%, 1Y 4.55%, 2Y 4.60%, 5Y 4.70%, 10Y 4.85%; replaced by the most recent published Treasury CMT yields when the instructor page loads)
- Empty banks, orders, trades, and histories; tick = 0; timers null
Students join from the lobby by entering a bank name. Each bank is created with newBank() → randomStartingBS(), which produces a unique but balanced sheet totaling ~$120B assets:
- Cash starts positive and above the day's risk-desk target. randomStartingBS draws 4-12; newBank then sets cash = target + cushion (0.5-2.0)
- Treasuries start in a 14–26 base range; the residual that used to sit in fixed loans is folded into Treasuries after cash is set to target + cushion (so free collateral is larger). Floating assets 12–26
- Volatile funding 12–28, sticky deposits the residual of the $110 funding side
- Equity fixed at 10; repo positions and pledged start at zero
- A default treasury book (face amounts) is allocated across the six tenors with heavier weights in 2Y/5Y/10Y
The sheet is immediately balanced. Free collateral for repo is marked Treasuries minus pledged. Banks can join at any time; their starting sheet is independent of the current day or phase.
1. Bank balance sheets & how they are generated
Each bank object holds the classic items plus a treasuryBook (face amounts by tenor) and a marked treasuries value. Key generation and mutation points:
- Initial generation —
randomStartingBS()(called only when a bank joins or on New Game). The ranges above are hard-coded constants in the engine; they are not exposed in the instructor UI. - Situation cards, systemic shock, cash re-randomize — these call
shockBank()which moves a field (usuallyvolatile) and cash by the same amount so the sheet stays balanced. Positive = inflow / surplus cash; negative = runoff / funding need. - Mark-to-market — any curve change calls
markToMarket(), which re-prices the treasury book (simple zero/bullet pricing) and updates thetreasuriesmarket value. Free collateral uses the new marked value immediately. - End-of-day interest & unwind —
advanceDay()accrues one night of interest into equity and cash, then matures every overnight repo (cash and collateral return to the original owners).
Adjustable in the instructor UI? Yes for post-creation shocks:
- Apply Systemic Shock (−5B volatile to every bank)
- Re-randomize Cash (~40% short)
- Situation cards (see below)
- New Game (re-draws every existing bank's sheet with fresh randoms while keeping the name)
These changes take effect immediately, including mid-session while the market is open. There is no “after-hours only” lock. The random ranges and coupon rates (sticky deposits 3.50%, floating assets = SOFR + 100 bp) are engine constants and are not UI-adjustable. Fixed loans have been removed; their residual is folded into Treasuries.
2. Yield curve & yield-curve history
The live curve is stored on the session as curve (six tenors). History is an array curveHistory of {day, curve} snapshots.
- Generation / first-game defaults —
newState()starts with the engine's hardcodedDEFAULT_CURVE(1M 4.45%, 6M 4.50%, 1Y 4.55%, 2Y 4.60%, 5Y 4.70%, 10Y 4.85%). On the instructor page, ~1.2 s after the session connects,loadMostRecentCurve()fetches the current year's daily Treasury CMT yield-curve CSV from treasury.gov. Treasury publishes rates after the trading day closes, so “today” is often empty; the code therefore parses every row, selects the one with the latest date, maps the live 1 Mo / 6 Mo / 1 Yr / 2 Yr / 5 Yr / 10 Yr values onto the game tenors, and (only if the session curve is still at the engine defaults) callsapplyCurve()and writes the state. This is the path that populates real current yields for a brand-new game. If the fetch fails or the curve has already been edited, the hardcoded defaults (or the existing curve) remain. The year in the URL is taken from the current date so the endpoint stays valid across year boundaries. - Instructor adjustments — the Yield Curve panel lets the instructor type any tenor, apply a parallel shift (bps to every tenor), or a short-end shift (bps to 1M/6M/1Y only). All routes call
applyCurve(), which stores the new curve and immediately marks every bank's Treasury book. - Situation cards — most cards also carry a
curveShiftobject (bps by tenor). Applying the card adds those deltas and marks books. - Automatic day-to-day drift — inside
advanceDay(), after interest and unwind, the engine takes the just-finished day's SOFR change and applies a small weighted move (heavy on the short end: 1M weight 0.75 down to 10Y weight 0.02) plus modest random noise (±4 bp). This is the only automatic curve evolution. - History — the curve that was in force for the finished day is pushed to
curveHistoryat the end ofadvanceDay(). The 3-D surface on the instructor and student pages is built from that history.
When adjustments take effect — the live Treasury load happens once at the start of a new session (instructor page). Manual curve edits, parallel/short shifts, and card-driven shifts take effect immediately (mid-game or after hours). The automatic SOFR-linked drift happens only when the instructor advances to the next day.
3. Situation cards
Named scenarios the instructor can apply at any time. Each card:
- Optionally overwrites the corridor rates (IORB / SRF).
- Applies a relative
curveShift(or an absolute curve) and marks books. - Draws a fixed pool of liquidity shocks and assigns them to banks according to a mode, then calls
shockBank()on thevolatilefield (cash moves by the same amount).
The five built-in cards (from SITUATION_CARDS in the engine):
| Card | Corridor | Curve shift (approx.) | Shock shape | Economic story |
|---|---|---|---|---|
| Pandemic shock | IORB 0.15 / SRF 0.25 | Sharp parallel drop, front end most (−150 to −40 bp) | Mostly large negative volatile shocks; a few positive; shuffled | Risk-off freezes funding; Fed cuts hard. Most banks lose wholesale funds; a few strong franchises see inflows. |
| Hot inflation print | IORB 5.40 / SRF 5.50 | Modest rise, front end most (+25 to +5 bp) | Mild-to-moderate negatives; lowest-cash banks hit first | Hot CPI forces a hike. Funding tightens; banks already short cash feel it most. |
| Liquidity crisis (2019-style) | IORB 4.40 / SRF 5.00 | Short-end rise (+40 to −5 bp) | A few very large negatives; most mild or zero; shuffled | Concentrated squeeze. Corridor widens as the Fed emphasizes the SRF backstop. |
| Flight to safety | IORB 4.25 / SRF 4.35 | Long-end decline (0 to −35 bp) | Mostly positive inflows; a couple modest negatives; shuffled | Risk aversion drives cash into the banking system. Longer yields fall on flight to quality. |
| Quarter-end turn | IORB 4.40 / SRF 4.55 | Mild short-end rise (+15 to 0 bp) | Mild even negatives; largest / more wholesale-funded banks hit first | Window-dressing and balance-sheet constraints create mild funding pressure into the turn. |
All card effects (rates, curve, balance-sheet shocks) are applied immediately when the instructor clicks Apply Card. They are not restricted to the start of the game or to after-hours. The story text and per-bank shock amounts are stored on s.shock so every page can display them.
4. Tick & timer system
The instructor sets the real-time length of a trading day (default 5 minutes) and clicks Start Trading. That writes:
timerStart,timerEnd,timerDurationMs- Resets
tickto 0
A client-side interval on the instructor page then computes the in-game tick:
- Total in-game trading window is 09:30–16:00 = 390 minutes = 78 five-minute ticks.
tick = floor(elapsed_real_ms / (timerDurationMs / 78)), capped at 78.- The displayed clock is 09:30 plus
tick × 5minutes.
When real time reaches timerEnd the market auto-closes (same path as a manual close). Pause/Resume freezes the elapsed-time calculation. The tick value is written back to Firebase so every client can see it.
Currently the tick is used for the clock display and for the auto-close trigger. The architecture is deliberately ready for future intraday events (for example, a scheduled curve tweak or balance-sheet drip at tick 20) because any client or the host can key off the shared tick field. No such intraday mutations exist today; all curve and balance changes are either instructor-driven or happen at the day boundary.
The timer length is chosen before (or at) the start of trading. Once the timer is running, only pause/resume is available; the length itself is not changed mid-session. Trading can also proceed without a timer (instructor closes manually).
5. Repo order book (overview)
Students submit orders from their bank page. A bid is a request to borrow cash overnight (pledge Treasuries); an offer is a request to lend cash overnight (receive Treasuries). Vocabulary follows the “price of cash” convention: higher bid / lower offer is more aggressive.
- Validation (
validateOrder) checks phase == trading, rate 0–25%, volume ≥ $0.01B, and capacity: a bank can only bid up to its free collateral and can only offer up to its available cash (after other open offers). Soft corridor warnings are shown but do not block the order. - The order is written to Firebase. The instructor page's
pumpMatches()loop detects crosses and callsmatchOrders(). - Matching is a continuous price-time priority double auction. A bid and offer trade when bid rate ≥ offer rate; the trade prints at the rate of the order that was resting first. Volume is limited by the smaller remaining size and by the lender's cash / borrower's free collateral. Self-trades are forbidden. Cash,
repoLent/repoBorrowed, andpledgedare updated immediately on the fill. - On market close every still-open order is expired. Any residual shortfall is funded by the Fed SRF (secured by remaining free Treasuries) or, beyond collateral, as an unsecured overdraft at SRF + 100 bp. Surplus cash is recorded as parked at IORB.
SOFR itself is the volume-weighted median of the day's private interbank trades (Fed operations are excluded), calculated at the close.
Reserve targets and tick-driven cash flows
generateReservePlans runs when a bank joins, when the instructor clicks Start Trading, when the instructor clicks Recalculate planned cashflows for next trading day, and with force=true at the end of every day inside advanceDay. Before each of those calls the instructor page copies the current values of the Banks-section controls (kSticky, kVolatile, cushion, fractionShort, clustering, vol step, vol prob) into gameParams; those controls are the sole source of truth. It computes each bank's risk-desk target as kSticky × sticky deposits + kVolatile × volatile funding + cushion (higher weight on volatile funding to reflect runoff risk) and assigns an assignedNetCashFlow for the day. The short cohort size is round(n * fractionShort) (default 0.40); those banks receive a net outflow large enough that they finish below target if they do nothing, and the rest receive a net inflow. A pre-computed sequence of tick-by-tick jumps is built so that the jumps sum exactly to the assigned net cash flow. Existing plans are left alone unless the call is forced.
Students see a live Reserve shortfall / surplus vs target line (current cash minus the day's target). They start the day above target. The instructor page shows each bank's assigned net cash flow; students do not. The host (instructor page) applies the pre-computed jumps as the shared tick advances, with catch-up so that lagged intervals do not skip intermediate flows. Mid-session joining is restricted: banks cannot be added while a trading day is actively running (timer started and market open).
Game loop — key phases
Start of trading day
After advanceDay() finishes, the session is in phase "trading", day has been incremented, the previous day's orders have been cleaned, timers and tick are reset, SOFR is null, and reserve plans have been force-regenerated for the new day. The instructor may optionally start the real-time timer (which begins the 5-minute tick clock and enables host application of the pre-computed cash-flow jumps). Students may already have banks or may join now. The curve is whatever was left by the previous day's drift (or the default on day 1). No automatic processes run until an order is submitted or the instructor acts.
During the trading day
- Students place, update, or cancel orders. Updates that change price or increase size lose time priority.
- The instructor page continuously pumps matches whenever a cross exists, writing the resulting trades and balance-sheet updates back to Firebase.
- If a timer is running, the shared
tickadvances with real time and the in-game clock moves from 09:30 toward 16:00. The host applies any pre-computed cash-flow jumps whose tick falls in the advanced interval (with catch-up for skipped ticks) and persists the updated cash and plans. - The instructor can apply corridor changes, curve edits/shifts, situation cards, systemic shocks, or cash re-rolls at any moment; all take effect immediately (balances change, books are re-marked, free collateral updates).
- Corridor warnings appear on orders that bid above SRF or offer below IORB, but students may still proceed.
End of trade day
Triggered by the instructor's “Close Market & Print SOFR” button or automatically when the timer expires. Host jump application stops with the timer. closeMarket():
- Expires every open order.
- Sets
sofr= volume-weighted median of the day's private trades. - Funds any remaining cash shortfall: first secured at the SRF rate up to free collateral, then the rest as an unsecured overdraft at SRF + 100 bp. Records surplus cash as an IORB placement.
- Appends a snapshot (SOFR, volume, gross cash, pledged, available) to
sofrHistory. - Sets phase =
"closed", clears timers and tick, recordsclosedBy(“timer” or “manual”).
No further matching occurs. Students can still see the tape, their sheets, and the curve, but cannot place new orders.
After hours
While the market is closed the instructor can still apply situation cards, curve changes, systemic shocks, or cash re-rolls (all take effect immediately). The primary “after hours” action is “Advance to Next Day”, which calls advanceDay():
- If the market was not yet closed, it closes it first.
- Accrues one night of interest for every bank (floating assets at yesterday's SOFR + 100 bp, positive cash at IORB, sticky deposits at 3.50%, plus the actual interest on every repo trade) and adds the net to equity and cash. There is no fixed-loan coupon.
- Unwinds every overnight repo: cash returns to the lender, collateral is released,
repoLent/repoBorrowed/pledgedgo back to zero. - Archives the day into
history, snapshots the curve that was in force intocurveHistory, and applies the small SOFR-linked curve drift + noise for the coming day. - Increments the day, clears SOFR, sets phase back to
"trading", resets timers and tick, deletes orders from the finished day, and force-regenerates reserve plans for the new day.
The session is now ready for the next trading day. “New Game” is a stronger reset: it re-draws every bank's entire starting balance sheet with fresh randoms (keeping only the bank name) and returns to day 1 with a clean slate.